body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I've been working on a project to make myself more comfortable with NodeJS, especially Express and TypeScript. Searching and reviewing a lot of approaches of the people, providing bootstraps for it, I was merely satisfied with the results I've found (including the git repos from Microsoft). So I started with the Express generator and started to convert it to a TypeScript conform structure. I moved the root/bin folder with it's "www" file to root/src/bin and renamed the file "index.ts".</p> <p>Now the problem I faced was that the port variable, which was initialized in the outer function, has lead tslint to mark the port variable inside the <code>normalizePort</code> function as "no-shadowed-variable". That's when I decided to extract the <code>normalizePort</code> function, as well as the event handlers <code>onError</code> and <code>onListening</code> into modules at the same directory. I'd like to get some advice, if the conversion of the variables (var -> let, const) and the modularization seems reasonable to you.</p> <p>Please let me know if you want me to also include the other two modules.</p> <p>Please keep in mind that I'm fairly new to programming in general and haven't had the opportunity to work on a project in a production environment.</p> <p>The whole project until now can be found <a href="https://github.com/owme/express-typescript" rel="nofollow noreferrer">here</a>.</p> <p>tslint.json:</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>{ "defaultSeverity": "error", "extends": [ "tslint:recommended" ], "jsRules": {}, "rules": { "quotemark": [true, "single"], "trailing-comma": [ false ] }, "rulesDirectory": [] }</code></pre> </div> </div> </p> <p>root/src/bin/index.ts:</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>#!/usr/bin/env node 'use strict'; /** * Module dependencies. * @private */ import { createServer } from 'http'; import app from '../app'; import { onError, onListening } from './expressHandlers'; import { normalizePort } from './normalizePort'; /** * Get port from environment and store in Express. */ const port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** * Create HTTP server. */ const server = createServer(app); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Module exports. * @public */ export { port, server };</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T12:20:09.660", "Id": "222017", "Score": "2", "Tags": [ "beginner", "node.js", "typescript", "express.js", "revealing-module-pattern" ], "Title": "The modularization of the Express entry point" }
222017
<p>I need to read a range of bytes from a file and return it as a <code>std::vector&lt;std::byte&gt;</code>.</p> <p>My current code looks like this:</p> <pre><code>#include &lt;cstdint&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; using bytes = std::vector&lt;std::byte&gt;; using namespace std; bytes read_block(uint32_t offset, uint32_t length, const string&amp; filename) { ifstream is(filename, ios::binary); is.seekg(offset); byte data[length]; is.read(reinterpret_cast&lt;char*&gt;(data), length); return bytes(data, data + length); } </code></pre> <p>But as can be seen I read it into a byte array and then create the vector by copying the bytes in the constructor. I have some issues with this implementation:</p> <ul> <li>Copying of bytes when creating output variable.</li> <li>Use of C style array.</li> <li>Use of casts.</li> </ul> <p>I have left out error handling for now to focus on the specific issues above.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:48:03.247", "Id": "429713", "Score": "1", "body": "Creating `byte data[length];` then creating a vector forces a copy. Why not make `data` a vector and simply return it. Then the compiler can do lots of optimization and build the vector directly at the destination so removing the need for a copy." } ]
[ { "body": "<p>I played around with this a bit more and came up with some alternatives.</p>\n\n<p>First I tried to use <code>basic_ifstream&lt;byte&gt;</code> like this:</p>\n\n<pre><code>bytes read_block(uint32_t offset,\n uint32_t length,\n const string&amp; filename) {\n basic_ifstream&lt;byte&gt; is(filename, ios::binary);\n istreambuf_iterator&lt;byte&gt; it(is);\n bytes data;\n copy_n(next(it, offset), length, data.begin());\n return data;\n}\n</code></pre>\n\n<p>this compiles without issues and does not use C style arrays nor casts and copies directly from the file to the output vector (thus solving all of my mentioned issues).</p>\n\n<p>However this throws a <code>std::bad_cast</code> at runtime. Based on <a href=\"https://stackoverflow.com/questions/17628207/stdbasic-ifstream-throws-stdbad-cast\">this</a> it might be due to stl not having a <code>char_traits</code> for <code>std::byte</code>. Annoying that it's a runtime issue and not a compile issue. As of now I don't know how or if it's simple/possible to implement a char_traits for <code>std::byte</code> myself.</p>\n\n<p>My next version loosens up on the cast restriction, but works also at runtime:</p>\n\n<pre><code>bytes read_block(uint32_t offset,\n uint32_t length,\n const string&amp; filename) {\n ifstream is(filename, ios::binary);\n is.seekg(offset);\n bytes data;\n data.resize(length);\n is.read(reinterpret_cast&lt;char*&gt;(data.data()), length);\n return data;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T18:06:31.430", "Id": "222040", "ParentId": "222021", "Score": "2" } }, { "body": "<p>Nice:</p>\n<pre><code>using bytes = std::vector&lt;std::byte&gt;;\n</code></pre>\n<p>I would call it <code>Bytes</code> to make it clear it is a type rather than an object.</p>\n<hr />\n<p>This is not a good idea:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>See: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n<hr />\n<p>This is technically not valid C++.</p>\n<pre><code> byte data[length];\n</code></pre>\n<p>Variable sized arrays (VSA) are an extension to the language supported by several compilers but not actually part of the C++ standard. Though it is part of the more recent versions C standard.</p>\n<p>Also creating a local array means that the data is being created on the local stack frame (here I am assuming a Von-Neumann like architecture). This means for the data to exist after the function completes means you will need to copy it out of the function. So an alternative data object is probably a good idea.</p>\n<p>Also there is a limitation on the size of array allowed on the stack (there are hardware limitations on the size of stack frames on lots of architecture).</p>\n<hr />\n<p>So a good idea would be to use the same data structure that you return.</p>\n<pre><code> Bytes data(length); // This is basically std::vector\n</code></pre>\n<p>Now in older versions of C++ there are some nice optimizations that can be applied to <code>std::vector</code> when it is returned from a function that allow the compiler to build the <code>std::vector</code> at the final destination so that it is not actually copied on return.</p>\n<p>In modern versions of the compiler the language has the concept of move semantics built into the language. So returning a <code>std::vector</code> is not an expensive operation as the internal buffer is moved (just the pointer is copied) from the function to the destination result.</p>\n<p>Also the compiler is now required to perform copy elision of objects when it can.</p>\n<hr />\n<h2>Error checking</h2>\n<p>This code does zero error checking. There are several things that can go wrong and you don't check for any of them. But you said you removed this (you should have left it in).</p>\n<hr />\n<p>So a better version:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\n#include &lt;fstream&gt;\n#include &lt;cstdint&gt;\n\nusing Bytes = std::vector&lt;std::byte&gt;;\n\nBytes read_block(std::uint32_t offset,\n std::uint32_t length,\n std::string const&amp; filename)\n{\n // Not going to explicitly check these.\n // The use of gcount() below will compensate for a failure here.\n std::ifstream is(filename, std::ios::binary);\n is.seekg(offset);\n\n Bytes data(length);\n is.read(reinterpret_cast&lt;char*&gt;(data.data()), length);\n\n // We have to check that reading from the stream actually worked.\n // If any of the stream operation above failed then `gcount()`\n // will return zero indicating that zero data was read from the\n // stream.\n data.resize(is.gcount());\n\n // Simply return the vector to allow move semantics take over.\n return data;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T01:51:07.507", "Id": "504704", "Score": "0", "body": "I gave you a thumbs up for the gcount() method. No one else checked the result after a read, which is sad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T21:13:38.217", "Id": "504782", "Score": "1", "body": "@user3235: number of bytes in a file does not equal the number of bytes in memory. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-08T21:26:40.157", "Id": "504785", "Score": "0", "body": "My point was, if I call read for a given number of bytes, into a vector, gcount() can tell me if I was successful. That was what I was looking for and found in your answer.\nIn your example, the check would be the value that gcount() returns against the length." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T14:10:02.973", "Id": "222088", "ParentId": "222021", "Score": "12" } }, { "body": "<p>Let's look at the signature of the function:</p>\n<blockquote>\n<pre><code>bytes read_block(uint32_t offset,\n uint32_t length,\n const string&amp; filename)\n</code></pre>\n</blockquote>\n<p>Instead of using the (optional) <code>std::uint32_t</code> we should accept the type we actually need for <code>seekg()</code> and <code>read()</code>, namely <code>std::ifstream::pos_type</code> and <code>std::streamsize</code>.</p>\n<p>Consider reordering the arguments so that users get the benefit of default values. I'd suggest filename first (as that's non-defaultable), then offset (default to beginning of file), then length (default to the whole file):</p>\n<pre><code>bytes read_block(const std::string&amp; filename,\n std::ifstream::pos_type offset = {},\n std::streamsize length = std::numeric_limits&lt;std::streamsize&gt;::max())\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T07:23:56.917", "Id": "268245", "ParentId": "222021", "Score": "2" } }, { "body": "<h1>Pass a <code>std::istream&amp;</code> instead of a filename</h1>\n<p>Your function has two responsibilities: opening the file and reading it. I would let it only read from an already opened file. This means the function can be shorter and have less responsibilities, and at the same time flexibility is increased because now it can read from any <code>std::istream</code>, not just from a <code>std::ifstream</code>. So:</p>\n<pre><code>bytes read_block(..., std::istream &amp;is) {\n is.seekg(offset);\n ...\n}\n</code></pre>\n<p>This way, your function will also be able to work on a <a href=\"https://en.cppreference.com/w/cpp/io/basic_stringstream\" rel=\"nofollow noreferrer\"><code>std::stringstream</code></a>, and in the future with <a href=\"https://en.cppreference.com/w/cpp/io/basic_spanstream\" rel=\"nofollow noreferrer\"><code>std::spanstream</code></a>.</p>\n<p>Note that this is similar to how <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a> works.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-22T20:31:35.047", "Id": "268266", "ParentId": "222021", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T13:17:56.507", "Id": "222021", "Score": "13", "Tags": [ "c++", "file", "vectors" ], "Title": "Read file into vector<byte>" }
222021
<p>I was implementing a simple neural network, and I noticed that, if I ever wanted to change the layers' activation functions, i would have had to completely rewrite some parts of the code, so I tried adding some flexibility to the network, using template meta-programming, because I thought that having most things resolved at compile time would have made everything faster.</p> <p>The network is a feedforward neural-network with stochastic gradient descent, and for the matrix calculations I'm using the Eigen library.</p> <p>I only implemented the Sigmoid and ReLU neuron types, but, with this architecture, it is trivial to add other ones; the same holds for the cost functions.</p> <p>These neurons are implemented as structs, containing two functions, one computing the output of the neuron and the other computing its first derivative; these functions are static, to access them directly from the neuron type.</p> <p>The neuron types are stored in the template parameters of the Network class, and to access them I wrapped them in a <code>std::tuple</code>:</p> <pre><code>using ActivationFuncsTuple = std::tuple&lt;ActivationFuncs...&gt;; </code></pre> <p>To access the type of neuron of a layer I used <code>std::tuple_element_t</code>, like this:</p> <pre><code>std::tuple_element_t&lt;Layer, ActivationFuncsTuple&gt; </code></pre> <p>Actually the neuron type always refers to Layer + 1, because the input layer doesn't have an associated neuron type </p> <p>To iterate over the tuple, I took a static-for implementation from this thread <a href="https://stackoverflow.com/questions/13816850/is-it-possible-to-develop-static-for-loop-in-c">Is it possible to develop static for loop in c++?</a>, but I modified it a bit to allow going backwards.</p> <p>Declaring a Network object is pretty straightforward, for example:</p> <pre><code>Network&lt;Sigmoid, Sigmoid&gt; net({784, 30, 10}); Network&lt;Sigmoid, ReLU, Sigmoid&gt; net({1000, 70, 40, 20}); </code></pre> <p>The number of activation function is one less the the number of layers because the first layer is the input layer.</p> <p>Training the network is just as easy:</p> <pre><code>net.train&lt;CrossEntropyCost&gt;(training_dataset, epochs, mini_batch_size, learning rate, regularization parameter, test_dataset); </code></pre> <p>Dataset is just a class I created to keep together the training or test inputs and the expected outputs, the make the code more compact.</p> <p>What I'm most interested in is the correctness of the template-metaprogramming, as it is the first time I employed it in a "big" project. And can it be done in a cleaner and more elegant (maybe faster) way?</p> <p><strong>Network.h</strong></p> <pre><code>#pragma once #include &lt;array&gt; #include &lt;cmath&gt; #include &lt;random&gt; #include &lt;tuple&gt; #include &lt;Eigen/Eigen&gt; #include "Functions.h" #include "Helpers.h" struct Dataset { Eigen::MatrixXf samples; Eigen::MatrixXf expected_outputs; Dataset slice(int startIndex, int n) const { return { samples.block(0, startIndex, samples.rows(), n), expected_outputs.block(0, startIndex, expected_outputs.rows(), n) }; } Eigen::Index size() const { return samples.cols(); } }; template &lt;typename ...ActivationFuncs&gt; class CustomNeuralNetwork { private: static constexpr std::size_t n_layers = sizeof...(ActivationFuncs) + 1; using ActivationFuncsTuple = std::tuple&lt;ActivationFuncs...&gt;; std::array&lt;Eigen::VectorXf, n_layers - 1&gt; biases; std::array&lt;Eigen::MatrixXf, n_layers - 1&gt; weights; public: CustomNeuralNetwork(const std::array&lt;std::size_t, n_layers&gt;&amp; layersSizes) { std::mt19937 gen(std::random_device{}()); std::normal_distribution&lt;float&gt; normalDist; for (int l = 0; l &lt; layersSizes.size() - 1; l++) { biases[l] = Eigen::VectorXf(layersSizes[l + 1]); std::generate_n(biases[l].data(), biases[l].size(), std::bind(normalDist, gen)); weights[l] = Eigen::MatrixXf(layersSizes[l + 1], layersSizes[l]); std::generate_n(weights[l].data(), weights[l].size(), std::bind(normalDist, gen)); weights[l] /= std::sqrt(static_cast&lt;float&gt;(layersSizes[l + 1])); } } template&lt;typename CostFunc&gt; void train(Dataset training_dataset, int epochs, int mini_batch_size, float eta, float lambda, const Dataset&amp; test_dataset = Dataset()) { Eigen::PermutationMatrix&lt;Eigen::Dynamic, Eigen::Dynamic&gt; permMatrix(training_dataset.size()); permMatrix.setIdentity(); std::mt19937 gen(std::random_device{}()); for (int epoch = 0; epoch &lt; epochs; epoch++) { std::shuffle(permMatrix.indices().data(), permMatrix.indices().data() + permMatrix.indices().size(), gen); training_dataset.samples *= permMatrix; training_dataset.expected_outputs *= permMatrix; for (int i = 0; i &lt; training_dataset.size(); i += mini_batch_size) { update_mini_batch&lt;CostFunc&gt;(training_dataset.slice(i, mini_batch_size), eta, lambda, training_dataset.size()); } if (test_dataset.size() &gt; 0) std::cout &lt;&lt; "Epoch " &lt;&lt; epoch + 1 &lt;&lt; " : " &lt;&lt; evaluate(test_dataset) &lt;&lt; " / " &lt;&lt; test_dataset.size() &lt;&lt; "\n"; } } template&lt;typename CostFunc&gt; void update_mini_batch(const Dataset&amp; mini_batch, float eta, float lambda, int n) { std::array&lt;Eigen::MatrixXf, n_layers - 1&gt; z; std::array&lt;Eigen::MatrixXf, n_layers&gt; a; a[0] = mini_batch.samples; static_for&lt;0, n_layers - 1&gt;::apply([&amp;](auto l) { z[l] = biases[l].replicate(1, mini_batch.size()); z[l].noalias() += weights[l] * a[l]; a[l + 1] = std::tuple_element_t&lt;l, ActivationFuncsTuple&gt;::value(z[l]); }); Eigen::MatrixXf delta = compute_delta&lt;CostFunc&gt;(z.back(), a.back(), mini_batch.expected_outputs); //BACKPROPROPAGATION BEGINS HERE Eigen::VectorXf delta_b = delta.rowwise().sum(); Eigen::MatrixXf delta_w = delta * a[a.size() - 2].transpose(); static_for&lt;n_layers - 2, 0&gt;::apply([&amp;](auto l) { delta = (weights[l].transpose() * delta).cwiseProduct(std::tuple_element_t&lt;l - 1, ActivationFuncsTuple&gt;::prime(a[l])); biases[l] -= delta_b * (eta / mini_batch.size()); weights[l] = weights[l] * (1 - eta * lambda / n) - delta_w * (eta / mini_batch.size()); delta_b.noalias() = delta.rowwise().sum(); delta_w.noalias() = delta * a[l - 1].transpose(); }); biases[0] -= delta_b * (eta / mini_batch.size()); weights[0] = weights[0] * (1 - eta * lambda / n) - delta_w * (eta / mini_batch.size()); } template&lt;typename CostFn&gt; Eigen::MatrixXf compute_delta(const Eigen::MatrixXf&amp; z, const Eigen::MatrixXf&amp; a, const Eigen::MatrixXf&amp; y) { if constexpr (std::is_same&lt;std::tuple_element_t&lt;n_layers - 2, ActivationFuncsTuple&gt;, Sigmoid&gt;::value &amp;&amp; std::is_same&lt;CostFn, CrossEntropyCost&gt;::value) { return a - y; //Specialization for Sigmoid neuron and Cross-Entropy cost function } else return CostFn::gradient(a, y).cwiseProduct(std::tuple_element_t&lt;n_layers - 2, ActivationFuncsTuple&gt;::prime(z, a)); } Eigen::MatrixXf feedforward(Eigen::MatrixXf input) { static_for&lt;0, n_layers - 1&gt;::apply([&amp;](auto l) { input = std::tuple_element_t&lt;l, ActivationFuncsTuple&gt;::value((weights[l] * input).colwise() + biases[l]); }); return input; } int evaluate(const Dataset&amp; test_dataset) { int accuracy = 0; Eigen::MatrixXf outputs = feedforward(test_dataset.samples); for (int i = 0; i &lt; test_dataset.size(); i++) { int prediction; outputs.col(i).maxCoeff(&amp;prediction); int correct; test_dataset.expected_outputs.col(i).maxCoeff(&amp;correct); accuracy += (prediction == correct); } return accuracy; } }; </code></pre> <p><strong>Functions.h</strong></p> <pre><code>#pragma once #include &lt;Eigen/Eigen&gt; struct Sigmoid { static Eigen::MatrixXf value(const Eigen::MatrixXf&amp; z) { return 1.f / (1.f + z.array().exp().inverse()); } static Eigen::MatrixXf prime(const Eigen::MatrixXf&amp; a) { return a.array() * (1 - a.array()); } }; struct ReLU { static Eigen::MatrixXf value(const Eigen::MatrixXf&amp; z) { return (z.array().max(0.f)); } static Eigen::MatrixXf prime(const Eigen::MatrixXf&amp; z) { return (z.array() &gt; 0.f).cast&lt;float&gt;(); } }; struct QuadraticCost { static float cost(const Eigen::MatrixXf&amp; output, const Eigen::MatrixXf&amp; expected_outputs) { return 0.5f * (output - expected_outputs).colwise().squaredNorm().sum() / output.cols(); } static Eigen::MatrixXf gradient(const Eigen::MatrixXf&amp; outputs, const Eigen::MatrixXf&amp; expected_outputs) { return (outputs - expected_outputs).cwiseProduct(Sigmoid::prime(outputs)); } }; struct CrossEntropyCost { static float cost(const Eigen::MatrixXf&amp; outputs, const Eigen::MatrixXf&amp; expected_outputs) { return -(expected_outputs.array() * outputs.array().log() + expected_outputs.array() * (1.f - outputs.array()).log()).colwise().sum().sum() / outputs.cols(); } static Eigen::MatrixXf gradient(const Eigen::MatrixXf&amp; outputs, const Eigen::MatrixXf&amp; expected_outputs) { return (outputs - expected_outputs).cwiseQuotient(Sigmoid::prime(outputs)); } }; </code></pre> <p><strong>Helpers.h</strong></p> <pre><code>#pragma once template &lt;int First, int Last&gt; struct static_for { template &lt;typename Func&gt; static constexpr void apply(Func&amp;&amp; f) { if constexpr(First &lt; Last) { f(std::integral_constant&lt;int, First&gt;{}); static_for&lt;First + 1, Last&gt;::apply(f); } else if constexpr (First &gt; Last) { f(std::integral_constant&lt;int, First&gt;{}); static_for&lt;First - 1, Last&gt;::apply(f); } } }; </code></pre>
[]
[ { "body": "<p>Awesome work. Some further suggestions are mentioned as below.</p>\n<h3 id=\"consider-to-add-some-unit-tests-with-a-testing-framework-y6yh\">Consider to add some unit tests with a testing framework</h3>\n<blockquote>\n<p>What I'm most interested in is the correctness of the template-metaprogramming</p>\n</blockquote>\n<p>You can add some tests for verify the correctness. No matter the single layer cases or multiple layer cases, and the usage of various types of activation functions.</p>\n<h3 id=\"consider-to-use-size_t-for-sizes-and-epochs-g44l\">Consider to use <code>size_t</code> for sizes and epochs</h3>\n<p>The line <code>for (int l = 0; l &lt; layersSizes.size() - 1; l++)</code> in <code>CustomNeuralNetwork</code> class constructor, you use <code>int</code> for iteration. The type <code>size_t</code> can be used here to represent all sizes of things.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-28T23:52:46.880", "Id": "264497", "ParentId": "222025", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T14:20:56.537", "Id": "222025", "Score": "8", "Tags": [ "c++", "performance", "template-meta-programming", "neural-network" ], "Title": "Neural Network with Template Metaprogramming" }
222025
<p>I'm a newbie and I wrote code that gets a WAV file and exports a RAW (only PCM data) to *.raw file. But I am confused about the structure. The code is written as one procedure (LISP style) and there are no functions. Can I get some advice how to reorganize the code?</p> <p>main.c</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "wave.h" byte buf[5]; // 4 char string buffer char filename[200]; // FILE *fp; FILE *pcm_data; int main(int argc, char *argv[]) { strcat(filename, argv[1]); struct riff_chunk riff = {"RIFF", 0, "WAVE"}; struct fmt_chunk fmt = {"fmt "}; struct data_chunk data = {"data"}; if ((fp = fopen(argv[1], "rb"))==NULL) { printf("Can't open the file. Exit.\n"); return 1; } // Reading RIFF section if (fread(&amp;riff.id, sizeof(byte), 12, fp)!= 12) { printf("Can't read RIFF chunk or EOF is met. Exit.\n"); return 1; } else { memccpy(buf, riff.id, '\0', 4); if (strcmp(buf, "RIFF")!=0) { printf("File format is not RIFF. Exit.\n"); return 1; } memccpy(buf, riff.type, '\0', 4); if (strcmp(buf, "WAVE")!=0) { printf("File format is not WAVE. Exit.\n"); return 1; } }; // Reading fmt.id and fmt.size if (fread(&amp;fmt, sizeof(byte), 8, fp)!=8) { printf("Can't read fmt chunk or EOF is met. Exit.\n"); return 1; } else { memccpy(buf, fmt.id, '\0', 4); if (strcmp(buf, "fmt ")!=0) { printf("File have no fmt chunk. Exit.\n"); return 1; } } // Reading fmt Sample Format Info if (fread(&amp;fmt.compression, sizeof(byte), fmt.size, fp) != fmt.size) { printf("Can't read Sample Format Info in fmt chunk or EOF is met. Exit.\n"); return 1; } printf("Compression: %d\n", fmt.compression); printf("Channels: %d\n", fmt.chanels); printf("Sample Rate: %d\n", fmt.sample_rate); printf("Bit Rate: %d\n", fmt.bit_per_sample); // Reading data/some chunk if (fread(&amp;data, sizeof(byte), 8, fp)!=8) { printf("Error of reading data chunk. Exit.\n"); return 1; } else { while (memccpy(buf, data.id, '\0', 4), strcmp(buf, "data")!=0) { fseek(fp, data.size, 1); // перемещаем указатель файла на конец чанка (его размер) fread(&amp;data, sizeof(byte), 8, fp); } } // Reading PCM byte *dump = (byte*)malloc(data.size); if (dump == NULL) { printf("Allocation memory error"); return 1; } if (fmt.compression == 1) { fmt.number_of_blocks = data.size / fmt.block_align; if ((fread(dump, fmt.block_align, fmt.number_of_blocks, fp))!=fmt.number_of_blocks) { printf("Readin PCM data error.\n"); return 1; } else { strcat(filename, ".raw"); if ((pcm_data = fopen(filename, "wb"))==NULL) { printf("Can't open the PCM file for write. Exit.\n"); return 1; } if(fwrite(dump, fmt.block_align, fmt.number_of_blocks, pcm_data)!=fmt.number_of_blocks) { printf("Can't write PCM file. Exit.\n"); return 1; } printf("------------\nDone. PCM data writing in PCM file. Exit.\n"); } } else { printf("Compression type is not PCM. Exit.\n"); return 1; } free(dump); fclose(fp); fclose(pcm_data); return 0; } </code></pre> <p>wave.h</p> <pre class="lang-c prettyprint-override"><code>typedef char byte; // 1 byte \ 8 bit typedef short int word; // 2 byte \ 16 bit typedef unsigned int dword; // 4 byte \ 32 bit struct riff_chunk { byte id[4]; // 4b "RIFF" string &gt;| dword size; // 4b |-&gt; 12 byte byte type[4]; // 4b "WAVE" string &gt;| }; struct fmt_chunk { byte id[4]; // 4b "fmt" string dword size; // 4b _____ word compression; // 2b word chanels; // 2b dword sample_rate; // 4b _____ dword byte_per_sec; // 4b word block_align; // 2b word bit_per_sample; // 2b _____ word extra_format_size; // 2b _____ byte* extra_format_data; // 8b _____ dword number_of_blocks; // 4b _____ }; struct data_chunk { byte id[4]; // 4 "data" string dword size; // 4 }; int dump(word*, dword*); </code></pre>
[]
[ { "body": "<p>I don't see a great need to re-organise the structure of the code, other than to eliminate the unnecessary global variables (most can be moved to function scope).</p>\n\n<p>There are a few portability problems that need to be addressed. I'll start with the assumption about the width of integer types:</p>\n\n<blockquote>\n<pre><code>typedef char byte; // 1 byte \\ 8 bit \ntypedef short int word; // 2 byte \\ 16 bit\ntypedef unsigned int dword; // 4 byte \\ 32 bit\n</code></pre>\n</blockquote>\n\n<p>The comments are assumptions that will need to be verified for every platform you build this for. There's a portable way to get what you want:</p>\n\n<pre><code>typedef uint8_t byte;\ntypedef uint16_t word;\ntypedef uint32_t dword;\n</code></pre>\n\n<p>Or just use the standard fixed-width types throughout - that's less confusing than inventing your own terminology.</p>\n\n<p>Note that when using <code>printf()</code> and family, we need to use the correct specifiers. This is wrong:</p>\n\n<blockquote>\n<pre><code>printf(\"Compression: %d\\n\", fmt.compression);\nprintf(\"Channels: %d\\n\", fmt.chanels);\nprintf(\"Sample Rate: %d\\n\", fmt.sample_rate);\nprintf(\"Bit Rate: %d\\n\", fmt.bit_per_sample);\n</code></pre>\n</blockquote>\n\n<p>With your original definitions, we should be using <code>%hu</code> for the first two of these and <code>%u</code> for the last two. Using the standard fixed-width types, we get macros we can use for formatting:</p>\n\n<pre><code>printf(\"Compression: %\" PRIu16 \"\\n\", fmt.compression);\nprintf(\"Channels: %\" PRIu16 \"\\n\", fmt.chanels);\nprintf(\"Sample Rate: %\" PRIu32 \"\\n\", fmt.sample_rate);\nprintf(\"Bit Rate: %\" PRIu32 \"\\n\", fmt.bit_per_sample);\n</code></pre>\n\n<p>Here's an inefficiency:</p>\n\n<pre><code> memccpy(buf, riff.id, '\\0', 4);\n if (strcmp(buf, \"RIFF\")!=0) {\n</code></pre>\n\n<p>Firstly, <code>memccpy</code> isn't standard C (though it is defined by POSIX), so there's a small reduction in portability. But there's no need to copy to <code>buf</code> here - just compare in place using <code>strncmp()</code>:</p>\n\n<pre><code> if (strncmp(\"RIFF\", riff.id, sizeof riff.id)) {\n</code></pre>\n\n<p>There's a lot of hard-coded sizes. For example:</p>\n\n<blockquote>\n<pre><code>if (fread(&amp;riff.id, sizeof(byte), 12, fp)!= 12) {\n</code></pre>\n</blockquote>\n\n<p>It's strange that we write <code>sizeof (byte)</code>, even though <code>byte</code> is just an alias for <code>char</code> (and so has size of 1 char), but then use <code>12</code> where we could more meaningfully write <code>sizeof riff</code>:</p>\n\n<pre><code>if (fread(&amp;riff, 1, sizeof riff, fp) != sizeof riff) {\n</code></pre>\n\n<p>(I also changed <code>&amp;riff.id</code> to just <code>&amp;riff</code> to make it clear that we're writing to the whole structure, not just the <code>id</code> member.)</p>\n\n<p>When allocating, there's no need for (and possibly slight harm in) casting the returned <code>void</code> pointer to a more specific pointer size. It's also idiomatic to use the inherent truthiness of a non-null pointer, rather that testing explicitly against <code>NULL</code>:</p>\n\n<pre><code>byte *dump = malloc(data.size);\nif (!dump) {\n</code></pre>\n\n<p>I'm glad you didn't forget error checking here, and when opening files - that's an important part of programming in C, and you've got that right. One small improvement: error messages should go to <code>stderr</code>, not <code>stdout</code>:</p>\n\n<pre><code> fprintf(stderr, \"Memory allocation error\\n\");\n</code></pre>\n\n<p>BTW, don't forget when compiling to ensure that the structures are <em>packed</em>, without any padding between members.</p>\n\n<p>An enhancement suggestion: allow the user to specify where to write the output (or just send it to standard out, and let them use their shell to redirect it). We'll fail if the input file is in a read-only directory at present.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:21:26.957", "Id": "429688", "Score": "0", "body": "Thank You so much for detailed answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:39:37.330", "Id": "429692", "Score": "0", "body": "It is my first application on C. I did't know about `uint` types and `PRIu16` formatting. About `memccpy`: I'v tried to use `strcmp`, but `riff.id` and other members have only 4 bytes and no `\\0` in last byte. Every comparison return `false`, but `buf` have 5 bytes where memccpy add the `\\0` in last. Maybe I wrong. I don't know. What You think about it? Thank You for other." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:42:57.953", "Id": "429693", "Score": "1", "body": "Use `strncmp()` instead of `strcmp()` - this is how we compare sequences that might not be null terminated. The extra argument is a maximum number of characters to compare if no NUL is reached. BTW, welcome to the wonderful world of C programming. It's frustrating at times, but rewarding eventually!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:52:04.640", "Id": "429695", "Score": "0", "body": "Sorry, I look at `strncmp()` but read `strcmp()` :) Thank You again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:15:02.800", "Id": "429700", "Score": "0", "body": "I'v tried to use `strncmp()` but get a warning: `passing 'byte [4]' to parameter of type 'const char *' converts between pointers to integer types with different sign`. It is named **implicitly convert**, I think, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:19:48.487", "Id": "429703", "Score": "1", "body": "Well, we could explicitly cast, but it's probably better to change the type of `id` to `char[4]`, since we want to treat them as *characters* rather than unsigned small values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:23:56.433", "Id": "429706", "Score": "0", "body": "Ok, what the right way to portability? Is `char` always equal 1 byte on all machines?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:29:23.770", "Id": "429709", "Score": "1", "body": "`char` is the smallest addressable unit of memory. On any machine that has a `uint8_t`, then `char` must be 8 bits (it's not allowed to be less than that, and if it were greater, then there would be a smaller addressable type, which isn't allowed). On systems where `char` is wider than 8 bits, `uint8_t` will be an error (rather than just silently wrong)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:54:06.100", "Id": "429715", "Score": "1", "body": "Just to add - systems with `char` between 9 and 15 are now quite rare; some specialised platforms (e.g. certain DSPs) have 16-bit `char`, but practically all general-purpose computers have 8-bit `char`. The widths of `int`, `long`, etc. are more varied." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T09:04:11.380", "Id": "222068", "ParentId": "222026", "Score": "2" } } ]
{ "AcceptedAnswerId": "222068", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T14:34:59.327", "Id": "222026", "Score": "7", "Tags": [ "beginner", "c", "audio", "file-structure" ], "Title": "Parse a WAV file and export PCM data" }
222026
<p>My use case is this:</p> <p><strong><em><code>RangeDemo.java:</code></em></strong></p> <pre><code>package net.coderodde.util; public class RangeDemo { public static void main(String[] args) { for (Integer i : new Ranges(new Range(-9, 0), new Range(3, 5), new Range(15, 10), new Range(11, 11), new Range(16, 17))) { System.out.print(i + " "); } } } </code></pre> <p>... which gives me:</p> <pre><code>-9 -8 -7 -6 -5 -4 -3 -2 -1 3 4 10 11 12 13 14 16 </code></pre> <p>My implementation is this:</p> <p><strong><em><code>Range.java:</code></em></strong></p> <pre><code>package net.coderodde.util; /** * This class implements a range of integers. * * @author Rodion "rodde" EfremoB. * @version 1.6 (Jun 10, 2019) */ public final class Range { private final int fromIndex; private final int toIndex; public Range(final int fromIndex, final int toIndex) { this.fromIndex = Math.min(fromIndex, toIndex); this.toIndex = Math.max(fromIndex, toIndex); } int get(int index) { return fromIndex + index; } int size() { return toIndex - fromIndex; } } </code></pre> <p><strong><em><code>Ranges.java:</code></em></strong></p> <pre><code>package net.coderodde.util; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; /** * This class implements an integer iterator over a range of ranges. * * @author rodde */ public final class Ranges implements Iterable&lt;Integer&gt; { /** * This static inner class implements the actual iterator. */ private static final class RangeIterator implements Iterator&lt;Integer&gt; { /** * Holds the actual ranges. */ private final Range[] ranges; /** * The index of the current range. */ private int currentRangeIndex; /** * The current index within the current range. */ private int currentElementIndex; /** * The total number of integers to iterate. */ private final int globalSize; /** * The global number of integers already iterated. */ private int globalIndex; private RangeIterator(Range[] ranges) { this.ranges = ranges; this.globalSize = countGlobalSize(); } @Override public boolean hasNext() { return globalIndex &lt; globalSize; } @Override public Integer next() { if (!hasNext()) { throw new NoSuchElementException("Nothing to iterate."); } while (currentElementIndex == ranges[currentRangeIndex].size()) { currentRangeIndex++; currentElementIndex = 0; } globalIndex++; return ranges[currentRangeIndex].get(currentElementIndex++); } private int countGlobalSize() { int globalSize = 0; for (Range r : ranges) { globalSize += r.size(); } return globalSize; } } private final Range[] ranges; public Ranges(Range... ranges) { this.ranges = Objects.requireNonNull(ranges); } @Override public Iterator&lt;Integer&gt; iterator() { return new RangeIterator(ranges); } @Override public void forEach(Consumer&lt;? super Integer&gt; action) { RangeIterator rangeIterator = new RangeIterator(this.ranges); rangeIterator.forEachRemaining(action); } } </code></pre>
[]
[ { "body": "<p>I think <code>RangeCollection</code> would be a better name than <code>Ranges</code>.</p>\n\n<p>To my mind, the <code>RangeIterator</code> is doing too much. It's iterating over a collection of ranges and over each range in the collection. To me it would make more sense for the <code>Range</code> class to have its own iterator and the <code>RangeCollection</code> its own iterator</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T17:38:16.177", "Id": "429609", "Score": "0", "body": "I would also opt for restructuring the iterators. One for the range collection iterating ranges, one for the range iterating integers and one for the algorithm that uses both others." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T17:29:08.180", "Id": "222036", "ParentId": "222034", "Score": "4" } }, { "body": "<p>This is fairly minor, but I don't think <code>countGlobalSizes</code> is ideal. Its use in the constructor requires that the assignment of <code>ranges</code> happens first; which may cause breakage if you refactor later. It also barely has any reliance on individual instances. I'd make it <code>static</code> and accept the ranges directly as an argument:</p>\n\n<pre><code>private static int sumRangeLengths(Range[] ranges) {\n int totalSize = 0;\n\n for (Range r : ranges) {\n totalSize += r.size();\n }\n\n return totalSize;\n}\n</code></pre>\n\n<p>I'm also not a fan of the word \"global\" being used everywhere. The variables aren't really \"global\" in most senses. They're private members of instances; which is a pretty constrained scope. They're global to the instance; but every member is, so that's redundant.</p>\n\n<hr>\n\n<p>You may also want to add a <code>step</code> to your range. It's fairly trivial to implement, and is a fairly common aspect of most range implementations.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T11:12:19.703", "Id": "429681", "Score": "1", "body": "Don't you mean that the assignment of `ranges` has to happen before the invocation of `countGlobalSize()`, rather than the assignment of `globalSize`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:22:02.343", "Id": "429705", "Score": "0", "body": "@Stingy Whoops, thanks. Fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T17:36:39.947", "Id": "222037", "ParentId": "222034", "Score": "3" } } ]
{ "AcceptedAnswerId": "222036", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T17:04:29.857", "Id": "222034", "Score": "2", "Tags": [ "java", "integer", "iterator", "iteration", "interval" ], "Title": "Iterating over a range of integer ranges in Java" }
222034
<p>Every time I toggle active class in a list (to dynamically change DOM content) I find that I always go to this approach to check and clear which class is <code>active</code>. I'm still fairly new to using pure javascript so I'm wondering if there is a better, simpler approach?</p> <p>It feels like having to run a second function to clear out all active classes seems grunty. </p> <p>I've included an example of how I do it.</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>var specialNav = document.getElementById("special-nav"); if (specialNav) { var navItems = specialNav.getElementsByTagName('li'); var i; for (i = 0; i &lt; navItems.length; i++) { navItems[i].addEventListener("click", function() { if (!this.classList.contains('active')) { clearActives(navItems); this.classList.toggle('active'); } }); } } function clearActives(classlist) { if (classlist) { for (i = 0; i &lt; classlist.length; i++) { classlist[i].classList.remove('active'); } } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.active { color: red } li { cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="special-nav"&gt; &lt;ul&gt; &lt;li class="active"&gt; 1&lt;/li&gt; &lt;li&gt;2&lt;/li&gt; &lt;li&gt;3&lt;/li&gt; &lt;li&gt;4&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T18:40:06.313", "Id": "429627", "Score": "2", "body": "Check out a recent post about this: https://codereview.stackexchange.com/questions/221597/jquery-dynamic-toggle-class-function/221598#221598" } ]
[ { "body": "<p>You could use some newer methods like spread syntax in array and <code>forEach</code> loop on node list for this. You could also write separate function to get sibling nodes and to toggle class based on sibling nodes. </p>\n\n<p>This way you can toggle class on one element and also toggle based on other element nodes.</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 li = document.querySelectorAll('li');\n\nfunction siblings(elem) {\n const nodes = [...elem.parentNode.children]\n return nodes.filter(node =&gt; node !== elem)\n}\n\nfunction toggleClass(elem, cls) {\n elem.classList.toggle(cls);\n siblings(elem).forEach(node =&gt; {\n node.classList.remove(cls)\n })\n}\n\nli.forEach(el =&gt; {\n el.addEventListener('click', function() {\n toggleClass(this, 'active')\n })\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.active {\n color: red;\n}\n\nli {\n cursor: pointer;\n user-select: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"special-nav\"&gt;\n &lt;ul&gt;\n &lt;li class=\"active\"&gt; 1&lt;/li&gt;\n &lt;li&gt;2&lt;/li&gt;\n &lt;li&gt;3&lt;/li&gt;\n &lt;li&gt;4&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T18:51:22.360", "Id": "222044", "ParentId": "222042", "Score": "1" } }, { "body": "<p>Another approach could be with hidden radio inputs and :checked CSS selector :</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-css lang-css prettyprint-override\"><code>input { display: none }\ninput:checked ~ * { color: red }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label&gt;&lt;input type=\"radio\" name=\"li\" checked&gt;&lt;li&gt;1&lt;/li&gt;&lt;/label&gt;\n&lt;label&gt;&lt;input type=\"radio\" name=\"li\"&gt;&lt;li&gt;2&lt;/li&gt;&lt;/label&gt;\n&lt;label&gt;&lt;input type=\"radio\" name=\"li\"&gt;&lt;li&gt;3&lt;/li&gt;&lt;/label&gt;\n&lt;label&gt;&lt;input type=\"radio\" name=\"li\"&gt;&lt;li&gt;4&lt;/li&gt;&lt;/label&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T10:37:32.817", "Id": "222076", "ParentId": "222042", "Score": "2" } }, { "body": "<h2>Build reusable</h2>\n<p>Always try to code in such a way that the effort you put in can be reused, first in the same app, and maybe in other apps.</p>\n<p>One would assume that you likely have more than one list that acts like radio group, or even unrelated DOM items as part of a radio group.</p>\n<p>Your best bet is to create a simple object that tracks the state of a group and provides functionality to switch selected items.</p>\n<h2>Track current selected item</h2>\n<p>There is no need to check all the elements each time one is clicked if you keep track of the currently active element. If you have the currently selected item then you need only remove the class name from that element and add it to the new element.</p>\n<p>The following snippet is a very basic radio group via JavaScript.</p>\n<pre><code>const RadioGroup = (activeClass, ...elements) =&gt; {\n var active = elements.find(el =&gt; el.classList.contains(activeClass));\n return {\n set selected(element) {\n if(elements.includes(element) &amp;&amp; active !== element) {\n active &amp;&amp; active.classList.remove(activeClass);\n element.classList.add(activeClass);\n active = element;\n }\n },\n get selected() { return active },\n };\n}\n// example create group and select first list item\nconst rGroup = RadioGroup(&quot;active&quot;, ...document.querySelectorAll(&quot;li&quot;));\nrGroup.selected = document.querySelector(&quot;li&quot;);\n</code></pre>\n<h2>Custom interfaces</h2>\n<p>Javascript lets you build powerful reusable interfaces to suit your specific needs.</p>\n<p>The example below creates a more sophisticated object that stores many radio groups by name and provides two interfaces and a on selected <code>callback</code></p>\n<h2>Example</h2>\n<p>Note that the second group is unselected at start.</p>\n<p>The interface also lets you turn off a selection by selecting an item not in the selectable elements list eg <code>undefined</code>. This is demonstrated when an item in the first group is selected, if there is one selected in the second it is turned off.</p>\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>setTimeout(() =&gt; { // for snippet rather than doc load/ed\n createGroup(document.getElementById(\"special-nav-one\"), );\n createGroup(document.getElementById(\"special-nav-two\"), \"activeTwo\");\n function createGroup(container, className = \"active\") {\n const group = radioGroups.addGroup(\n container.id, onItemSelected, className, \n ...container.querySelectorAll('LI')\n );\n // NOTE property tagName is UPPERCASE\n container.addEventListener(\"click\", e =&gt; (e.target.tagName === \"LI\") &amp;&amp; (group.selected = e.target));\n }\n}, 0);\n\nfunction onItemSelected(group, element) {\n info.textContent = \"Selected from \\\"\" + group.name + \"\\\" item \" + element.textContent;\n if(group.name === \"special-nav-one\") {\n radioGroups.select(\"special-nav-two\"); // unselect group 2\n }\n}\n\n\n\nconst radioGroups = (()=&gt;{\n const namedGroups = {};\n function select(groupName, element) {\n const group = namedGroups[groupName];\n if (group &amp;&amp; group.active !== element) {\n group.active &amp;&amp; group.active.classList.remove(group.activeClass);\n if (group.elements.includes(element)) {\n group.callback &amp;&amp; group.callback(group.API, element);\n element.classList.add(group.activeClass);\n group.active = element;\n } else {\n group.active = undefined;\n }\n }\n }\n return Object.freeze({\n select,\n addGroup(name, callback, activeClass, ...elements) {\n const active = elements.find(el =&gt; el.classList.contains(activeClass));\n const API = Object.freeze({\n get name() { return name },\n set selected(element) { select(name, element) },\n get selected() { return group.active }, \n });\n const group = namedGroups[name] = {name, elements, active, activeClass, callback, API};\n return API;\n\n },\n });\n})();\n\n/** Use ****************************************************************************\n Selects element from named group\n radioGroups.select(groupName, element) \n \n Create a new group. Will replace a group if name is same.\n group = radioGroups.select(name, callback, activeClassName, ...elements)\n\n Arguments\n name: Unique name of group\n callback: Called when selection changed, null or undefined if not used\n activeClassName: Name of class to toggle\n ...elements: Selectable elements\n Returns a group object\n group.selected (read, write) To select or get the current selected item.\n group.name (read only) name of group\n***********************************************************************************/</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.active {\n color: red;\n cursor: default;\n}\n.activeTwo {\n background: #AFA;\n cursor: default;\n}\nli {\n cursor: pointer;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"info\"&gt;Select items&lt;/div&gt;\n&lt;div id=\"special-nav-one\"&gt;\n &lt;ul&gt;\n &lt;li class=\"active\"&gt;A: one&lt;/li&gt;\n &lt;li&gt;A: two&lt;/li&gt;\n &lt;li&gt;A: three&lt;/li&gt;\n &lt;li&gt;A: four&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;\n&lt;div id=\"special-nav-two\"&gt;\n &lt;ul&gt;\n &lt;li&gt;B: one&lt;/li&gt;\n &lt;li&gt;B: two&lt;/li&gt;\n &lt;li&gt;B: three&lt;/li&gt;\n &lt;li&gt;B: four&lt;/li&gt;\n &lt;li&gt;B: five&lt;/li&gt;\n &lt;/ul&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you plan to add and remove items from the lists you will need to extend the <code>radioGroups</code> interfaces so that you can do so safely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T20:55:10.510", "Id": "429921", "Score": "0", "body": "I always overlook the fact of creating objects in JS. This is a beautiful and detailed answer, I thank you. \n\nDefinitely makes me rethink my designs going forward. I come back from a heavy react background and I've become very used to the ES6 syntax, but I rarely used JS without a framework/library." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T20:26:38.400", "Id": "222108", "ParentId": "222042", "Score": "1" } } ]
{ "AcceptedAnswerId": "222108", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T18:37:00.523", "Id": "222042", "Score": "4", "Tags": [ "javascript", "beginner", "html" ], "Title": "Toggling only a single class as active in a list with vanilla JS or CSS" }
222042
<p>I am writing an event sourced system in which I need to have the state based on the events that already occurred for a given bank account.</p> <p>The events are defined such as:</p> <pre><code>type AccountOpenedEvent = { AccountId: Guid Contact: Contact Timestamp: DateTimeOffset } type AccountClosedEvent = { AccountId: Guid Reason: string Timestamp: DateTimeOffset } type AccountCreditedEvent = { AccountId: Guid Amount: decimal Description: string Timestamp: DateTimeOffset } type AccountDebitedEvent = { AccountId: Guid Amount: decimal Description: string Timestamp: DateTimeOffset } type AddressChangeRequestedEvent = { AccountId: Guid NewAddress: Address Timestamp: DateTimeOffset } type PhoneNumberChangeRequestedEvent = { AccountId: Guid NewPhoneNumber: PhoneNumber Timestamp: DateTimeOffset } type EmailChangeRequestedEvent = { AccountId: Guid NewEmail: string Timestamp: DateTimeOffset } type AddressChangeValidatedEvent = { AccountId: Guid NewAddress: Address Timestamp: DateTimeOffset } type PhoneNumberChangeValidatedEvent = { AccountId: Guid NewPhoneNumber: PhoneNumber Timestamp: DateTimeOffset } type EmailChangeValidatedEvent = { AccountId: Guid NewEmail: string Timestamp: DateTimeOffset } type InvalidOperationAttemptedEvent = { Error: string Timestamp: DateTimeOffset } type Event = | AccountOpened of AccountOpenedEvent | AccountClosed of AccountClosedEvent | AccountCredited of AccountCreditedEvent | AccountDebited of AccountDebitedEvent | AddressChangeRequested of AddressChangeRequestedEvent | PhoneNumberChangeRequested of PhoneNumberChangeRequestedEvent | EmailChangeRequested of EmailChangeRequestedEvent | AddressChangeValidated of AddressChangeValidatedEvent | PhoneNumberChangeValidated of PhoneNumberChangeValidatedEvent | EmailChangeValidated of EmailChangeValidatedEvent | InvalidOperationAttempted of InvalidOperationAttemptedEvent </code></pre> <p>The projection system is defined as:</p> <pre><code>type Projection&lt;'State,'Event&gt; = { Init : 'State Update : 'State -&gt; 'Event -&gt; 'State } let project projection events = events |&gt; Seq.fold projection.Update projection.Init </code></pre> <p>and the update function to update the state depending on the event received:</p> <pre><code>let updateAccountState (state : AccountState) (event : Event)= match event with | AccountOpened accountOpened -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when accountOpened.AccountId = state.Id.Value -&gt; let message = "The account cannot be opened cause it is already opened." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Opened when accountOpened.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot be opened cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when accountOpened.AccountId = state.Id.Value -&gt; let message = "The account cannot be opened cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when accountOpened.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot be opened cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; { state with Contact = Some accountOpened.Contact Status = Some AccountStatus.Opened Balance = Some 0m Created = Some accountOpened.Timestamp Updated = Some accountOpened.Timestamp Id = Some accountOpened.AccountId } | AccountClosed accountClosed -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when accountClosed.AccountId = state.Id.Value -&gt; { state with Status = Some AccountStatus.Closed Updated = Some accountClosed.Timestamp } | AccountStatus.Opened when accountClosed.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot be closed cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when accountClosed.AccountId = state.Id.Value -&gt; let message = "The account cannot be closed cause it is already closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when accountClosed.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot be closed cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot be closed cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountCredited accountCredited -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when accountCredited.AccountId = state.Id.Value -&gt; { state with Balance = Some (state.Balance.Value + accountCredited.Amount) Updated = Some accountCredited.Timestamp } | AccountStatus.Opened when accountCredited.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot be credited cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when accountCredited.AccountId = state.Id.Value -&gt; let message = "The account cannot be credited cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when accountCredited.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot be credited cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot be credited cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountDebited accountDebited -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when accountDebited.AccountId = state.Id.Value -&gt; { state with Balance = Some (state.Balance.Value - accountDebited.Amount) Updated = Some accountDebited.Timestamp } | AccountStatus.Opened when accountDebited.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot be debited cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when accountDebited.AccountId = state.Id.Value -&gt; let message = "The account cannot be debited cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when accountDebited.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot be debited cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot be debited cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | AddressChangeRequested addressChangeRequested -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when addressChangeRequested.AccountId = state.Id.Value -&gt; { state with NewAddressRequested = Some addressChangeRequested.NewAddress Updated = Some addressChangeRequested.Timestamp } | AccountStatus.Opened when addressChangeRequested.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot receive an address change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when addressChangeRequested.AccountId = state.Id.Value -&gt; let message = "The account cannot receive an address change request cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when addressChangeRequested.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot receive an address change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot receive an address change cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | PhoneNumberChangeRequested phoneNumberChangeRequested -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when phoneNumberChangeRequested.AccountId = state.Id.Value -&gt; { state with NewPhoneNumberRequested = Some phoneNumberChangeRequested.NewPhoneNumber Updated = Some phoneNumberChangeRequested.Timestamp } | AccountStatus.Opened when phoneNumberChangeRequested.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot receive a phone number change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when phoneNumberChangeRequested.AccountId = state.Id.Value -&gt; let message = "The account cannot receive a phone number change request cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when addressChangeRequested.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot receive a phone number change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot receive a phone number change cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | EmailChangeRequested emailChangeRequested -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when emailChangeRequested.AccountId = state.Id.Value -&gt; { state with NewEmailRequested = Some emailChangeRequested.NewEmail Updated = Some emailChangeRequested.Timestamp } | AccountStatus.Opened when emailChangeRequested.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot receive an email change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when emailChangeRequested.AccountId = state.Id.Value -&gt; let message = "The account cannot receive an email change request cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when emailChangeRequested.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot receive an email change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot receive an email change request cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | AddressChangeValidated addressChangeValidated -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when addressChangeValidated.AccountId = state.Id.Value &amp;&amp; addressChangeValidated.NewAddress = state.NewAddressRequested.Value -&gt; let contact = { state.Contact.Value with Address = state.NewAddressRequested.Value } { state with Contact = Some contact Updated = Some addressChangeValidated.Timestamp NewAddressRequested = None } | AccountStatus.Opened when addressChangeValidated.AccountId = state.Id.Value &amp;&amp; addressChangeValidated.NewAddress &lt;&gt; state.NewAddressRequested.Value -&gt; let message = "The account cannot validate an address change request cause the request was made for a different address." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Opened when addressChangeValidated.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot validate an address change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when addressChangeValidated.AccountId = state.Id.Value -&gt; let message = "The account cannot validate an address change request cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when addressChangeValidated.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot validate an address change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot validate an address change cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | PhoneNumberChangeValidated phoneNumberChangeValidated -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when phoneNumberChangeValidated.AccountId = state.Id.Value &amp;&amp; phoneNumberChangeValidated.NewPhoneNumber = state.NewPhoneNumberRequested.Value -&gt; let contact = { state.Contact.Value with PhoneNumber = state.NewPhoneNumberRequested.Value } { state with Contact = Some contact Updated = Some phoneNumberChangeValidated.Timestamp NewPhoneNumberRequested = None } | AccountStatus.Opened when phoneNumberChangeValidated.AccountId = state.Id.Value &amp;&amp; phoneNumberChangeValidated.NewPhoneNumber &lt;&gt; state.NewPhoneNumberRequested.Value -&gt; let message = "The account cannot validate a phone number change request cause the request was made for a different phone number." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Opened when phoneNumberChangeValidated.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot validate a phone number change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when phoneNumberChangeValidated.AccountId = state.Id.Value -&gt; let message = "The account cannot validate a phone number change request cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when phoneNumberChangeValidated.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot validate a phone number change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot validate a phone number change cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | EmailChangeValidated emailChangeValidated -&gt; match state.Status with | Some status -&gt; match status with | AccountStatus.Opened when emailChangeValidated.AccountId = state.Id.Value &amp;&amp; emailChangeValidated.NewEmail = state.NewEmailRequested.Value -&gt; let contact = { state.Contact.Value with PhoneNumber = state.NewPhoneNumberRequested.Value } { state with Contact = Some contact Updated = Some emailChangeValidated.Timestamp NewEmailRequested = None } | AccountStatus.Opened when emailChangeValidated.AccountId = state.Id.Value &amp;&amp; emailChangeValidated.NewEmail &lt;&gt; state.NewEmailRequested.Value -&gt; let message = "The account cannot validate an email change request cause the request was made for a different phone number." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Opened when emailChangeValidated.AccountId &lt;&gt; state.Id.Value -&gt; let message = "The account cannot validate an email change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | AccountStatus.Closed when emailChangeValidated.AccountId = state.Id.Value -&gt; let message = "The account cannot validate an email change request cause it is closed." { state with AuditInvalidations = message :: state.AuditInvalidations } // | AccountStatus.Closed when emailChangeValidated.AccountId &lt;&gt; state.Id.Value -&gt; | _ -&gt; let message = "The account cannot validate an email change request cause the account id does not match this account." { state with AuditInvalidations = message :: state.AuditInvalidations } | None -&gt; let message = "The account cannot validate a phone number change cause it is not yet created." { state with AuditInvalidations = message :: state.AuditInvalidations } | InvalidOperationAttempted invalidOperationAttempted -&gt; { state with AuditInvalidations = invalidOperationAttempted.Error :: state.AuditInvalidations Updated = Some invalidOperationAttempted.Timestamp } </code></pre> <p>I found my implementations being a wee bit redundant about the points below:</p> <ul> <li>the <code>option</code> check (ie. <code>Some</code> / <code>None</code>) not sure how it can be avoided or refactored to make the pattern matching "lighter"</li> <li>the <code>Id</code> check for the same reasons</li> </ul> <p>I am not too sure how can this be changed and have something more readable.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:14:54.583", "Id": "429666", "Score": "0", "body": "@dfhwze I think so, why?" } ]
[ { "body": "<p>I think, I would change <code>AccountState</code> to the following:</p>\n\n<pre><code>type AccountStatus =\n | Uninitialized\n | Opened\n | Closed\n</code></pre>\n\n<p>In this way you have the full life cycle of an account and you then can avoid <code>Some/None</code> for the account status</p>\n\n<hr>\n\n<p>The <code>AccountState</code> could then be changed to:</p>\n\n<pre><code>type AccountState = {\n Id: Guid\n Status: AccountStatus\n AuditInvalidations: string list\n Contact: Contact\n Balance: decimal\n Created: DateTimeOffset option\n Updated: DateTimeOffset option\n NewAddressRequested: Address option\n NewPhoneNumberRequested: PhoneNumber option\n NewEmailRequested: string option\n }\n</code></pre>\n\n<p>Where <code>option</code> is removed from fields that IMO shouldn't be optional: An Account without an <code>Id</code> or a <code>Contact</code> seems rather scary to me and the <code>Balance</code> has always a value (that may be <code>0.0m</code>), and with the <code>AccountStatus.Uninitialized</code>, <code>Status</code> can also always have a value.</p>\n\n<hr>\n\n<p>In <code>updateAccountState</code> you can consider to evaluate the <code>Id</code> at the first match level in order to get rid of repetitive checks of it. Below is the first two matches as examples:</p>\n\n<pre><code>let updateAccountState (state : AccountState) (event : Event)=\n match event with\n | AccountOpened account -&gt;\n match account.AccountId with\n | id when id = state.Id -&gt;\n match state.Status with\n | AccountStatus.Opened -&gt;\n let message = \"The account cannot be opened cause it is already opened.\"\n { state with AuditInvalidations = message :: state.AuditInvalidations }\n | AccountStatus.Closed -&gt;\n let message = \"The account cannot be opened cause it is closed.\"\n { state with AuditInvalidations = message :: state.AuditInvalidations }\n | AccountStatus.Uninitialized -&gt;\n { state with\n Contact = account.Contact\n Status = AccountStatus.Opened\n Balance = 0m\n Created = Some account.Timestamp\n Updated = Some account.Timestamp\n Id = account.AccountId\n }\n | _ -&gt; \n let message = \"The account cannot be opened cause the account id does not match this account.\"\n { state with AuditInvalidations = message :: state.AuditInvalidations }\n | AccountClosed account -&gt;\n match account.AccountId with\n | id when id = state.Id -&gt;\n match state.Status with\n | AccountStatus.Opened -&gt;\n { state with\n Status = AccountStatus.Closed\n Updated = Some account.Timestamp\n }\n | AccountStatus.Closed -&gt;\n let message = \"The account cannot be closed cause it is already closed.\"\n { state with AuditInvalidations = message :: state.AuditInvalidations }\n | AccountStatus.Uninitialized -&gt;\n let message = \"The account cannot be closed cause it is not yet created.\"\n { state with AuditInvalidations = message :: state.AuditInvalidations }\n | _ -&gt;\n let message = \"The account cannot be closed cause the account id does not match this account.\"\n { state with AuditInvalidations = message :: state.AuditInvalidations }\n</code></pre>\n\n<p>This is IMO more clear and easy to follow.</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>All your <code>AccountXXXEvent</code> events have <code>AccountId</code> and <code>Timestamp</code> in common, so these properties could be placed on <code>Event</code> and then <code>AccountXXXEvent</code> could be discriminated unions as well:</p>\n\n<pre><code>type AccountEvent =\n | AccountOpenedEvent of Contact: Contact\n | AccountClosedEvent of Reason: string\n | AccountCreditEvent of Amount:decimal * Description:string\n | etc...\n</code></pre>\n\n<p><code>Event</code> could then look like:</p>\n\n<pre><code>type Event = Event of Id:Guid * Timestamp:DateTimeOffset * AccountEvent:AccountEvent\n</code></pre>\n\n<p>and finally <code>updateAccountState</code> as:</p>\n\n<pre><code>let updateAccountState (state : AccountState) (event : Event) =\n match event with\n | Event(id, timestamp, accountEvent) -&gt;\n match id with\n | stateId when stateId = state.Id -&gt;\n match accountEvent with\n | AccountOpenedEvent contact -&gt;\n match state.Status with\n | AccountStatus.Opened -&gt; invalidate state \"The account cannot be opened cause it is already opened.\"\n | AccountStatus.Closed -&gt; invalidate state \"The account cannot be opened cause it is closed.\"\n | AccountStatus.Uninitialized -&gt;\n { state with\n Contact = contact\n Status = AccountStatus.Opened\n Balance = 0m\n Created = Some timestamp\n Updated = Some timestamp\n Id = id\n }\n | AccountClosedEvent reason -&gt; \n match state.Status with\n | AccountStatus.Opened -&gt;\n { state with\n Status = AccountStatus.Closed\n Updated = Some timestamp\n }\n | AccountStatus.Closed -&gt; invalidate state \"The account cannot be closed cause it is already closed.\"\n | AccountStatus.Uninitialized -&gt; invalidate state \"The account cannot be closed cause it is not yet created.\"\n | // TODO all the other events\n | _ -&gt; \n invalidate state \"The transaction can not be fulfilled because the ids don't match.\" \n</code></pre>\n\n<p>where <code>invalidate</code> is defined as:</p>\n\n<pre><code>let invalidate state message = { state with AuditInvalidations = message :: state.AuditInvalidations }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T14:15:14.450", "Id": "429716", "Score": "0", "body": "thanks, interesting suggestions, I am gonna refactor my code" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:06:47.817", "Id": "222080", "ParentId": "222047", "Score": "3" } } ]
{ "AcceptedAnswerId": "222080", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T20:29:34.957", "Id": "222047", "Score": "6", "Tags": [ "f#", "state-machine" ], "Title": "F# pattern matching to determine the state of a bank account based on past events" }
222047
<p>Here is my coded solution for the N-queens challenge</p> <blockquote> <p>The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.</p> </blockquote> <p>The program outputs all valid chess boards, where the queen is represented by the digit 2. </p> <p>Are there any improvements that can be made to my code?</p> <p>One of the main things I want to improve is the <code>counter</code>. I have to make the variable <code>global</code> because I can't work out any other way to do it.</p> <pre><code>"""Find all possible chess-board combinations of size n*n with n queens, where queens are represented by the digit 2""" from collections import Counter import numpy as np def block_positions(chess_board, row, column, limit): """Fills all squares that can no longer contain a queen with the value -1 There are a maximum of 8 directions that must be blocked from a given square""" # Block left for col in range(column - 1, -1, -1): chess_board[row, col] = 0 # Block right for col in range(column + 1, limit): chess_board[row, col] = 0 # Block up for rw in range(row - 1, -1, -1): chess_board[rw, column] = 0 # Block down for rw in range(row + 1, limit): chess_board[rw, column] = 0 # Block L up-diag rw = row col = column while rw &gt; 0 and col &gt; 0: rw -= 1 col -= 1 chess_board[rw, col] = 0 # Block L down-diag rw = row col = column while rw &lt; limit - 1 and col &gt; 0: rw += 1 col -= 1 chess_board[rw, col] = 0 # Block R up-diag rw = row col = column while rw &gt; 0 and col &lt; limit - 1: rw -= 1 col += 1 chess_board[rw, col] = 0 # Block R down-diag rw = row col = column while rw &lt; limit - 1 and col &lt; limit - 1: rw += 1 col += 1 chess_board[rw, col] = 0 return chess_board def initialise_board(num): """Build the empty board""" board = np.ones(num * num).reshape(num, num) return board def valid_boards(board, row, num): """Find all valid N-queen boards""" global counter while row &lt; num: indices = [index for index in range(num) if board[row, index] == 1] if indices == []: return False for index in indices: old_board = board.copy() board[row, index] = 2 board = block_positions(board, row, index, num) is_possible = valid_boards(board, row + 1, num) board = old_board if not is_possible and index == indices[-1]: return False flattened = Counter(board.flatten()) if flattened[2] == num: print(board) print() counter += 1 if __name__ == "__main__": counter = 0 num = 5 board = initialise_board(num) valid_boards(board, row=0, num=num) print(counter, "solutions") print("Finished") </code></pre>
[]
[ { "body": "<blockquote>\n <p><em>One of the main things I want to improve is the <code>counter</code>. I have to\n make the variable global because I can't work out any other way to do\n it.</em></p>\n</blockquote>\n\n<p>You could declare a global variable, and then increment on it, but that clutters the module namespace. So the idiomatic workaround to avoid declaring a global variable is to point to a mutable object that contains the integer on which you wish to increment so that you're not attempting to reassign the variable name -</p>\n\n<pre><code>def valid_boards(board, row, num):\n #rest of the code\n counter[0] += 1\n\nif __name__ == \"__main__\":\n counter = [0]\n num = 5\n board = initialise_board(num)\n valid_boards(board, row = 0, num = num)\n print(counter[0], \"solutions\")\n print(\"Finished\")\n</code></pre>\n\n<p><strong>OR</strong></p>\n\n<p>Use an attribute on the function. Set a counter attribute on your function manually after creating it -</p>\n\n<pre><code>def valid_boards(board, row, num):\n #rest of the code\n valid_boards.counter += 1\n\nif __name__ == \"__main__\":\n valid_boards.counter = 0\n num = 5\n board = initialise_board(num)\n valid_boards(board, row = 0, num = num)\n print(valid_boards.counter, \"solutions\")\n print(\"Finished\")\n</code></pre>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T17:57:39.347", "Id": "429742", "Score": "1", "body": "Perfect. Thank you for your help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T17:59:18.633", "Id": "429743", "Score": "0", "body": "@EML - Glad to help you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:51:28.833", "Id": "429779", "Score": "0", "body": "using a mutable argument in the global scope to my opinion is even worse than using `global`. at least that makes it clear you're dealing with global scope" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T17:46:48.717", "Id": "222098", "ParentId": "222048", "Score": "0" } }, { "body": "<h1>Separate generation and presentation</h1>\n\n<p><code>valid_boards</code> both generates the solutions, prints and counts them. Better would be to have 1 method to generate the solutions, another to present the result. The simplest way to do this is to make a generator that <code>yield</code>s the solutions, and another method that prints and counts them</p>\n\n<h1><code>reversed</code></h1>\n\n<p><code>reversed(range(row))</code> is a lot more clear than <code>range(row - 1, -1, -1)</code></p>\n\n<h1>magical values</h1>\n\n<p>you use 0 for blocked, 1 for free and 2 for an occupied tile. defining these as global constants would be a lot clearer</p>\n\n<pre><code>BLOCKED = 0\nFREE = 1\nOCCUPIED = 2\n</code></pre>\n\n<p>and then use if for example</p>\n\n<pre><code>chess_board[row, col] = BLOCKED\n</code></pre>\n\n<h1>board size</h1>\n\n<p>You use <code>num</code> and <code>limit</code> for the same value, the size of the board. Lat's just call this <code>boardsize</code></p>\n\n<h1>DRY</h1>\n\n<p>In <code>block_positions</code> you do a lot of repetition for the different directions to block. More clear would be to use a generator that <code>yield</code>s all the neighbour of a tile, and use the coordinates yielded to block those</p>\n\n<p>To do this you need a method to check whether a coordinate is valid:</p>\n\n<pre><code>def valid_coord(coordinate, boardsize=5):\n row, column = coordinate\n return 0 &lt;= row &lt; boardsize and 0 &lt;= column &lt; boardsize\n</code></pre>\n\n<p>then using <code>itertools.takewhile</code>, <code>functools.partial</code> and <code>itertools.count</code></p>\n\n<pre><code>def neighbours(row, column, boardsize):\n validator = partial(valid_coord, boardsize=boardsize)\n yield from ((row, i) for i in range(0, column))\n yield from ((row, i) for i in range(column + 1, boardsize))\n yield from ((i, column) for i in range(0, row))\n yield from ((i, column) for i in range(row + 1, boardsize))\n yield from takewhile(validator, ((row - i, column - i) for i in count(1)))\n yield from takewhile(validator, ((row + i, column + i) for i in count(1)))\n yield from takewhile(validator, ((row - i, column + i) for i in count(1)))\n yield from takewhile(validator, ((row + i, column - i) for i in count(1)))\n</code></pre>\n\n<blockquote>\n<pre><code>list(neighbours(2, 3, boardsize=5))\n</code></pre>\n</blockquote>\n\n<pre><code>[(2, 0), (2, 1), (2, 2), (2, 4), (0, 3), (1, 3), (3, 3), (4, 3), (1, 2), (0, 1), (3, 4), (1, 4), (3, 2), (4, 1)]\n</code></pre>\n\n<p>Then the <code>block_positions</code> suddenly becomes very simple</p>\n\n<pre><code>def block_positions(chess_board, row, column, boardsize):\n \"\"\"Fills all squares that can no longer contain a queen with the value -1\n There are a maximum of 8 directions that must be blocked from a given square\"\"\"\n for x, y in neighbours(row, column, boardsize):\n chess_board[x, y] = BLOCKED\n</code></pre>\n\n<p>This method doesn't need to return the board. The standard library's convention is that if a method changes the object, it doesn't return something. If it returns a new object, that is returned.</p>\n\n<p>By just changing the <code>neighbours</code>, you can easily change this to find the solutions for [related puzzles(<a href=\"https://en.wikipedia.org/wiki/Eight_queens_puzzle#Related_problems\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Eight_queens_puzzle#Related_problems</a>)</p>\n\n<h1><code>numpy</code></h1>\n\n<p>You hardly use any of the numpy strengts, but even then this can be simpler\nYou can pass a tuple to <code>np.one</code>, so <code>initialise_board</code> can be as simple as</p>\n\n<pre><code>def initialise_board(num):\n \"\"\"Build the empty board\"\"\"\n return np.ones((num, num)) * FREE\n</code></pre>\n\n<p>Counting the number of places queens can be simpler too: <code>(board == OCCUPIED).sum() == num</code> instead of <code>np.flatten</code> and <code>Counter</code></p>\n\n<h1>generator</h1>\n\n<p>Now the <code>valid_boards</code> method both generates the solutions, prints them and augments the counter. Simpler would be to have them just generate the solutions, and have something else take care of the printing and counting.</p>\n\n<p>Slightly adapting your algorithm to a generator approach:</p>\n\n<pre><code>def add_queen(board, row, boardsize):\n if row == boardsize:\n yield board\n return\n free_columns = (index for index in range(boardsize) if board[row, index] == FREE)\n for column in free_columns:\n new_board = board.copy()\n new_board[row, column] = OCCUPIED\n block_positions(new_board, row, column, boardsize)\n yield from add_queen(new_board, row + 1, boardsize)\n</code></pre>\n\n<p>and call it like this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n boardsize = 5\n board = initialise_board(boardsize)\n for solution_count, solution in enumerate(\n add_queen(board, row=0, boardsize=boardsize), 1\n ):\n print(solution)\n print()\n print(f\"{solution_count} solutions\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:58:05.463", "Id": "429785", "Score": "0", "body": "Wow. Thanks for such an amazing reply!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T23:09:06.733", "Id": "429787", "Score": "0", "body": "I assume by ```itertools.partial``` you mean ```functools.partial```? I can' find ```collections.count``` only ```collections.counter```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T23:39:27.527", "Id": "429790", "Score": "0", "body": "It seems the ```for i in count(1)))``` argument in the ```neighbours``` function should be ```for i in range(1, boardsize)))```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T00:02:08.283", "Id": "429794", "Score": "0", "body": "Ahh. It is the ```itertools.count``` not ```collections.count```. Solved it. Thanks :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T04:31:27.980", "Id": "429807", "Score": "0", "body": "You are correct. Silly mistakes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T08:56:05.947", "Id": "431167", "Score": "0", "body": "Can the one downvoting please explain what is wrong here?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:49:15.307", "Id": "222112", "ParentId": "222048", "Score": "1" } }, { "body": "<h3>Get classy</h3>\n\n<p>In the generation process, you have three things to keep track of: the size of the board, the location of the queens, and the blocked/unblocked status of the individual cells.</p>\n\n<p>This is two things too many.</p>\n\n<p>When you're managing multiple data items, trying to keep them all in sync with each other, that's an indicator you need a class or a separate module. I'll suggest you maintain all this data in a class.</p>\n\n<h3>Make it snappy</h3>\n\n<p>Next, I'll suggest that you reconsider your storage. Python has a good mechanism for smoothly and transparently scaling the size of integer values. I suggest that you can manage your arrays and positions as integer bitmasks.</p>\n\n<p>How would this work?</p>\n\n<p>First, use generator functions to iterate over everything. Only at dire need will you convert from a bitmask to a position tuple.</p>\n\n<p>Thus, write code that just \"assumes\" you have whatever it is you want:</p>\n\n<pre><code>for q in board.available_queen_positions():\n new_board = board.with_queen(q)\n</code></pre>\n\n<p>What is the type of <code>q</code>? I don't know! What is the type of <code>new_board</code>? Presumably the same type as <code>board</code>, but ... I don't know! Maybe it's <code>class Board</code>?</p>\n\n<p>With that approach in mind, now you can make things fast. Let's imaging a 5x5 board. That's 25 cells, which means a 25-bit number. Should be no problem, right? Assume you'll always use the least-significant bits, so <code>1 &lt;&lt; 24 ... 1 &lt;&lt; 0</code> in this case. How you map them is up to you, but I'll suggest <code>1 &lt;&lt; (row * 5 + col)</code>. Similarly for unmapping them: <code>row, col = divmod(log2(position), 5)</code></p>\n\n<p>So a <code>Position(4, 1)</code> would be expressed as <code>1 &lt;&lt; 21</code>. </p>\n\n<p>What does that give you? Well, integers are hashable. So you can perform bitops with them, and lookups in a dict with them. </p>\n\n<p>Iterate over all the available queen positions:</p>\n\n<pre><code>class Board:\n def available_queen_positions(self):\n pos = self.max_pos # Computed at __init__\n\n while True:\n if not (pos &amp; self.blocked):\n yield pos\n if pos == 0:\n break\n pos &gt;&gt;= 1\n\n def cells_blocked_by_pos(self, pos):\n if pos in self.cell_block_cache:\n return self.cell_block_cache[pos]\n\n # Dicts created at __init__, or make them functions?\n blocks = (self.row_blocks[pos] \n | self.col_blocks[pos]\n | self.right_diag_blocks[pos] \n | self.left_diag_blocks[pos])\n self.cell_block_cache[pos] = blocks\n return blocks\n</code></pre>\n\n<p>You might find that storing positions as integers (such that 4,1 -> 21) is faster than as a bitmask -- that deserves a little timing research. But I expect you'll find that using bitwise operations to perform your blocking will speed things up considerably, and enable you to run with larger board sizes.</p>\n\n<h3>Optimize</h3>\n\n<p>It's important that you perform timing tests before you start chasing performance. Use timeit, or just print the time before and after your runs - whatever seems appropriate to you. This way you'll be able to avoid going down a non-productive branch. (And the branches which are non-productive will surprise you!)</p>\n\n<p>With that said, one \"algorithmic\" optimization springs to mind: symmetry. If a particular configuration of queens is valid, then performing various rotations and reflections of that board configuration should also be valid. You should be able to reduce the number of configurations that you check, because of this- you know that if board <code>A</code> is valid then automatically you know that <code>rot90(A)</code> and <code>rot180(A)</code> and <code>rot270(A)</code> are also valid, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T00:21:50.857", "Id": "222124", "ParentId": "222048", "Score": "1" } } ]
{ "AcceptedAnswerId": "222098", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T21:36:09.067", "Id": "222048", "Score": "5", "Tags": [ "python", "programming-challenge", "numpy", "n-queens" ], "Title": "Python solution for the N-Queens challenge" }
222048
<p>I need to create a <strong>circle</strong> with numbers from <strong>1 to n</strong> , however it is necessary to respect some rules:</p> <blockquote> <ol> <li>All numbers from 1 to n are used in the circle only once.</li> <li>The sum of two consecutive numbers is a prime number</li> <li>The sum of a number with what is diametrically opposite it is also a prime number</li> </ol> </blockquote> <p>So I need to create an algorithm that receives an integer n and determines whether there is a circle of size n, <strong>if it exists</strong>.</p> <p>For example:</p> <p><a href="https://i.stack.imgur.com/nTmGN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nTmGN.png" alt="enter image description here"></a></p> <p>Program response: <strong>1 6 7 16 15 8 5 12 11 18 13 10 3 4 9 14 17 2</strong></p> <p>I managed to get the expected result, but I do not know if I made the faster way, or if there is something badly written.</p> <pre class="lang-java prettyprint-override"><code>import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Vector; import javax.swing.JOptionPane; public class QuintoDesafio { private static int j; private static int k; private static Vector primes = new Vector(); public static void main(String[] args) { long start = System.currentTimeMillis(); ArrayList list = new ArrayList(); primes.add( new Integer( 2 ) ); primes.add( new Integer( 3 ) ); primes.add( new Integer( 5 ) ); primes.add( new Integer( 7 ) ); primes.add( new Integer( 11 ) ); primes.add( new Integer( 13 ) ); primes.add( new Integer( 17 ) ); primes.add( new Integer( 19 ) ); primes.add( new Integer( 23 ) ); primes.add( new Integer( 31 ) ); primes.add( new Integer( 37 ) ); primes.add( new Integer( 41 ) ); String n = JOptionPane.showInputDialog( "Input n (even) "); int ene = Integer.parseInt( n ); for ( int i=1; i &lt;= ene; i++ ) { list.add( new Integer(i) ); } exchange(list, 0); long end = System.currentTimeMillis(); System.out.println(new SimpleDateFormat("ss.SSS").format(new Date(end - start))); } static void exchange(ArrayList arr, int k){ boolean passed = true; for(int i = k; i &lt; arr.size(); i++){ java.util.Collections.swap(arr, i, k); exchange(arr, k+1); java.util.Collections.swap(arr, k, i); } if (k == arr.size() -1){ int half = arr.size()/2; for ( int j=0; j&lt;arr.size(); j++ ) { int one = (int) arr.get(j); int two; if ( j+1 == arr.size() ) { two = (int) arr.get(0); } else { two = (int) arr.get(j+1); } Integer number_test = new Integer( one+two ); if ( !primes.contains( number_test )) { passed = false; } } for ( int j=0; j&lt;half; j++ ) { int one = (int) arr.get(j); int two = (int) arr.get(j+half); Integer number_test = new Integer( one+two ); if ( !primes.contains( number_test )) { passed = false; } } if ( passed ) { System.out.println(java.util.Arrays.toString(arr.toArray())); } } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T22:31:56.590", "Id": "429644", "Score": "0", "body": "What geito means?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T22:39:20.510", "Id": "429646", "Score": "0", "body": "For me it looks like you are brute forcing meaning iterating all possible lists and checking whether they fit your conditions. It is slowest way to solve any problem. I don't know solution, but you could be looking in dynamic programming where you create sets of pairs and then try to combine them or graph search algorithms, where you find a path of numbers with fit conditions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T23:36:41.293", "Id": "429656", "Score": "2", "body": "By the way I get a lexicographically earlier result `[1, 2, 5, 8, 9, 10, 7, 6, 11, 12, 17, 14, 15, 4, 3, 16, 13, 18]`, perhaps because you are missing the prime 29" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:40:13.090", "Id": "429668", "Score": "1", "body": "An observation about the problem rather than your solution. There can be no such circle if n is a multiple of 4. This is because opposite numbers would be both even or both odd. Such quick tests are often worth putting in before trying to exhaust possibilities expensively." } ]
[ { "body": "<p>First, <code>Vector</code> shouldn't be used here. It's essentially a synchronized <code>ArrayList</code>, and you don't need any synchronization in this case. Just change it to an <code>ArrayList</code>.</p>\n\n<p>This has the potential to be a little faster.</p>\n\n<hr>\n\n<p>Second, you're using a raw <code>ArrayList</code> which isn't typesafe:</p>\n\n<pre><code>list.add(\"Some nonsense\"); // Doesn't cause an error\n</code></pre>\n\n<p>and is necessitating your <code>(int)</code> type-casts later on. Specify that the list is holding integers using <a href=\"https://en.wikipedia.org/wiki/Generics_in_Java#Motivation\" rel=\"noreferrer\">generics</a>, and it will be typesafe. Read the <code>&lt; &gt;</code> as \"of\" here:</p>\n\n<pre><code>// Note how we specify what the list can hold\n// An ArrayList of Integers\nArrayList&lt;Integer&gt; list = new ArrayList&lt;&gt;();\n\nlist.add(\"Some nonsense\") // This causes an error now at compile time\n</code></pre>\n\n<hr>\n\n<p>You're also doing odd stuff with the <code>Integer</code> constructor. You don't need to manually cast unboxed integers like <code>Integer(2)</code>. <code>2</code> will be \"auto-boxed\" into its object wrapper as necessary implicitly.</p>\n\n<hr>\n\n<p>You're calling <code>Integer/parseInt</code> outside of a <code>try</code>; which is risky. If the user enters bad input, your whole program with crash. Wrap it up and handle failure (yes, users will enter bad input):</p>\n\n<pre><code>try {\n int ene = Integer.parseInt(n);\n // Code using \"ene\"\n\n} catch (NumberFormatException e) {\n // Just an example. You'll need to do something more involved, like re-asking for input\n System.out.println(\"Parse failed\");\n}\n</code></pre>\n\n<hr>\n\n<p>Just as an example of what I mentioned earlier:</p>\n\n<pre><code>static void exchange(ArrayList arr, int k){\n ...\n int one = (int) arr.get(j);\n int two = (int) arr.get(j + half);\n Integer number_test = new Integer(one + two);\n</code></pre>\n\n<p>Make the parameter generic, and do away with the casts and boxing. Just write:</p>\n\n<pre><code>static void exchange(ArrayList&lt;Integer&gt; arr, int k){\n ...\n int one = arr.get(j);\n int two = arr.get(j + half);\n int number_test = one + two;\n</code></pre>\n\n<p>And then similarly below that.</p>\n\n<hr>\n\n<p>Also, Java prefers camelCase, not snake_case. It's best to stick to the conventions of the language you're using.</p>\n\n<hr>\n\n<pre><code>import java.sql.Date;\n</code></pre>\n\n<p>is a little worrying. You shouldn't really be raiding a SQL library just to make use of some date object. Java has a <a href=\"https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html\" rel=\"noreferrer\"><code>java.time</code> package</a> for this purpose.</p>\n\n<hr>\n\n<p>Just as a tip,</p>\n\n<pre><code>int two;\nif (j + 1 == arr.size()) {\n two = arr.get(0);\n\n} else {\n two = arr.get(j + 1);\n}\n</code></pre>\n\n<p>Can also be written as:</p>\n\n<pre><code>int two = j + 1 == arr.size() ? arr.get(0) : arr.get(j + 1);\n</code></pre>\n\n<p>or, alternatively:</p>\n\n<pre><code>int two = arr.get(j + 1 == arr.size() ? 0 : j + 1);\n</code></pre>\n\n<p>Depending on how much duplication you can tolerate. The <code>? :</code> part is known as the \"ternary operator\"/a \"conditional expression\".</p>\n\n<hr>\n\n<pre><code>if (!primes.contains(number_test)) {\n</code></pre>\n\n<p>This is quite expensive when done on a <code>List</code> like an <code>ArrayList</code>. If you need to use <code>contains</code>, you should <em>probably</em> be using a <code>Set</code> like a <code>HashSet</code>. Membership lookups are <em>much</em> faster using sets. The time difference will become increasingly noticeable as <code>primes</code> grows.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T16:01:52.423", "Id": "429730", "Score": "0", "body": "`int two = arr.get(j + 1 == arr.size() ? 0 : j + 1);` is complex enough that I'd probably break that up into `int wrapped_idx = (j + 1 == arr.size()) ? 0 : j + 1;` and `int two = arr.get(wrapped_idx);`. Or peel that last iteration so I don't need a hand-rolled modulo inside the loop. Or walk 2 pointers / indices, like `j2 = j1; j1++;` So you can start with `j2=arr.size()-1;` and `j1=0;` and don't need to do any wrap-checking inside the loop but also don't need to manually peel an iteration of the loop body." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T22:46:11.803", "Id": "222052", "ParentId": "222050", "Score": "8" } }, { "body": "<p>Your algorithm, if I understand it correctly, is to recursively enumerate all permutations and then check every one of them until a solution is found. There is a very simple improvement to that which can skip huge chunks of the search space: try to detect violations of the constraints as early as possible.</p>\n\n<p>For example, if the current permutation starts with \"1, 3, ..\" and we are in the process of calling <code>exchange</code> recursively to create the \"tails\" of these permutations, then all work done by these recursive calls will ultimately be useless. At this point it is unavoidable that the \"1, 3\" pair will violate the second constraint no matter what the rest of the permutation will be. If this situation was detected, we could return straight away and continue with \"1, 4, ..\". It should be possible to adapt your current check to work on a partial configuration, and use it to prune in this way.</p>\n\n<p>To give a sense of the impact, with this pruning and nothing especially clever, my code takes 0.06s on ideone for that circle of 18 elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T23:06:09.947", "Id": "222054", "ParentId": "222050", "Score": "6" } } ]
{ "AcceptedAnswerId": "222052", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T22:21:20.817", "Id": "222050", "Score": "7", "Tags": [ "java", "performance", "algorithm", "programming-challenge", "primes" ], "Title": "Arranging numbers in a circle such that the sums of neighbors and sums of diametric opposites are prime" }
222050
<p>I have this question asked as home assignment for an interview. I submitted my solution and did not get selected. Wanted to know your feedback for the solution.</p> <blockquote> <h1>Question:</h1> <p>Write a very simple event bus system in C++. You can use whatever version you are comfortable with.</p> <p>For this system to operate you will need two functions. (How they are grouped etc is a challenge left up to you)</p> <ul> <li><p>A function that can take an event name. For example "email" and a function that can be executed later.</p></li> <li><p>A function that can trigger any stored events. For example when we trigger the "email" event any stored events where we called the above adding function would be invoked. in other words in pseudo code: <code>add("email", executeMe)</code> then <code>invoke("email")</code> I would expect <code>executeMe</code> to be called once. However</p> <p>add("email", executeMe) add("email1", dontExecuteMe) add("email", executeMe) invoke("email")</p></li> </ul> <p>I would expect <code>executeMe</code> to be called twice, while <code>dontExecuteMe</code> shouldn't be called. <code>invoke("email1")</code> would obviously be the inverse. Once you have this working, please extend the system to allow the event functions to take a string argument. For example:</p> <pre><code>add("email", executeMe) invoke("email", "our email to be sent"); </code></pre> <p>When invoke is called executeMe should be called with "our email to be sent" as its argument. As a final stage, please extend the system to allow events to be cancelled. For example:</p> <pre><code>add("email", executeMe) add("email", dontExecuteMe) add("email", dontExecuteMe2) invoke("email", "our email to be sent"); </code></pre> <p>In this example, only <code>executeMe</code> should be run and it should cancel any other events for <code>"email"</code>. All other subscribed events should not be invoked.</p> <p>The existing functionality we have built should still work For example, if <code>executeMe</code> didn't cancel the other events. This would also be a valid use of the same system.</p> <pre><code>add("email", executeMe); add("email", executeMe2); add("email", executeMe3); invoke("email", "our email to be sent") </code></pre> <p>All three functions (<code>executeMe</code>, <code>executeMe2</code>, <code>executeMe3</code>) should still execute. All API design, data structure choices are left up to you. It should be assumed that this system will continue to need to have features added.</p> <h1>Event manager description:</h1> <ol> <li>Use Event class to define events</li> <li>class EventHandler is an abstract class which wraps the handler methods. </li> <li>class ExecuteEventHandler is inherited from EventHandler.</li> <li><p>EventManager brings the Event and EventHandler together and provides following interface method</p> <p>a) Add (locks before adding) with a flag with default param indicating whether the handler should be executed</p> <p>b) Invoke (locks before invoking).</p></li> <li>class Utility added to log. Log method writes to the console.</li> </ol> <h1>Assumption:</h1> <ol> <li>Defined Event and EventHandler as objects instead of string and function pointers respectively.</li> <li>Cleanup only those handlers with execute handler flag disabled.</li> <li>Do nothing if Invoke is called with an unregistered event.</li> </ol> </blockquote> <pre><code>#include &lt;algorithm&gt; #include &lt;mutex&gt; #include &lt;string&gt; #include &lt;unordered_map&gt; #include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; class Utility { public: static void Log(const std::string&amp; message) { std::cout &lt;&lt; message &lt;&lt; std::endl; } }; class Event { std::string name; public: Event(const std::string&amp; name) :name{ name } { } ~Event() { } const std::string&amp; GetName() const { return name; } bool operator==(const Event &amp; ev) { return this-&gt;name == ev.name; } }; class EventHandler { public: EventHandler() {}; virtual ~EventHandler() {}; virtual void Execute() = 0; virtual void Execute(const std::string&amp; str) = 0; }; class ExecuteEventHandler : public EventHandler { public: ExecuteEventHandler() : EventHandler() { } ~ExecuteEventHandler() { } void Execute() { std::string msg = "ExecuteEventHandler::execute called"; Utility::Log(msg); } void Execute(const std::string&amp; str) { if (str.size() == 0) Execute(); else { std::string msg = "ExecuteEventHandler::execute called with argument: " + str; Utility::Log(msg); } } }; std::mutex gMu; class EventManager { std::unordered_map&lt;Event*, std::vector&lt;std::pair&lt;EventHandler*, bool&gt;&gt;&gt; eventAndHandler; void Remove(EventHandler* eh) {}; public: EventManager() { } ~EventManager() { } //Adds an Event with its corresponding EventHandler //bool execute indicates whether the handler should be executed //If the event exists just adds the EventHandler //Else creates a new entry void Add(Event* ev, EventHandler* eh, bool execute=true) { std::lock_guard&lt;std::mutex&gt; lock(gMu); //auto it = find_if(eventAndHandler.begin(), eventAndHandler.end(), [&amp;](auto&amp; e) //{ // return e.first.Name == ev.Name; //}); auto it = eventAndHandler.begin(); for (; it != eventAndHandler.end(); ++it) { if (*it-&gt;first == *ev) break; } std::string msg; if (it != eventAndHandler.end()) { it-&gt;second.push_back(std::make_pair(eh, execute)); msg = "Adding an EventHandler to an existing event [" + it-&gt;first-&gt;GetName() + "]"; } else { eventAndHandler[ev].push_back(std::make_pair(eh, execute)); msg = "Adding a new event [" + ev-&gt;GetName() + "] with its EventHandler"; } Utility::Log(msg); } //Invokes the EventHandlers for the given Event. //If the Event is not registered, does notthing //Also removes EventHanlders with disabled execution void Invoke(Event* ev, const std::string &amp; arg = "") { std::lock_guard&lt;std::mutex&gt; lock(gMu); auto it = eventAndHandler.begin(); for (; it != eventAndHandler.end(); ++it) { if (it-&gt;first == ev) break; } std::string msg; if (it != eventAndHandler.end()) { msg = "Executing handlers for event [" + it-&gt;first-&gt;GetName() + "]:"; Utility::Log(msg); for (auto iteh = it-&gt;second.begin(); iteh != it-&gt;second.end(); ) { if ((*iteh).second)//check if the handler should be executed :) { (*iteh).first-&gt;Execute(arg); ++iteh; } else { iteh = it-&gt;second.erase(iteh); //Remove the dont execute handlers msg = "Removing a do not execute handler for event [" + it-&gt;first-&gt;GetName() + "]:"; Utility::Log(msg); if (iteh == it-&gt;second.end()) break; } } } else { msg = "Event [" + ev-&gt;GetName() + "] is not registered"; Utility::Log(msg); } } }; int main() { EventManager evMgr; Event evEmail{ "email" }, evEmail2{ "email2" }, evEmail3{ "email3" }; ExecuteEventHandler execute, execute2, execute3, execute4; ExecuteEventHandler dontExecute, dontExecute2; evMgr.Add(&amp;evEmail, &amp;execute); evMgr.Add(&amp;evEmail, &amp;dontExecute, false); //false indicates do not execute the handler evMgr.Add(&amp;evEmail, &amp;dontExecute2, false); evMgr.Add(&amp;evEmail, &amp;execute2); //Invoking email without argument evMgr.Invoke(&amp;evEmail); //Invoking email with argument evMgr.Invoke(&amp;evEmail, "this is email content"); evMgr.Add(&amp;evEmail2, &amp;execute4); evMgr.Add(&amp;evEmail2, &amp;dontExecute2); //Registering dontExecute2 with email2 and it will be executed evMgr.Invoke(&amp;evEmail2); //Invoking not registered event email3 evMgr.Invoke(&amp;evEmail3); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T22:39:19.993", "Id": "429645", "Score": "1", "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." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T22:48:30.887", "Id": "429648", "Score": "3", "body": "Assuming that this is a working solution, please [edit] the code to add the relevant `#include` statements, so that we can run it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T23:43:45.003", "Id": "429657", "Score": "1", "body": "Hi Edward, This post is to request in design / implementation improvements on working code.\n\nHi 200_success, \nAdded the include statements. Please let me know if it compiles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:34:59.027", "Id": "429691", "Score": "0", "body": "Does the c++11 tag here mean that you chose C++11 as your C++ version and improvements in future versions don't matter for the review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:03:07.463", "Id": "429721", "Score": "0", "body": "Yes, improvements in higher versions definitely matters. Is there a tag for c++11 or higher then I would use that. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T17:01:24.330", "Id": "429738", "Score": "0", "body": "Is the `\"Event manager description:\"` and `\"Assumption:\"` yours or are they part of the question? I ask becuase they add extra things that are not required and the assumptions do not seem to be logical extensions of the original question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T02:20:29.670", "Id": "429800", "Score": "0", "body": "Hi Martin, Yes they are mine. Please list your concerns with them.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T03:05:54.800", "Id": "430081", "Score": "0", "body": "Anyone who can help with this?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T22:34:39.260", "Id": "222051", "Score": "2", "Tags": [ "c++", "c++11", "interview-questions", "event-handling" ], "Title": "Event management system in C++" }
222051
<p>I have been struggling to make typescript happy about the types. I am pulling data from our backend API and I wanted to give context to the data. Basically it is a monad with 4 shapes: </p> <ul> <li>Initial (nothing)</li> <li>Loading (maybe with percent?)</li> <li>Failed (maybe with error?)</li> <li>Loaded(with the actual value).</li> </ul> <p>I want it to have the usual <code>.of()</code>, <code>.map()</code>, <code>.chain()</code> functions that you would expect in a monadic data structure.</p> <p>After trying many different ways (with average success). I came up with this implementation:</p> <pre><code>type Kind = 'initial' | 'loading' | 'loaded' | 'failed' type DefaultError = any export class Data&lt;T, E = DefaultError&gt; { private constructor( public readonly kind: Kind, public readonly data: T | undefined, private readonly error: E | undefined, private readonly percent: number | undefined, ) {} static initial&lt;T, E&gt;() { return new Data&lt;T, E&gt;('initial', undefined, undefined, undefined) } static loading&lt;T, E&gt;(percent?: number) { return new Data&lt;T, E&gt;('loading', undefined, undefined, percent) } static failed&lt;T, E&gt;(error?: E) { return new Data&lt;T, E&gt;('failed', undefined, error, undefined) } static loaded&lt;T, E&gt;(value: T) { return new Data&lt;T, E&gt;('loaded', value, undefined, undefined) } static orInitial&lt;T, E&gt;(value: Data&lt;T, E&gt; | undefined) { if (value === undefined) { return Data.initial&lt;T, E&gt;() } return value } static getData&lt;T, E&gt;(wrapped: Data&lt;T, E&gt;) { return wrapped.data } static getDataOrElse&lt;T, E&gt;(defaultValue: T) { return function(wrapped: Data&lt;T, E&gt;) { return wrapped.kind === 'loaded' ? wrapped.data! : defaultValue } } join() { return this.data! } map&lt;R&gt;(f: (wrapped: T) =&gt; R): Data&lt;R, E&gt; { switch (this.kind) { case 'loaded': return Data.loaded(f(this.data!)) case 'loading': return Data.loading() case 'failed': return Data.failed(this.error) case 'initial': return Data.initial() } } flatMap&lt;R, E&gt;(f: (wrapped: T) =&gt; Data&lt;R, E&gt;): Data&lt;R, E&gt; { switch (this.kind) { case 'loaded': return f(this.data!) case 'loading': return Data.loading&lt;R,E&gt;() case 'failed': return Data.failed&lt;R,E&gt;((this.error as unknown) as E) case 'initial': return Data.initial&lt;R,E&gt;() } } match&lt;O1, O2, O3, O4&gt;({ initial, loaded, loading, failed, }: { initial: () =&gt; O1 loaded: (value?: T) =&gt; O2 loading: (percent?: number) =&gt; O3 failed: (error?: E) =&gt; O4 }) { switch (this.kind) { case 'loaded': return loaded(this.data!) case 'loading': return loading(this.percent) case 'failed': return failed(this.error) case 'initial': return initial() } } static isInitial&lt;T, E&gt;(wrapped: Data&lt;T, E&gt;): wrapped is Data&lt;T, E&gt; &amp; { kind: 'initial' } { return wrapped.kind === 'initial' } static isLoading&lt;T, E&gt;(wrapped: Data&lt;T, E&gt;): wrapped is Data&lt;T, E&gt; &amp; { kind: 'loading'; percent?: number } { return wrapped.kind === 'loading' } static isFailed&lt;T, E&gt;(wrapped: Data&lt;T, E&gt;): wrapped is Data&lt;T, E&gt; &amp; { kind: 'failed'; error?: E } { return wrapped.kind === 'failed' } static isLoaded&lt;T, E&gt;(wrapped: Data&lt;T, E&gt;): wrapped is Data&lt;T, E&gt; &amp; { kind: 'loaded'; data: T } { return wrapped.kind === 'loaded' } isInitial(): this is { kind: 'initial' } { return this.kind === 'initial' } isLoading(): this is { kind: 'loading'; percent?: number } { return this.kind === 'loading' } isFailed(): this is { kind: 'failed'; error?: E } { return this.kind === 'failed' } isLoaded(): this is { kind: 'loaded'; data: T } { return this.kind === 'loaded' } getValueOrElse(defaultValue: T) { return this.kind === 'loaded' ? this.data : defaultValue } getPercentOrElse(defaultPercent: number) { return this.kind === 'loading' ? this.percent : defaultPercent } getErrorOrElse(defaultError: E) { return this.kind === 'failed' ? this.error : defaultError } } </code></pre> <p>I am not too happy with it. Mainly because I have to do <code>null</code> checks on error, value, percent fields. I wanted to have some sort of a tagged union type but I couldn't make it work. Also the <code>isLoaded()</code> type guard doesn't seem to really work when doing something like this:</p> <pre><code>// I cast to make typescript forget about the fact that the data is loaded const data:Data&lt;number&gt; = Data.loaded(3) as any as Data&lt;number&gt; data.data // &lt;-- says number | undefined, but I would really prefer it not even allowing me to access the field if(data.isLoaded()) { data.data // &lt;-- number, so that is correct because it know the data is loaded } const dataArray: Data&lt;number&gt;[] = [Data.failed(), Data.loaded(2)] dataArray.filter(Data.isLoaded) .map(Data.getData) .map(x =&gt; x) // &lt;-- number or undefined, that shouldn't happen dataArray.filter(Data.isLoaded) .map(x =&gt; x.data) .map(x =&gt; x) // &lt;-- number but not undefined? </code></pre> <p>How can I best modify it and have strong typing with it?</p> <p>This is a crucial part in our project because we use it everywhere.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:00:33.533", "Id": "429663", "Score": "0", "body": "Welcome to Code Review! IMHO your question title can and should be improved. Be sure to check [*How do I ask a good question?*](https://codereview.stackexchange.com/help/how-to-ask) and especially *Titling your question* in the Help Center." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T02:51:21.683", "Id": "430986", "Score": "0", "body": "I'm having difficulty understanding, what is the point of the `initial` state? If this is wrapping backend data it seems like it should only ever be loading, loaded, or failed. What does `initial` signify?" } ]
[ { "body": "<p>Since this is Code Review, and not Stack Overflow where you'd just want an answer... first a couple comments on your code:</p>\n\n<ol>\n<li><p>First off, this is not a monad with 4 shapes. This is a monad with 6 shapes. \"maybe with\" indicates you have more than one shape. This is a <em>lot</em> of shapes to keep track of with a single class. The data class is really: <code>Maybe&lt;OneOf&lt;Maybe&lt;Error&gt;, Maybe&lt;Percent&gt;, Data&gt;&gt;</code>... and that's bound to be messy.</p></li>\n<li><p>If you declare the type of the variable, TypeScript will not infer a more specific type. There's no cast needed here.</p>\n\n<pre><code>// I cast to make typescript forget about the fact that the data is loaded\nconst data: Data&lt;number&gt; = Data.loaded(3) as any as Data&lt;number&gt;\n</code></pre></li>\n<li><p>Don't lie to the compiler. The <code>flatMap</code> implementation has:</p>\n\n<pre><code>case 'failed':\n return Data.failed&lt;R, E&gt;((this.error as unknown) as E);\n</code></pre>\n\n<p>This can (and likely will) result in an error which isn't correct. You should either return <code>Data&lt;R, E | E2&gt;</code> or force the callback to return <code>Data&lt;R, E&gt;</code> where <code>E</code> is the same as the container.</p></li>\n<li><p>Does it make sense to have a <code>Data&lt;Data&lt;number, Error&gt;, Error&gt;</code>? I don't think it does... this is the same problem that the authors of the <code>Promise</code> spec had to solve, and they decided to solve it by breaking the monad laws. It may make sense to do the same. <code>Data</code> seems conceptually closer to <code>Promise</code> than <code>Either</code> to me.</p></li>\n<li><p>Since you have the <code>join</code> accessor, I would make <code>data</code> private. You can then use the <code>this</code> parameter to force an error if TS doesn't <em>know</em> that there is data present.</p>\n\n<pre><code>static getData&lt;T, E&gt;(wrapped: Data&lt;T, E&gt; &amp; { kind: \"loaded\", data: T }) {\n return wrapped.join();\n}\n\njoin(this: { data: T }) {\n return this.data;\n}\n</code></pre></li>\n<li><p>I would expect the <code>get*OrElse</code> functions to return <code>NonNullable</code> types. When I call <code>getPercentOrElse(5)</code> I'd expect to receive a number, but I still might get <code>undefined</code>.</p></li>\n<li><p>It might be worth making a <code>const enum DataState { initial, loading, loaded, failed }</code> to avoid typing strings everywhere. As <code>const enum</code>s are inlined by the compiler, there will be no performance loss (and you can still use strings if you like).</p></li>\n</ol>\n\n<hr>\n\n<p>Here's one possible fix for your <code>Data.getData</code> function. I assume you don't want it to work unless you know <code>Data&lt;T, E&gt;</code> is actually <code>loaded</code>, so make that explicit, and your <code>number | undefined</code> issue goes away.</p>\n\n<pre><code>static getData&lt;T, E&gt;(wrapped: Data&lt;T, E&gt; &amp; { kind: \"loaded\", data: T }) {\n wrapped.data;\n}\n</code></pre>\n\n<p>Alternatively, you can use conditional types to optionally include <code>undefined</code> in the return type, but this would be messier.</p>\n\n<hr>\n\n<p>Putting this last as it is more of a frame challenge than a review of your code:</p>\n\n<p>I believe the <code>Data</code> class does too much. I'd rather deal with multiple less complicated objects.</p>\n\n<p>What is the problem we are trying to solve here? We are pulling data from a back end API. This API might return the data we want, an error, or the network response itself might error. Thus, we have <code>Either&lt;NetworkError | APIError, Data&gt;</code>.</p>\n\n<p>Now, before the request resolves (either with data or an error) we will be in a loading state. We <em>could</em> overload our <code>Either&lt;NetworkError | APIError, Data&gt;</code> with another possible state, or we could let our caller deal with that, and only call this class once a concrete result is available.</p>\n\n<p>I prefer the second option. This will be achieved with a <code>Request</code> which will always have a \"percent\" completion (just 0 if not updated by the user) and a result. For convenience, a <code>Request</code> (unlike <code>Either</code>) will be mutable. Also for convenience, it will include the <code>Left</code> side of an <code>Either</code> result as its own <code>Error</code> state.</p>\n\n<p>If you might not have actually made a request yet, we might not have a percent completion or a result. Instead of adding an \"initial\" state, I'll just wrap cases which require this in <code>Maybe</code>.</p>\n\n<p>With these changes, here's what a simple app that makes an API request when the user clicks a button and displays the result could look like. </p>\n\n<pre><code>// This would be nicer to do with a React component\nlet state: Maybe&lt;Request&lt;string, string&gt;&gt; = Maybe.nothing();\n\nconst button = document.querySelector('button')!;\nconst result = document.querySelector('#result') as HTMLDivElement;\nfunction render() {\n state.match({\n nothing() {\n button.hidden = false;\n result.hidden = true;\n },\n just(request) {\n button.hidden = true;\n result.hidden = false;\n\n request.match({\n loading(percent) {\n result.textContent = `Loading: ${percent * 100}%`;\n },\n error(error) {\n result.textContent = `ERROR: ${error}`;\n },\n result(data) {\n result.textContent = data;\n }\n });\n }\n });\n}\n\n// Todo\nfunction makeResponse(): Request&lt;string, string&gt; {}\n\nbutton.addEventListener('click', () =&gt; {\n state = Maybe.just(makeResponse());\n render();\n});\n\nrender();\n</code></pre>\n\n<p>I don't actually need fully fleshed out <code>Maybe</code> and <code>Either</code> classes, so here's what I'll use:</p>\n\n<pre><code>export class Maybe&lt;T&gt; {\n static nothing&lt;T&gt;() { return new Maybe&lt;T&gt;(undefined) }\n static just&lt;T&gt;(value?: T) { return new Maybe(value) }\n\n private constructor(private value?: T) {}\n\n match&lt;A, B&gt;({ nothing, just }: {\n nothing: () =&gt; A,\n just: (value: T) =&gt; B\n }): A | B {\n return this.value == null ? nothing() : just(this.value)\n }\n}\n\n// It isn't safe to use `undefined` as an empty signal since we could have `Either&lt;undefined, number&gt;`\n// Technically this applies to Maybe&lt;T&gt; as well, but I find it useful to allow undefined to signal nothing.\nconst EMPTY: unique symbol = Symbol()\ntype Empty = typeof EMPTY\n\nexport class Either&lt;Left, Right&gt; {\n private constructor(private data: [Left, Empty] | [Empty, Right]) {}\n\n static left&lt;Left = unknown, Right = unknown&gt;(value: Left): Either&lt;Left, Right&gt; {\n return new Either&lt;Left, Right&gt;([value, EMPTY]);\n }\n\n static right&lt;Left = unknown, Right = unknown&gt;(value: Right): Either&lt;Left, Right&gt; {\n return new Either&lt;Left, Right&gt;([EMPTY, value]);\n }\n\n match&lt;T&gt;(left: (left: Left) =&gt; T, right: (right: Right) =&gt; T) {\n return this.data[0] !== EMPTY ?\n left(this.data[0]) :\n right(this.data[1] as Right) // Unfortunately TS isn't smart enough to infer\n }\n}\n</code></pre>\n\n<p>Now to implement our <code>Request</code>... it is surprisingly easy to model! This is an indication that the design is a good idea, since good design should make it easy to achieve our goals.</p>\n\n<pre><code>import { Either } from \"./either\";\n\nexport class Request&lt;TData, TError = unknown&gt; {\n private constructor(private percent: number, private data: Either&lt;TError, TData&gt; | undefined) {}\n\n static incomplete() {\n return new Request(0, undefined);\n }\n\n match&lt;T&gt;({ loading, error, result }: {\n loading: (percent: number) =&gt; T,\n error: (error: TError) =&gt; T,\n result: (result: TData) =&gt; T\n }) {\n if (this.data === undefined) {\n return loading(this.percent);\n }\n return this.data.match(error, result);\n }\n\n setPercent(percent: number) {\n this.percent = percent;\n }\n\n setResult(result: TData) {\n this.data = Either.right(result);\n }\n\n setError(error: TError) {\n this.data = Either.left(error);\n }\n}\n</code></pre>\n\n<p>With everything at once, here's our little demo app.</p>\n\n<pre><code>class Maybe&lt;T&gt; {\n static nothing&lt;T&gt;() { return new Maybe&lt;T&gt;(undefined) }\n static just&lt;T&gt;(value?: T) { return new Maybe(value) }\n\n private constructor(private value?: T) {}\n\n match&lt;A, B&gt;({ nothing, just }: {\n nothing: () =&gt; A,\n just: (value: T) =&gt; B\n }): A | B {\n return this.value == null ? nothing() : just(this.value)\n }\n}\n\nconst EMPTY: unique symbol = Symbol()\ntype Empty = typeof EMPTY\n\nclass Either&lt;Left, Right&gt; {\n private constructor(private data: [Left, Empty] | [Empty, Right]) {}\n\n static left&lt;Left = unknown, Right = unknown&gt;(value: Left): Either&lt;Left, Right&gt; {\n return new Either&lt;Left, Right&gt;([value, EMPTY]);\n }\n\n static right&lt;Left = unknown, Right = unknown&gt;(value: Right): Either&lt;Left, Right&gt; {\n return new Either&lt;Left, Right&gt;([EMPTY, value]);\n }\n\n match&lt;T&gt;(left: (left: Left) =&gt; T, right: (right: Right) =&gt; T) {\n return this.data[0] !== EMPTY ?\n left(this.data[0]) :\n right(this.data[1] as Right); // Unfortunately TS isn't smart enough to infer\n }\n}\n\nclass Request&lt;TData, TError = unknown&gt; {\n private constructor(private percent: number, private data: Either&lt;TError, TData&gt; | undefined) {}\n\n static incomplete&lt;TData, TError&gt;() {\n return new Request&lt;TData, TError&gt;(0, undefined);\n }\n\n match&lt;T&gt;({ loading, error, result }: {\n loading: (percent: number) =&gt; T,\n error: (error: TError) =&gt; T,\n result: (result: TData) =&gt; T\n }) {\n if (this.data === undefined) {\n return loading(this.percent);\n }\n return this.data.match(error, result);\n }\n\n setPercent(percent: number) {\n this.percent = percent;\n }\n\n setResult(result: TData) {\n this.data = Either.right(result);\n }\n\n setError(error: TError) {\n this.data = Either.left(error);\n }\n}\n\n// This would be nicer to do with a React component\nlet state: Maybe&lt;Request&lt;string, string&gt;&gt; = Maybe.nothing();\n\nconst button = document.querySelector('button')!;\nconst result = document.querySelector('#result') as HTMLDivElement;\nfunction render() {\n state.match({\n nothing() {\n button.hidden = false;\n result.hidden = true;\n },\n just(request) {\n button.hidden = true;\n result.hidden = false;\n\n request.match({\n loading(percent) {\n result.textContent = `Loading: ${percent * 100}%`;\n },\n error(error) {\n result.textContent = `ERROR: ${error}`;\n },\n result(data) {\n result.textContent = data;\n }\n });\n }\n });\n}\n\nfunction makeResponse(): Request&lt;string, string&gt; {\n const response = Request.incomplete&lt;string, string&gt;();\n setTimeout(function () {\n response.setPercent(.99);\n render();\n }, 500)\n setTimeout(function () {\n if (Math.random() &lt; 0.5) {\n response.setResult('Got a result!')\n } else {\n response.setError('Got an error!')\n }\n render();\n }, 2000)\n return response;\n}\n\nbutton.addEventListener('click', () =&gt; {\n state = Maybe.just(makeResponse());\n render();\n});\n\nrender();\n</code></pre>\n\n<p>And here's the app with the compiled source.</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>class Maybe {\n constructor(value) {\n this.value = value;\n }\n static nothing() { return new Maybe(undefined); }\n static just(value) { return new Maybe(value); }\n match({ nothing, just }) {\n return this.value == null ? nothing() : just(this.value);\n }\n}\nconst EMPTY = Symbol();\nclass Either {\n constructor(data) {\n this.data = data;\n }\n static left(value) {\n return new Either([value, EMPTY]);\n }\n static right(value) {\n return new Either([EMPTY, value]);\n }\n match(left, right) {\n return this.data[0] !== EMPTY ?\n left(this.data[0]) :\n right(this.data[1]);\n }\n}\nclass Request {\n constructor(percent, data) {\n this.percent = percent;\n this.data = data;\n }\n static incomplete() {\n return new Request(0, undefined);\n }\n match({ loading, error, result }) {\n if (this.data === undefined) {\n return loading(this.percent);\n }\n return this.data.match(error, result);\n }\n setPercent(percent) {\n this.percent = percent;\n }\n setResult(result) {\n this.data = Either.right(result);\n }\n setError(error) {\n this.data = Either.left(error);\n }\n}\nlet state = Maybe.nothing();\nconst button = document.querySelector('button');\nconst result = document.querySelector('#result');\nfunction render() {\n state.match({\n nothing() {\n button.hidden = false;\n result.hidden = true;\n },\n just(request) {\n button.hidden = true;\n result.hidden = false;\n request.match({\n loading(percent) {\n result.textContent = `Loading: ${percent * 100}%`;\n },\n error(error) {\n result.textContent = `ERROR: ${error}`;\n },\n result(data) {\n result.textContent = data;\n }\n });\n }\n });\n}\nfunction makeResponse() {\n const response = Request.incomplete();\n setTimeout(function () {\n response.setPercent(.99);\n render();\n }, 500);\n setTimeout(function () {\n if (Math.random() &lt; 0.5) {\n response.setResult('Got a result!');\n }\n else {\n response.setError('Got an error!');\n }\n render();\n }, 2000);\n return response;\n}\nbutton.addEventListener('click', () =&gt; {\n state = Maybe.just(makeResponse());\n render();\n});\nrender();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button&gt;Click me!&lt;/button&gt;\n&lt;div id=\"result\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T20:38:57.413", "Id": "222826", "ParentId": "222061", "Score": "2" } } ]
{ "AcceptedAnswerId": "222826", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T06:45:49.220", "Id": "222061", "Score": "5", "Tags": [ "functional-programming", "error-handling", "typescript", "type-safety", "monads" ], "Title": "Typescript monad for data being loaded" }
222061
<p>I've coded this function as a secure file upload function in PHP.</p> <p>Currently I'm woking on an academic grading system (PHP script) which's really sensitive, so tell me what you think, and if you have any comments or recommendations please share it with me.</p> <pre class="lang-php prettyprint-override"><code>&lt;?php function secureUpload($fileField = null, $uploadPath = 'uploads/', $maxSize = 8000000, $newName = 1, $isImage = true, $checkImage = false, $allowedMimeTypes = []) { // Create an array to hold any outputs: $output = []; if($isImage) $allowedMimeTypes = ['jpeg'=&gt; 'image/jpeg', 'jpg' =&gt; 'image/jpeg', 'png' =&gt; 'image/png', 'bmp' =&gt; 'image/bmp', 'gif' =&gt; 'image/gif']; elseif(!is_array($allowedMimeTypes) || @count($allowedMimeTypes) &lt; 1) $allowedMimeTypes = ['ez'=&gt;'application/andrew-inset','hqx'=&gt;'application/mac-binhex40','cpt'=&gt;'application/mac-compactpro', 'doc'=&gt;'application/msword','bin'=&gt;'application/octet-stream','dms'=&gt;'application/octet-stream','lha'=&gt;'application/octet-stream', 'lzh'=&gt;'application/octet-stream','exe'=&gt;'application/octet-stream','class'=&gt;'application/octet-stream','so'=&gt;'application/octet-stream', 'dll'=&gt;'application/octet-stream','oda'=&gt;'application/oda','pdf'=&gt;'application/pdf','ai'=&gt;'application/postscript','eps'=&gt;'application/postscript', 'ps'=&gt;'application/postscript','smi'=&gt;'application/smil','smil'=&gt;'application/smil','wbxml'=&gt;'application/vnd.wap.wbxml','wmlc'=&gt;'application/vnd.wap.wmlc', 'wmlsc'=&gt;'application/vnd.wap.wmlscriptc','bcpio'=&gt;'application/x-bcpio','vcd'=&gt;'application/x-cdlink','pgn'=&gt;'application/x-chess-pgn','cpio'=&gt;'application/x-cpio', 'csh'=&gt;'application/x-csh','dcr'=&gt;'application/x-director','dir'=&gt;'application/x-director','dxr'=&gt;'application/x-director','dvi'=&gt;'application/x-dvi','spl'=&gt;'application/x-futuresplash', 'gtar'=&gt;'application/x-gtar','hdf'=&gt;'application/x-hdf','js'=&gt;'application/x-javascript','skp'=&gt;'application/x-koan','skd'=&gt;'application/x-koan','skt'=&gt;'application/x-koan', 'skm'=&gt;'application/x-koan','latex'=&gt;'application/x-latex','nc'=&gt;'application/x-netcdf','cdf'=&gt;'application/x-netcdf','sh'=&gt;'application/x-sh','shar'=&gt;'application/x-shar', 'swf'=&gt;'application/x-shockwave-flash','sit'=&gt;'application/x-stuffit','sv4cpio'=&gt;'application/x-sv4cpio','sv4crc'=&gt;'application/x-sv4crc','tar'=&gt;'application/x-tar', 'tcl'=&gt;'application/x-tcl','tex'=&gt;'application/x-tex','texinfo'=&gt;'application/x-texinfo','texi'=&gt;'application/x-texinfo','t'=&gt;'application/x-troff','tr'=&gt;'application/x-troff', 'roff'=&gt;'application/x-troff','man'=&gt;'application/x-troff-man','me'=&gt;'application/x-troff-me','ms'=&gt;'application/x-troff-ms','ustar'=&gt;'application/x-ustar', 'src'=&gt;'application/x-wais-source','xhtml'=&gt;'application/xhtml+xml','xht'=&gt;'application/xhtml+xml','zip'=&gt;'application/zip','au'=&gt;'audio/basic','snd'=&gt;'audio/basic','mid'=&gt;'audio/midi', 'midi'=&gt;'audio/midi','kar'=&gt;'audio/midi','mpga'=&gt;'audio/mpeg','mp2'=&gt;'audio/mpeg','mp3'=&gt;'audio/mpeg','aif'=&gt;'audio/x-aiff','aiff'=&gt;'audio/x-aiff','aifc'=&gt;'audio/x-aiff', 'm3u'=&gt;'audio/x-mpegurl','ram'=&gt;'audio/x-pn-realaudio','rm'=&gt;'audio/x-pn-realaudio','rpm'=&gt;'audio/x-pn-realaudio-plugin','ra'=&gt;'audio/x-realaudio','wav'=&gt;'audio/x-wav', 'pdb'=&gt;'chemical/x-pdb','xyz'=&gt;'chemical/x-xyz','bmp'=&gt;'image/bmp','gif'=&gt;'image/gif','ief'=&gt;'image/ief','jpeg'=&gt;'image/jpeg','jpg'=&gt;'image/jpeg','jpe'=&gt;'image/jpeg', 'png'=&gt;'image/png','tiff'=&gt;'image/tiff','tif'=&gt;'image/tif','djvu'=&gt;'image/vnd.djvu','djv'=&gt;'image/vnd.djvu','wbmp'=&gt;'image/vnd.wap.wbmp','ras'=&gt;'image/x-cmu-raster', 'pnm'=&gt;'image/x-portable-anymap','pbm'=&gt;'image/x-portable-bitmap','pgm'=&gt;'image/x-portable-graymap','ppm'=&gt;'image/x-portable-pixmap','rgb'=&gt;'image/x-rgb','xbm'=&gt;'image/x-xbitmap', 'xpm'=&gt;'image/x-xpixmap','xwd'=&gt;'image/x-windowdump','igs'=&gt;'model/iges','iges'=&gt;'model/iges','msh'=&gt;'model/mesh','mesh'=&gt;'model/mesh','silo'=&gt;'model/mesh','wrl'=&gt;'model/vrml', 'vrml'=&gt;'model/vrml','css'=&gt;'text/css','html'=&gt;'text/html','htm'=&gt;'text/html','asc'=&gt;'text/plain','txt'=&gt;'text/plain','rtx'=&gt;'text/richtext','rtf'=&gt;'text/rtf', 'sgml'=&gt;'text/sgml','sgm'=&gt;'text/sgml','tsv'=&gt;'text/tab-seperated-values','wml'=&gt;'text/vnd.wap.wml','wmls'=&gt;'text/vnd.wap.wmlscript','etx'=&gt;'text/x-setext', 'xml'=&gt;'text/xml','xsl'=&gt;'text/xml','mpeg'=&gt;'video/mpeg','mpg'=&gt;'video/mpeg','mpe'=&gt;'video/mpeg','qt'=&gt;'video/quicktime','mov'=&gt;'video/quicktime','mxu'=&gt;'video/vnd.mpegurl', 'avi'=&gt;'video/x-msvideo','movie'=&gt;'video/x-sgi-movie','ice'=&gt;'x-conference-xcooltalk']; else if(isset($allowedMimeTypes['0'])) $output['errors'][] = 'The allowed extensions must be used as index for each MIME type in the ‘$allowedMimeTypes’ array.'; $uploadPath = rtrim($uploadPath, '/') . '/'; // Checking if path ends in '/' ... if not then tack it on. // || Validation || if(!$fileField) $output['errors'][] = 'Please specify a valid file field.'; if(!$uploadPath) $output['errors'][] = 'Please specify a valid upload path.'; if(@count($output['errors']) &gt; 0) return $output; if((!empty($_FILES[$fileField])) &amp;&amp; ($_FILES[$fileField]['error'] == 0)) { // Get file info: $fileInfo = pathinfo($_FILES[$fileField]['name']); $fileName = $fileInfo['filename']; $fileSize = $_FILES[$fileField]['size']; $fileExt = strtolower($fileInfo['extension']); // Check if the file has the right extension and type: if(!@isset($allowedMimeTypes[$fileExt])) $output['errors'][] = 'Invalid file format.'; //'Invalid file extension.'; if(!@in_array($_FILES[$fileField]['type'], $allowedMimeTypes)) $output['errors'][] = 'Invalid file type.'; // Check that the file is not too big .. Given $maxSize in (byets). if($fileSize &gt; $maxSize) $output['errors'][] = 'File is too big. Max allowed size is: '.($maxSize / 1024).' Kb, yours is '.($fileSize / 1024).' Kb.'; // If ‘$isImage’ AND ‘$checkImage’ are set to ‘true’ // Then, using getimagesize(), we'll be processing the image with the GD library. // If it isn’t an image, this will fail and therefor the entire upload will fail: if($checkImage &amp;&amp; $isImage){if(!getimagesize($_FILES[$fileField]['tmp_name'])) $output['errors'][] = 'Uploaded file is not a valid image.';} $newFileName = ($newName === 1 ? sprintf('%s.%s', md5_file($_FILES[$fileField]['tmp_name']), $fileExt) // If ($newName = 1) &lt;- $newFileName = Md5_file : ($newName === 2 ? sprintf('%s.%s', substr(md5(microtime()),0,15), $fileExt) // If ($newName = 2) &lt;- $newFileName = Random name : ($newName === 3 ? sprintf('%s.%s', $fileName, $fileExt) // If ($newName = 3) &lt;- $newFileName = Same name : sprintf('%s.%s', $newName, $fileExt)))); // Else &lt;- $newFileName = The name passed in ‘$newName’ // Check if file already exists on server: if(file_exists($uploadPath.$newFileName)) $output['errors'][] = 'A file with the same name already exists.'; // Create the $uploadPath if it doesn't already exist: if(!is_dir($uploadPath)) @mkdir($uploadPath) OR $output['errors'][] = 'Error creating directory: '.str_replace(['mkdir(): ','File'],['','Directory'], error_get_last()['message']); // The file has not correctly validated: if(@count($output['errors']) &gt; 0) return $output; if(move_uploaded_file($_FILES[$fileField]['tmp_name'], $uploadPath.$newFileName)) { $output['filename'] = $newFileName; $output['filepath'] = $uploadPath; $output['filesize'] = $fileSize; } else $output['errors'][] = 'Server error.'; } else $output['errors'][] = 'No file uploaded.'; return $output; } </code></pre> <p>I've uploaded it on GitHub with a complete documentation if anyone is interested: <a href="https://github.com/RyadPasha/PHPFileUploader" rel="nofollow noreferrer">https://github.com/RyadPasha/PHPFileUploader</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T09:10:06.140", "Id": "429669", "Score": "0", "body": "It looks secure but hugely over-engineered." } ]
[ { "body": "<p>A conditional lookup array? Why do it? I never have and don't see the advantage. I think it would be cleaner to separate the data from the processing. To do this, just add a higher level key...</p>\n\n<pre><code>$allowedMimeTypes = [\n 'images' =&gt; [\n 'jpeg' =&gt; ...\n ],\n 'all' =&gt; [\n 'ez' =&gt; ...\n ]\n];\n</code></pre>\n\n<p>This places all of the data with a similar purpose in a single, expressive lookup. Downscript, you won't ever need to scroll back up to the top of your function to check which lookup array (which in your code will have one variable name, but two potential sets of data) that you are dealing with.</p>\n\n<p>Furthermore, if you define the lookup as a constant, it becomes globally available. This will afford you the ability to pull the general-use lookup out of the function and potentially share it elsewhere -- this is best practice.</p>\n\n<p>With a static lookup array, all of your conditional logic can be written in a much tighter condition block. You simply use your incoming function parameters to determine which parent key should be used on the lookup array.</p>\n\n<p>Never use <code>@</code> as a silencer. Always properly handle your data.</p>\n\n<p>If you want to know if something <code>isset</code> and has <code>count</code>, use <code>!empty()</code>. After you ensure that a variable exists via <code>isset()</code>, <code>array_key_exists()</code>, or <code>empty()</code>, then you can move on to accessing or counting the data as required. If you know an array-type variable exist and you want to check if it is empty, you can simply use <code>!$variable</code> and spare a function call.</p>\n\n<p>This line doesn't do what the comment says it does:</p>\n\n<pre><code>$uploadPath = rtrim($uploadPath, '/') . '/'; // Checking if path ends in '/' ... if not then tack it on.\n</code></pre>\n\n<p>Either explain that it eliminates any right-hand side slashes, then appends a slash or change the code to something like:</p>\n\n<pre><code>if (substr($uploadPath, -1) != '/') {\n $uploadPath .= '/';\n}\n</code></pre>\n\n<p>Always use curly braces for every loop and condition block. This will avoid accidental typos and make your code easier to read. Never write nested if conditions in a single line ...for the same reason.</p>\n\n<p>For simplicity,</p>\n\n<pre><code>if((!empty($_FILES[$fileField])) &amp;&amp; ($_FILES[$fileField]['error'] == 0)) {\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>if (!empty($_FILES[$fileField]) &amp;&amp; !$_FILES[$fileField]['error']) {\n</code></pre>\n\n<p>As a matter of consistency, I recommend always using <code>&amp;&amp;</code> and <code>||</code> in php versus <code>AND</code> and <code>OR</code>. This will prevent any trip ups regarding precedence. <a href=\"https://stackoverflow.com/a/2803576/2943403\">'AND' vs '&amp;&amp;' as operator</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T18:02:42.510", "Id": "429745", "Score": "0", "body": "Why would I pass the array `$allowedMimeTypes` with all these data into memory?\nIf it's an image then only define it with needed data, and let's say I used your way, I won't be able to use the user defined types, the way I used is the best to solve these two issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T18:04:18.153", "Id": "429747", "Score": "0", "body": "I'm already using `&&` and `||` in my statements" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:27:06.913", "Id": "429777", "Score": "0", "body": "Building a master lookup array to handle a single function call is not going to significantly impact memory, especially compared to the images that you are actually processing. The advantages are portability of the data and code clarity in this script. If you want to pass a separate, user-defined array of approved extensions, okay, but that seems like a loss of control. I didn't go to your github and I don't plan to. In the end, there is nothing in my suggestions to stop you from passing an overriding custom lookup." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:27:13.880", "Id": "429778", "Score": "0", "body": "As far as `AND`, don't take the link title too literally, it is also about `OR` and precedence. You may have overlooked `OR` because it is squeezed into `if(!is_dir$uploadPath)) @mkdir($uploadPath) OR $output['errors'][] = ...`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:31:13.790", "Id": "222084", "ParentId": "222066", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:50:25.187", "Id": "222066", "Score": "2", "Tags": [ "php", "security" ], "Title": "Secure file upload in PHP" }
222066
<p>I would like to know whether I could make my solution to this <a href="https://leetcode.com/problems/brick-wall/" rel="nofollow noreferrer">Leetcode challenge</a> much faster. </p> <blockquote> <p><em>There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. The bricks have the same heights but different widths. You want to draw a vertical line from the <strong>top</strong> to the <strong>bottom</strong> and cross the <strong>least</strong> bricks.</em></p> <p><em>The brick wall is represented by a list of rows. Each row is a list of integers representing the width of each brick in this row from left to right.</em></p> <p><em>If your line goes through the edge of a brick, then the brick is not considered as crossed. You need to find out how to draw the line to cross the least bricks and return the number of crossed bricks.</em></p> <p><strong><em>You cannot draw a line just along one of the two vertical edges of the wall, in which case the line will obviously cross no bricks.</em></strong></p> <p><strong><em>Note -</em></strong></p> <ul> <li><p><em>The width sum of bricks in different rows are the same and won't exceed <code>INT_MAX</code>.</em></p></li> <li><p><em>The number of bricks in each row is in the range <code>[1, 10,000]</code>. The height of the wall is in the range <code>[1, 10,000]</code>. The total number of bricks in the wall won't exceed <code>20,000</code>.</em></p></li> </ul> <p><strong><em>Example -</em></strong></p> <pre><code>Input: [[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]] Output: 2 </code></pre> <p><strong><em>Explanation -</em></strong></p> <p><a href="https://i.stack.imgur.com/VnwKq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VnwKq.png" alt="enter image description here"></a></p> </blockquote> <p>Here is my solution to this challenge -</p> <pre><code>import collections def least_bricks(wall): return len(wall) - max(collections.Counter(sum(row[:i + 1]) for row in wall for i in range(len(row[:-1]))).values(), default = 0) </code></pre> <p>Here is the time taken for the example output -</p> <pre><code>%timeit least_bricks([[1,2,2,1], [3,1,2], [1,3,2], [2,4], [3,1,2], [1,3,1,1]]) &gt;&gt;&gt; 13 µs ± 1.07 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each) </code></pre> <p>Here is my Leetcode result (85 test cases) -</p> <blockquote> <p><a href="https://i.stack.imgur.com/8nHLH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8nHLH.png" alt="enter image description here"></a></p> </blockquote> <p>Taken from - <em><a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer">https://docs.python.org/3/library/collections.html#collections.Counter</a></em> -</p> <blockquote> <p><em>A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.</em></p> </blockquote>
[]
[ { "body": "<p>There's a lot of repeated summing taking place in this part:</p>\n\n<pre><code>(sum(row[:i + 1]) for row in wall for i in range(len(row[:-1])))\n</code></pre>\n\n<p>So this is summing the first i+1 elements in the row, with an upper bound that steps through all values except the last. If the row was [1, 2, 3, 4, 5], these are the sums:</p>\n\n<ul>\n<li>1</li>\n<li>1+2 = 3</li>\n<li>1+2+3 = 6</li>\n<li>1+2+3+4 = 10</li>\n</ul>\n\n<p>The sums differ, but only by the last term. It would therefore save effort to use a running sum instead, only adding that last term each time:</p>\n\n<ul>\n<li>1</li>\n<li>1+2 = 3</li>\n<li>3+3 = 6</li>\n<li>6+4 = 10</li>\n</ul>\n\n<p>This can be done with <a href=\"https://docs.python.org/3/library/itertools.html#itertools.accumulate\" rel=\"noreferrer\">itertools.accumulate</a>:</p>\n\n<pre><code>(s for row in wall for s in itertools.accumulate(row[:-1]))\n</code></pre>\n\n<p>Another thing in your code that this approach solves is the i+1 summing. Instead of having this addition performed on every iteration, you could iterate through the correct values directly with <code>for i in range(1, len(row))</code>. But using accumulate, this is already taken care of.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T10:34:19.807", "Id": "222074", "ParentId": "222069", "Score": "6" } }, { "body": "<h1>Counter</h1>\n\n<p>Great use of <code>Counter</code>. One thing that can be improved, is to use <code>most_common</code> instead of <code>max</code>.</p>\n\n<p>If <code>edges</code> is the Counter of all the edges in the wall, <code>_, max_edges = edges.most_common(1)</code> gives you the index with the most edges, and how many edges it has. Since this is the right side of the wall, you need the 2nd most common element: <code>edges.most_common(2)[1]</code></p>\n\n<h1>aggregating the counter</h1>\n\n<p>Python is batteries included. Whenever you want to do advanced iteration, it can pay to look at the <code>itertools</code> module. For this, you can use <code>accumulate</code> (as @sedsarq notes in his answer) and <code>chain</code>.</p>\n\n<pre><code>edges = collections.Counter(\n chain.from_iterable(accumulate(row) for row in wall)\n)\n</code></pre>\n\n<hr>\n\n<pre><code>def least_bricks2(wall):\n edges = collections.Counter(\n chain.from_iterable(accumulate(row) for row in wall)\n )\n if len(edges) == 1: # only one brick wide\n return len(wall)\n _, max_edges = edges.most_common(2)[1] #skipping the right edge of the wall\n return len(wall) - max_edges\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T20:57:24.653", "Id": "429923", "Score": "1", "body": "To be pedantic, you need to check for the case where the counter only has one element. That can occur if there is only one width of brick, for instance the testcase [[2],[2],[2],[2],[2],[2]]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T08:15:29.913", "Id": "429953", "Score": "0", "body": "You are correct. Fixed that" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T09:50:11.763", "Id": "222140", "ParentId": "222069", "Score": "3" } } ]
{ "AcceptedAnswerId": "222074", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T09:21:53.407", "Id": "222069", "Score": "0", "Tags": [ "python", "performance", "python-3.x", "programming-challenge" ], "Title": "(Leetcode) Brick wall" }
222069
<p><strong>I asked this question over at stackoverflow but was told it may be better suited here.</strong></p> <p>So I absolutely want to store <code>DateTimeOffset</code> objects in UTC format. To achieve the correct conversions, I've created my own methods to deal with the conversions.</p> <pre><code>/// &lt;summary&gt;String representation of the specified time zone.&lt;/summary&gt; private const String LOCAL_TIME_ZONE_STRING_REPRESENTATION = "GMT Standard Time"; /// &lt;summary&gt;TimeZoneInfo representation of the specified time zone.&lt;/summary&gt; private static TimeZoneInfo LOCAL_TIME_ZONE = TimeZoneInfo.FindSystemTimeZoneById(LOCAL_TIME_ZONE_STRING_REPRESENTATION); /// &lt;summary&gt;With a given DateTime, passed DateTime is assumed it has been parsed and shares the same time zone as TimeZoneInfo LOCAL_TIME_ZONE.&lt;/summary&gt; /// &lt;param name="dateAndTime"&gt;DateTime in TimeZoneInfo LOCAL_TIME_ZONE.&lt;/param&gt; /// &lt;returns&gt;UTC DateTime.&lt;/returns&gt; public static DateTime ConvertToUtcDateTime(DateTime dateAndTime) { return TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE).ToUniversalTime(); } /// &lt;summary&gt;With a given DateTime, the DateTime is assumed to be a UTC time. It will then return a DateTime converted to TimeZoneInfo LOCAL_TIME_ZONE.&lt;/summary&gt; /// &lt;param name="dateAndTime"&gt;DateTime that is in UTC.&lt;/param&gt; /// &lt;returns&gt;Converted to TimeZoneInfo LOCAL_TIME_ZONE DateTime.&lt;/returns&gt; public static DateTime ConvertToLocalDateTime(DateTime dateAndTime) { return TimeZoneInfo.ConvertTimeFromUtc(dateAndTime, LOCAL_TIME_ZONE); } </code></pre> <p>Using the String constant <code>LOCAL_TIME_ZONE_STRING_REPRESENTATION</code>, any user who wishes to compile the code can specify which time zone they want the code to run in, rather than it try to use Window's local time zone.</p> <p>Then the two above methods can be used to make a conversion between between the two:</p> <pre><code>private static void Main() { //Parse a date and time. It is to be assumed this parsed date and time is in the same time zone // as LOCAL_TIME_ZONE. DateTimeOffset dateTime = ConvertToUtcDateTime(new DateTime(2019,6,1,15,30,0)); //Assuming we have retrieved a date and time that is in UTC time, we can now convert it // to the same time zone as LOCAL_TIME_ZONE. DateTime convertedFromUTC = ConvertToLocalDateTime(dateTime.DateTime); } </code></pre> <p>The system would be able to parse <code>DateTime</code>'s that have no time zone associated with them regardless where they would've came from, and convert them into UTC time assuming that <code>DateTime</code> came from the same <code>TimeZone</code> as <code>LOCAL_TIME_ZONE</code>. The only time where we would need to convert retrieved UTC <code>DateTimes</code> back into the same time zone as <code>LOCAL_TIME_ZONE</code> would be when we are visually displaying it to a user. All <code>TimeSpan</code> calculations etc, would use the UTC <code>DateTimeOffset</code>.</p> <p>This seems to work as intended, and I can change <code>LOCAL_TIME_ZONE_STRING_REPRESENTATION</code> to any time zone I want, and using the methods I created, the system uses that time zone instead of Window's local time zone.</p> <p>This would be particularly useful for me as the server hosting an application may be in a different time zone and have a different culture, but its intended users could be for a totally different time zone.</p> <p>Am I making too much work for myself, or would this be a reasonable way to implement what I need?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T10:32:41.040", "Id": "429679", "Score": "0", "body": "Welcome to Code Review! I changed your title to follow the recommendations at [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) found in the Help Center." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T10:33:26.417", "Id": "429680", "Score": "0", "body": "Thanks, that title is definitely easier to read!" } ]
[ { "body": "<blockquote>\n <p>Using the String constant LOCAL_TIME_ZONE_STRING_REPRESENTATION, any user who wishes to compile the code can specify which time zone they want the code to run in, rather than it try to use Window's local time zone.</p>\n</blockquote>\n\n<p>I think this is not the right way to provide flexibility. Lets say you sell your application to three different customers that want three different <code>LOCAL_TIME_ZONE</code>, then you'll have to compile the application three times. Do yourself the favor and place this as a setting in a configuration file or database. And what if the application is to be used world wide by a global customer? Do you plan to use the same time zone in all their offices?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)\n {\n return TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE).ToUniversalTime();\n }\n</code></pre>\n</blockquote>\n\n<p>I don't think this is working correctly: </p>\n\n<p>A <code>DateTime</code> object can either represent a local time which is always regarded as local according to the system settings or a UTC time if created with kind = <code>DateTimeKind.Utc</code> - seen from the <code>DateTime</code> api.</p>\n\n<p>Let say <code>LOCAL_TIME_ZONE_STRING_REPRESENTATION = \"GMT Standard Time\";</code> and the system time zone = <code>\"Romance Standard Time\" (+01.00)</code>.</p>\n\n<p>Because <code>TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE)</code> converts from local time (<code>Romance Standard Time</code>), it converts </p>\n\n<pre><code>DateTime inputDate = new DateTime(2019, 3, 1, 15, 30, 0);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>01-03-2019 14:30:00\n</code></pre>\n\n<p>and the call to <code>ToUniversalTime()</code> converts it further to:</p>\n\n<pre><code>01-03-2019 13:30:00\n</code></pre>\n\n<p>because this too anticipate the <code>DateTime</code> object to be in local time, which is <code>\"Romance Standard Time\"</code> and not <code>\"GMT Standard Time\"</code>. </p>\n\n<p>But if you - as you write in the explanation to the method - expect the input date time object to be in <code>LOCAL_TIME_ZONE</code>, no change should occur, because <code>GMT = UTC</code>.</p>\n\n<p>To do it correctly I'll suggest this approach if the input <code>DateTime</code> object is still expected to be in <code>LOCAL_TIME_ZONE</code>:</p>\n\n<pre><code>public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)\n{\n return TimeZoneInfo.ConvertTimeToUtc(dateAndTime, LOCAL_TIME_ZONE);\n}\n</code></pre>\n\n<hr>\n\n<p>That said, if I were you, I would reconsider the whole setup thoroughly before using it in a larger scale. Dates, Times and globalization in general is rather complicated, so do yourself the favor to read and test a lot before taking a concept into use that is not just relying on the system. A place to start reading could be <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/datetime/converting-between-time-zones?view=netframework-4.8\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T15:54:15.367", "Id": "430293", "Score": "0", "body": "This is a good explanation to show that `DateTime` is not context-free. The consumer should always assert a timezone when the `Kind` is `LocalTime`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-02T13:01:59.993", "Id": "432770", "Score": "0", "body": "Thanks for the information. One thing I am having a real hard time understanding is how I would use DateTimeOffset.Parse() and specifically specify a TimeZoneInfo if I specifically know the time zone that the date and time has been parsed from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-02T13:20:29.403", "Id": "432776", "Score": "0", "body": "@Izacch: If you parse the datetime string with `DateTime.Parse()`, you can use `TimeSpan offset = TimeZoneInfo.GetUtcOffset(dateTime)` to get the offset from UTC and then call the constructor: `var utcOffset = DateTimeOffset(dateTime, offset);` If I understand you right." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T14:26:35.193", "Id": "222356", "ParentId": "222071", "Score": "1" } } ]
{ "AcceptedAnswerId": "222356", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T09:48:58.433", "Id": "222071", "Score": "2", "Tags": [ "c#", "datetime", "converting" ], "Title": "Static Methods for Dealing with Conversions from and to UTC" }
222071
<p>I have made some code that operates on multiple entities and creates 'time windows' for them. Basically, the entities will contain states, usually in boolean or int. They will be timestamped and in order to reduce the number of rows when creating a graph for a large date range, I am calculating time windows of 5 mins, 15 mins and 60 mins. If I'm calculating the 5 minute time windows, and a state is true from 00:00:00 to 00:02:59 and false from 00:03:00 onwards, the time window for the first 5 minutes of the day would be true, since the state was true for 3 out of 5 minutes.</p> <p>I have used custom attributes, generics and reflection in order to check what properties the entities have and which of them I need to process.</p> <p>The code works, but I'm sure it can be improved.</p> <p>Sometimes, the code works fast for a couple of thousands of rows across 16 entities, i.e. 16 calls to the <code>CalculateTimeWindows&lt;T&gt;()</code> method (less than a second) but sometimes it's really slow (takes some 45 seconds). Any ideas how I can optimise this code?</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; namespace Services.Helpers { #region Custom Attributes [AttributeUsage(AttributeTargets.Property)] public class DoNotCopyIntoTimeWindow : System.Attribute { } // leave default [AttributeUsage(AttributeTargets.Property)] public class IsProcessedIntoTimeWindow : System.Attribute { } // calculate time window for this property [AttributeUsage(AttributeTargets.Property)] public class IsTimeWindowDate : Attribute { } // attribute to mark property as the datetime [AttributeUsage(AttributeTargets.Property)] public class IsTimeWindowIdentifier : Attribute { } // this is the time window property #endregion public class TimeWindow { #region Structs public struct TimeWindowDictionary { public string Name { get; set; } public Dictionary&lt;NullObject&lt;dynamic&gt;, int&gt; Dictionary { get; set; } } public struct NullObject&lt;T&gt; { [DefaultValue(true)] private readonly bool isnull;// default property initializers are not supported for structs private NullObject(T item, bool isnull) : this() { this.isnull = isnull; Item = item; } public NullObject(T item) : this(item, item == null) { } public static NullObject&lt;T&gt; Null() { return new NullObject&lt;T&gt;(); } public T Item { get; private set; } public bool IsNull() { return isnull; } public static implicit operator T(NullObject&lt;T&gt; nullObject) { return nullObject.Item; } public static implicit operator NullObject&lt;T&gt;(T item) { return new NullObject&lt;T&gt;(item); } public override string ToString() { return (Item != null) ? Item.ToString() : "NULL"; } public override bool Equals(object obj) { if (obj == null) return IsNull(); if (!(obj is NullObject&lt;T&gt;)) return false; var no = (NullObject&lt;T&gt;)obj; if (IsNull()) return no.IsNull(); if (no.IsNull()) return false; return Item.Equals(no.Item); } public override int GetHashCode() { if (IsNull()) return 0; var result = Item.GetHashCode(); if (result &gt;= 0) result++; return result; } } #endregion public static IEnumerable&lt;T&gt; CalculateTimeWindows&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels) where T : new() { if (stateModels.Count() == 0) return new List&lt;T&gt;(); dateFrom = GetPropertiesAndDictionaries(dateFrom, stateModels, out PropertyInfo datePropertyInfo, out List&lt;PropertyInfo&gt; copyProperties, out PropertyInfo timeWindowIdentifier, out int size, out TimeWindowDictionary[] dictionaries, out int i); return CalculateTimeWindow(dateFrom, dateTo, stateModels, 5, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i) .Concat(CalculateTimeWindow(dateFrom, dateTo, stateModels, 15, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i)) .Concat(CalculateTimeWindow(dateFrom, dateTo, stateModels, 60, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i)); } public static IEnumerable&lt;T&gt; CalculateTimeWindow&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels, byte timeWindowMinutes, PropertyInfo datePropertyInfo, List&lt;PropertyInfo&gt; copyProperties, PropertyInfo timeWindowIdentifier, int size, TimeWindowDictionary[] dictionaries, int i) where T : new() { if (stateModels.Count() &gt; 0) { DateTime currentWindowFrom, currentWindowTo, nextWindowFrom; nextWindowFrom = dateFrom; int itemPointer = 0; T prevItem = default; T prevTimeWindow = default; KeyValuePair&lt;NullObject&lt;dynamic&gt;, int&gt; maxValue = new KeyValuePair&lt;NullObject&lt;dynamic&gt;, int&gt;(); int j = 1; do // one time window { for (i = 0; i &lt; size; i++) dictionaries[i].Dictionary = new Dictionary&lt;NullObject&lt;dynamic&gt;, int&gt;(); currentWindowFrom = nextWindowFrom; nextWindowFrom = currentWindowFrom.AddMinutes(timeWindowMinutes); currentWindowTo = nextWindowFrom.AddSeconds(-1); var calculateTime = currentWindowFrom; for (itemPointer = itemPointer; itemPointer &lt; stateModels.Count(); itemPointer++) { var item = stateModels.ElementAt(itemPointer); var date = (DateTime)datePropertyInfo.GetValue(item); if (date &gt;= currentWindowTo) break; var endDate = (date &gt; currentWindowTo) ? nextWindowFrom : date; // state might extend more than the end of the time window CalculateStateSeconds(prevItem, dictionaries, calculateTime, endDate); prevItem = item; calculateTime = (date &lt; currentWindowFrom) ? currentWindowFrom : date; // to fix the 'yesterday' date } if (calculateTime &lt; currentWindowTo) CalculateStateSeconds(prevItem, dictionaries, calculateTime, nextWindowFrom); if (dictionaries[0].Dictionary.Count &gt; 0) { bool sameAsPrevious = (prevTimeWindow != null); var output = new T(); foreach (var dictionary in dictionaries) { //var valToSet = dictionary.Dictionary.FirstOrDefault(x =&gt; x.Value.Equals(dictionary.Dictionary.Values.Max())).Key.Item; for (i = 0; i &lt; dictionary.Dictionary.Count; i++) { maxValue = dictionary.Dictionary.First(); for (j = 1; j &lt; dictionary.Dictionary.Count; j++) { var valuePair = dictionary.Dictionary.ElementAt(j); if (valuePair.Value &gt; maxValue.Value) maxValue = valuePair; } } var valToSet = maxValue.Key.Item; if (sameAsPrevious) { var prevVal = GetValue(prevTimeWindow, dictionary.Name); if (valToSet == null &amp;&amp; prevVal == null) { } else if ((valToSet == null &amp;&amp; prevVal != null) || (valToSet != null &amp;&amp; prevVal == null) || !valToSet.Equals(prevVal)) sameAsPrevious = false; } SetValue(output, dictionary.Name, valToSet); } if (!sameAsPrevious) { foreach (var copyProperty in copyProperties) SetValue(output, copyProperty.Name, copyProperty.GetValue(prevItem)); timeWindowIdentifier.SetValue(output, timeWindowMinutes); datePropertyInfo.SetValue(output, currentWindowFrom); prevTimeWindow = output; yield return output; } } } while (nextWindowFrom &lt;= dateTo); } } private static DateTime GetPropertiesAndDictionaries&lt;T&gt;(DateTime dateFrom, List&lt;T&gt; stateModels, out PropertyInfo datePropertyInfo, out List&lt;PropertyInfo&gt; copyProperties, out PropertyInfo timeWindowIdentifier, out int size, out TimeWindowDictionary[] dictionaries, out int i) where T : new() { Type tType = typeof(T); var propInfos = tType.GetProperties(); datePropertyInfo = propInfos.Single(p =&gt; p.GetCustomAttributes(typeof(IsTimeWindowDate), true).Any()); var firstDate = (DateTime)datePropertyInfo.GetValue(stateModels.First()); if (firstDate &lt; dateFrom) dateFrom = new DateTime(firstDate.Year, firstDate.Month, firstDate.Day, firstDate.Hour, 0, 0, DateTimeKind.Utc); var properties = propInfos.Where(p =&gt; p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any()).Select(x =&gt; x.Name); copyProperties = propInfos.Where(p =&gt; !p.GetCustomAttributes(typeof(IsTimeWindowIdentifier), true).Any() &amp;&amp; !p.GetCustomAttributes(typeof(DoNotCopyIntoTimeWindow), true).Any() &amp;&amp; !p.GetCustomAttributes(typeof(IsTimeWindowDate), true).Any() &amp;&amp; !p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any() &amp;&amp; p.CanWrite &amp;&amp; !p.GetMethod.IsVirtual).ToList(); timeWindowIdentifier = propInfos.Single(p =&gt; p.GetCustomAttributes(typeof(IsTimeWindowIdentifier), true).Any()); size = properties.Count(); dictionaries = new TimeWindowDictionary[size]; i = 0; foreach (var property in properties) { dictionaries[i] = new TimeWindowDictionary() { Name = property }; i++; } return dateFrom; } private static dynamic GetValue(object inputObject, string propertyName) { Type type = inputObject.GetType(); PropertyInfo propertyInfo = type.GetProperty(propertyName); return propertyInfo.GetValue(inputObject); } private static void SetValue(object inputObject, string propertyName, object propertyVal) { //find out the type Type type = inputObject.GetType(); //get the property information based on the type PropertyInfo propertyInfo = type.GetProperty(propertyName); if (propertyVal != null) { //find the property type Type propertyType = propertyInfo.PropertyType; //Convert.ChangeType does not handle conversion to nullable types //if the property type is nullable, we need to get the underlying type of the property var targetType = IsNullableType(propertyType) ? Nullable.GetUnderlyingType(propertyType) : propertyType; //Returns an System.Object with the specified System.Type and whose value is //equivalent to the specified object. propertyVal = Convert.ChangeType(propertyVal, targetType); } //Set the value of the property propertyInfo.SetValue(inputObject, propertyVal, null); } private static bool IsNullableType(Type type) { return type.IsGenericType &amp;&amp; type.GetGenericTypeDefinition().Equals(typeof(Nullable&lt;&gt;)); } private static void CalculateStateSeconds&lt;T&gt;(T prevItem, IEnumerable&lt;TimeWindowDictionary&gt; dictionaries, DateTime calculateTime, DateTime endDate) { if (prevItem != null) { var seconds = Convert.ToInt32(endDate.Subtract(calculateTime).TotalSeconds); Type tType = typeof(T); foreach (var dictionary in dictionaries) { PropertyInfo propertyInfo = tType.GetProperty(dictionary.Name); var key = propertyInfo.GetValue(prevItem); dictionary.Dictionary.TryGetValue(key, out int existingSeconds); dictionary.Dictionary[key] = existingSeconds + seconds; } } } } } </code></pre> <p>Here's a sample class and Unit test:</p> <pre><code>public abstract class MyBaseModel : ICloneable { [DoNotCopyIntoTimeWindow] public int Id { get; set; } public short fk_TenantId { get; set; } [IsTimeWindowIdentifier] public byte TimeWindow { get; set; } [IsTimeWindowDate] public DateTime Date { get; set; } [IsProcessedIntoTimeWindow] public byte ActuallyAnEnum { get; set; } public abstract bool CalculatorOn { get; } public object Clone() { return this.MemberwiseClone(); } } public class MyModel : MyBaseModel { public short ShortId { get; set; } public short AnotherShortId { get; set; } [IsProcessedIntoTimeWindow] public decimal Value { get; set; } public override bool CalculatorOn { get { throw new NotImplementedException(); } } } [TestMethod] public void TestLowerResolution() { /* generate test data */ DateTime dateFrom = new DateTime(2018, 1, 28, 15, 0, 0, DateTimeKind.Utc); var dateTo = dateFrom.AddDays(1).AddSeconds(-1); var myValues = new List&lt;MyModel&gt;(); myValues.Add(new MyModel() { Date = new DateTime(2018, 1, 9, 15, 48, 46, DateTimeKind.Utc), ShortId = 5, AnotherShortId = 0, TimeWindow = 0, Value = 30, fk_TenantId = 1006 }); myValues.Add(new MyModel() { Date = new DateTime(2018, 1, 29, 10, 11, 31, DateTimeKind.Utc), ShortId = 5, AnotherShortId = 0, TimeWindow = 0, Value = 14336, fk_TenantId = 1006 }); myValues.Add(new MyModel() { Date = new DateTime(2018, 1, 29, 10, 11, 59, DateTimeKind.Utc), ShortId = 5, AnotherShortId = 0, TimeWindow = 0, Value = 30, fk_TenantId = 1006 }); var windows = TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myValues).ToList(); } </code></pre> <p><strong>EDIT:</strong> Updated code at <a href="https://codereview.stackexchange.com/questions/222505/performance-issue-with-empty-lists">Performance issue with empty lists</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:47:27.317", "Id": "429836", "Score": "3", "body": "Interesting question. You could make it easier for reviewers to follow, if you provide a simple working test case also showing the expected output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T11:54:00.483", "Id": "429842", "Score": "1", "body": "Thanks @HenrikHansen, I've just done so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:44:49.227", "Id": "429852", "Score": "0", "body": "Your code is hard to read because of the many lengthy lines. A couple of line-breaks would greatly improve its readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:57:44.473", "Id": "429856", "Score": "0", "body": "@t3chb0t, better now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:08:40.833", "Id": "429860", "Score": "0", "body": "mhmm... only a little" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:27:40.017", "Id": "429871", "Score": "0", "body": "@t3chb0t, re-ordered further." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:24:59.817", "Id": "429979", "Score": "0", "body": "@dfhwze, changed the `myValues` part, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:41:28.597", "Id": "429994", "Score": "1", "body": "Could you clarify this: _If I'm calculating the 5 minute time windows, and a state is true from 00:00:00 to 00:02:59 and false from 00:03:00 onwards_ - why isn't the sate valid until 00:04:59 which would be _almost_ 5 minutes but some other random number? Why do you just have 5, 15, and 60 steps instead of any number spanning between two timestamps? Why do you need all these attributes? It'd be much easier to use an interface and where the properties don't match it just create _dummy_ properties on your entities to map to the actual ones. I find this solution is currently super complex o_O" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:57:38.057", "Id": "429997", "Score": "0", "body": "@t3chb0t, I need these steps to reduce resolution. Typically, hundreds of thousands of rows could be retrieved and would need to be plotted onto a graph that is obviously going to be restricted by the amount of horizontal pixels on screen. The process is slow and in order to make it faster, depending on the timeframe required, I decide whether to SELECT those with TimeWindow=0, 5, 15 or 60. The graph looks virtually the same, and then you can zoom in to a section and it would get a lower resolution, perhaps TimeWindow=0 (the real data)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:59:10.037", "Id": "429998", "Score": "0", "body": "One thing I didn't add is that if 2 rows are the same, say an entity only has a boolean and it spends 2 hours in that state, it won't create an entry every 5 minutes for TimeWindow=5, but still one until the next 5 minute timeframe where the state changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:04:38.783", "Id": "430001", "Score": "0", "body": "I still doubt you need that much reflection. Could you add some of the real entities you are working with so that we have the full picture? Do they really all have different properties?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:09:46.753", "Id": "430002", "Score": "0", "body": "There's some 10 different entities, @t3chb0t, with an average of around 4 properties each (for which the TimeWindow needs to be calculated). The whole idea of using reflection was to avoid adding additional maintenance that needs to be done if a property is added or removed from an entity, apart from adding a custom attribute at most. It reduces the chance of a developer forgetting to need to do something else in another place. That's why reflection was used. And yes, all properties are different, and I'd rather not reveal the entities here because it's a bit sensitive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T15:32:56.367", "Id": "430024", "Score": "0", "body": "@MarkCiliaVincenti You don't need to reveal the entities, but the current trivial example is not clear. I hope you find a way to visualise how exactly you want the algorithm to slice data in time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T15:45:12.987", "Id": "430026", "Score": "0", "body": "@dfhwze let's say you're manually calculating a time window for 17:40 to 17:45. You check if there is an entry with the date exactly 17:40:00. If not, you check the one before that. Now you know that at 17:40:00 all properties would have been according to this entry. Now you check all DB rows until and including 17:44:59 and you build a dictionary with values of each property and the amount of seconds they spent with that value during this time window. It's a sort of popularity contest. The value with the highest amount of seconds for each property wins." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T15:55:30.983", "Id": "430033", "Score": "0", "body": "@MarkCiliaVincenti I understand what you want now, thanks. I would normally solve this with a view or stored procedure, but I can assert you only want a C# solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:10:25.237", "Id": "430039", "Score": "0", "body": "Yes @dfhwze, because despite me talking about entities and DB rows, they're actually items that have just been processed from something else and have not yet even been inserted in a database. When I insert, I insert not just the ones with TimeWindow=0 (the real data), but all of the time window data. So as such, this code is purely LINQ to objects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:39:30.290", "Id": "430285", "Score": "1", "body": "I went through your code and like you... I have absolutely no idea what you are doing there and why. There are so many classes, structs and properties and logic that you have not described that it is virtually incomprihensible without reverse-engineering it for a couple of hours. I wish you luck in optimizing it, you'll need a lot of it :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T18:33:04.113", "Id": "430303", "Score": "1", "body": "@t3chb0t I feel the same way. There is no beginning this task. Respect to the reviewers that take a shot at this. https://en.wikipedia.org/wiki/Sisyphus" } ]
[ { "body": "<p>I found something that looks really weird to me</p>\n\n<blockquote>\n<pre><code> for (i = 0; i &lt; dictionary.Dictionary.Count; i++)\n {\n maxValue = dictionary.Dictionary.First();\n for (j = 1; j &lt; dictionary.Dictionary.Count; j++)\n {\n var valuePair = dictionary.Dictionary.ElementAt(j);\n\n if (valuePair.Value &gt; maxValue.Value)\n maxValue = valuePair;\n }\n }\n var valToSet = maxValue.Key.Item;\n</code></pre>\n</blockquote>\n\n<p>This looks like it could be replaced with </p>\n\n<pre><code>var valToSet = dictionary.Values.Max();\n</code></pre>\n\n<p>if you are trying to get the key with the max value you could use this</p>\n\n<pre><code>var valToSet = dictionary.OrderByDescending(x =&gt; x.Value).First().Key;\n</code></pre>\n\n<p>found on <a href=\"https://stackoverflow.com/a/42508315/1214743\">https://stackoverflow.com/a/42508315/1214743</a> be sure to test around values that are the same.</p>\n\n<hr>\n\n<p>I also found something else that I would do differently as well</p>\n\n<blockquote>\n<pre><code> if (sameAsPrevious)\n {\n var prevVal = GetValue(prevTimeWindow, dictionary.Name);\n\n if (valToSet == null &amp;&amp; prevVal == null)\n { }\n else if ((valToSet == null &amp;&amp; prevVal != null) || (valToSet != null &amp;&amp; prevVal == null) || !valToSet.Equals(prevVal))\n sameAsPrevious = false;\n }\n</code></pre>\n</blockquote>\n\n<p>your if/else statement could be written like this:</p>\n\n<pre><code>if (valToSet == null &amp;&amp; prevVal == null)\n{ \n}\nelse\n{\n sameAsPrevious = (valToSet == preval);\n}\n</code></pre>\n\n<p>because</p>\n\n<ul>\n<li>if <code>valToSet</code> is null and the other has a value it won't be the same, it also works the other way around. This would make <code>sameAsPrevious == false</code></li>\n<li>if they are both null they get caught in the initial if statement</li>\n<li>if they are both have a value and it is the same we want the <code>sameAsPrevious</code> value to be <code>true</code> anyway. if <code>valToSet == preval</code> will set <code>sameAsPrevious</code> to true, which it should be in that situation.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T04:42:06.993", "Id": "430085", "Score": "3", "body": "I am sure you mean `!(valToSet != preval)` or `valToSet == preval`. Or what is `!(valToSet <> preval)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T08:22:29.503", "Id": "430102", "Score": "0", "body": "Cheers I'll run some tests on both today :)\n\nThat first part looks really weird to me too. I wrote the code over a year ago and to be honest I can't understand what I was doing there either, because it seems to me like there's an extra loop `for (i = 0; i < dictionary.Dictionary.Count; i++)` which seems like it's completely useless." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T08:53:01.843", "Id": "430105", "Score": "0", "body": "Also, I'm assuming that for the first part you meant `var valToSet = dictionary.Dictionary.Max().Key.Item;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T12:19:57.473", "Id": "430126", "Score": "2", "body": "_I can't understand what I was doing there either_ o_O so how can we? @MarkCiliaVincenti" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:24:28.583", "Id": "430133", "Score": "0", "body": "@t3chb0t :P :P :P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:29:33.940", "Id": "430139", "Score": "0", "body": "I implemented these two and did one process that generally takes practically 2 hours (with only part of this being the time window processing) and it took 1.1 hours instead, so I think this made a significant difference. However, I still don't understand why sometimes it takes 200ms and sometimes over 30 seconds, even though it had only some 12 rows to process!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:23:16.263", "Id": "430145", "Score": "0", "body": "@MarkCiliaVincenti, dictionaries hold `<key, value>` Pairs, and it appears the you want the max value out of the dictionary, if that is the case, then the key doesn't really matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:25:54.477", "Id": "430147", "Score": "1", "body": "@dfhwze, thank you for pointing that out, I put the not equals from SQL in there and see what you mean...oops. it is fixed now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:44:12.287", "Id": "430150", "Score": "0", "body": "@Malachi I have an issue getting your first change to work actually. The only code I can see is the one that is commented out in my code, but I would usually comment something out because it wasn't working properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:47:26.343", "Id": "430151", "Score": "0", "body": "When I get back to my laptop I will edit the past. You still need the foreach (var dictionary in dictionaries) unless you are setting the valToSet variable to a key, value pair, then you would need to grab the pair for the max value" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:38:56.083", "Id": "430676", "Score": "0", "body": "Gentle reminder @Malachi" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T20:24:26.460", "Id": "430846", "Score": "0", "body": "@MarkCiliaVincenti I am not sure what you mean. what isn't working? I edited my answer. the `foreach` wasn't part of my review, the nested `for` loops were part of my review. what isn't working, what error are you getting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T07:22:38.243", "Id": "430890", "Score": "0", "body": "@Malachi, there is no property `.maxValue()` on a Dictionary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T17:43:48.083", "Id": "431077", "Score": "0", "body": "@MarkCiliaVincenti, I cannot find where I saw the usage so I will edit my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T07:39:22.883", "Id": "431158", "Score": "0", "body": "@Malachi, valToSet is not supposed to be set to the dictionary value (which is a count) but to the inner item of the dictionary key. It's of type dynamic. I previously had `var valToSet = dictionary.Dictionary.FirstOrDefault(x => x.Value.Equals(dictionary.Dictionary.Values.Max())).Key.Item;` but for some reason it wasn't working as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T09:49:26.833", "Id": "431170", "Score": "0", "body": "@Malachi, I shortened it to `var valToSet = dictionary.Dictionary.Aggregate((l, r) => l.Value > r.Value ? l : r).Key.Item;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T12:35:22.313", "Id": "431189", "Score": "0", "body": "So you want the key of the highest value?" } ], "meta_data": { "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:41:18.887", "Id": "222246", "ParentId": "222072", "Score": "4" } }, { "body": "<blockquote>\n<pre><code> var firstDate = (DateTime)datePropertyInfo.GetValue(stateModels.First());\n\n if (firstDate &lt; dateFrom)\n dateFrom = new DateTime(firstDate.Year, firstDate.Month, firstDate.Day, firstDate.Hour, 0, 0, DateTimeKind.Utc);\n</code></pre>\n</blockquote>\n\n<p>You take the first stateModel, but what if they are not ordered by date?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>for (itemPointer = itemPointer; itemPointer &lt; stateModels.Count(); itemPointer++)\n</code></pre>\n</blockquote>\n\n<p><code>itemPointer = itemPointer</code> isn't neccesary:</p>\n\n<pre><code>for (; itemPointer &lt; stateModels.Count(); itemPointer++)\n</code></pre>\n\n<hr>\n\n<p>The last parameter to <code>CalculateTimeWindow&lt;T&gt;(..., ..., int i)</code> is initialized with the <code>out int i</code> parameter from <code>GetPropertiesAndDictionaries()</code>, but the values is actually not used and <code>i</code> is used as an iterator index set to <code>0</code> the first time used, so why have it as a parameter and not just a local variable? Get rid of that, if it's not used.</p>\n\n<hr>\n\n<p>This:</p>\n\n<pre><code> public static IEnumerable&lt;T&gt; CalculateTimeWindows&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels) where T : new()\n {\n if (stateModels.Count() == 0)\n return new List&lt;T&gt;();\n\n dateFrom = GetPropertiesAndDictionaries(dateFrom, stateModels, out PropertyInfo datePropertyInfo, out List&lt;PropertyInfo&gt; copyProperties, out PropertyInfo timeWindowIdentifier, out int size, out TimeWindowDictionary[] dictionaries, out int i);\n\n return CalculateTimeWindow(dateFrom, dateTo, stateModels, 5, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i)\n .Concat(CalculateTimeWindow(dateFrom, dateTo, stateModels, 15, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i))\n .Concat(CalculateTimeWindow(dateFrom, dateTo, stateModels, 60, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i));\n }\n</code></pre>\n\n<p>I would write as:</p>\n\n<pre><code> public static IEnumerable&lt;T&gt; CalculateTimeWindows&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels) where T : new()\n {\n if (stateModels == null || stateModels.Count() == 0)\n yield break; // return new List&lt;T&gt;();\n\n dateFrom = GetPropertiesAndDictionaries(\n dateFrom, \n stateModels, \n out PropertyInfo datePropertyInfo, \n out List&lt;PropertyInfo&gt; copyProperties, \n out PropertyInfo timeWindowIdentifier, \n out int size, \n out TimeWindowDictionary[] dictionaries, \n out int i);\n\n byte[] windowDurations = { 5, 15, 60 };\n\n foreach (byte duration in windowDurations)\n {\n foreach (T result in CalculateTimeWindow(dateFrom, dateTo, stateModels, duration, datePropertyInfo, copyProperties, timeWindowIdentifier, size, dictionaries, i))\n {\n yield return result;\n }\n }\n</code></pre>\n\n<p>or as: </p>\n\n<pre><code> public static IEnumerable&lt;T&gt; CalculateTimeWindows&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels) where T : new()\n {\n if (stateModels.Count() == 0)\n return new List&lt;T&gt;();\n\n dateFrom = GetPropertiesAndDictionaries(\n dateFrom,\n stateModels,\n out PropertyInfo datePropertyInfo,\n out List&lt;PropertyInfo&gt; copyProperties,\n out PropertyInfo timeWindowIdentifier,\n out int size,\n out TimeWindowDictionary[] dictionaries,\n out int i);\n\n byte[] windowDurations = { 5, 15, 60 };\n\n return windowDurations.SelectMany(wd =&gt;\n CalculateTimeWindow(\n dateFrom,\n dateTo,\n stateModels,\n wd,\n datePropertyInfo,\n copyProperties,\n timeWindowIdentifier,\n size,\n dictionaries,\n i));\n }\n</code></pre>\n\n<p>It is much more readable and easy to maintain if you want to add a new time window.</p>\n\n<hr>\n\n<pre><code> copyProperties = propInfos\n .Where(\n p =&gt; \n !p.GetCustomAttributes(typeof(IsTimeWindowIdentifier), true).Any() \n &amp;&amp; !p.GetCustomAttributes(typeof(DoNotCopyIntoTimeWindow), true).Any() \n &amp;&amp; !p.GetCustomAttributes(typeof(IsTimeWindowDate), true).Any() \n &amp;&amp; !p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any() \n &amp;&amp; p.CanWrite \n &amp;&amp; !p.GetMethod.IsVirtual).ToList();\n</code></pre>\n\n<p>In the above you determine which properties to fetch data from in a negative way by checking what they are not. I think, I would define a <code>ValuePropertyAttribute</code> to mark the properties to get data from with. It is easier to maintain, because you'll always be able to see from this attribute which properties values are copied from on an object.</p>\n\n<hr>\n\n<p>When handling properties (setting and getting) there is a little too much conversion between <code>PropertyInfo</code>s and <code>string</code>s (names) IMO.</p>\n\n<p>You can reduce that by changing the definition of:</p>\n\n<pre><code> public struct TimeWindowDictionary\n {\n public string Name { get; set; }\n public Dictionary&lt;NullObject&lt;dynamic&gt;, int&gt; Dictionary { get; set; }\n }\n</code></pre>\n\n<p>to </p>\n\n<pre><code> public struct TimeWindowDictionary\n {\n public PropertyInfo PropertyInfo { get; set; }\n public Dictionary&lt;NullObject&lt;dynamic&gt;, int&gt; Dictionary { get; set; }\n }\n</code></pre>\n\n<p>and then change everything to accomodate to that - for instance:</p>\n\n<pre><code> var properties = propInfos.Where(p =&gt; p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any()).Select(x =&gt; x.Name);\n size = properties.Count();\n\n dictionaries = new TimeWindowDictionary[size];\n i = 0;\n\n foreach (var property in properties)\n {\n dictionaries[i] = new TimeWindowDictionary() { Name = property };\n i++;\n }\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code> dictionaries =\n propInfos\n .Where(p =&gt; p.GetCustomAttributes(typeof(IsProcessedIntoTimeWindow), true).Any())\n .Select(p =&gt; new TimeWindowDictionary { PropertyInfo = p })\n .ToArray();\n\n size = dictionaries.Length;\n</code></pre>\n\n<p>and <code>GetValue(...)</code> could be:</p>\n\n<pre><code> private static dynamic GetValue(object inputObject, PropertyInfo propertyInfo)\n {\n return propertyInfo.GetValue(inputObject);\n //Type type = inputObject.GetType();\n //System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyName);\n //return propertyInfo.GetValue(inputObject);\n }\n</code></pre>\n\n<p>and <code>SetValue(...)</code> could likewise have the signature:</p>\n\n<pre><code> private static void SetValue(object inputObject, PropertyInfo propertyInfo, object propertyVal)\n</code></pre>\n\n<p>and in <code>CalculateStateSeconds&lt;T&gt;(...)</code>:</p>\n\n<pre><code> //PropertyInfo propertyInfo = tType.GetProperty(dictionary.Name);\n var key = dictionary.PropertyInfo.GetValue(prevItem);\n dictionary.Dictionary.TryGetValue(key, out int existingSeconds);\n dictionary.Dictionary[key] = existingSeconds + seconds;\n</code></pre>\n\n<hr>\n\n<pre><code> private static DateTime GetPropertiesAndDictionaries&lt;T&gt;(\n DateTime dateFrom,\n List&lt;T&gt; stateModels,\n out PropertyInfo datePropertyInfo,\n out List&lt;PropertyInfo&gt; copyProperties,\n out PropertyInfo timeWindowIdentifier,\n out int size,\n out TimeWindowDictionary[] dictionaries,\n out int i) where T : new()\n {\n</code></pre>\n\n<p>When having all these arguments passed from method to method, I think I would make a container object for them and pass that instead. Alternatively you could make the class statefull with these parameters as members instead, so you can avoid having arguments to the methods at all. The methods should then be non static members of course. Your one and only static method could then be something like:</p>\n\n<pre><code> public static IEnumerable&lt;T&gt; GetTimeWindows&lt;T&gt;(DateTime dateFrom, DateTime dateTo, List&lt;T&gt; stateModels) where T : new()\n {\n TimeWindow timeWindow = new TimeWindow(dateFrom, dateTo, stateModels);\n return timeWindow.Calculate();\n }\n</code></pre>\n\n<p>where the <code>TimeWindow</code> class should have an appropriate generric type parameter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:20:04.517", "Id": "430131", "Score": "1", "body": "Wow thanks! I'll go through them one by one but I have an answer to your first question. _You take the first stateModel, but what if they are not ordered by date?_ Good observation, but I am sure that they are sorted by date, so (purely) for optimization purposes I'm not re-checking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:25:50.217", "Id": "430146", "Score": "1", "body": "I'm going to be testing your changes. One thing I'm going to add right afterwards (after I've taken benchmarks) is to store the properties in a singleton dictionary where the key is the Type, such that getting the properties through reflection happens only once for each entity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:34:47.440", "Id": "430148", "Score": "0", "body": "@MarkCiliaVincenti: Sound good, if I understand you right. When done, you could consider to post an self-answer, with the updated code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:53:25.723", "Id": "430153", "Score": "0", "body": "Ah that's what you usually do? I was going to edit my original post. OK." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:16:19.497", "Id": "430158", "Score": "2", "body": "@MarkCiliaVincenti: Yes, It's done now and then that way. On the other hand you are not allowed to edit the question, when answers are posted, because that would invalidate them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T14:53:19.297", "Id": "430575", "Score": "0", "body": "I'll post my code soon, as soon as I fix an issue. I can't understand why I am calling the method in this way: `myList.AddRange(TimeWindow.CalculateTimeWindows(dateFrom, dateTo, myList).ToList());` where myList would be an empty list, and I'd have 16 lines like this (for different lists, all of which are empty), and the code is taking approximately 4.5 seconds to run, despite that I have this: `if (stateModels.Count() == 0) return new List<T>();` at the very top of the `CalculateTimeWindows` method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:02:45.990", "Id": "430604", "Score": "0", "body": "@MarkCiliaVincenti: I can't tell you what the problem is with empty lists. I sounds strange. But I think, if the gap between dateFrom and dateTo is too large it will slow the calculations drastically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:51:24.693", "Id": "430616", "Score": "0", "body": "the gap between dateFrom and dateTo is always 24 hours, and in this case (empty lists) should not make a difference." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T12:12:12.443", "Id": "222277", "ParentId": "222072", "Score": "4" } }, { "body": "<h2>Alternative approach</h2>\n\n<p>Instead of using attributes and reflection, I'd go for a set of generic methods that take type-specific date and value-selector methods as parameters.</p>\n\n<p>First, a method that returns items grouped by time segment:</p>\n\n<pre><code>public static IEnumerable&lt;TimeSegmentItems&lt;T&gt;&gt; GetItemsPerTimeSegment(\n IEnumerable&lt;T&gt; items,\n DateTime from,\n DateTime to,\n TimeSpan segmentDuration,\n Func&lt;T, DateTime&gt; getTimestamp) { ... }\n\n// Contains all items within a given time segment,\n// as well as the last item from the preceding time segment\n// (that item determines the initial state):\npublic class TimeSegmentItems&lt;T&gt;\n{\n public DateTime Start { get; }\n public DateTime End { get; }\n public IEnumerable&lt;T&gt; Items { get; }\n}\n</code></pre>\n\n<p>Then, a utility method for obtaining the dominant value for a given time segment:</p>\n\n<pre><code>public static TValue GetDominantValue&lt;TItem, TValue&gt;(\n IEnumerable&lt;TItem&gt; items,\n DateTime from,\n DateTime to,\n Func&lt;TItem, DateTime&gt; getTimestamp,\n Func&lt;TItem, TValue&gt; getValue) { ... }\n</code></pre>\n\n<p>Together, they allow you to do the following:</p>\n\n<pre><code>GetItemsPerTimeSegment(myValues, fromDate, toDate, TimeSpan.FromMinutes(5), m =&gt; m.Date)\n .Select(segment =&gt; new MyModel {\n Value = GetDominantValue(segment.Items, segment.Start, segment.End, m =&gt; m.Date, m =&gt; m.Value),\n ActuallyAnEnum = GetDominantValue(segment.Items, segment.Start, segment.End, m =&gt; m.Date, m =&gt; m.ActuallyAnEnum),\n });\n</code></pre>\n\n<p>Which can further be streamlined, but that's the gist of it.</p>\n\n<h2>Comparison</h2>\n\n<p>Comparing this to your original approach:</p>\n\n<ul>\n<li>Reflection and <code>dynamic</code> are both relatively slow, and especially with <code>dynamic</code> you lose compile-time checking. This approach should be more succinct, more robust and (much) faster.</li>\n<li>With attributes, you are limited to types that you can add attributes to. This approach lets you work with any type, and even create different 'views' for the same type, at the cost of having to write type-specific logic (the date and value selectors, and the final result-building code).</li>\n<li>Instead of a single public method that does everything, these utility methods each focus on a specific task, which makes them more reusable. You can swap the dominant-value logic for average-value logic without having to touch the time-segment grouping logic. You can also build an attribute/reflection-based layer on top of this that removes the need for type-specific code, if necessary.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T18:35:25.630", "Id": "430304", "Score": "0", "body": "I would also focus on an alternative than to analyse the OP's code for refactoring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:54:41.320", "Id": "430684", "Score": "0", "body": "It depends. If you want to include another property then yes, you'll need to add a `GetDominantValue` call for that - similar to how, with your approach, you'd need to add an attribute to that property. If you rename a property or change its type then no manual changes are required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:55:05.863", "Id": "430685", "Score": "0", "body": "Interesting, but I'm not sure I understand. I have fixed the problems with reflection (I think) by storing the results in a concurrent dictionary (code posted at https://codereview.stackexchange.com/questions/222505/performance-issue-with-empty-lists). What I don't understand with your solution is whether or not I would need to edit some code whenever the database models change. That was the idea behind using reflection, to avoid problems with developers forgetting to also do changes elsewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T07:58:05.480", "Id": "430687", "Score": "0", "body": "I see @PieterWitvoet, thanks, I'll give it some thought, though to be honest I still think it's more difficult for myself and colleagues to forget making a call to `GetDominantValue` than adding an attribute to a property given that all the lines above and below it would have attributes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T08:25:38.390", "Id": "430694", "Score": "1", "body": "That makes sense. As I said, you can still put an attribute-based layer on top of these methods if necessary. You'd still benefit from a better separation of concerns." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T18:23:45.530", "Id": "222368", "ParentId": "222072", "Score": "5" } } ]
{ "AcceptedAnswerId": "222277", "CommentCount": "18", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T10:06:54.083", "Id": "222072", "Score": "6", "Tags": [ "c#", "performance", "generics", "reflection", "interval" ], "Title": "Calculating time windows for entities" }
222072
<p>Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.</p> <p>The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. <a href="https://i.stack.imgur.com/ZNqrV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZNqrV.png" alt="enter image description here"></a></p> <pre><code>Example: Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 </code></pre> <p>Please review for performance.</p> <pre><code>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/trapping-rain-water/ /// &lt;/summary&gt; [TestClass] public class TrappingRainWater { [TestMethod] public void TestMethod1() { int[] height = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; Assert.AreEqual(6, Trap(height)); } public int Trap(int[] height) { int left = 0; int right = height.Length - 1; int ans = 0; int leftMax = 0; int rightMax = 0; while (left &lt; right) { if (height[left] &lt; height[right]) { //if height left &lt; left max that means we can trap water if (height[left] &lt; leftMax) { ans += leftMax - height[left]; } else // otherwise left max needs to be updated { leftMax = height[left]; } left++; } else { if (height[right] &lt; rightMax) { ans += rightMax - height[right]; } else { rightMax = height[right]; } right--; } } return ans; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:15:44.183", "Id": "429702", "Score": "2", "body": "Seems perfect to me, O(1), only 2 quick if statements per iteration, minimal math." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:24:37.150", "Id": "429707", "Score": "2", "body": "correction: O(n)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T10:48:11.043", "Id": "222077", "Score": "2", "Tags": [ "c#", "programming-challenge", "array" ], "Title": "LeetCode: trapping rain water C#" }
222077
<p>Please review performance</p> <p><a href="https://leetcode.com/problems/transpose-matrix/" rel="nofollow noreferrer">https://leetcode.com/problems/transpose-matrix/</a></p> <blockquote> <p>Given a matrix A, return the transpose of A.</p> <p>The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.</p> <p>Example 1:</p> <p>Input: [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]]</p> <p>Example 2:</p> <p>Input: [[1,2,3],[4,5,6]] Output: [[1,4],[2,5],[3,6]]</p> <p>Note:</p> <p>1 &lt;= A.length &lt;= 1000 1 &lt;= A[0].length &lt;= 1000</p> </blockquote> <pre><code>using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { [TestClass] public class TransposeMatrix { /// &lt;summary&gt; /// 1 2 3 1 4 7 /// 4 5 6 2 5 8 /// 7 8 9 3 6 9 /// &lt;/summary&gt; [TestMethod] public void Transpose3X3() { int[][] matrix = { new[] { 1, 2, 3 }, new[] { 4, 5, 6 }, new[] { 7, 8, 9 } }; int[][] expected = { new[] { 1, 4, 7 }, new[] { 2, 5, 8 }, new[] { 3, 6, 9 } }; int[][] output = Transpose(matrix); for (int i = 0; i &lt; output.GetLength(0); i++) { CollectionAssert.AreEqual(expected[i], output[i]); } } [TestMethod] public void Transpose2X3() { int[][] matrix = { new[] { 1, 2, 3 }, new[] { 4, 5, 6 } }; int[][] expected = { new[] { 1, 4 }, new[] { 2, 5 }, new[] { 3, 6} }; int[][] output = Transpose(matrix); for (int i = 0; i &lt; output.GetLength(0); i++) { CollectionAssert.AreEqual(expected[i], output[i]); } } public int[][] Transpose(int[][] A) { int h = A.GetLength(0); int w = A[0].GetLength(0); //we need to allocate the matrix as transposed already //for example 2x3 should allocate 3x2 int[][] res = new int[w][]; for (int i = 0; i &lt; w; i++) { res[i] = new int[h]; } for (int r = 0; r &lt; h; r++) { for (int c = 0; c &lt; w; c++) { res[c][r] = A[r][c]; } } return res; } } } </code></pre>
[]
[ { "body": "<p>You iterate through the same array twice (once while initializing and once while assigning values), you can do both inside the same loop.</p>\n\n<pre><code>for (int i = 0; i &lt; w; i++)\n{\n res[i] = new int[h];\n for (int j = 0; j &lt; h; j++)\n {\n res[i][j] = A[j][i];\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T14:11:18.243", "Id": "222090", "ParentId": "222078", "Score": "6" } } ]
{ "AcceptedAnswerId": "222090", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T11:26:30.047", "Id": "222078", "Score": "3", "Tags": [ "c#", "performance", "programming-challenge", "array", "matrix" ], "Title": "LeetCode: Transpose Matrix C#" }
222078
<p>I have an asp.net web api and I would like to use basic authentication. Is there any way to make this loosely coupled? I tried constructor DI but I couldn't figure it out how to pass Dbcontext into WebApiConfig.</p> <p>Here is my Interface:</p> <pre><code>public interface IUserValidate { bool Login(string username, string password); } </code></pre> <p>Here is my class:</p> <pre><code>public class UserValidate : IUserValidate { //This method is used to check the user credentials public bool Login(string username, string password) { using (var context = new EPINMiddleWareAPIContext()) { return context.Companies.Any(user =&gt; user.userName.Equals(username, StringComparison.OrdinalIgnoreCase) &amp;&amp; user.password == password); } } } </code></pre> <p>Here is my Basic Authentication Filter:</p> <pre><code>public class BasicAuthenticationAttribute : AuthorizationFilterAttribute { private const string Realm = "My Realm"; public override void OnAuthorization(HttpActionContext actionContext) { //If the Authorization header is empty or null //then return Unauthorized if (actionContext.Request.Headers.Authorization == null) { actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized); // If the request was unauthorized, add the WWW-Authenticate header // to the response which indicates that it require basic authentication if (actionContext.Response.StatusCode == HttpStatusCode.Unauthorized) { actionContext.Response.Headers.Add("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", Realm)); } } else { //Get the authentication token from the request header string authenticationToken = actionContext.Request.Headers .Authorization.Parameter; //Decode the string string decodedAuthenticationToken = Encoding.UTF8.GetString( Convert.FromBase64String(authenticationToken)); //Convert the string into an string array string[] usernamePasswordArray = decodedAuthenticationToken.Split(':'); //First element of the array is the username string username = usernamePasswordArray[0]; //Second element of the array is the password string password = usernamePasswordArray[1]; //call the login method to check the username and password UserValidate uv = new UserValidate(); if (uv.Login(username, password)) { var identity = new GenericIdentity(username); IPrincipal principal = new GenericPrincipal(identity, null); Thread.CurrentPrincipal = principal; if (HttpContext.Current != null) { HttpContext.Current.User = principal; } } else { actionContext.Response = actionContext.Request .CreateResponse(HttpStatusCode.Unauthorized); } } } } </code></pre> <p>Here is my WebApiConfig:</p> <pre><code>public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services config.Filters.Add(new BasicAuthenticationAttribute()); // Web API routes config.MapHttpAttributeRoutes(); //Registering GlobalExceptionHandler config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); //Registering UnhandledExceptionLogger config.Services.Replace(typeof(IExceptionLogger), new UnhandledExceptionLogger()); //Registering RequestResponseHandler config.MessageHandlers.Add(new RequestResponseHandler()); //Validate Token //config.MessageHandlers.Add(new TokenValidationHandler()); //Registering CustomExceptionFilter config.Filters.Add(new CustomExceptionFilter()); } } </code></pre> <p>Here is my Dbcontext:</p> <pre><code>public class EPINMiddleWareAPIContext : DbContext { public EPINMiddleWareAPIContext() : base("name=EPINMiddleWareAPIContext") { } public DbSet&lt;InitiateRequest&gt; InitiateRequests { get; set; } public DbSet&lt;InitiateResponse&gt; InitiateResponses { get; set; } public DbSet&lt;Company&gt; Companies { get; set; } public DbSet&lt;ConfirmRequest&gt; ConfirmRequests { get; set; } public DbSet&lt;ConfirmResponse&gt; ConfirmResponses { get; set; } public DbSet&lt;GameBank&gt; GameBanks { get; set; } public DbSet&lt;GameCouponBank&gt; GameCouponBanks { get; set; } } </code></pre> <p>Here is my Ninject Web Common:</p> <pre><code>using EPINMiddleWareAPI.Controllers; [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(EPINMiddleWareAPI.App_Start.NinjectWebCommon), "Start")] [assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(EPINMiddleWareAPI.App_Start.NinjectWebCommon), "Stop")] namespace EPINMiddleWareAPI.App_Start { using System; using System.Web; using Microsoft.Web.Infrastructure.DynamicModuleHelper; using Ninject; using Ninject.Web.Common; using Models; using Ninject.Web.Common.WebHost; public static class NinjectWebCommon { private static readonly Bootstrapper bootstrapper = new Bootstrapper(); /// &lt;summary&gt; /// Starts the application /// &lt;/summary&gt; public static void Start() { DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule)); DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule)); bootstrapper.Initialize(CreateKernel); } /// &lt;summary&gt; /// Stops the application. /// &lt;/summary&gt; public static void Stop() { bootstrapper.ShutDown(); } /// &lt;summary&gt; /// Creates the kernel that will manage your application. /// &lt;/summary&gt; /// &lt;returns&gt;The created kernel.&lt;/returns&gt; private static IKernel CreateKernel() { var kernel = new StandardKernel(); try { kernel.Bind&lt;Func&lt;IKernel&gt;&gt;().ToMethod(ctx =&gt; () =&gt; new Bootstrapper().Kernel); kernel.Bind&lt;IHttpModule&gt;().To&lt;HttpApplicationInitializationHttpModule&gt;(); RegisterServices(kernel); return kernel; } catch { kernel.Dispose(); throw; } } /// &lt;summary&gt; /// Load your modules or register your services here! /// &lt;/summary&gt; /// &lt;param name="kernel"&gt;The kernel.&lt;/param&gt; private static void RegisterServices(IKernel kernel) { kernel.Bind&lt;EPINMiddleWareAPIContext&gt;().ToSelf().InRequestScope(); } } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T11:32:35.730", "Id": "222079", "Score": "1", "Tags": [ "c#", "dependency-injection", "asp.net-web-api", "ninject" ], "Title": "Tightly coupled Basic Authentication Filter" }
222079
<p>In my effort to learn Rust I've tried implementing an Iterator that splits up a buffer in two halves, and correlates both halves by sliding them over each other with different positions (lags). You could use this e.g. to do autocorrelation, given a correlation function between two buffers (dot product for example).</p> <p>I'm fairly new to Rust (coming from a C++ background), so any and all advice is welcome. Specifically to lifetimes, generics and idiomatic usage of Rust.</p> <p>Also, should I turn this into an iterator adapter that takes an iterator and collects the data in an internal Vec? Would that cover a wider array of input?</p> <pre class="lang-rust prettyprint-override"><code>pub struct Slide&lt;'a, T, F&gt; { items: &amp;'a [T], func: F, lag: usize, } impl&lt;'a, T, F&gt; Slide&lt;'a, T, F&gt; { pub fn new&lt;Out&gt;(items: &amp;'a [T], func: F) -&gt; Slide&lt;'a, T, F&gt; where F: Fn(&amp;'a [T], &amp;'a [T]) -&gt; Out, { Slide { items, func, lag: 0, } } } impl&lt;'a, T, F, Out&gt; Iterator for Slide&lt;'a, T, F&gt; where F: Fn(&amp;[T], &amp;[T]) -&gt; Out, { type Item = Out; fn next(&amp;mut self) -&gt; Option&lt;Out&gt; { let half_length = self.items.len() / 2; if self.lag &lt; half_length { let y = (self.func)( &amp;self.items[0..half_length], &amp;self.items[self.lag..self.lag + half_length], ); self.lag += 1; Some(y) } else { None } } } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T12:08:30.797", "Id": "222081", "Score": "3", "Tags": [ "beginner", "rust", "iterator" ], "Title": "Rust Iterator that correlates a slice with itself" }
222081
<p>I have a very simple component, which should be styled differently based on the passed condition. </p> <p>I wonder if there is a better approach to refactor this piece of code?</p> <pre><code>function RandomComponent({ number, condition }) { let classNameToUse; switch (condition) { case 'high': classNameToUse = 'number number--high'; break; case 'medium': classNameToUse = 'number number--medium'; break; default: classNameToUse = 'number'; } return &lt;div className={classNameToUse}&gt;{number}&lt;/div&gt;; } </code></pre>
[]
[ { "body": "<p>if you're just trying to decide between <code>number--high</code> <code>number--medium</code> or <code>''</code> based on the <code>condition</code> variable, then just make a helper function that does that</p>\n\n<p>then do <code>return &lt;div className={\"number \" + getNumberClass(condition)}}&gt;{number}&lt;/div&gt;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:53:26.447", "Id": "429714", "Score": "0", "body": "Thanks, yeah I guess the best thing to do is to extract the selection into a separate function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:50:30.020", "Id": "222087", "ParentId": "222085", "Score": "4" } } ]
{ "AcceptedAnswerId": "222087", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:38:16.127", "Id": "222085", "Score": "1", "Tags": [ "react.js", "jsx" ], "Title": "Different class name based on condition in React" }
222085
<p>I wrote a simple program, that will make a string 'noisy' if the clipboard contains one. What disappoints me, is that I should manually check what I got from <code>getClipboardString</code> — in the <code>Nothing</code> case, we simply return from program, otherwise we modify the string. Is there a better way to do this kind of check?</p> <pre class="lang-hs prettyprint-override"><code>import Data.Char (toUpper) import System.Random (randomIO) import System.Clipboard (setClipboardString, getClipboardString) import Control.Monad (join) main :: IO () main = do join $ fmap (test doNoise) getClipboardString where test :: (String -&gt; IO ()) -&gt; (Maybe String) -&gt; IO () test _ Nothing = return () test f (Just s) = f s doNoise :: String -&gt; IO () doNoise s = do capsed &lt;- (sequence $ map randCap s) setClipboardString capsed randCap :: Char -&gt; IO Char randCap x = fmap ($ x) $ fmap choice (randomIO :: IO Bool) choice :: Bool -&gt; (Char -&gt; Char) choice x = if x then toUpper else id </code></pre>
[]
[ { "body": "<pre><code>main :: IO ()\nmain = traverse_ doNoise =&lt;&lt; getClipboardString where\n doNoise = setClipboardString &lt;=&lt; traverse randCap\n randCap x = bool id toUpper &lt;$&gt; (randomIO :: IO Bool) &lt;*&gt; pure x\n</code></pre>\n\n<p>Edit: Each change was arrived at through pattern-matching from my experience; compact code is usually easier to work with further. Looking at this again makes me think there ought to be a more <code>lens</code>y solution, one that fuses getting and setting, and indeed:</p>\n\n<pre><code>main = modifyClipboardString =&lt;&lt;\n zipWith (bool id toUpper) &lt;$&gt; getRandoms\n</code></pre>\n\n<p>We are fortunate to not actually need side effects depending on clipboard contents, but if we did, I would recommend writing a monadic variant of <code>modifyClipboardString</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:26:17.827", "Id": "429764", "Score": "2", "body": "That's a compact solution :) Could you elaborate how you got to this and how it's better than the original code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:26:24.157", "Id": "429765", "Score": "4", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/a/8404/120114)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T05:59:13.890", "Id": "429812", "Score": "0", "body": "Some thoughts that I have:\nfirst, that I should use hoogle more thoroughly (I didn't know of `traverse`, `traverse_` and `bool`); second, that I should read my code more closely, because I missed `join $ fmap == (=<<)`. Anyway, elegant solution, will upvote later, not enough rep right now" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:08:56.850", "Id": "222102", "ParentId": "222086", "Score": "0" } } ]
{ "AcceptedAnswerId": "222102", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T13:47:11.273", "Id": "222086", "Score": "3", "Tags": [ "haskell" ], "Title": "Modifying a random String stored in the clipboard" }
222086
<p>I created a simple script that implements log rotation. It checks the log file size (say, <code>out.log</code>) if it exceeds 5MB limit. If it does then the script copies it to <code>out1.log</code> and clears <code>out.log</code>. But it also copies <code>out1.log</code> to <code>out2.log</code>, etc. So log files are kind of 'shifted' and contents of the last one is discarded. In this implementation I keep only 5 files (initial <code>out.log</code> and <code>out[1-4].log</code>). </p> <p>I am not a Python programmer, although I find this language extremely useful for such kinds of tasks. I would like my code to be as much idiomatic as possible, so what can I change/improve in my script for this?</p> <pre><code>from os import listdir from os.path import getsize, exists from shutil import copyfile from argparse import ArgumentParser SIZE_5MB = 5e6 MAX_LOG_FILES_COUNT = 5 class LogRotator(object): def __init__(self, prefix, suffix): self.prefix = prefix self.suffix = suffix def __str__(self): return "{}[x].{}".format(self.suffix, self.prefix) def __touch(self, file_name): open(file_name, 'w').close() def rotate(self): files = ["{}{}.{}".format(self.prefix, x + 1, self.suffix) for x in range(MAX_LOG_FILES_COUNT)] [self.__touch(f) for f in files if not exists(f)] current_log = "{}.{}".format(self.prefix, self.suffix) if (getsize(current_log) &lt; SIZE_5MB): return files.insert(0, current_log) for i in range(len(files) - 1, 0, -1): copyfile(files[i-1], files[i]) self.__touch(files[0]) if __name__ == '__main__': parser = ArgumentParser(description="Rotate log files") parser.add_argument("-prefix", help="log file prefix") parser.add_argument("-suffix", help="log file suffix") args = parser.parse_args() logRotator = LogRotator(args.prefix, args.suffix) logRotator.rotate() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T14:35:13.737", "Id": "429719", "Score": "0", "body": "Could you add a short description on what this does. From my understanding of your code it finds a log that is <5mb and overwrites all files with `{self.prefix}5.{suffix}`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T14:36:27.120", "Id": "429720", "Score": "1", "body": "@Peilonrayz yes, sure" } ]
[ { "body": "<ol>\n<li>Return early, there's no need to touch files if the current file is &lt;5mb.</li>\n<li>DRY your code, move the <code>\"{}{}.{}\".format</code> into it's own function.</li>\n<li>Don't use comprehensions for mutations. Use an explicit <code>for</code> loop for that.</li>\n<li><p>As you want idiomatic code, you should be aware that some people discourage the use of <code>__</code> as it performs name mangling.</p>\n\n<p>If the function is intended to be private, not protected, then it should be ok.</p></li>\n<li>You can use the <code>pairwise</code> recipe to make the reversed pairwise loop. I think it's more readable, however you may not.</li>\n<li>It's unidiomatic to put brackets on if statements. Unless the statement spans multiple lines.</li>\n<li>It's idiomatic to put two newlines around top level classes and functions.</li>\n<li>I'm a bit confused why you want to touch everything.</li>\n<li>You may want to split all the different aspects of <code>rotate</code> into smaller functions to follow SRP.</li>\n</ol>\n\n<p>Your code's pretty idiomatic otherwise, your naming conventions are good, you've used a main guard and you've got white space where it should be.</p>\n\n<pre><code>from os import listdir\nfrom os.path import getsize, exists\nfrom shutil import copyfile\nfrom argparse import ArgumentParser\nimport itertools\n\n\ndef pairwise(iterable):\n \"s -&gt; (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\nSIZE_5MB = 5e6\nMAX_LOG_FILES_COUNT = 5\n\n\nclass LogRotator(object):\n def __init__(self, prefix, suffix):\n self.prefix = prefix\n self.suffix = suffix\n\n def __str__(self):\n return \"{}[x].{}\".format(self.suffix, self.prefix)\n\n def __touch(self, file_name):\n open(file_name, 'w').close()\n\n def _gen_file_name(self, name):\n return \"{}{}.{}\".format(self.prefix, name, self.suffix)\n\n def rotate(self):\n current_log = self._gen_file_name('')\n if getsize(current_log) &lt; SIZE_5MB:\n return\n\n files = [\n self._gen_file_name(i)\n for i in range(1, MAX_LOG_FILES_COUNT + 1)\n ]\n\n for file in files:\n if not exests(file):\n self.__touch(f)\n\n for older, newer in pairwise(reversed([current_log] + files)):\n copyfile(newer, older)\n\n self.__touch(current_log)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser(description=\"Rotate log files\")\n parser.add_argument(\"-prefix\", help=\"log file prefix\")\n parser.add_argument(\"-suffix\", help=\"log file suffix\")\n\n args = parser.parse_args()\n\n log_rotator = LogRotator(args.prefix, args.suffix)\n log_rotator.rotate()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:17:03.720", "Id": "429723", "Score": "0", "body": "_\"I'm a bit confused why you want to touch everything.\"_ => I’m even more confused as it not only touch, but also clears the files. A simple touch would be `open(file_name, 'a').close()`…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:24:45.337", "Id": "429725", "Score": "0", "body": "@MathiasEttinger That's a good point. It makes sense if it's renamed to `make_empty`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:28:17.367", "Id": "429726", "Score": "1", "body": "Also, 10. Using `os.rename` instead of `shutil.copyfile` since you don't need copies anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:30:30.093", "Id": "429727", "Score": "0", "body": "@MathiasEttinger Do you want to post an answer? Even if you copied your existing comments I'd upvote it :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:31:15.353", "Id": "429728", "Score": "0", "body": "No, I shouldn't even be here now, I’m a bit in a hurry now ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T04:56:55.810", "Id": "429809", "Score": "0", "body": "Since `touch` and `gen_file` don't need anything of the object, I would make them top level module functions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T07:34:22.183", "Id": "429817", "Score": "0", "body": "touch will work on the first run only `if not exists(f)` - but I agree, that `create_empty` would make much more sense" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:01:40.593", "Id": "222091", "ParentId": "222089", "Score": "9" } } ]
{ "AcceptedAnswerId": "222091", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T14:10:56.013", "Id": "222089", "Score": "11", "Tags": [ "python", "beginner", "python-3.x", "file", "logging" ], "Title": "Simple log rotation script" }
222089
<p>I'm looking to irreversibly hash valid email addresses which have been parsed from mail log data as part of a machine learning project. I need to ensure that the processed data has been scrubbed of personally identifiable information (specific users/client domain etc).</p> <p>A quick google-fu led me to pyffx and the inbuilt secrets package.</p> <p>I'm looking to scrub the email addresses while retain the formatting and beginning character sequence:</p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python # coding: utf-8 import pyffx, secrets def ffx_encrypt(email,secret): raw_user, raw_domain = email.split('@') #retaining first few characters to test entropy of bulk sender lists user_chars = raw_user[:3] user_rem = raw_user[3:] #get unique characters for each string to retain entropy uniq_user_chars = ''.join(set(raw_user)) uniq_dom_chars = ''.join(set(raw_domain)) e_user = pyffx.String(secret,alphabet=uniq_user_chars,length=len(user_rem)) e_dom = pyffx.String(secret,alphabet=uniq_dom_chars,length=len(raw_domain)) user_encrypt = e_user.encrypt(user_rem) dom_encrypt = e_dom.encrypt(raw_domain) return user_chars + user_encrypt + '@' + dom_encrypt; #To be generated at runtime secret = secrets.token_hex(32).encode() print(ffx_encrypt('test1@gmail.com',secret)) print(ffx_encrypt('firstname_surname1@mail.net',secret)) print(ffx_encrypt('username1@mail.co.uk',secret)) print(ffx_encrypt('username1@gmail.com',secret)) print(ffx_encrypt('username1@mail.net',secret)) print(ffx_encrypt('bounce-mc.uk1147123_813.721605-sue.test=mail.net@mail555.atl123.test.net',secret)) ##Sample run results #teste@limigooac #firms_smnnueefrna_@tnmaenmi #userersua@k.m.auuamo #userersua@limigooac #userersua@tnmaenmi #bout50um7=8s_t43n07s0.6tn5knt0e366u-7c73bl3_2iio@1.eisnss5i1l32s.3.ea..3 </code></pre> <p>At the moment I'm not focused on performance, elegance or robustness, it's more about avoiding stepping on a landmine if there's an obvious flaw with my implementation which could make the post-processed email addresses/domains reversible.</p> <p>Feedback would be greatly appreciated.</p> <p>EDIT: Clarified that input will be valid email addresses.</p>
[]
[ { "body": "<p>Test cases are very limited. You might want to normalise equivalent addresses before hashing; for example, these addresses are all equivalent:</p>\n\n<ul>\n<li><code>user@example.org</code></li>\n<li><code>user@Example.Org</code></li>\n<li><code>\"user\"@example.org</code></li>\n</ul>\n\n<p>It's probably desirable that they hash to the same value.</p>\n\n<p>Simply splitting on <code>@</code> is naive - it's better to split on <em>unquoted</em> <code>@</code>, or more simply, just on the last <code>@</code>, given that DNS names don't contain <code>@</code>.</p>\n\n<p>It's probably worth reading <a href=\"https://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx/\" rel=\"nofollow noreferrer\"><em>I Knew How To Validate An Email Address Until I Read The RFC</em></a>. After that, start looking for an email address parsing library for Python; I haven't used it, but it appears that <a href=\"https://github.com/mailgun/flanker\" rel=\"nofollow noreferrer\">Flanker</a> will handle the parsing much more robustly than this code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T16:39:09.050", "Id": "429737", "Score": "0", "body": "Whilst they may be equivalent from an MTA perspective, such deviations would be of interest from a ML standpoint as it would suggest different processes were responsible in generating the addresses. Parsing is out of scope for this as it'll be handled separately, probably with perl as the dataset is quite large. I'll update the question to make it clear the input will be valid email addresses. Thank you for the @ split advice, I'll make the suggested change." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T16:16:03.453", "Id": "222096", "ParentId": "222093", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:54:49.110", "Id": "222093", "Score": "6", "Tags": [ "python", "python-3.x", "email", "hashcode" ], "Title": "Irreversibly hash email addresses while preserving format/entropy" }
222093
<p>The internet as a whole and Code Review in special already provide a decent amount of implementations of the Luhn check digit algorithm. They often follow a relatively "naive" strategy, in that they are mostly straightforward translations of the algorithm's pseudo-code (as found e.g. on <a href="https://en.wikipedia.org/wiki/Luhn_algorithm#Pseudocode_Implementation" rel="noreferrer">Wikipedia</a>), like below:</p> <pre><code>class Luhn: @staticmethod def calculate_naive(input_): """Calculate the check digit using Luhn's algorithm""" sum_ = 0 for i, digit in enumerate(reversed(input_)): digit = int(digit) if i % 2 == 0: digit *= 2 if digit &gt; 9: digit -= 9 sum_ += digit return str(10 - sum_ % 10) </code></pre> <p>I chose <code>6304900017740292441</code> (the final <code>1</code> is the actual check digit) from <a href="https://formvalidation.io/guide/validators/credit-card/" rel="noreferrer">this</a> site about credit card validation as example to validate the coming changes. The mini-validaton and timing of this implementation generated the following results:</p> <pre><code>assert Luhn.calculate_naive("630490001774029244") == "1" %timeit -r 10 -n 100000 Luhn.calculate_naive("630490001774029244") 13.9 µs ± 1.3 µs per loop (mean ± std. dev. of 10 runs, 100000 loops each) </code></pre> <p>This algorithm IMHO lends itself to some optimizations. I came up with the following ones:</p> <ol> <li>Computing the double and then subtract 9 if above 9 of every second digit seems to cry for a lookup-table.</li> <li>The string-to-int and int-to-string conversion also seem like low hanging fruits for a lookup-table too, since the number of values is relatively limited.</li> </ol> <p>This lead to the following code:</p> <pre><code>class Luhn: DOUBLE_LUT = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) # CHECK_DIGIT_LUT = tuple(str(10 - i) for i in range(10)) CHECK_DIGIT_LUT = ("0", "9", "8", "7", "6", "5", "4", "3", "2", "1") # STR_TO_INT_LUT = {str(i): i for i in range(10)} STR_TO_INT_LUT = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9 } @classmethod def calculate_lut1(cls, input_): """Calculate the check digit using Luhn's algorithm""" sum_ = 0 for i, digit in enumerate(reversed(input_)): digit = int(digit) sum_ += digit if i % 2 else cls.DOUBLE_LUT[digit] return str(10 - sum_ % 10) @classmethod def calculate_lut12(cls, input_): """Calculate the check digit using Luhn's algorithm""" sum_ = 0 for i, digit in enumerate(reversed(input_)): digit = cls.STR_TO_INT_LUT[digit] sum_ += digit if i % 2 else cls.DOUBLE_LUT[digit] return cls.CHECK_DIGIT_LUT[sum_ % 10] </code></pre> <p>This piece of code was also validated and timed:</p> <pre class="lang-py prettyprint-override"><code>assert Luhn.calculate_lut1("630490001774029244") == "1" %timeit -r 10 -n 100000 Luhn.calculate_lut1("630490001774029244") 11.9 µs ± 265 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each) assert Luhn.calculate_lut12("630490001774029244") == "1" %timeit -r 10 -n 100000 Luhn.calculate_lut12("630490001774029244") 7.28 µs ± 166 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each) </code></pre> <p>I found the second result especially suprising, decided to go full berserk and went on to try to precompute as much as possible.</p> <p>Since all digits of the sum apart from the last one are irrelevant, the possible intermediate results can all be pre-computed <span class="math-container">\$mod\,10\$</span>.</p> <p>Enter this behemoth:</p> <pre class="lang-py prettyprint-override"><code>class Luhn: # ... other code from above, e.g. CHECK_DIGIT_LUT SUM_MOD10_LUT = { i: {str(j): (i + j) % 10 for j in range(10)} for i in range(10) } SUM_DOUBLE_MOD10_LUT = { i: {str(j): (i + (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)[j]) % 10 for j in range(10)} # ^ I don't like this. But doesn't seem to work with DOUBLE_LUT for i in range(10) } @classmethod def calculate_lut_overkill(cls, input_): """Calculate the check digit using Luhn's algorithm""" sum_ = 0 for i, digit in enumerate(reversed(input_)): if i % 2: sum_ = cls.SUM_MOD10_LUT[sum_][digit] else: sum_ = cls.SUM_DOUBLE_MOD10_LUT[sum_][digit] return cls.CHECK_DIGIT_LUT[sum_] </code></pre> <pre><code>assert Luhn.calculate_lut_overkill("630490001774029244") == "1" %timeit -r 10 -n 100000 Luhn.calculate_lut_overkill("630490001774029244") 5.63 µs ± 200 ns per loop (mean ± std. dev. of 10 runs, 100000 loops each) </code></pre> <p>This is were I stopped, shivered, and decided to go to The Happy Place.</p> <hr> <p>Leaving aside the old wisdom on "premature optimization": What I would like to know now is if there are any aspects that might be optimized further that I haven't thought?</p> <p>Would you let the later stages of the code pass in a code review? Especially the last one seems to be a good candidate for confusion. Should there be more explanation on how the lookup-tables came to be?</p> <p>Of course all thoughts and feedback whatsoever are much appreciated.</p> <hr> <p>This post is part of a (developing?) mini-series on check digit algorithms. You may also want to have a look at part 1 <a href="https://codereview.stackexchange.com/q/221229/92478"><em>Verhoeff check digit algorithm</em></a>.</p>
[]
[ { "body": "<ul>\n<li><p>List lookup is faster than dict lookup:</p>\n\n<pre><code>$ python -m timeit -s \"c = {i: i for i in range(10)}\" \"c[3]\"\n10000000 loops, best of 5: 30 nsec per loop\n$ python -m timeit -s \"c = {i: i for i in range(10)}\" \"c[9]\"\n10000000 loops, best of 5: 30.2 nsec per loop\n\n$ python -m timeit -s \"c = [i for i in range(10)]\" \"c[3]\"\n10000000 loops, best of 5: 26.3 nsec per loop\n$ python -m timeit -s \"c = [i for i in range(10)]\" \"c[9]\"\n10000000 loops, best of 5: 26.6 nsec per loop\n</code></pre></li>\n<li><p>Removing the <code>if</code> and instead using <code>zip</code> yields a speed up too.</p>\n\n<p>It doesn't matter too much whether you build the list with <code>[] * len(input_)</code> or using <code>itertools.cycle</code>.</p>\n\n<p>It does matter that the tables be the second item in the zip, otherwise the speed can fluctuate to being slower than 'Overkill'.</p></li>\n<li>Replacing <code>reversed</code> with a slice is the same speed, even though it removes a function call.</li>\n<li>It doesn't look like tuple lookup is faster than list lookup.</li>\n</ul>\n\n<p>And so this is the fastest I could get:</p>\n\n<pre><code>import itertools\n\n\nclass Luhn:\n CHECK_DIGIT_LUT = (\"0\", \"9\", \"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\", \"1\")\n SUM_MOD10_LUT = [\n {str(j): (i + j) % 10 for j in range(10)}\n for i in range(10)\n ]\n SUM_DOUBLE_MOD10_LUT = [\n {str(j): (i + (0, 2, 4, 6, 8, 1, 3, 5, 7, 9)[j]) % 10 for j in range(10)}\n for i in range(10)\n ]\n\n @classmethod\n def calculate_lut_overkill(cls, input_):\n \"\"\"Calculate the check digit using Luhn's algorithm\"\"\"\n sum_ = 0\n for digit, table in zip(\n reversed(input_),\n itertools.cycle([\n cls.SUM_DOUBLE_MOD10_LUT,\n cls.SUM_MOD10_LUT,\n ]),\n ):\n sum_ = table[sum_][digit]\n return cls.CHECK_DIGIT_LUT[sum_]\n</code></pre>\n\n<p>My timings were:</p>\n\n<pre><code>LuhnBase 0.581\nLuhnOverkill 0.279\nLuhnPeilList 0.271\nLuhnPeilTables 0.201\nLuhnPeilAltTables 0.202\nLuhnPeilItertools 0.207\nLuhnPeilAltItertools 0.203\nLuhnPeilSlice 0.204\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T06:22:25.330", "Id": "429813", "Score": "0", "body": "So just to be sure that I understood you correctly: the difference between `LuhnPeilList` and `LuhnPeilTables` came from getting rid of the `if`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T07:13:15.267", "Id": "429815", "Score": "0", "body": "Seems like it's a combination of `enumerate`, `i % 2`, and `if` that makes up the time difference. Just throwing in an unneccessary `enumerate` in your fastest solution slows it down about 25-30% on my laptop (4.5µs → 5.8µs)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T08:22:58.480", "Id": "429825", "Score": "0", "body": "@AlexV Yes `Table` removed `enumerate`, `i % 2` and `if`, `Alt` means the positions of the `zip` are reversed. `Itertools` means the argument to `zip` uses itertools rather than a list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T08:24:07.773", "Id": "429826", "Score": "0", "body": "@AlexV You should perform all timeits multiple times and take the minimum, as `LuhnPeilTables` randomly went from 0.2 to 0.35, because I had other things running on my PC. I repeated each timeit 10 times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T09:23:25.030", "Id": "429831", "Score": "0", "body": "I cannot guarantee that I really did 10 runs of each timeit, but definitely between 5 to 10 with short pauses in between to give the laptop some time for other workloads to happen. The negative effect of `enumerate` seemed to persist." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T21:42:52.350", "Id": "431475", "Score": "0", "body": "I hope you don't mind that I tried to summarize our discussion in chat as a community answer below. You can have a look at it and verify that I expressed your reasoning appropriately." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T00:35:10.390", "Id": "222125", "ParentId": "222100", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/users/42401\">Peilonrayz</a> was so kind to show and explain some of the steps taken in the optimization process for me to better follow along in <a href=\"https://chat.stackexchange.com/rooms/94796/\">chat</a>. I wanted to preserve them if the chat room ever goes to die.</p>\n\n<p>The following code pieces are supposed to be used with the <code>Luhn</code> class as presented in the question or <a href=\"https://codereview.stackexchange.com/a/222125/92478\">Peilonrayz' answer</a> to be able to access the look-up tables.</p>\n\n<pre><code>def luhn_peil_list(cls, input_):\n sum_ = 0\n for i, digit in enumerate(reversed(input_)):\n if i % 2:\n sum_ = cls.SUM_MOD10_LUT[sum_][digit]\n else:\n sum_ = cls.SUM_DOUBLE_MOD10_LUT[sum_][digit]\n return cls.CHECK_DIGIT_LUT[sum_]\n\n\ndef luhn_peil_without_if(cls, input_):\n tables = [cls.SUM_DOUBLE_MOD10_LUT, cls.SUM_MOD10_LUT]\n sum_ = 0\n for i, digit in enumerate(reversed(input_)):\n sum_ = tables[i % 2][sum_][digit]\n return cls.CHECK_DIGIT_LUT[sum_]\n\n\ndef luhn_peil_without_if_enumerate(cls, input_):\n tables = [cls.SUM_DOUBLE_MOD10_LUT, cls.SUM_MOD10_LUT]\n sum_ = 0\n for digit, i in zip(reversed(input_), range(len(input_))):\n sum_ = tables[i % 2][sum_][digit]\n return cls.CHECK_DIGIT_LUT[sum_]\n</code></pre>\n\n<p>With the following timings:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>LuhnPeilList 0.281\nLuhnPeilWithoutIf 0.254\nLuhnPeilWithoutIfEnumerate 0.29\n</code></pre>\n\n<p><a href=\"https://chat.stackexchange.com/transcript/message/50650475#50650475\">The conclusion</a> of these results were:</p>\n\n<blockquote>\n <p>This shows that removing the if leads to a 0.027 speedup. Changing\n from enumerate to zip however is slower than with the speedup. So\n enumerate is faster.</p>\n</blockquote>\n\n<p>In the following discussion if <code>enumerate</code> was to blame for those major performance differences between the different versions, Peilonrayz went on to produce the following variants:</p>\n\n<pre><code>def luhn_peil_without_if_mod(cls, input_):\n tables = [cls.SUM_DOUBLE_MOD10_LUT, cls.SUM_MOD10_LUT] * ((len(input_) + 1) // 2)\n sum_ = 0\n for i, digit in enumerate(reversed(input_)):\n sum_ = tables[i][sum_][digit]\n return cls.CHECK_DIGIT_LUT[sum_]\n\n\ndef luhn_peil_without_if_mod_enumerate(cls, input_):\n tables = [cls.SUM_DOUBLE_MOD10_LUT, cls.SUM_MOD10_LUT] * ((len(input_) + 1) // 2)\n sum_ = 0\n for digit, table in zip(reversed(input_), tables):\n sum_ = table[sum_][digit]\n return cls.CHECK_DIGIT_LUT[sum_]\n</code></pre>\n\n<p>Timing:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>LuhnPeilWithoutIfMod 0.23\nLuhnPeilWithoutIfModEnumerate 0.208\n</code></pre>\n\n<p><a href=\"https://chat.stackexchange.com/transcript/message/50650721#50650721\">Reasoning</a>:</p>\n\n<blockquote>\n <p>The difference between <code>LuhnPeilWithoutIfMod</code> and\n LuhnPeilWithoutIfModEnumerate is that <code>table[i]</code> is slow in Python, but\n fast in C. The speed increase outweighs the speed increase <code>enumerate</code>\n has over <code>zip</code>.</p>\n</blockquote>\n\n<p>Further mentioning that <code>luhn_peil_without_if_mod_enumerate</code> is found the same as <a href=\"https://codereview.stackexchange.com/a/222125/92478\"><code>LuhnPeilAltTables</code></a> (<a href=\"https://chat.stackexchange.com/transcript/message/50650780#50650780\">mine</a>, <a href=\"https://chat.stackexchange.com/transcript/message/50650789#50650789\">Peilonrayz'</a>) and concluding that </p>\n\n<blockquote>\n <p>\"It doesn't matter too much whether you build the list with <code>[] * len(input_)</code> or using <code>itertools.cycle</code>.\"</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T21:53:21.583", "Id": "431476", "Score": "1", "body": "Thank you for writing this up for me. :) I've commented here so if anyone disagrees with this analysis they can ping me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T02:04:46.997", "Id": "467676", "Score": "0", "body": "Hey, @AlexV I've removed all the pronouns from this post. There should be no loss of content, as pronouns are short hand for nouns but mostly unneeded. I hope this change is ok with you. Thank you :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T21:40:14.230", "Id": "222828", "ParentId": "222100", "Score": "2" } } ]
{ "AcceptedAnswerId": "222125", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T18:53:37.380", "Id": "222100", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "comparative-review", "checksum" ], "Title": "Optimizing Luhn check digit algorithm" }
222100
<p>I have coded a solution to build all valid permutations of parentheses. </p> <p>My code is below. </p> <p>I have a question on my code based on a comment by my PEP8 checker. It said that there was no need to include the line <code>return</code> anywhere in the code (initially I included one). The solution works but I have never had a case using recursion where I didn't have to use the <code>return</code> line in the base-case. </p> <p>How come I don't need it here?</p> <p>The following expression initially had a <code>return</code> statement but I was told this was obsolete.</p> <pre><code> if number_open == number_pairs and number_closed == number_pairs: print(output) build_parentheses.counter += 1 return </code></pre> <p>Python 3.7 code:</p> <pre><code>"""Module builds all valid permutations of n parentheses For example: n = 3: ((())) (()()) (())() ()(()) ()()() Total = 5 """ def build_parentheses(number_pairs: int, output="", number_open=0, number_closed=0)-&gt; str: """The function that builds the parentheses. Output as a string: number_pairs: number of parentheses pairs user desired All other parameters are private """ if number_open == number_pairs and number_closed == number_pairs: print(output) build_parentheses.counter += 1 else: if number_open &lt; number_pairs: output += "(" build_parentheses(number_pairs, output, number_open + 1, number_closed) output = output[:-1] if number_closed &lt; number_open and number_open: output += ")" build_parentheses(number_pairs, output, number_open, number_closed + 1) if __name__ == "__main__": build_parentheses.counter = 0 build_parentheses(5) print(f"=========\n{build_parentheses.counter} solutions") </code></pre> <p>By comparison, in <a href="https://codereview.stackexchange.com/questions/221554/print-the-string-equivalents-of-a-phone-number">this post</a> I made, I did use the return statement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:10:18.020", "Id": "429756", "Score": "0", "body": "At which line did you originally include the `return` statement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:14:35.673", "Id": "429757", "Score": "0", "body": "After the line ```build_parentheses.counter += 1``` in the base-case ```if....```" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:18:58.117", "Id": "429759", "Score": "0", "body": "Thanks. I have edited the post" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:21:01.973", "Id": "429760", "Score": "0", "body": "Do you happen to have a code snippet where you did in fact needed to use the `return`statement? This way, we can compare that code with your current snippet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:23:05.073", "Id": "429761", "Score": "0", "body": "Sorry. Yes. The following post I made on code-review is a nice comparison. \n\nhttps://codereview.stackexchange.com/questions/221554/print-the-string-equivalents-of-a-phone-number" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:24:32.040", "Id": "429762", "Score": "1", "body": "The key difference is you are using an `else:` block here, rendering the `return`obsolete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:25:30.690", "Id": "429763", "Score": "0", "body": "I see. So because I reach the end of an ```if``` statment, does it automatically ```return```?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:28:09.713", "Id": "429766", "Score": "1", "body": "No, but because all remaining code in the function is in the `else`, there is no more reachable code detected. If you have more questions about the scope of code blocks, take it to chat :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:30:45.437", "Id": "429767", "Score": "1", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/94780/discussion-between-dfhwze-and-eml)." } ]
[ { "body": "<p>As mentioned <a href=\"https://meta.stackexchange.com/questions/117251/what-should-be-done-with-questions-that-have-been-self-resolved-as-a-comment-ins\">here</a> I'll provide a short answer to summarize what we discussed. A <code>return</code> statement only impacts code that short-circuits any remaining code that would have been called if omitted.</p>\n\n<p><em>pseudo code snippets below</em></p>\n\n<p>The <code>return</code> statement here skips snippet 2.</p>\n\n<pre><code>if (condition) {\n // .. snippet 1\n return;\n}\n// snippet 2\n</code></pre>\n\n<p>The <code>return</code> statement here is unnecessary.</p>\n\n<pre><code>if (condition) {\n // .. snippet 1\n return;\n} else {\n // snippet 2\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T07:46:56.607", "Id": "429819", "Score": "0", "body": "in the second snippet I would say the `else` is unnecessary. It allows you to arrange the rest of the code with 1 less level of indentation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T08:01:22.507", "Id": "429821", "Score": "0", "body": "@MaartenFabré You are correct. But these snippets are just trivial examples to show the purpose of the `return` statement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:45:05.807", "Id": "222104", "ParentId": "222101", "Score": "3" } }, { "body": "<p>There is no need for a return statement here because when you reach the end of a function, there is an implicit return.</p>\n\n<p>For example:</p>\n\n<pre><code>1 def exampleFunction():\n2 if someCondition:\n3 doThis()\n4 else:\n5 doTheOtherThing()\n6\n</code></pre>\n\n<p>We could put a return statement after the call to <code>doThis()</code>, but this would make no difference to the execution of the code. When <code>someCondition</code> is <code>True</code>, we enter that code block and then call <code>doThis()</code>. Then, we go to line 6 and implicitly return from the function.</p>\n\n<p>So after executing line 3, we jump to line 6 and implicitly return, so explicitly returning after line 3 makes no difference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:46:34.213", "Id": "222105", "ParentId": "222101", "Score": "2" } }, { "body": "<h3>Effects</h3>\n<p>This is my main complaint about your code. <code>build_parentheses</code> prints out its results, but it would be cleaner for it to return them as a list, or yield them.</p>\n<h3><code>.counter</code></h3>\n<p>Using the attribute <code>build_parenthesis.counter</code> like this is technically fine, but it's really strange. I don't feel that ad-hoc attributes are particularly Pythonic, especially for functions. Also, <code>.counter</code> will not be needed if <code>build_parentheses</code> returns a list as suggested.</p>\n<h3>Names</h3>\n<p>I'd recommend <code>X_count</code> rather than <code>number_X</code>. It's mostly preference, though.</p>\n<h3>Public API</h3>\n<p>Since the <code>number_open</code> and <code>number_closed</code> parameters are not part of the public API, I'd recommend removing them. Make <code>build_parentheses</code> take only one parameter, <code>number_pairs</code>. It will call, and return the results of, <code>build_parentheses_aux</code>, an auxiliary/helper function, which takes <code>number_pairs</code> as well as several private/internal parameters.</p>\n<h3>Chained comparisons</h3>\n<p><code>number_open == number_pairs and number_closed == number_pairs</code> may be written as <code>number_open == number_closed == number_pairs</code>. Generally, Python interprets chained comparisons as if they were combined with <code>and</code>. Two comparisons <code>A</code> and <code>B</code> applied to three variables <code>x</code>, <code>y</code>, and <code>z</code> like <code>x A y B z</code> is the same as writing <code>x A y and y B z</code>.</p>\n<h3>Everything else looks good</h3>\n<p>Style is generally good, though a space to the left of <code>-&gt; str</code> would be nice; <code>and number_open</code> rather than <code>and number_open != 0</code> is Pythonic; <code>if __name__ == &quot;__main__&quot;</code> guard is good; <code>snake_case</code> is good; you have a docstring, ...</p>\n<h3>Suggested Code</h3>\n<p>Here is your code, with all suggestions implemented:</p>\n<pre><code>def build_parentheses(pair_count: int) -&gt; str:\n &quot;&quot;&quot;The function that builds the parentheses. Output as a string:\n pair_count: number of parentheses pairs user desired\n &quot;&quot;&quot;\n return build_parentheses_aux(pair_count, 0, 0)\n\ndef build_parentheses_aux(pair_count: int,\n open_count,\n closed_count)-&gt; str:\n &quot;&quot;&quot;Auxiliary build_parentheses function.\n pair_count: number of parentheses pairs\n open_count: number of open parens so far\n closed_count: number of closed parens so far\n &quot;&quot;&quot;\n if open_count == closed_count == pair_count:\n return [&quot;&quot;]\n else:\n result = []\n if open_count &lt; pair_count:\n for r in build_parentheses_aux(pair_count, open_count + 1, closed_count):\n result.append(&quot;(&quot; + r)\n if closed_count &lt; open_count and open_count:\n for r in build_parentheses_aux(pair_count, open_count, closed_count + 1):\n result.append(&quot;)&quot; + r)\n return result\n\nif __name__ == &quot;__main__&quot;:\n options = build_parentheses(5)\n print(&quot;\\n&quot;.join(options) + f&quot;\\n=========\\n{len(options)} solutions&quot;)\n</code></pre>\n<p>If you are familiar with generators, you could also write <code>build_parentheses_aux</code> as a generator, which would look cleaner (but may be less efficient).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T07:48:46.077", "Id": "429820", "Score": "0", "body": "I would skip the auxiliary function, and make `0` the default arguments for `open_count` and `closed_count`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T09:00:43.913", "Id": "429828", "Score": "0", "body": "Thank yo for this reply :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T15:37:25.603", "Id": "429885", "Score": "0", "body": "@EML You're welcome! @Maarten Fabré I don't agree; `open_count` and `closed_count` aren't a part of the public API, so they shouldn't be in the API function" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T04:37:04.383", "Id": "222130", "ParentId": "222101", "Score": "3" } } ]
{ "AcceptedAnswerId": "222104", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:05:44.987", "Id": "222101", "Score": "4", "Tags": [ "python", "recursion", "combinatorics", "balanced-delimiters" ], "Title": "Generate parentheses solution" }
222101
<p>I'm writing a small almost one method Java class for a job application and the advice given was to write it as though it was a piece of commercial software.</p> <p>The <code>processResult</code> method needs two string arguments of equal length. I thought the best thing to do is check that the args has at least 2 items, then inside the <code>processResult</code> method check that the strings have the same length. </p> <p>I am unsure about throwing a generic exception in my main method and then later using the try/catch statement. Is this a good practice to do? Would it be better practice to handle these as part of one try catch? Are custom Exceptions a good way to go for this type of problem?</p> <p>Here is what I have at the moment. </p> <pre><code>public class Task { public static void main(String[] args) throws Exception { if (args.length &lt; 2) { throw new Exception("Need 2 string arguments"); } try { int result = processResult(args[0], args[1]); System.out.println(result); } catch (IllegalArgumentException e) { System.err.println(e.getMessage()); } } private static boolean lengthsEqual(String a, String b) { return Integer.compare(a.length(), b.length()) == 0; } private static int processResult(String inputOne, String inputTwo) { if (!lengthsEqual(inputOne, inputTwo) { throw new IllegalArgumentException("Strings must be the same length"); } // method logic return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T20:33:08.677", "Id": "429774", "Score": "0", "body": "Ah yes.. edit on the way" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:42:09.533", "Id": "429879", "Score": "0", "body": "Uh, one thing: a.length == b.length is easier compared to Integer.compare(..) == 0." } ]
[ { "body": "<p>Usually, we throw an exception if some pre-condition or assumption we've made about the code is violated. So unless <code>processResult</code> assumes/requires that the two string arguments will be equal to do its job, I wouldn't throw an exception.</p>\n\n<p>When the program is as small as this, it could be okay to change the initial check to:</p>\n\n<pre><code>if (args.length != 2 || lengthsEqual(args[0], args[1])) {\n throw new IllegalArgumentException(\"Need 2 string arguments of the same length\");\n}\n</code></pre>\n\n<p>Though, if the program will ever have to be altered to accommodate for strings of unequal length, then this will have to be changed. Generally, commercial code tries to be as reusable and extensible as reasonably possible to allow for quick extension and minimal introduction of bugs upon extending or altering code behaviour. Since we can't always predict the future, this is usually done by the programmer attempting to make a some assumption about where/how the code might have to be expanded in the future. If this program was under active development and intended to be developed upon for the foreseeable future, it might be a reasonable assumption that at some point in the future the program may have to handle two strings of differing length due to a new business requirement and, thus, we wouldn't put this exception here.</p>\n\n<p>This is all highly contextual, and it's hard to make any meaningful decision with a single-purpose, one-time program like this. That being said, it's generally useful to keep an exception to as small a scope as you can so that you can more quickly pinpoint the potentially problematic code throwing the exception in the event of a bug, so I think it's okay to have two exceptions here, though maybe the first exception is better to be an <code>IllegalArgumentException</code> as well.</p>\n\n<p><strong>Two potential issues:</strong></p>\n\n<ul>\n<li><p>I don't think there's any reason to use Integer.compare() instead of the <code>==</code> operator, since the return type of <code>length()</code> is a primitive <code>int</code> according to the Oracle JavaSE 7 documentation.</p></li>\n<li><p>Check if <code>args.length != 2</code>, instead of checking it's less than 2 since somebody could supply too many strings as opposed to not enough.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:20:28.623", "Id": "429775", "Score": "0", "body": "Thanks for this, does that mean there is a time penalty for the casting in the Integer.compare() method? Just due to the description of the task I felt that the single if statement might give the impression that I'm not thinking on the larger scale in terms of production-level code. Maybe I'm over thinking it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:21:53.157", "Id": "429776", "Score": "0", "body": "Also, I feel like I need to show Exception handling in the method itself, since doing all the sanity checking in the main method would mean external methods wouldn't have the string length checking when called elsewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:53:50.313", "Id": "429780", "Score": "0", "body": "There would be a performance hit in using the Integer.compare() method due to autoboxing/unboxing in Java (https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). I'm not sure how significant the performance hit would be, you'd probably want to be making a lot of calls that result in autoboxing/unboxing in performance-sensitive section of code for it to be significant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:27:33.060", "Id": "429781", "Score": "0", "body": "The above only really applies if Integer.compare() actually does result in the autoboxing of the primitives passed to it -- maybe it doesn't, I'm not too familiar with the implementation. That's another good argument for curtailing the exception to the method so that the method can be called elsewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T09:18:24.443", "Id": "429830", "Score": "0", "body": "Unfortunately the requirement of making your code \"production-ready\" is a bit vague and difficult to apply to a small-scale problem. Often times, applying techniques to abstract and make code more re-usable that are often seen in large software projects don't make all that much practical sense to apply to a small project like this as you might end up over-engineering the code and hampering readability. I'd try to focus on simplicity, good variable naming and making sure the code is easy to understand and read." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T20:43:56.050", "Id": "222110", "ParentId": "222107", "Score": "0" } }, { "body": "<p>I took your code and rewrote it a bit, so that it satisfies my personal requirements for production-ready code.</p>\n\n<pre><code>if (args.length &lt; 2) {\n System.err.println(\"usage: Task &lt;arg1&gt; &lt;arg2&gt;\");\n System.exit(1);\n}\n</code></pre>\n\n<p>I removed the <code>throw new Exception</code> since passing the wrong number of arguments is not a programming error but a wrong invocation of the program. Only programming errors should print a stack trace. Instead of saying \"Need 2 string arguments\" I am following the \"usage:\" pattern that has been successfully established by Unix programs. Since you didn't provide any context in your question, the best variable names I could come up with are <code>&lt;arg1&gt; &lt;arg2&gt;</code>. If your task were to copy a file, the usage line should better be <code>usage: Copy &lt;source&gt; &lt;target&gt;</code>, of course.</p>\n\n<pre><code>} catch (IllegalArgumentException e) {\n System.err.println(e.getMessage());\n System.exit(1);\n}\n</code></pre>\n\n<p>I added the <code>System.exit</code> since it was missing. If the program fails, it must report this via <code>System.exit</code> or by throwing an exception from the <code>main</code> function.</p>\n\n<pre><code>private static int processResult(String inputOne, String inputTwo) {\n if (inputOne.length() != inputTwo.length()) {\n throw new IllegalArgumentException(\"Strings must be the same length\");\n }\n</code></pre>\n\n<p>There's no need to have a separate function for checking the lengths of the strings. Using IntelliJ it was quite simple to inline the method call to <code>lengthsEqual</code> (I just pressed Ctrl+Alt+N) and to remove the redundant call to <code>Integer.compare</code> (which was already marked in dark gray, so I just had to press Alt+Enter there).</p>\n\n<p>It's unfortunate that the exception message says \"String must be the same length\". This message does not tell <em>which</em> strings are meant, and since that message is printed to <code>System.err</code> later, it should be worded with the same care as the usage message.</p>\n\n<p>I disagree with <a href=\"https://codereview.stackexchange.com/a/222110\">bag's answer</a>, especially the part that commercial code needs to be extensible. It doesn't. It needs to be easy to read, and it needs to clearly tell its intention. If the business requires that the two strings be equal (for whatever reason), the code should say exactly this, and the code should match the wording of the original requirement as closely as possible, so that later changes to the requirements can be programmed as easily as possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:48:29.833", "Id": "222117", "ParentId": "222107", "Score": "2" } } ]
{ "AcceptedAnswerId": "222110", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T19:54:24.580", "Id": "222107", "Score": "2", "Tags": [ "java", "interview-questions", "validation", "error-handling" ], "Title": "Validating that a Java program has two equal-length arguments" }
222107
<p>I am running a simulation study where I am using two-part hurdle modeling on different effect sizes. I tried to stream-line my code for the best optimization including foreach loops and parallelization. I attempted to post here prematurely a few weeks ago and am now posting my updated code.</p> <p>I keep running into an error where the hessian matrix is singular that stopped the loops. I continued the loops and logged the errors (any advice on this would be great). I recognize this is a statistical problem, but often others know more than I.</p> <p>Any feedback on optimization would be ideal as I am running 1000 resamples and 1000 bootstraps. For 50 iterations and 50 bootstraps, it took 7 minutes. For 500 and 500, it took around 3.5 hours. </p> <pre><code>install.packages("boot") install.packages("doParallel") install.packages("doRNG") library(pscl) library(boot) library(doParallel) library(doRNG) # if TRUE, keeps a processor free to be used by the OS. kFlag.free.processor &lt;- TRUE #Store the path coefficients as a list and a matrix (for different uses) kParameters &lt;- (function(){ ##path coefficient vectors sizes &lt;- c(50, 100, 200, 300, 500, 1000) seeds.small &lt;- c(51, 53, 55, 57, 58, 59) seeds.medium &lt;- c(61, 63, 65, 67, 68, 69) seeds.large &lt;- c(81, 73, 75, 77, 78, 79) #cbind call will coerce an integer to a vector filled with that value c &lt;- .25 i &lt;- 1 ##end path coefficient vectors effect.small &lt;- cbind(a = .18, b = .16, c, i, n = sizes, seed = seeds.small) effect.medium &lt;- cbind(a = .31, b = .35, c, i, n = sizes, seed = seeds.medium) effect.large &lt;- cbind(a = .52, b = .49, c, i, n = sizes, seed = seeds.large) list(list = list(small = effect.small, medium = effect.medium, large = effect.large), matrix = rbind(effect.small, effect.medium, effect.large))#return })() #IIFE # RNG MODULE FOR TWO_PART HURDLE MODEL gen.hurdle = function(n, a, b1, b2, c1, c2, i0, i1, i2){ x = round(rnorm(n),3) e = rnorm(n) m = round(i0 + a*x + e, 3) lambda = exp(i1 + b1*m + c1*x) # PUT REGRESSION TERMS FOR THE CONTINUUM PART HERE; KEEP exp() ystar = qpois(runif(n, dpois(0, lambda), 1), lambda) # Zero-TRUNCATED POISSON DIST.; THE CONTINUUM PART z = i2 + b2*m + c2*x # PUT REGRESSION TERMS FOR THE BINARY PART HERE z_p = exp(z) / (1+exp(z)) # p(1) = 1-p(0) tstar = rbinom(n, 1, z_p) # BINOMIAL DIST. ; THE BINARY PART y= ystar*tstar # TWO-PART COUNT OUTCOME return(cbind(x,m,y,z,z_p,tstar)) } ################################################################################################## # MODEL ########################################################################################## ################################################################################################## #model iterations = 500 r = 500 # capture runtime system.time({ ## Setup Parallelization message("Setting up Parallelization...") # create clusters for each available processor cl &lt;- makeCluster(detectCores() - 1*kFlag.free.processor, outfile="") message(paste0("Created ", detectCores() - 1*kFlag.free.processor, " workers...")) # register parallelization backend registerDoParallel(cl) # pass functions and variables from the "Global Environment" to the "master R process" (being run on each processor) clusterExport(cl, c("gen.hurdle", "hurdle")) message(paste0("Parallelization ready. Reserving ", 1*kFlag.free.processor, " processor for the OS...")) ## end Setup Parallelization results.all &lt;- foreach(parameters.index = 1:nrow(kParameters$matrix), .combine = rbind) %do%{ message("Beginning simulation on new set of parameters...") n &lt;- kParameters$matrix[[parameters.index, 'n']] a &lt;- kParameters$matrix[[parameters.index, 'a']] b &lt;- kParameters$matrix[[parameters.index, 'b']] c &lt;- kParameters$matrix[[parameters.index, 'c']] i &lt;- kParameters$matrix[[parameters.index, 'i']] seed &lt;- kParameters$matrix[[parameters.index, 'seed']] registerDoRNG(seed) # set.seed() for parallel code errors &lt;- 0 no.zeros &lt;- 0 results &lt;- foreach(iiii=icount(iterations), .combine = rbind) %do%{ message(paste0("Iteration ", iiii, " of ", iterations)) data = data.frame(gen.hurdle(n, a, b, b, c, c, i, i, i)) data0 = data.frame(gen.hurdle(n, a, 0, 0, c, c, i, i, i)) p_0 =1-mean(data$z_p) p_0_hat =1-mean(data$tstar) p_0_b0 =1-mean(data0$z_p) p_0_hat_b0 =1-mean(data0$tstar) #power fit1 = lm(m ~ x, data=data) fit2 = hurdle(formula = y ~ m + x, data=data, dist = "poisson", zero.dist = "binomial") a_hat = summary(fit1)$coef[2,1] b1_hat = summary(fit2)[[1]]$count[2,1] b2_hat = summary(fit2)[[1]]$zero[2,1] ab1_hat = prod(a_hat,b1_hat) ab2_hat = prod(a_hat,b2_hat) #type I error fit3 = lm(m ~ x, data=data0) fit4 = hurdle(formula = y ~ m + x, data=data0, dist = "poisson", zero.dist = "binomial") a_hat_b0 = summary(fit3)$coef[2,1] b1_hat_b0 = summary(fit4)[[1]]$count[2,1] b2_hat_b0 = summary(fit4)[[1]]$zero[2,1] ab1_hat_b0 = prod(a_hat_b0,b1_hat_b0) ab2_hat_b0 = prod(a_hat_b0,b2_hat_b0) message(paste0("Bootstrapping...")) # bootstrap boot &lt;- foreach(jjjj = icount(r), .combine = rbind, .errorhandling = "remove", .packages = c("pscl")) %dopar%{ #power boot.data = data[sample(nrow(data), replace = TRUE), ] has.zero &lt;- prod(boot.data$y) &gt; 0 if(!has.zero) { no.zeros &lt;- no.zeros + 1 boot.data$y[1] = 0 warning(paste0("Iteration #",iiii, " Bootstrap #",jjjj, " had no zeros!"), immediate. = TRUE, call. = FALSE) } boot.fit1 = lm(m ~ x, data=boot.data) boot.fit2 = hurdle(formula = y ~ m + x, data=boot.data, dist = "poisson", zero.dist = "binomial") boot.a = summary(boot.fit1)$coef[2,1] boot.b1 = summary(boot.fit2)[[1]]$count[2,1] boot.b2 = summary(boot.fit2)[[1]]$zero[2,1] boot.ab1 = prod(boot.a,boot.b1) boot.ab2 = prod(boot.a,boot.b2) #Type I error boot.data0 = data0[sample(nrow(data0), replace = TRUE), ] boot.data0$y[1] = if(prod(boot.data0$y) &gt; 0) 0 else boot.data0$y[1] boot.fit3 = lm(m ~ x, data=boot.data0) boot.fit4 = hurdle(formula = y ~ m + x, data=boot.data0, dist = "poisson", zero.dist = "binomial") boot.a_b0 = summary(boot.fit3)$coef[2,1] boot.b1_b0 = summary(boot.fit4)[[1]]$count[2,1] boot.b2_b0 = summary(boot.fit4)[[1]]$zero[2,1] boot.ab1_b0 = prod(boot.a_b0,boot.b1_b0) boot.ab2_b0 = prod(boot.a_b0,boot.b2_b0) cbind(ab1_hat, ab2_hat, boot.ab1, boot.ab2, ab1_hat_b0, ab2_hat_b0, boot.ab1_b0, boot.ab2_b0) #return } # end bootstrap if(nrow(boot)!=r){ warning(paste0("Iteration #",iiii," threw ",r-nrow(boot)," error(s)"), immediate. = TRUE, call. = FALSE) errors &lt;- errors + r-nrow(boot) } z0.1 = qnorm((sum(boot[,3] &gt; boot[,1])+sum(boot[,3]==boot[,1])/2)/nrow(boot)) z0.2 = qnorm((sum(boot[,4] &gt; boot[,2])+sum(boot[,4]==boot[,2])/2)/nrow(boot)) z0.1_b0 = qnorm((sum(boot[,7] &gt; boot[,5])+sum(boot[,7]==boot[,5])/2)/nrow(boot)) z0.2_b0 = qnorm((sum(boot[,8] &gt; boot[,6])+sum(boot[,8]==boot[,6])/2)/nrow(boot)) alpha=0.05 # 95% limits z=qnorm(c(alpha/2,1-alpha/2)) # Std. norm. limits p1 = pnorm(z-2*z0.1) # bias-correct &amp; convert to proportions p2 = pnorm(z-2*z0.2) p1_b0 = pnorm(z-2*z0.1_b0) p2_b0 = pnorm(z-2*z0.2_b0) ci1 = quantile(boot[,3],p=p1) # Bias-corrected percentile lims ci2 = quantile(boot[,4],p=p2) ci1_b0 = quantile(boot[,7],p=p1_b0) ci2_b0 = quantile(boot[,8],p=p2_b0) sig.ab1 = if(prod(ci1) &gt; 0) 1 else 0 sig.ab2 = if(prod(ci2) &gt; 0) 1 else 0 sig.ab1_b0 = if(prod(ci1_b0) &gt; 0) 1 else 0 sig.ab2_b0 = if(prod(ci2_b0) &gt; 0) 1 else 0 #results cbind(sig.ab1, sig.ab2, sig.ab1_b0, sig.ab2_b0) } # end iterations mean.results &lt;- t(apply(results, 2, mean)) colnames(mean.results) &lt;- c("power of ab1", "power of ab2", "type I error of ab1", "type I error of ab2") cbind(t(kParameters$matrix[parameters.index, ]), mean.results, errors, no.zeros) } # end parameters loop # release cores back to the OS stopCluster(cl) View(results.all) }) # end System.time </code></pre> <p>Please tear me apart as I love to learn and am relying on your wisdom. Also, realize I am fairly new to R/Programming. Thank you in advance.</p>
[]
[ { "body": "<p>A couple of style / minor performance improvement comments. I believe it will take someone with statistical knowledge of the model you are using to help you more:</p>\n\n<ul>\n<li><p><code>message()</code> and <code>warning()</code> will concatenate strings if provided with multiple arguments so no need for <code>paste0()</code> here. <strong>Note that excessive verbosity might slow down your program because too much resources are used to print messages.</strong></p></li>\n<li><p>when working with scalars, it is better/faster to use <code>*</code> rather than <code>prod</code>.</p></li>\n</ul>\n\n<pre class=\"lang-r prettyprint-override\"><code>library(microbenchmark)\n\nmicrobenchmark({prod(10, 11)}, {10*11}, times = 10000)\n#&gt; Unit: nanoseconds\n#&gt; expr min lq mean median uq max neval\n#&gt; { prod(10, 11) } 394 413 461.8892 430 456 7903 10000\n#&gt; { 10 * 11 } 204 221 242.8107 228 241 4206 10000\n</code></pre>\n\n<ul>\n<li>as far as I can tell, you can drop the following lines because you're not using them:</li>\n</ul>\n\n<pre class=\"lang-r prettyprint-override\"><code>p_0 =1-mean(data$z_p)\np_0_hat =1-mean(data$tstar)\np_0_b0 =1-mean(data0$z_p)\np_0_hat_b0 =1-mean(data0$tstar)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:25:38.113", "Id": "429849", "Score": "0", "body": "Thank you for taking the time to review this. I had no idea that ```message()``` and ```warning()``` functioned like that. Also, a very good point about less is more for printing.\n\nI meant to comment those lines out. I do not need them. Another great catch." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T11:04:56.523", "Id": "222148", "ParentId": "222109", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T20:35:42.277", "Id": "222109", "Score": "1", "Tags": [ "multithreading", "functional-programming", "r" ], "Title": "Two-Part Hurdle Model Simulation with Bootstrapping" }
222109
<p>I'm trying to become better at javascript and have written a simple script that just creates some html from getting some details from some elements (e.g. the image alt text) and inserts it onto the page to create a caption. Hover over the top right of the image to see this caption.</p> <p>I was able to successfully achieve what I wanted through my code. However, my javascript feels a bit 'wet', and I'd like to be able to improve this for brevity and clarity.</p> <p>Can anyone recommend any improvements to my javascript, and make it either more concise or clear?</p> <p>I know that jQuery can achieve this in fewer lines of code, but I'm less of a fan of jQuery and believe that ES6/ES7 etc can often write more concise code.</p> <p>Thanks for any help here. Find a working demo below:</p> <p>Codepen: <a href="https://codepen.io/anon/pen/PrwzBj" rel="nofollow noreferrer">https://codepen.io/anon/pen/PrwzBj</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>/* --- Wide Image Caption --- */ // Define Elements: const wideImg = document.querySelector('.full-width-image-atf img'), captionText = wideImg.getAttribute('alt'), captionInnerHTML = '&lt;span class="image-caption"&gt;' + captionText + '&lt;/span&gt;', caption = document.createElement('div'); // Amend caption: caption.setAttribute('class', 'image-caption-wrap'); caption.style.cssText = 'background: none;'; caption.innerHTML = captionInnerHTML; // Insert on page: wideImg.parentNode.appendChild(caption); /* --- End of Wide Image Caption --- */</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>img {width: 100%} .full-width-image-atf .content-main-image { position: relative; color: #fff; } .full-width-image-atf .image-caption-wrap { position: absolute; top: 0; right: 0; display: flex; flex-flow: row-reverse; align-items: center; padding: 15px 20px; } .full-width-image-atf .image-caption-wrap:before { content: '\f05a'; font-family: 'Font Awesome 5 Pro'; font-size: 2em; } .full-width-image-atf .image-caption { opacity: 0; padding-right: 10px; } .full-width-image-atf .image-caption-wrap:hover .image-caption { opacity: 1; } .full-width-image-atf .image-caption-wrap:hover { background: black !important; cursor: pointer; } .full-width-image-atf .content-main-image, .full-width-image-atf .content-main-image * { transition: 0.4s ease all }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class='full-width-image-atf'&gt; &lt;div class="content-main-image"&gt; &lt;img src="https://static.independent.co.uk/s3fs-public/thumbnails/image/2018/12/31/10/lion-face.jpg?w968h681" alt="This is a test"&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Not a comment on functionality, but here:</p>\n\n<pre><code>const wideImg = document.querySelector('.full-width-image-atf img'),\n captionText = wideImg.getAttribute('alt'),\n captionInnerHTML = '&lt;span class=\"image-caption\"&gt;' + captionText + '&lt;/span&gt;',\n caption = document.createElement('div');\n</code></pre>\n\n<p>I don't think chaining declarations using <code>,</code> like you are is a good idea for a couple reasons:</p>\n\n<ol>\n<li><p>It isn't immediately clear that all the variables involved are being declared as <code>const</code>. Yes, you can tell if you check the indentation, or notice the commas at the end, but it isn't as clear as explicit <code>const</code>s all the way down.</p></li>\n<li><p>It makes refactoring more of a pain. Say in the future you want to break that up and maybe stick a <code>log</code> call in there or some other non-declaration. Now you need to manually replace the commas with semi-colons, <strong>and remember to add <code>const</code> to all the now separate declarations</strong>.</p></li>\n</ol>\n\n<p>I'd suggest just writing it out fully from the start, and maybe space out the last one since it has a separate purpose:</p>\n\n<pre><code>const wideImg = document.querySelector('.full-width-image-atf img');\nconst captionText = wideImg.getAttribute('alt');\nconst captionInnerHTML = '&lt;span class=\"image-caption\"&gt;' + captionText + '&lt;/span&gt;';\n\nconst caption = document.createElement('div');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:00:33.623", "Id": "222114", "ParentId": "222111", "Score": "4" } }, { "body": "<p>I'd recommend looking into using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\" rel=\"nofollow noreferrer\"><code>&lt;template&gt;</code></a> tag, and possibly templates with <a href=\"https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots#Adding_flexibility_with_slots\" rel=\"nofollow noreferrer\">slots</a> unless the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot#Browser_compatibility\" rel=\"nofollow noreferrer\">browser compatibility</a> causes an issue. That way the template can remain in the markup, and all the Javascript logic might need to do is update the content that is dynamic (e.g. the caption text).</p>\n<hr />\n<p>Instead of using <code>setAttribute()</code> to add a class name to element:</p>\n<blockquote>\n<pre><code>caption.setAttribute('class', 'image-caption-wrap');\n</code></pre>\n</blockquote>\n<p>There is a method: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods\" rel=\"nofollow noreferrer\"><code>classList.add()</code></a> that can be used instead:</p>\n<pre><code>caption.classList.add('image-caption-wrap');\n</code></pre>\n<hr />\n<p>I see the CSS has <code>!important</code>:</p>\n<blockquote>\n<pre><code>.full-width-image-atf .image-caption-wrap:hover {\n</code></pre>\n</blockquote>\n<pre><code> background: black !important;\n</code></pre>\n<p>It is wise to not depend on <code>!important</code> if possible, <a href=\"https://stackoverflow.com/a/3427813/1575353\">to avoid confusion</a>. If you add the <code>background: none</code> style in the regular CSS then that should allow you to remove the <code>!important</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T23:40:21.840", "Id": "222122", "ParentId": "222111", "Score": "3" } }, { "body": "<h2>General points</h2>\n\n<ul>\n<li><p>I think that multi line declarations are poor practice and can easily lead to global declarations if you have a miss placed <code>;</code> and don't use the <code>\"use strict\"</code> directive.</p></li>\n<li><p>As the DOM interface is rather verbose you can create some helper functions to reduce the amount of noise in your code and save yourself the trouble of having to repeat the same thing over and over.. </p></li>\n<li><p>Avoid inserting HTML directly via JavaScript, it is incredibly slow compared to using <code>document.createElement</code>, <code>appendChild</code>, etc...</p></li>\n<li><p>Do not change the cursor to a pointer if there is nothing to click. </p></li>\n<li><p>Rather than have an empty box (it is meaningless) put a question mark in there and create a box around it via CSS rule border..</p></li>\n</ul>\n\n<h2>Helper functions</h2>\n\n<p>Example of helper functions to do some common tasks. I never use jQuery and thus name the functions tag to $ and append to $$ to further reduce the code noise.</p>\n\n<pre><code>const query = (qStr, parent = document) =&gt; parent.querySelector(qStr);\nconst style = (element, style) =&gt; (Object.assign(element.style, style), element);\nconst tag = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\nconst append = (parent, ...sibs) =&gt; sibs.reduce((p, sib) =&gt; (p.appendChild(sib), p), parent);\n</code></pre>\n\n<p><strong>Note</strong> that each function returns an element so can be used as an argument for tag and append. There are many more helpers you can create to reduce the code verbosity.</p>\n\n<p>or when not using jQuery</p>\n\n<pre><code>// $ creates tag, <span class=\"math-container\">$$ appends elements\nconst query = (qStr, parent = document) =&gt; parent.querySelector(qStr);\nconst style = (element, style) =&gt; (Object.assign(element.style, style), element);\nconst $ = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\nconst $$</span> = (parent, ...sibs) =&gt; sibs.reduce((p, sib) =&gt; (p.appendChild(sib), p), parent);\n</code></pre>\n\n<h2>Example</h2>\n\n<p>With these function you can then simplify your code to</p>\n\n<pre><code>addImageCaption(query(\".full-width-image-atf img\")); \nfunction addImageCaption(img) {\n <span class=\"math-container\">$$(img.parentNode,\n $$</span>(style($(\"div\", {className:\"image-caption-wrap\"}), {background: \"none\"}), \n $(\"span\", {className:\"image-caption\", textContent: img.alt})\n )\n );\n}\n</code></pre>\n\n<h2>Demo</h2>\n\n<p><strong>Note</strong> that the CR snippet will not work when it contains the string $$</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\n \nsetTimeout(()=&gt; addImageCaption(query(\".full-width-image-atf img\")), 0);\n\nfunction addImageCaption(img) {\n append(img.parentNode,\n append(style($(\"div\", {className:\"image-caption-wrap\"}), {background: \"none\"}), \n $(\"span\", {className:\"image-caption\", textContent: img.alt})\n )\n );\n}\n\n\n// DOM helpers \nconst query = (qStr, parent = document) =&gt; parent.querySelector(qStr);\nconst style = (element, style) =&gt; (Object.assign(element.style, style), element);\nconst $ = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\nconst append=(par, ...sibs)=&gt;sibs.reduce((p, sib)=&gt;(p.appendChild(sib), p), par);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>img {width: 100%}\n.full-width-image-atf .content-main-image {\n position: relative;\n color: #fff;\n}\n\n.full-width-image-atf .image-caption-wrap {\n position: absolute;\n top: 0;\n right: 0;\n display: flex;\n flex-flow: row-reverse;\n align-items: center;\n padding: 15px 20px;\n}\n.full-width-image-atf .image-caption-wrap:before {\n content: '?';\n padding-left: 5px;\n padding-right: 5px;\n border: 1px solid white;\n}\n.full-width-image-atf .image-caption {\n opacity: 0;\n padding-right: 10px;\n}\n.full-width-image-atf .image-caption-wrap:hover .image-caption {\n opacity: 1;\n}\n.full-width-image-atf .image-caption-wrap:hover {\n background: black !important;\n cursor: help;\n}\n.full-width-image-atf .content-main-image, .full-width-image-atf .content-main-image * { transition: 0.4s ease all }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class='full-width-image-atf'&gt;\n &lt;div class=\"content-main-image\"&gt;\n &lt;img src=\"https://static.independent.co.uk/s3fs-public/thumbnails/image/2018/12/31/10/lion-face.jpg?w968h681\" alt=\"This image is of a lion.\"&gt;\n &lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T01:51:50.673", "Id": "222128", "ParentId": "222111", "Score": "4" } } ]
{ "AcceptedAnswerId": "222128", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:48:40.030", "Id": "222111", "Score": "3", "Tags": [ "javascript", "css", "ecmascript-6", "dom" ], "Title": "Simple javascript code to create an image caption" }
222111
<p>I have this code that I've made to parse a string of HTML and tell me if it is all enclosed within a specified tag:</p> <pre><code>const textIsWrappedWithTag = (text, tag) =&gt; { const tempDocument = new DOMParser().parseFromString(text, "text/xml"); if (tempDocument.getElementsByTagName("parsererror").length) { return false; } if (tempDocument.children.length === 1 &amp;&amp; tempDocument.children[0].tagName.toLowerCase() === tag.toLowerCase()) { return true; } return false; }; </code></pre> <p>My test cases do what I want them to do:</p> <pre><code>const yes = '&lt;p&gt;&lt;div&gt;&lt;span&gt;one&lt;/span&gt;&lt;/div&gt;&lt;div&gt;&lt;p&gt;two&lt;/p&gt;&lt;/div&gt;&lt;/p&gt;'; const no = '&lt;p&gt;one&lt;/p&gt;&lt;p&gt;two&lt;/p&gt;&lt;p&gt;three&lt;/p&gt;'; const no2 = '&lt;div&gt;&lt;p&gt;one&lt;/p&gt;&lt;p&gt;two&lt;/p&gt;&lt;p&gt;three&lt;/p&gt;&lt;/div&gt;'; textIsWrappedWithTag(yes, 'p'); &gt; true textIsWrappedWithTag(no, 'p'); &gt; false textIsWrappedWithTag(no2, 'p'); &gt; false </code></pre> <p>I played around with this in the console to develop it, but I'm not super famliar with <code>DOMParser</code> and <code>parsererror</code>, so I want to be sure that I'm not overlooking something</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:35:15.710", "Id": "429783", "Score": "0", "body": "Welcome to Code Review. `textIsWrappedWithTag(yes, 'p');` actually returns `false` instead of `true`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:39:03.087", "Id": "429784", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ ah sorry, I left out a `.length` check. Fixed that and now it returns `true`." } ]
[ { "body": "<p>Your code looks good and concise.</p>\n\n<p>Your test cases cover almost every branch of the code, which is also good.</p>\n\n<p>You can improve the variable names:</p>\n\n<ul>\n<li><p>The <code>temp</code> in <code>tempDocument</code> is not necessary. Therefore the variable name should better be <code>document</code>, or if that is too long, <code>doc</code>. Be careful though when abbreviating variable names, and don't make them ambiguous.</p></li>\n<li><p>The <code>no</code> test case should rather be called <code>parsererror</code>. I had to run the code to see that it really tests this branch of the code. By improving the name of the variable, you make this more obvious.</p></li>\n</ul>\n\n<p>There is a test case missing for a tag name other than <code>p</code>.</p>\n\n<pre><code>if (doc.children.length === 1 &amp;&amp; doc.children[0].tagName.toLowerCase() === tag.toLowerCase()) {\n return true;\n}\nreturn false;\n</code></pre>\n\n<p>If you want, you can write this code a bit shorter:</p>\n\n<pre><code>return doc.children.length === 1\n &amp;&amp; doc.children[0].tagName.toLowerCase() === tag.toLowerCase();\n</code></pre>\n\n<p>Your current code is a bit longer, but it allows you to set a breakpoint on the <code>return true</code> statement, which may be useful when debugging the code. But since you already have automated tests running, you will probably not need to set a breakpoint there. Your choice. Many programmers prefer the shorter form, but the longer form is not bad per se.</p>\n\n<p>The expression <code>doc.children.length === 1</code> is always true. This is because you are parsing the text using the <code>text/xml</code> type, and the XML standard requires exactly 1 root element. Everything else will end up in the parsererror branch. To verify this, you should add a test case for an empty string. And a test case for an XML comment, such as <code>&lt;!-- comment --&gt;</code>.</p>\n\n<p>When I first read the function name <code>textIsWrappedWithTag</code>, I didn't know exactly what to expect from that function. My first thought was that <code>textIsWrappedWithTag('&lt;div&gt;&lt;p&gt;text&lt;/p&gt;&lt;/div&gt;', 'p')</code> would return true, since there is some text that is enclosed in a <code>p</code> tag. You could try to find a better name for that function, maybe <code>topLevelElementIs</code>.</p>\n\n<p>By the way, the DOM API talks about <em>elements</em>, while the HTML standard calls them <em>tags</em>. If you want your function to feel like it belongs to the DOM API, you should call it <code>textIsWrappedWithElement</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T23:13:15.900", "Id": "222118", "ParentId": "222113", "Score": "5" } } ]
{ "AcceptedAnswerId": "222118", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T21:52:35.467", "Id": "222113", "Score": "3", "Tags": [ "javascript", "html", "parsing", "dom" ], "Title": "helper function to determine if html text is wrapped with a certain tag" }
222113
<p>I'm calling these two methods on a Worker that is executed every 24 hours at midnight in the background.</p> <p>The code seems to be a little bit difficult to read and I'm not sure if i'm iterating through the collections in the smartest way.</p> <p>Is there a more elegant or faster way to iterate on these methods? Would you suggest any other change?</p> <pre><code> # Deletes UserDiscounts when the discount belongs to a segment that the user does not belong to def clean_user_discounts UserDiscount.all.each do |user_discount| user_segment = UserSegment.find_by(user: user_discount.user) discount_segment = DiscountSegment.find_by(discount: user_discount.discount) user_segment_id = user_segment ? user_segment.segment_id : nil discount_segment_id = discount_segment ? discount_segment.segment_id : nil user_discount.delete unless discount_segment_id == user_segment_id end end # Creates UserDiscounts when a user belongs to a segment and that segment has a discount def create_user_discounts UserSegment.all.each do |user_segment| DiscountSegment.where(segment: user_segment.segment).each do |discount_segment| unless UserDiscount.find_by(discount: discount_segment.discount, user: user_segment.user) UserDiscount.create(discount: discount_segment.discount, user: user_segment.user) end end end end </code></pre>
[]
[ { "body": "<p>The first thing that I noticed that could be improved is to use <code>find_each</code> instead of <code>all</code>.</p>\n\n<p><code>all</code> will load all the records from the database at once, which can blow up your server. Using <code>find_each</code> instead, you'll load records in batches.</p>\n\n<p>Also, another thing here is that you're using heavily object in queries, for instance: <code>UserSegment.find_by(user: user_discount.user)</code> instead of <code>UserSegment.find_by(user_id: user_discount.user_id)</code></p>\n\n<p>When using object references like that, if the object isn't loaded rails will perform a query to retrieve the object - therefore this code have a N+1 problem in it - meaning you end up loading those objects (such as user, discount and segment) even though have basically the same info in the parent object already loaded.</p>\n\n<p>So always prefer to ids instead of objects for those type of queries.</p>\n\n<p>If I understood your problem correctly I think you can simplify greatly its performance and syntax by just leveraging ActiveRecord query options. Instead of loading the objects in memory and using ruby to do the verifications for you, you can just instruct ActiveRecord to perform joins and whatnot and just return to you the information that you need.</p>\n\n<p>Here's how I'd do it:</p>\n\n<p>First, for removing invalid user discounts I'd create a query that return them to me, like so:</p>\n\n<pre><code>class UserDiscount &lt; ApplicationRecord\n belongs_to :user\n belongs_to :discount\n\n def self.invalid_user_discounts\n UserDiscount.\n joins(\"INNER JOIN discount_segments ON user_discounts.discount_id = discount_segments.discount_id\").\n joins(\"INNER JOIN user_segments ON user_discounts.user_id = user_segments.user_id\").\n where(\"user_segments.segment_id &lt;&gt; discount_segments.segment_id\")\n end\nend\n</code></pre>\n\n<p>See how instead of loading multiple classes I just let the powerful SQL and rails do the job for me? This query isn't too complicated to understand and does the same job as the previous loop.</p>\n\n<p>Once we have a query that returns invalid discounts, I can use <code>find_each</code> and remove them:</p>\n\n<pre><code>def self.clean_user_discounts\n invalid_user_discounts.find_each do |user_discount|\n user_discount.destroy\n end\nend\n</code></pre>\n\n<p>For creating discounts, I use the same approach, I let AR and SQL do the heavy lifting in this case, and just use the final formatted response to iterate over the results, like so:</p>\n\n<pre><code>def self.create_user_discounts\n query = UserSegment.\n joins(\"INNER JOIN discount_segments ON user_segments.segment_id = discount_segments.segment_id\").select(:id, :discount_id, :user_id)\n\n\n query.find_each do |user_and_discount_segment|\n UserDiscount.find_or_create_by(\n discount_id: user_and_discount_segment.discount_id,\n user_id: user_and_discount_segment.user_id)\n end\nend\n</code></pre>\n\n<p>Rails allows us to merge the two tables <code>UserSegment</code> and <code>DiscountSegment</code> and as well to select just the fields from that query that we need, in this case: <code>user_id</code>, <code>discount_id</code> - making the creation of <code>UserDiscount</code> much easier.</p>\n\n<p>Finally, you can see the usage of <code>find_or_create_by</code> - this is provided by Rails as well, so we don't have to issue two commands.</p>\n\n<p>full source code: <a href=\"https://gist.github.com/jonduarte/c54146cb7e00f0045193aad739301c13\" rel=\"nofollow noreferrer\">https://gist.github.com/jonduarte/c54146cb7e00f0045193aad739301c13</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-26T10:52:37.597", "Id": "222973", "ParentId": "222115", "Score": "2" } } ]
{ "AcceptedAnswerId": "222973", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:45:27.203", "Id": "222115", "Score": "1", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Re-creating user discounts nightly" }
222115
<p>I am fairly new to React, but I have been reading a lot of the official documentation and trying to do things correctly.</p> <p><strong>Background:</strong></p> <p>I am building a simple lyrics application in ReactJS, it looks something like this:</p> <p><a href="https://i.stack.imgur.com/AvXE8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AvXE8.png" alt="enter image description here"></a></p> <p>The application is deployed <a href="https://bejebeje.com" rel="nofollow noreferrer">here</a> and the code is <a href="https://github.com/JwanKhalaf/Bejebeje.React" rel="nofollow noreferrer">open source</a>.</p> <p><strong>The bit to review</strong></p> <p>The code for the search component is the <code>Search.jsx</code> file:</p> <pre><code>import React from "react"; import posed from "react-pose"; import "./Search.css"; const SearchButton = posed.div({ active: { width: 600, borderRadius: 3 // transition: { duration: 20000 } }, inactive: { width: 68, borderRadius: 50 // transition: { duration: 20000 } } }); const SearchInput = posed.input({ active: { width: 600, padding: 15 }, inactive: { width: 0, padding: 0 } }); class Search extends React.Component { constructor(props) { super(props); this.searchInput = React.createRef(); this.handleInputChange = this.handleInputChange.bind(this); this.handleSearchButtonClick = this.handleSearchButtonClick.bind(this); this.state = { query: "", isActive: false }; } handleSearchButtonClick(event) { event.preventDefault(); this.setState({ isActive: !this.state.isActive }); this.searchInput.current.focus(); } handleInputChange(event) { this.props.search(event.target.value); } render() { const { isActive } = this.state; return ( &lt;SearchButton className="search__wrap" pose={isActive ? "active" : "inactive"} &gt; &lt;form className="search__form"&gt; &lt;SearchInput type="text" className="search__input" onChange={this.handleInputChange} ref={this.searchInput} /&gt; &lt;button className="search__button" onClick={this.handleSearchButtonClick} &gt; &lt;i className="fal fa-search search__icon" /&gt; &lt;/button&gt; &lt;/form&gt; &lt;/SearchButton&gt; ); } } export default Search; </code></pre> <p>Here is the top level <code>App.jsx</code>:</p> <pre><code>import React from "react"; import { render } from "react-dom"; import { Router } from "@reach/router"; import Authorisation from "./components/Authorisation/Authorisation"; import Artists from "./components/Artists/Artists"; import ArtistLyrics from "./components/ArtistLyrics/ArtistLyrics"; import Lyric from "./components/Lyric/Lyric"; import { API_CONSTANTS } from "./helpers/apiEndpoints"; import "./App.css"; class App extends React.Component { constructor(props) { super(props); this.searchArtists = this.searchArtists.bind(this); this.handleSearchInput = this.handleSearchInput.bind(this); const artists = JSON.parse(localStorage.getItem("artists")); this.state = { error: null, isLoaded: false, isLoading: false, artists: artists || [], searchTerm: "" }; } componentDidMount() { const artistFetchDate = localStorage.getItem("artistsFetchTimestamp"); const date = artistFetchDate &amp;&amp; new Date(parseInt(artistFetchDate, 10)); const currentDate = Date.now(); const dataAgeInMinutes = Math.round((currentDate - date) / (1000 * 60)); const tooOld = dataAgeInMinutes &gt;= 15; if (tooOld) { if (!this.state.isLoading) { this.fetchArtists(); } } else { console.log( `Using data from local storage that is ${dataAgeInMinutes} minutes old.` ); } } fetchArtists() { this.setState({ artists: [], isLoaded: false, isLoading: true }); fetch(API_CONSTANTS.artists) .then(res =&gt; res.json()) .then( result =&gt; { this.setState({ isLoaded: true, isLoading: false, artists: result }); localStorage.setItem("artists", JSON.stringify(this.state.artists)); localStorage.setItem("artistsFetchTimestamp", Date.now()); }, error =&gt; { this.setState({ isLoaded: true, isLoading: false, error }); } ); } handleSearchInput(searchTerm) { if (searchTerm.length &gt;= 3) { this.searchArtists(searchTerm); } else { this.fetchArtists(); } } searchArtists(name) { this.setState({ artists: [], isLoaded: false, isLoading: true }); fetch(API_CONSTANTS.searchArtists(name)) .then(res =&gt; res.json()) .then( result =&gt; { console.table(result); this.setState({ isLoaded: true, isLoading: false, artists: result }); }, error =&gt; { this.setState({ isLoaded: true, isLoading: false, error }); } ); } render() { return ( &lt;div&gt; &lt;Router&gt; &lt;Artists path="/" artists={this.state.artists} search={this.handleSearchInput} /&gt; &lt;ArtistLyrics path="artists/:artistSlug/lyrics" /&gt; &lt;Lyric path="artists/:artistSlug/lyrics/:lyricSlug" /&gt; &lt;Authorisation path="/callback" /&gt; &lt;/Router&gt; &lt;/div&gt; ); } } render(&lt;App /&gt;, document.getElementById("root")); </code></pre> <p>Although the search currently "works", it isn't ideal, on each key pressed it re-renders the list of artists and even when the actual search starts happening (when the user types 3 characters or more), it against re-renders on each key press.</p> <p>A few concerns I have:</p> <ol> <li>In terms of data flow and lifting state up, have I got that correct? My <code>searchTerm</code> is kept in the <code>App.jsx</code> component and so is my artist list. The artist list is passed to <code>Artists.jsx</code> component for rendering.</li> <li>How can I stop unnecessary re-rendering?</li> </ol>
[]
[ { "body": "<p>Yes you can stop re-rendering. Just don't <code>.setState()</code> :)</p>\n\n<p>I think what would are trying to achieve is the illusion of all the band data being on hand, when search is snappy.</p>\n\n<p>UX-wise you have a choice to make:</p>\n\n<ul>\n<li>is search instantaneous, or</li>\n<li>is search an activity</li>\n</ul>\n\n<h3>Live search</h3>\n\n<ul>\n<li>if you have the artist list, search in-memory, that's always best!</li>\n<li>if you must make a network call, maintain cache of responses:\n\n<ul>\n<li>either in-memory / localStorage cache, or</li>\n<li>set response header and rely on browser to cache the responses</li>\n</ul></li>\n<li>when search input is changed:\n\n<ul>\n<li>if you have matches in cache, display them</li>\n<li>if you don't, kick off async fetch, but don't change the screen</li>\n<li>when you get the results, if input changed yet again, don't display</li>\n<li>[maybe] after a timeout (input idle, NNNms passed, results not ready) show spinner</li>\n<li>when you have matches in cache that match the input, display them</li>\n</ul></li>\n</ul>\n\n<p>Here's a first, ugly pass at how I'd start prototyping this flow:</p>\n\n<pre><code>const [current, setCurrent] = useState(\"\");\nconst [, refresh] = useState();\nconst [lastChangeTime, setLastChangeTime] = useState(0);\nconst [lastData, setLastData] = useState([]);\n\nconst search = async (what) =&gt; {\n global_cache[what] = await (await fetch(`${url}/?q=${what}`)).json();\n // FIXME ugly, consider observing cache\n refresh(Math.random());\n};\n\nconst timeout = (ms) =&gt; new Promise(\n resolve =&gt; setTimeout(resolve, ms));\n\nconst kickSpinner = async () =&gt; {\n await timeout(500);\n refresh(Math.random());\n}\n\nconst change = (e) =&gt; {\n setLastChangeTime(Date.now());\n setCurrent(e.target.value);\n search(e.target.value);\n kickSpinner();\n};\n\n// FIXME ugly, not functional, maybe redux?\nconst data = global_cache[current];\n\nif (data) {\n // FIXME ugly, may loop, maybe useEffect?\n setLastData(data);\n}\n\nconst spinner = (Date.now() - lastChangeTime) &gt;= 500;\n\nreturn (data?\n &lt;BandList data={data}&gt;:\n spinner?\n &lt;Spinner/&gt;:\n &lt;BandList data={lastData}&gt;);\n</code></pre>\n\n<h3>Activity</h3>\n\n<ul>\n<li>require user to hit Enter or click the search button</li>\n<li>gray out current screen or show \"loading...\" or a snipper</li>\n<li>show list of matches when you have them.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T01:56:22.260", "Id": "222129", "ParentId": "222116", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T22:48:01.330", "Id": "222116", "Score": "1", "Tags": [ "react.js", "jsx" ], "Title": "Simple lyrics application" }
222116
<h2>Algorithm</h2> <blockquote> <p>Let <span class="math-container">\$M_0\$</span> denote the null model which contains no predictors. This model simply predicts the sample mean of each observation. </p> <p>For <span class="math-container">\$k=1,2,\ldots,n\$</span>:</p> <ul> <li>Fit all <span class="math-container">\$n \choose k\$</span> models that contain exactly <span class="math-container">\$k\$</span> predictors.</li> <li>Pick the best among these <span class="math-container">\$n \choose \$</span> models, and call it <span class="math-container">\$M_k\$</span>. Here the best is defined as having the smallest RSS or equivalent measure.</li> </ul> <p>Select the single best model among <span class="math-container">\$M_0,M_1,\ldots,M_n\$</span> using cross validated prediction error, <span class="math-container">\$C_p\$</span>, BIC, <span class="math-container">\$R^2_{\mathit{adj}}\$</span> or any other method.</p> </blockquote> <p>I looked up a tutorial and created a function based upon its script. It's essentially used so I can select dependent variables that's a subset of a data frame. It runs but it is very very slow.</p> <p>How would I flatten a nested for-loop such as this?</p> <pre class="lang-py prettyprint-override"><code># Loop over all possible combinations of k features for k in range(1, len(X.columns) + 1): # Looping over all possible combinations: from 11 choose k for combo in itertools.combinations(X.columns,k): # Store temporary results temp_results = fit_linear_reg(X[list(combo)],Y) # Append RSS to RSS Lists RSS_list.append(temp_results[0]) </code></pre> <p>I tried implementing an enumerate version but it did not work. I'm not sure, how I can flatten the nested for loop, such that I can append the results of a function to a list. </p> <pre class="lang-py prettyprint-override"><code># This function takes in a subset of a dataframe representing independent # variables (X) and a column for dependent variable (Y). This function fits # separate models for each possible combination of the k predictors (which is # based on the column length of X) and then select the best subset. The # resulting output is a dataframe. def BestSubsetSelection(X,Y): # number of predictors k = len(X.columns) # Store the RSS from a linear regression model RSS_list = [] # Store the R-square from a linear regression model R_squared_list = [] # Store the features for a given iteration. feature_list = [] # Store the number of features used for a given iteration. This corresponds with the feature_list. numb_features = [] # Loop over all possible combinations of k features for k in range(1, len(X.columns) + 1): # Looping over all possible combinations: from 11 choose k for combo in itertools.combinations(X.columns,k): # Store temporary results temp_results = fit_linear_reg(X[list(combo)],Y) # Append RSS to RSS Lists RSS_list.append(temp_results[0]) # Append R-Squared TO R-Squared list R_squared_list.append(temp_results[1]) # Append Feature/s to Feature list feature_list.append(combo) # Append the number of features to the number of features list numb_features.append(len(combo)) df = pd.DataFrame({ 'No_of_Features': numb_features, 'RSS' : RSS_list, 'R-Squared' : R_squared_list, 'Features' : feature_list }) # Finding the Best Subsets for each number of features # The smallest RSS df_min = df[df.groupby('No_of_Features')['RSS'].transform(min) == df['RSS']] # The Largest R-Squared Value df_max = df[df.groupby('No_of_Features')['R-Squared'].transform(min) == df['R-Squared']] display(df_min) display(df_max) # Adding columns to the dataframe with RSS and R-Squared values of the best subset df['min_RSS'] = df.groupby('No_of_Features')['RSS'].transform(min) df['max_R_Squared'] = df.groupby('No_of_Features')['R-Squared'].transform(max) </code></pre> <p>This code is taken from my <a href="https://github.com/melmaniwan/Elections-Analysis/tree/5fa0bae0ffbd0ad9db390002feee3e36e88e2422/Implementing%20Subset%20Selections.ipynb" rel="nofollow noreferrer">IPython notebook</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T01:23:38.830", "Id": "429798", "Score": "0", "body": "@Peilonrayz I hope the modifications clarifies the situation. I was also told that if all combinations are to be checked then there is no way it could be linear, but does that mean it cannot be made more efficient?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T07:09:28.063", "Id": "429814", "Score": "0", "body": "Is there a good reason for using different measures to select the best between two models with the same number of predictors vs two models with a different number of predictors? It seems unnecessarily complicated to me." } ]
[ { "body": "<h1>comments</h1>\n\n<p>comments should explain why you do something, not what you do. <code># Append R-Squared TO R-Squared list</code> adds nothing of value. On the contrary, it uses vertical space, and if ever you change something of the code you will need to change the coàmments as well</p>\n\n<pre><code># This function takes in a subset of a dataframe representing independent \n# variables (X) and a column for dependent variable (Y). This function fits \n# separate models for each possible combination of the k predictors (which is \n# based on the column length of X) and then select the best subset. The \n# resulting output is a dataframe.\n</code></pre>\n\n<p>could be the <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> of the method if it were correct. This function does not return a DataFrame, but only prints the results</p>\n\n<h1>functions</h1>\n\n<p>Now you have 1 monster function that:\n- calls the test\n- aggregates the values\n- displays the results</p>\n\n<p>Better would be to split this</p>\n\n<h1>getting the results</h1>\n\n<p>instead of having to append the results to 4 lists, I would extract this to a generator that <code>yield</code>s a <code>dict</code> and then use something like <a href=\"http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.from_records.html#pandas.DataFrame.from_records\" rel=\"nofollow noreferrer\"><code>DataFrame.from_records</code></a> to combine this.</p>\n\n<h2>powerset</h2>\n\n<p>what you do here:</p>\n\n<pre><code>for k in range(1, len(X.columns) + 1):\n # Looping over all possible combinations: from 11 choose k\n for combo in itertools.combinations(X.columns,k):\n</code></pre>\n\n<p>looks a lot like the <code>powerset</code> <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\">itertools-recipe</a>, so let's use that one:</p>\n\n<pre><code>from itertools import chain, combinations\n\n\ndef powerset(iterable):\n \"powerset([1,2,3]) --&gt; () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)\"\n s = list(iterable)\n return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n\n\ndef generate_combo_comparisons(X, Y):\n for combo in powerset(X.columns):\n if not combo: # the first combo is empty\n continue\n RSS, R_squared = fit_linear_reg(X[list(combo)], Y)\n yield {\n \"No_of_Features\": len(combo),\n \"RSS\": RSS,\n \"R-Squared\": R_squared,\n \"Features\": combo,\n }\n</code></pre>\n\n<p>To get the maximum indices of each group, you can use <a href=\"https://stackoverflow.com/a/51496653/1562285\"><code>groupby.idxmax</code></a></p>\n\n<p>You add columns <code>'min_RSS'</code> to the original <code>DataFrame</code>. Better here would be to generate a new summary DataFrame</p>\n\n<pre><code>def subset_results(X, Y):\n df = pd.DataFrame.from_records(\n data=list(generate_combo_comparisons(X, Y)),\n index=[\"No_of_Features\", \"RSS\", \"R-Squared\", \"Features\"],\n )\n\n summary = df.groupby(\"No_of_Features\")[\"R-Squared\"].agg(\n {\"RSS\": \"min\", \"R-Squared\": \"max\"}\n )\n df_min = df.loc[df.groupby(\"No_of_Features\")[\"RSS\"].idxmin()]\n df_max = df.loc[df.groupby(\"No_of_Features\")[\"R-Squared\"].idxmax()]\n return df, df_min, df_max, summary\n</code></pre>\n\n<p>And then you can pass these results on to the plotting function</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T08:29:48.340", "Id": "222137", "ParentId": "222123", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T23:53:57.550", "Id": "222123", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "combinatorics", "statistics" ], "Title": "Pick the best combination of n choose k models" }
222123
<p>This is my account table:</p> <pre><code>CREATE TABLE mwUser ( username varchar2(20) primary key not null, salt varchar2(64) unique not null, hashedpw varchar2(64) not null, email varchar2(320) unique not null ); </code></pre> <p>When I register a new user with my java webservice I automatically generate a random salt and store in the database base (see code below):</p> <pre><code>Connection c = dataSource.getConnection(); Statement stmt = c.createStatement(); boolean isFound=true; String randomSalt=""; while(isFound){ isFound=false; String randomSalt=createRandomString(); //creates salt/random string ResultSet rs = stmt.executeQuery("SELECT * FROM mvUser where salt="+randomString); //check if salt is unique while (rs.next()) { isFound=true; } } Statement insertStmt = c.createStatement(); String hashedPW=hash(randomSalt+pw); //generates hashed pw ResultSet rs = stmt.executeQuery("INSERT INTO mvUser VALUES(.....)); stmt.close(); c.close(); </code></pre> <p>But as you can see, from my point of view my code is not clean/performant/readable because I have two statements (for checking if salt is unique and and second statement is for inserting).</p> <p>How can I automatically generate an unique string(salt) and hash it at the same time. I am trying to make my code more performant and read able.</p>
[]
[ { "body": "<p>Please use <a href=\"https://en.wikipedia.org/wiki/Key_derivation_function\" rel=\"nofollow noreferrer\">best practices</a> in general when dealing with password hashing.</p>\n\n<ul>\n<li>If you have to verify the database for your generated <em>salt</em> to be unique, <strong>you're using a bad <em>salt generator</em></strong>. Make sure to focus on using a <a href=\"https://codereview.stackexchange.com/questions/93614/salt-generation-in-c\">good generator</a> instead.</li>\n<li>Your hash function also seems weak. Consider using <a href=\"https://en.wikipedia.org/wiki/Key_stretching\" rel=\"nofollow noreferrer\">key stretching</a>.</li>\n</ul>\n\n<hr>\n\n<p>This should not be required:</p>\n\n<blockquote>\n<pre><code>while(isFound){\n isFound=false;\n String randomSalt=createRandomString(); //creates salt/random string\n ResultSet rs = stmt.executeQuery(\"SELECT * FROM mvUser where salt=\"+randomString);\n //check if salt is unique\n while (rs.next()) {\n isFound=true;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>And for hash, I would expect something like below, where <code>hash</code> is an established hash library (PBKDF2, bcrypt, scrypt, ..).</p>\n\n<pre><code>var hashedPW = hash(iterations, randomSalt, pw);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:14:56.330", "Id": "429834", "Score": "1", "body": "but even a good salt generator doesnt ensure that the salt is unique? The likelihood that the salt already exsists is just smaller?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:25:04.977", "Id": "429835", "Score": "0", "body": "@Lebron11 Exactly, and in combination with a variable number of `iterations`, even if two users happen to have the same plain text password and salt, they would end up having different hashes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T12:53:49.480", "Id": "429843", "Score": "1", "body": "And even if they don't, the chances of that happening are extremely small. So I doubt there's much risk after that. I mean, what attack is going to abuse 2 random users having the same hash if you don't know which 2 users it's about?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T04:38:55.080", "Id": "222131", "ParentId": "222127", "Score": "4" } } ]
{ "AcceptedAnswerId": "222131", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T01:46:51.703", "Id": "222127", "Score": "2", "Tags": [ "java", "performance", "sql", "jdbc", "oracle" ], "Title": "Generating and storing a unique salt in Oracle database using Java" }
222127
<p>I have a procedure for looping through all files in folders and subfolders starting at a folder which the user can select. The user can select both the source and target folder. I'm using Excel VBA for this. The worksheets contain all the files names or part of it, to search for. </p> <p>It works like this. I have function <code>GetFiles</code> which returns a string (including the path) separated by a pipeline (|). Then I loop through all the cells in column A which contains the filename (or part of it) to search for. The <code>GetFiles</code> loops through all the folders and subfolders from the selected Source path. This takes longer if a High level of the source folder is selected.</p> <p>The main function looks like this:</p> <pre><code>Sub MoveFilesToFolder() Dim filePath As String: filePath = "" Dim moveToPath As String: moveToPath = "" Dim filename As String Dim fileNameFront As String Dim fileNameRear As String Dim currentFileName As String Dim cell As Range Dim fileCopied As Boolean: fileCopied = False Dim i As Integer Dim J As Long Dim StartTime As Double Dim SecondsElapsed As Double Dim result As String Dim ws As Worksheet Dim frm As ufImageSearcher ExactMatch = True OverwriteExistingFile = False Application.DisplayAlerts = False Application.ScreenUpdating = False On Error GoTo ErrorHandling If (wsExists("Images")) Then fileNameString = "" 'filePath = InputBox("Path to the files, close with backslash (\)", "Source folder", ActiveWorkbook.Path) 'moveToPath = InputBox("Path to copy files to! Close with backslash (\)", "Target folder", ActiveWorkbook.Path &amp; "\copy\") filePath = GetFolderPath("Bron directory") If (IsStringEmpty(filePath)) Then Exit Sub End If moveToPath = GetFolderPath("Doel directory") If (IsStringEmpty(moveToPath)) Then Exit Sub End If If Not (IsStringEmpty(filePath) Or IsStringEmpty(moveToPath)) Then If ((FolderExists(filePath)) And _ (FolderExists(moveToPath))) And (filePath &lt;&gt; moveToPath) Then If Right(moveToPath, 1) &lt;&gt; "\" Then moveToPath = moveToPath &amp; "\" End If If (Dir(moveToPath &amp; "*.*") &lt;&gt; "") Then result = MsgBox(moveToPath &amp; " contains files! Choose an empty folder!" &amp; _ vbCrLf &amp; vbCrLf &amp; "Go to folder: " &amp; moveToPath &amp; "?", vbYesNo + vbQuestion, "Result!") If (result = vbYes) Then OpenFolderInExplorer (moveToPath) End If Exit Sub End If wsActivate ("Images") Set frm = New ufImageSearcher With frm .lblSource.Caption = filePath .lblTarget.Caption = moveToPath .Show If .Tag &lt;&gt; "Canceled" Then ExactMatch = .cbxExactMatch.Value OverwriteExistingFile = .cbxOverwrite.Value Else Exit Sub End If End With StartTime = Timer 'Get all files, including the path, seperated with a pipeline. GetFiles (filePath) If Not (IsStringEmpty(fileNameString)) Then Dim imgArray As Variant: imgArray = Split(fileNameString, "|") 'Column A contains all strings which are used to compare to the found files from the GetFiles-function For Each cell In ActiveSheet.Range("A1:A" &amp; Range("A1").End(xlDown).row) DoEvents fileCopied = False filename = Mid(cell.Value, lastpositionOfChar(cell.Value, "/") + 1, Len(cell.Value)) Application.StatusBar = "(Nr. of files:" &amp; CStr(UBound(imgArray)) &amp; ")" If Not (IsStringEmpty(filename)) Then For i = LBound(imgArray) To UBound(imgArray) DoEvents If Not (IsStringEmpty(CStr(imgArray(i)))) Then If ExactMatch Then If (GetFileName(imgArray(i)) = filename) Then If DoesFileExist(moveToPath &amp; GetFileName(imgArray(i))) And Not OverwriteExistingFile Then FileCopy imgArray(i), moveToPath &amp; GetFileName(imgArray(i)) &amp; "-" &amp; Format(Now, "yyyymmddhhmmss") Else FileCopy imgArray(i), moveToPath &amp; GetFileName(imgArray(i)) End If fileCopied = True If fileCopied Then ActiveSheet.Range("B" &amp; cell.row).Value = imgArray(i) For J = 2 To 15 Dim newFileName As String newFileName = CreateFileName(CStr(imgArray(i)), LeadingZeroString(J)) If Not (IsStringEmpty(newFileName)) Then If (DoesFileExist(newFileName)) Then If Not (IsFileOpen(newFileName)) Then FileCopy newFileName, moveToPath &amp; Right(newFileName, Len(newFileName) - lastpositionOfChar(newFileName, "\") + 1) ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.row).Value = newFileName ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.row).Font.Color = RGB(0, 102, 0) End If Else ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.row).Value = "(Niet aanwezig) " &amp; Right(newFileName, Len(newFileName) - lastpositionOfChar(newFileName, "\") + 1) ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.row).Font.Color = RGB(255, 153, 51) End If End If Next J End If End If Else If (InStr(1, GetFileName(imgArray(i)), filename, vbTextCompare) &gt; 0) Then If Not (IsFileOpen(CStr(imgArray(i)))) Then If DoesFileExist(moveToPath &amp; GetFileName(imgArray(i))) And Not OverwriteExistingFile Then FileCopy imgArray(i), moveToPath &amp; GetFileName(imgArray(i)) &amp; "-" &amp; Format(Now, "yyyymmddhhmmss") Else FileCopy imgArray(i), moveToPath &amp; GetFileName(imgArray(i)) End If fileCopied = True 'Find first empty columnid. lCol = Cells(cell.row, Columns.Count).End(xlToLeft).Column ActiveSheet.Cells(cell.row, lCol + 1).Value = imgArray(i) End If End If End If End If Next i If Not fileCopied Then ActiveSheet.Range("B" &amp; cell.row).Value = "** NOT FOUND **" ActiveSheet.Range("B" &amp; cell.row).Font.Color = RGB(250, 0, 0) End If End If Next End If Worksheets("Images").Columns("B:Z").AutoFit SecondsElapsed = Timer - StartTime Application.DisplayAlerts = True Application.ScreenUpdating = True result = MsgBox("Date Exported in: " &amp; moveToPath &amp; vbCrLf &amp; "This was done in: " &amp; Format(SecondsElapsed / 86400, "hh:mm:ss") &amp; " seconds." &amp; _ vbCrLf &amp; vbCrLf &amp; "Go to folder: " &amp; moveToPath &amp; "?", vbYesNo + vbQuestion, "Resultaat!") If (result = vbYes) Then OpenFolderInExplorer (moveToPath) End If Else If Not (FolderExists(filePath)) Then MsgBox (filePath &amp; ": Path is niet gevonden!") End If If Not (FolderExists(moveToPath)) Then MsgBox (moveToPath &amp; ": Path is niet gevonden!") End If End If Else MsgBox ("No Source and/or Target selected" &amp; vbCrLf &amp; _ "Source: " &amp; filePath &amp; vbCrLf &amp; _ "Target: " &amp; moveToPath) End If Else MsgBox ("This procedure expect a worksheet 'Images' " &amp; vbCrLf &amp; _ "and the name or part of the name of the image to find in column A") End If Done: If (IsObject(ws)) Then Set ws = Nothing End If Application.DisplayAlerts = True Application.ScreenUpdating = True Exit Sub ErrorHandling: MsgBox ("Something went wrong!(" &amp; err.Description &amp; ")") End Sub </code></pre> <p>The GetFiles function looks like:</p> <pre><code>Sub GetFiles(ByVal path As String) On Error GoTo ErrorHandling Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject") Dim folder As Object: Set folder = fso.GetFolder(path) Dim subfolder As Object Dim file As Object For Each subfolder In folder.SubFolders DoEvents GetFiles (subfolder.path) Next subfolder For Each file In folder.Files fileNameString = fileNameString &amp; file.path &amp; "|" Next file Done: Set fso = Nothing Set folder = Nothing Set subfolder = Nothing Set file = Nothing Exit Sub ErrorHandling: MsgBox ("Something went wrong!(" &amp; err.Description &amp; ")") End Sub </code></pre> <p>It all works, but it takes a long time to run, especially when there are a lot of folders and subfolders under the selected source folder. </p> <p>To give you an idea, the procedure takes 13 minutes to compare 100 rows in column A against 10.000 files found. The means it loops 100 x 10.000 = 1milion times.</p> <p>I have two questions:</p> <ol> <li>Is there a more efficient way of doing this using Excel VBA?</li> <li>Is the DoEvents function used in the correct way?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-23T15:19:33.963", "Id": "469408", "Score": "0", "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": "2020-03-23T15:24:29.600", "Id": "469410", "Score": "1", "body": "I have rolled back Rev 7 → 4. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). Protip: you might be able to gain more reputation score if you opt for option 1 or 2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-24T16:37:16.377", "Id": "469493", "Score": "0", "body": "This was not an update off code, but adding a piece of code which was missing in the total answer. It is more complete now. It does not influence the answer." } ]
[ { "body": "<h2><code>MoveFilesToFolder()</code></h2>\n<p><code>MoveFilesToFolder()</code> is doing too much.</p>\n<p>Testing filePath and moveToPath in a separate sub would greatly reduce <code>MoveFilesToFolder()</code> size making it easier to read, test and modify.</p>\n<pre><code>Private Const DirctoryBron As String = &quot;Bron directory&quot;\nPrivate Const DirctoryDoel As String = &quot;Doel directory&quot;\nPrivate Const WorksheetImages As String = &quot;Images&quot;\n\nSub Main()\n Dim filePath As String, moveToPath As String\n \n If Not (wsExists(WorksheetImages)) Then\n MsgBox WorksheetImages &amp; &quot; worksheet not found&quot;\n Else\n filePath = GetFolderPath(DirctoryBron)\n If Len(filePath) &gt; 0 And Not IsStringEmpty(filePath) Then\n moveToPath = GetFolderPath(DirctoryDoel)\n If Len(moveToPath) &gt; 0 Then\n MoveFilesToFolder filePath, moveToPath\n End If\n End If\n End If\n \nEnd Sub\n\nFunction GetFolderPath(ByVal SubFolderName As String)\n Dim filePath As String\n '..... Some Code...\n \n If Len(Dir(filePath, vbDirectory)) = 0 Then\n MsgBox (filePath &amp; &quot;: Path is niet gevonden!&quot;)\n Else\n GetFolderPath = filePath\n End If\nEnd Function\n\nSub MoveFilesToFolder(filePath As String, moveToPath As String)\n '..... Some Code...\nEnd Sub\n\nFunction IsStringEmpty(filePath As String) As Boolean\n If Len(Dir(filePath)) = 0 Then\n MsgBox filePath &amp; &quot; has no files&quot;\n IsStringEmpty = True\n End If\nEnd Function\n</code></pre>\n<h2><code>GetFiles()</code></h2>\n<p><code>fileNameString</code> should not be a global variable. It is a best practice to avoid global variables whenever possible. The name <code>GetFiles()</code> implies that it is a function ans it should be a function.<br />\nA single <code>FileSystemObject</code> is being created every time <code>GetFiles()</code> is getting called. It is better to create a single instance of the <code>FileSystemObject</code> and pass it as a parameter.</p>\n<pre><code>Function GetFiles(ByVal path As String, Optional fso As Object) As String\n If fso Is Nothing Then Set fso = CreateObject(&quot;Scripting.FileSystemObject&quot;)\n</code></pre>\n<p>The main reason that <code>GetFiles()</code> is so slow is string concatenation is inefficient. Everytime a string is concatenated a new string variable is created. Let's say that the average file path is 50 bytes long. After 2K files, <code>fileNameString</code> would be 100K bytes and by the time we reach the 10K <code>fileNameString</code> would be 500k bytes. Creatin an array of filename and using <code>Join()</code> to concatenate the array would be much faster.</p>\n<p>An easier solution is to use <code>WScript.Shell</code> to return filenames:</p>\n<pre><code>Function GetFiles(ByVal rootPath As String) As Variant\n Dim result As String\n result = CreateObject(&quot;WScript.Shell&quot;).exec(&quot;cmd /c dir &quot;&quot;&quot; &amp; rootPath &amp; &quot;&quot;&quot; /a:d-h-s /b /s&quot;).StdOut.ReadAll\n result = Left(result, Len(result) - 2)\n result = Replace(result, vbNewLine, &quot;|&quot;)\n GetFiles = result\nEnd Function\n</code></pre>\n<p>For faster lookups I would add the file paths to a dictionary.</p>\n<pre><code>Function GetFileMap(ByVal rootPath As String) As Scripting.Dictionary\n Dim map As New Scripting.Dictionary\n Dim key\n \n Dim result As String\n result = CreateObject(&quot;WScript.Shell&quot;).exec(&quot;cmd /c dir &quot;&quot;&quot; &amp; rootPath &amp; &quot;&quot;&quot; /a:d-h-s /b /s&quot;).StdOut.ReadAll\n \n For Each key In Split(result, vbNewLine)\n If Len(key) &gt; 0 Then\n map.Add key, vbNullString\n End If\n Next\n \n Set GetFileMap = map\nEnd Function\n</code></pre>\n<h2>Addendum</h2>\n<p>I didn't elaborate much on using a dictionary but it is much faster than looping over all the cells for each item in the file array. It looks like you would need to have the file name for the dictionary keys and the file paths for the the dictionary values.</p>\n<p>I personally don't like <code>GetColLetter()</code>. I can see where it my be handy for creating cell formulas but there is always another way when working with ranges.</p>\n<p>I'm not a fan of creating functions to that basically rename built-in functions. In this project <code>lastpositionOfChar()</code> was used instead <code>Instr()</code>. 2 years from now you might forget <code>lastpositionOfChar()</code> and write <code>lastCharPosition()</code>. It also makes code reuse more difficult because you created a dependency on another function.</p>\n<pre><code> filename = Mid(cell.Value, lastpositionOfChar(cell.Value, &quot;/&quot;) + 1, Len(cell.Value))\n</code></pre>\n<p><code>Len(cell.Value)</code> is not needed. I prefer <code>filename = Mid(cell.Value, InStrRev(cell.Value, &quot;/&quot;))</code>.</p>\n<p><code>LeadingZeroString()</code> I would use a public Const to store the number format.</p>\n<blockquote>\n<p>Public Const LeadingZero As String = &quot;000&quot;</p>\n</blockquote>\n<p>Although you have done an outstanding job of naming your custom functions I would still use the built-in ones.</p>\n<p>Here is a small sample of how I would refactor the code:</p>\n<h2>Before</h2>\n<pre><code>If fileCopied Then\n ActiveSheet.Range(&quot;B&quot; &amp; cell.Row).Value = imgArray(i)\n\n For J = 2 To 15\n Dim newFileName As String\n newFileName = CreateFileName(CStr(imgArray(i)), LeadingZeroString(J))\n If Not (IsStringEmpty(newFileName)) Then\n If (DoesFileExist(newFileName)) Then\n If Not (IsFileOpen(newFileName)) Then\n FileCopy newFileName, moveToPath &amp; Right(newFileName, Len(newFileName) - lastpositionOfChar(newFileName, &quot;\\&quot;) + 1)\n ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.Row).Value = newFileName\n ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.Row).Font.Color = RGB(0, 102, 0)\n End If\n Else\n ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.Row).Value = &quot;(Niet aanwezig) &quot; &amp; Right(newFileName, Len(newFileName) - lastpositionOfChar(newFileName, &quot;\\&quot;) + 1)\n ActiveSheet.Range(GetColLetter(J + 1) &amp; cell.Row).Font.Color = RGB(255, 153, 51)\n End If\n End If\n Next J\nEnd If\n</code></pre>\n<h2>After</h2>\n<pre><code>If fileCopied Then\n cell.EntireColumn.Columns(&quot;B&quot;).Value = imgArray(i)\n\n For J = 2 To 15\n Dim newFileName As String\n newFileName = CreateFileName(CStr(imgArray(i)), Format(J, LeadingZero))\n If Len(newFileName) &gt; 0 Then\n If Len(Dir(newFileName)) &gt; 0 Then\n If Not (IsFileOpen(newFileName)) Then\n FileCopy newFileName, moveToPath &amp; Right(newFileName, Len(newFileName) - InStrRev(newFileName, &quot;\\&quot;) + 1)\n cell.Offset(0, J).Value = newFileName\n cell.Offset(0, J).Font.Color = RGB(0, 102, 0)\n End If\n Else\n cell.Offset(0, J).Value = &quot;(Niet aanwezig) &quot; &amp; Right(newFileName, Len(newFileName) - InStrRev(newFileName, &quot;\\&quot;) + 1)\n cell.Offset(0, J).Font.Color = RGB(255, 153, 51)\n End If\n End If\n Next J\nEnd If\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:42:16.987", "Id": "429950", "Score": "0", "body": "Totally agree on making it better readable. I like your suggestions and improvement. Thank you for that. Now that you mentioned the concatenation thing, I do remember reading about it. I will adjust the code. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:34:56.067", "Id": "429993", "Score": "0", "body": "I see your point. And I must admit, I often forget about functions I wrote before, doing the whole thing again. Totally against the D.N.R.Y.. Selecting the file infor using the CMD command is superfast indeed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:26:19.160", "Id": "430006", "Score": "1", "body": "D.N.R.Y? Dictionary? You have a nice coding style, It is really easy to follow. Keep in mind that my review is just my opinion. I am by no means a guru." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:14:39.073", "Id": "430013", "Score": "1", "body": "But is it good thinking. I like it. I'm no Guru either. And this is my first code review. Learning every day. ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T13:55:07.020", "Id": "467596", "Score": "1", "body": "DNRY is more commonly known as DRY: Do Not Repeat Yourself or Don't Repeat Yourself. It's anti-WET: Write Everything Twice." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T20:37:09.383", "Id": "222176", "ParentId": "222134", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T05:42:26.393", "Id": "222134", "Score": "5", "Tags": [ "performance", "vba", "excel", "file-system", "iterator" ], "Title": "Most efficient way to loop through files using VBA Excel" }
222134
<p>I have written a simple <code>java.util.Properties</code> wrapping class. Unfortunately, in my opinion, it isn't testable at the moment and I don't have any idea how to improve it. I could use PowerMockito to change <code>properties</code> after loading, or add a setter for them, or inject some class that provides <code>properties</code>, but I don't like any of that. I would like to avoid exposing <code>properties</code> by making it public or by getter/setter.</p> <p>My application details:</p> <ul> <li>Spring boot</li> <li>my class is injected by <code>@Bean</code> mechanic</li> <li><code>CONF_FILE_NAME</code> contains <code>key=value</code> formatted properies with names same as in <code>Keys</code> subclass.</li> </ul> <p>I would like to unit-test logic in this class (both public method) without relying on values in file.</p> <p><code>PropertiesManager.java</code>:</p> <pre><code>package pl.propertiesdemo; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Properties; public class PropertiesManager { private final String secretToken = "SECRET"; public final class Keys { public final static String KEY1 = "KEY1"; public final static String KEY2 = "KEY2"; } private final String CONF_FILE_NAME = "conf_file.conf"; private Properties properties; public PropertiesManager() throws IOException { properties = new Properties(); InputStream in = new FileInputStream(CONF_FILE_NAME); properties.load(in); } public String getProperty(String name) { String property = properties.getProperty(name); if (property == null) { System.out.println("Property " + name + " not found in properties file"); } return property; } public HashMap&lt;String, String&gt; getAllPublicProperties() { HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;(); properties.keySet().stream().map(f -&gt; (String)f).filter(f -&gt; !f.contains(secretToken)).forEach(f -&gt; map.put(f, properties.getProperty(f))); return map; } } </code></pre> <p><code>PropertiesDemo.java</code>: (<code>main</code> method and usage of both public methods)</p> <pre><code>package pl.propertiesdemo; import java.io.IOException; public class PropertiesDemo { public static void main(String[] args) throws IOException { PropertiesManager manager = new PropertiesManager(); System.out.println(manager.getProperty(PropertiesManager.Keys.KEY1)); System.out.println(manager.getAllPublicProperties()); } } </code></pre> <p><code>conf_file_conf</code>: (file loaded by <code>PropertyManager</code>)</p> <pre><code>KEY1=value_of_key1 KEY2=value_of_key2 </code></pre> <p><code>PropertiesManager.java</code>: (<code>JUnit</code> test I have so far)</p> <pre><code>package pl.propertiesdemo; import java.io.IOException; import java.util.HashMap; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public class PropertiesManagerTest extends TestCase { public PropertiesManagerTest(String testName) { super(testName); } public static Test suite() { return new TestSuite(PropertiesManagerTest.class); } private PropertiesManager getPropertiesManager() { PropertiesManager prop = null; try { prop = new PropertiesManager(); } catch (IOException ioe) { fail(); } return prop; } public void testGetProperty() { PropertiesManager prop = getPropertiesManager(); String value = prop.getProperty(PropertiesManager.Keys.KEY1); assertEquals("value_of_key1", value); } public void testGetAllProperties() { PropertiesManager prop = getPropertiesManager(); HashMap&lt;String,String&gt; values = prop.getAllPublicProperties(); assertTrue(values.size() &gt; 0); assertEquals(0, values.keySet().stream().filter(k -&gt; k.contains("SECRET")).count()); } } </code></pre> <p>I don't like my tests, because right now they are dependant of value in real configuration file.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T08:09:08.397", "Id": "429822", "Score": "0", "body": "Could you provide working code and the unit tests you have so far? At the moment, this question is off-topic without such information. https://codereview.stackexchange.com/help/dont-ask" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T08:31:33.310", "Id": "429827", "Score": "0", "body": "Thank you for advice. I added rest of classes to make it work and my tests I have right now (which I don't like)." } ]
[ { "body": "<p>Your class is non-testable mainly because : </p>\n\n<ol>\n<li>it reads datas from disk/network</li>\n<li>it doesn't use any injection</li>\n</ol>\n\n<p>Firstly, please note that Spring has some utility to read property file and fills java beans automaticly. You should check this if you don't want to reinvent the wheel. ;)\nAlso, <em>Properties</em> is a fairly old school class in Java and isn't used that much recently.</p>\n\n<p>If you do want to have your own implementation, the let's see what we can do line-by-line, shall we ?</p>\n\n<pre><code>private final String secretToken = \"SECRET\";\n</code></pre>\n\n<p>Either you plan on making this variable (and then it should be injected in the constructor) or this is a constant (so it should be <code>private static final</code>).</p>\n\n<pre><code>public final class Keys \n{\n public final static String KEY1 = \"KEY1\";\n public final static String KEY2 = \"KEY2\";\n}\n</code></pre>\n\n<p>I don't really get what you were trying to accomplish here. Why didn't you put those constants in the main classes ? I'd remove this code altogether IMHO.</p>\n\n<pre><code>private Properties properties;\n</code></pre>\n\n<p>This is set in the constructor so this is a good candidate for <code>final</code> ;)</p>\n\n<pre><code>public PropertiesManager() throws IOException\n{\n properties = new Properties();\n InputStream in = new FileInputStream(CONF_FILE_NAME);\n properties.load(in);\n}\n</code></pre>\n\n<p>Maybe some people will disagree but I'm no big fan of constructor that do I/O.<br>\nAlso this is non-configurable : what if you want to change the file name ? what if you want to read not from a file but from a string or from the console ?<br>\nYou should read about dependency injection if you've never heard of it before.<br>\nFor a quick introduction, it's a principle that some codes delegates the configuration of the object to the calling code allowing for more and easier code reuse.</p>\n\n<p>The InputStream is not closed which may lead to ressource-leak. See <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close()\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html#close()</a> ;)</p>\n\n<p>IMO I'd have a constructor that takes a <code>Properties</code> object. However, this may pose others problems (such as the Properties object still being accessed by another object and be modified directly).<br>\nSo, I'd consider using a static factory method that takes a <em>Reader</em> and returns the <em>PropertiesManager</em>. The calling code will be the one responsible to close the stream.\nThis allows you to inject any time of Reader making your code more reusable.</p>\n\n<pre><code>public String getProperty(String name)\n{\n //...\n</code></pre>\n\n<p>This is fine. As a side-note : you shouldn't use <code>System.out.println</code> for log in production code.</p>\n\n<pre><code>public HashMap&lt;String, String&gt; getAllPublicProperties()\n</code></pre>\n\n<p>Your return type shouldn't be HashMap ; when possible you should code against the interface that most suits your need, in this case : <em>Map</em>.</p>\n\n<pre><code>HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;();\n\nproperties.keySet().stream().map(f -&gt; (String)f).filter(f -&gt; !f.contains(secretToken)).forEach(f -&gt; map.put(f, properties.getProperty(f)));\n</code></pre>\n\n<p>This code may be dangerous as it is not thread-safe due to the forEach that modify a non thread-safe object. From a FP pov, you should try to delegate to the collect method (check <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/stream/Collectors.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/9/docs/api/java/util/stream/Collectors.html</a>).</p>\n\n<p>This leads us to the following code :</p>\n\n<pre><code>package pl.propertiesdemo;\n\nimport static java.util.stream.Collectors.toMap;\n\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.function.Function;\n\npublic class PropertiesManager {\n public static final String DEFAULT_CONF_FILE_NAME = \"conf_file.conf\";\n\n private static final String SECRET_TOKEN = \"SECRET\";\n\n private final Properties properties;\n\n public static PropertiesManager createFrom(final Reader r) throws IOException {\n var properties = new Properties();\n properties.load(r);\n return new PropertiesManager(properties);\n }\n\n protected PropertiesManager(final Properties properties) {\n this.properties = properties;\n }\n\n public String getProperty(final String name) {\n String property = properties.getProperty(name);\n if (property == null) {\n System.out.println(\"Property \" + name + \" not found in properties file\");\n }\n return property;\n }\n\n public Map&lt;String, String&gt; getAllPublicProperties() {\n return properties.keySet()\n .stream()\n .map(f -&gt; (String) f)\n .filter(f -&gt; !f.contains(SECRET_TOKEN))\n .collect(toMap(Function.identity(), f -&gt; properties.getProperty(f)));\n }\n}\n</code></pre>\n\n<p>Now that your object don't read from disk and can be easily injected, the object instantiation in the test class may look like this :</p>\n\n<pre><code>PropertiesManager prop = null;\ntry {\n prop = PropertiesManager.createFrom(new StringReader(\"someKey=someValue\"));\n} catch (IOException ioe) {\n fail();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:58:17.370", "Id": "222161", "ParentId": "222135", "Score": "3" } } ]
{ "AcceptedAnswerId": "222161", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T07:14:09.127", "Id": "222135", "Score": "3", "Tags": [ "java", "unit-testing" ], "Title": "Non-testable class wrapping Java Properties with basic logic" }
222135
<p>I have written code in the language Go. I wonder if anyone can do it in a very simple and effective way, because every language has its own way to solve this problem. My experience is in JavaScript. Please guide me how I can improve this solution. Thank you in advance. </p> <p>What I'm doing here:</p> <blockquote> <p>Input - </p> </blockquote> <ul> <li>"I love dogs" </li> <li>"fun&amp;!! time"</li> </ul> <blockquote> <p>Output :-</p> </blockquote> <ul> <li>love </li> <li>time</li> </ul> <blockquote> <p>Here I return the longest word in the string. If there are two or more words that are of same length, return the first word from the string with that length.</p> </blockquote> <pre><code>package main import ( "fmt" "regexp" ) func main() { re := regexp.MustCompile(`[A-Za-z]+|[*?()$&amp;.,!]`) matches := re.FindAllString("fun&amp;!! time", -1) var count int for i := 0; i &lt; len(matches); i++ { if (i+1)%len(matches) &gt; 0 { if len(matches[(i+1)%len(matches)]) &gt; len(matches[i]) { count = (i + 1) % len(matches) } } } fmt.Println(matches[count]) } </code></pre>
[]
[ { "body": "<p>The first thing to do is to incorporate some basic notions of organization and design into your program, for example, a <code>maxWord</code> function.</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"regexp\"\n)\n\nvar re = regexp.MustCompile(`[A-Za-z]+|[*?()$&amp;.,!]`)\n\nfunc maxWord(s string) string {\n matches := re.FindAllString(s, -1)\n var count int\n for i := 0; i &lt; len(matches); i++ {\n if (i+1)%len(matches) &gt; 0 {\n if len(matches[(i+1)%len(matches)]) &gt; len(matches[i]) {\n count = (i + 1) % len(matches)\n }\n }\n }\n return matches[count]\n}\n\nfunc main() {\n for _, s := range []string{\n \"I love dogs\",\n \"fun&amp;!! time\",\n loremipsum,\n } {\n fmt.Printf(\"%q\\n\", maxWord(s))\n }\n}\n\nvar loremipsum = `\nLorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, \nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \nExcepteur sint occaecat cupidatat non proident, \nsunt in culpa qui officia deserunt mollit anim id est laborum.\n`\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>\"love\"\n\"time\"\n\"laborum\"\n</code></pre>\n\n<p>Test your code. Your result for the <code>loremipsum</code> text doesn't look right.</p>\n\n<hr>\n\n<p>Consider writing a simple, efficient word parser. For example,</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"unicode\"\n)\n\nfunc maxWord(s string) string {\n var word string\n inWord := false\n j, k := 0, 0\n for i, r := range s {\n if !unicode.IsLetter(r) {\n if inWord {\n k = i\n if k-j &gt; len(word) {\n word = s[j:k]\n }\n }\n inWord = false\n } else if !inWord {\n inWord = true\n j = i\n }\n }\n if inWord {\n k = len(s)\n if k-j &gt; len(word) {\n word = s[j:k]\n }\n }\n return word\n}\n\nfunc main() {\n for _, s := range []string{\n \"I love dogs\",\n \"fun&amp;!! time\",\n loremipsum,\n } {\n fmt.Printf(\"%q\\n\", maxWord(s))\n }\n}\n\nvar loremipsum = `\nLorem ipsum dolor sit amet, consectetur adipiscing elit, \nsed do eiusmod tempor incididunt ut labore et dolore magna aliqua. \nUt enim ad minim veniam, \nquis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. \nDuis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. \nExcepteur sint occaecat cupidatat non proident, \nsunt in culpa qui officia deserunt mollit anim id est laborum.\n`\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>\"love\"\n\"time\"\n\"reprehenderit\"\n</code></pre>\n\n<hr>\n\n<p>Go programmers often write reasonably efficient programs. The Go standard library <code>testing</code> package provides a benchmark facility.</p>\n\n<p>For example,</p>\n\n<pre><code>$ go test maxword_test.go -bench=. -benchmem \nBenchmarkPeterSO-4 24316906 47.7 ns/op 0 B/op 0 allocs/op\nBenchmarkMannu-4 557594 2022 ns/op 448 B/op 10 allocs/op\n</code></pre>\n\n<p><code>maxword_test.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"regexp\"\n \"testing\"\n \"unicode\"\n)\n\nfunc maxWordP(s string) string {\n var word string\n inWord := false\n j, k := 0, 0\n for i, r := range s {\n if !unicode.IsLetter(r) {\n if inWord {\n k = i\n if k-j &gt; len(word) {\n word = s[j:k]\n }\n }\n inWord = false\n } else if !inWord {\n inWord = true\n j = i\n }\n }\n if inWord {\n k = len(s)\n if k-j &gt; len(word) {\n word = s[j:k]\n }\n }\n return word\n}\n\nfunc BenchmarkPeterSO(b *testing.B) {\n for N := 0; N &lt; b.N; N++ {\n for _, s := range []string{\"I love dogs\", \"fun&amp;!! time\"} {\n maxWordP(s)\n }\n }\n}\n\nvar re = regexp.MustCompile(`[A-Za-z]+|[*?()$&amp;.,!]`)\n\nfunc maxWordM(s string) string {\n matches := re.FindAllString(s, -1)\n var count int\n for i := 0; i &lt; len(matches); i++ {\n if (i+1)%len(matches) &gt; 0 {\n if len(matches[(i+1)%len(matches)]) &gt; len(matches[i]) {\n count = (i + 1) % len(matches)\n }\n }\n }\n return matches[count]\n}\n\nfunc BenchmarkMannu(b *testing.B) {\n for N := 0; N &lt; b.N; N++ {\n for _, s := range []string{\"I love dogs\", \"fun&amp;!! time\"} {\n maxWordM(s)\n }\n }\n}\n\nvar benchTexts = []string{\"I love dogs\", \"fun&amp;!! time\"}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T05:05:45.583", "Id": "429934", "Score": "0", "body": "Thank you so much, Peter, for your guidance. I will work on it and try to understand to write efficient code in Go." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T16:52:20.440", "Id": "222168", "ParentId": "222139", "Score": "2" } } ]
{ "AcceptedAnswerId": "222168", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T09:38:50.150", "Id": "222139", "Score": "5", "Tags": [ "beginner", "algorithm", "strings", "go" ], "Title": "Find the longest word in a string" }
222139
<p>I am using a Bash script to execute a Python script multiple times. In order to speed up the execution, I would like to execute these (independent) processes in parallel. The code below does so: </p> <pre><code>#!/usr/bin/env bash script="path_to_python_script" N=16 # number of processors mkdir -p data/ for i in `seq 1 1 100`; do for j in {1..100}; do ((q=q%N)); ((q++==0)) &amp;&amp; wait if [ -e data/file_$i-$j.txt ] then echo "data/file_$i-$j.txt exists" else ($script -args_1 $i &gt; data/file_$i-$j.txt ; $script -args_1 $i -args_2 value -args_3 value &gt;&gt; data/file_$i-$j.txt) &amp; fi done done </code></pre> <p>However, I am wondering if this code follow common best practices of parallelization of for loops in Bash? Are there ways to improve the efficiency of this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T20:55:34.563", "Id": "429922", "Score": "6", "body": "You can use GNU Parallel, it’s very helpful the execute a number of tasks in a controlled way." } ]
[ { "body": "<p>Some suggestions:</p>\n\n<ul>\n<li>The trailing slash in the <code>mkdir</code> command is redundant.</li>\n<li><code>$(…)</code> is preferred over backticks for command substitution.</li>\n<li>Why use <code>seq</code> in one command? They both do the same loop, so you might as well use <code>{1..100}</code> in both places.</li>\n<li>Semicolons are unnecessary in the vast majority of cases. Simply use a newline to achieve the same separation between commands.</li>\n<li><a href=\"https://mywiki.wooledge.org/Quotes\" rel=\"noreferrer\">Use More Quotes™</a></li>\n<li><code>set -o errexit -o noclobber -o nounset</code> at the start of the script will be helpful. It'll exit the script instead of overwriting any files, for example, so you can get rid of the inner <code>if</code> statement if it's OK that the script stops when the file exists.</li>\n<li><a href=\"https://stackoverflow.com/a/669486/96588\"><code>[[</code> is preferred over <code>[</code></a>.</li>\n<li>The whole exercise is probably easier to achieve with some <a href=\"https://mywiki.wooledge.org/ProcessManagement#I_want_to_process_a_bunch_of_files_in_parallel.2C_and_when_one_finishes.2C_I_want_to_start_the_next._And_I_want_to_make_sure_there_are_exactly_5_jobs_running_at_a_time.\" rel=\"noreferrer\">standard pattern</a> like GNU parallel. Currently the script starts <code>N</code> commands, then waits for <em>all</em> of them to finish before starting any more. Unless the processes take very similar time this is going to waste a lot of time waiting.</li>\n<li><code>N</code> (or for example <code>processors</code> for readability) should be determined dynamically, using for example <a href=\"https://stackoverflow.com/a/17089001/96588\"><code>nproc --all</code></a>, rather than hardcoded.</li>\n<li>If you're worried about speed you should probably <em>not</em> create a subshell for your two script commands. <code>{</code> and <code>}</code> will group commands without creating a subshell.</li>\n<li>For the same reason you probably want to do a single redirection like <code>{ \"$script\" … &amp;&amp; \"$script\" …; } &gt; \"data/file_${i}-${j}.txt\"</code></li>\n<li><p>Since you're \"only\" counting to 10,000 you don't need to reset <code>q</code> every time. You can for example set <code>process_count=0</code> outside the outer loop and check the modulo in a readable way such as:</p>\n\n<pre><code>if [[ \"$process_count\" % \"$processors\" -eq 0 ]]\nthen\n wait\nfi\n</code></pre></li>\n<li>The inner code (from the line starting with <code>((q=q%N))</code>) should be indented one more time.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T11:41:53.013", "Id": "429841", "Score": "4", "body": "`[` is [more portable and more consistent](//stackoverflow.com/a/47576482) than `[[`. So your preference is certainly arguable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T20:58:19.503", "Id": "429924", "Score": "3", "body": "@TobySpeight 1) Writing truly portable scripts is an absolute nightmare and not a good idea in terms of maintainability. 2) OP asked about Bash specifically. 3) The accepted answer (above the one you linked to) has about eight times more votes, so I would say the community has spoken." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:17:37.043", "Id": "222142", "ParentId": "222141", "Score": "11" } }, { "body": "<p>Using GNU Parallel you code will look something like this:</p>\n\n<pre><code>#!/usr/bin/env bash\n\nexport script=\"path_to_python_script\"\n\ndoit() {\n i=\"$1\"\n j=\"$2\"\n $script -args_1 \"$i\"\n $script -args_1 \"$i\" -args_2 value -args_3 value\n}\nexport -f doit\n\nparallel --resume --results data/file_{1}-{2}.txt doit ::: {1..100} ::: {1..100}\n</code></pre>\n\n<p>In your original code if one job in a batch of 16 takes longer than the other 15, then you will have 15 cores sitting idle waiting for the last to finish.</p>\n\n<p>Compared to your original code this will use the CPUs better because a new job is started as soon as a job finishes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T22:41:21.190", "Id": "222382", "ParentId": "222141", "Score": "4" } } ]
{ "AcceptedAnswerId": "222142", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:06:19.287", "Id": "222141", "Score": "11", "Tags": [ "bash", "concurrency", "iteration", "multiprocessing" ], "Title": "Parallelized for loop in Bash" }
222141
<p>For my game that I'm writing, I need, among other things, a data structure for storing best values. For this purpose, I tried to write a class that meets the most general needs, and yet does not seem overloaded.</p> <p>Can the class be further improved in terms of code quality or performance? Is the interface (not to be confused with the keyword) sufficiently comprehensible?</p> <p><strong>ScoreList.java</strong></p> <pre><code>import java.util.Collections; import java.util.List; import java.util.ArrayList; public class ScoreList &lt;T extends Comparable&lt;T&gt;&gt; { private final List&lt;T&gt; scores; // determines if lowest or highest value will be treaten as best private final boolean highestIsBest; private final int entryLimit; public ScoreList(int entryLimit, boolean highestIsBest) { scores = new ArrayList&lt;T&gt;(); this.highestIsBest = highestIsBest; this.entryLimit = entryLimit; } // returns false if score is to low (or high) public boolean add(T newScore) { if (scores.size() &lt; entryLimit) { scores.add(newScore); sortScores(); return true; } T lastScore = scores.get(scores.size() - 1); if (highestIsBest) { if (newScore.compareTo(lastScore) &gt; 0) { scores.remove(lastScore); scores.add(newScore); sortScores(); return true; } } else { if (newScore.compareTo(lastScore) &lt; 0) { scores.remove(lastScore); scores.add(newScore); sortScores(); return true; } } return false; } public List&lt;T&gt; getScores() { return new ArrayList&lt;T&gt;(scores); } private void sortScores() { if (highestIsBest) { Collections.sort(scores, Collections.reverseOrder()); } else { Collections.sort(scores); } } } </code></pre> <p><strong>Main.java</strong></p> <pre><code>import java.util.Random; // this class tests the functionality of ScoreList public class Main { private static Random random = new Random(); // two ScoreList-objects get created // one with highestIsBest = true, one with = false // random values are added // after that, the values of the ScoreList-objects get shown public static void main(String[] args) { // create first score list that treats highest values as best int numberOfEntries = 5; boolean highestIsBest = true; ScoreList&lt;Integer&gt; scoreList1 = new ScoreList&lt;&gt;(numberOfEntries, highestIsBest); // add values for (int i = 0; i &lt; 10; i++) { int number = random.nextInt(20); if (scoreList1.add(number)) { System.out.println(number + " was added to scoreList"); } else { System.out.println(number + " was not added to scoreList"); } } System.out.println(); // show score list System.out.print("order of scores: "); for(Integer entry : scoreList1.getScores()) { System.out.print(entry + " "); } System.out.println('\n'); // create second score list that treats lowest values as best numberOfEntries = 5; highestIsBest = false; ScoreList&lt;Integer&gt; scoreList2 = new ScoreList&lt;&gt;(numberOfEntries, highestIsBest); // add values for (int i = 0; i &lt; 10; i++) { int number = random.nextInt(20); if (scoreList2.add(number)) { System.out.println(number + " was added to scoreList"); } else { System.out.println(number + " was not added to scoreList"); } } System.out.println(); // show score list System.out.print("order of scores: "); for(Integer entry : scoreList2.getScores()) { System.out.print(entry + " "); } System.out.println(); } } </code></pre> <p><strong>Example Output</strong></p> <pre><code>+++ ScoreList-object that prefers high values +++ 0 was added to scoreList 19 was added to scoreList 11 was added to scoreList 19 was added to scoreList 9 was added to scoreList 4 was added to scoreList 3 was not added to scoreList 7 was added to scoreList 1 was not added to scoreList 10 was added to scoreList order of scores: 19 19 11 10 9 +++ ScoreList-object that prefers low values +++ 13 was added to scoreList 1 was added to scoreList 12 was added to scoreList 2 was added to scoreList 9 was added to scoreList 15 was not added to scoreList 6 was added to scoreList 18 was not added to scoreList 10 was added to scoreList 11 was not added to scoreList order of scores: 1 2 6 9 10 </code></pre> <p>Thank you for your attention!</p>
[]
[ { "body": "<h3>Deque</h3>\n\n<p>If you need both <em>Stack</em> and <em>Queue</em> operability, consider using a <a href=\"https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Deque.html\" rel=\"nofollow noreferrer\">Deque</a>.</p>\n\n<p>Summary of Deque methods</p>\n\n<pre><code>- First Element (Head) Last Element (Tail)\n- Throws exception Special value Throws exception Special value\n- Insert addFirst(e) offerFirst(e) addLast(e) offerLast(e)\n- Remove removeFirst() pollFirst() removeLast() pollLast()\n- Examine getFirst() peekFirst() getLast() peekLast()\n</code></pre>\n\n<hr>\n\n<h3>Implementation</h3>\n\n<p>Your code is really convoluted for what you want to achieve. Use a deque instead of the list <code>private final List&lt;T&gt; scores;</code> Depending on <code>highestIsBest</code>, you'd either use the <em>Head</em> or <em>Tail</em> functions. The code below can be simplified using the deque operations described above.</p>\n\n<blockquote>\n<pre><code> T lastScore = scores.get(scores.size() - 1);\n if (highestIsBest) {\n if (newScore.compareTo(lastScore) &gt; 0) {\n scores.remove(lastScore);\n scores.add(newScore);\n sortScores();\n return true;\n }\n } else {\n if (newScore.compareTo(lastScore) &lt; 0) {\n scores.remove(lastScore);\n scores.add(newScore);\n sortScores();\n return true;\n } \n }\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:42:23.027", "Id": "429965", "Score": "0", "body": "What functionality of `Stack` that the OP requires is provided by `Deque` but not by `Queue`? Unless I missed something, the OP doesn't require insertion/removal at both ends, which is the advantage of `Deque` over `Queue`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:57:57.360", "Id": "429966", "Score": "0", "body": "Also, the code duplication you pointed out won't be eliminated by using a `Deque` instead of a `Queue`, because the difference between the two code blocks is not the point of element removal/insertion, but the comparison of the two scores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T10:29:39.657", "Id": "429968", "Score": "0", "body": "@Stingy Exactly, my proposed solution allows for having both implementations in a single instance. But since the OP does not need this, I am in favor of the other answer. Much simpler design." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:34:40.917", "Id": "222146", "ParentId": "222144", "Score": "4" } }, { "body": "<p>You want a list of elements, sorted to descending order by highest perceived value where least valued element is removed if an add operation causes the list size to exceed it's limit.</p>\n\n<pre><code>private final boolean highestIsBest;\n</code></pre>\n\n<p>This adds unnecessary responsibilities to the score list. It shouldn't care what the perceived value of a score is. Just pass a <code>Comparator&lt;T&gt;</code> in the constructor (instead of requiring T to implement <code>Comparable</code>) and let the caller worry about reversing the comparator if \"smaller is better\" order is needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:56:50.750", "Id": "429837", "Score": "1", "body": "I like this approach, since it simplifies things even more. Specially, since the OP does not want both orders to be available in a single `ScoreList` instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:37:40.717", "Id": "429963", "Score": "1", "body": "Actually, a `Comparator<? super T>` would suffice." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:52:56.167", "Id": "222147", "ParentId": "222144", "Score": "6" } }, { "body": "\n<ul>\n<li><p>Have you considered the possibility of <code>ScoreList&lt;T&gt;</code> implementing <code>List&lt;T&gt;</code> directly? This can be easily achieved by extending <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractList.html\" rel=\"nofollow noreferrer\"><code>AbstractList</code></a>. However, you would have to be careful not to violate the contract of <code>List</code> when implementing your desired functionality: For example, your <code>add(T)</code> method adds an element in a way different from any of the <code>add</code> methods declared in <code>List</code> (if it adds the element at all), so you cannot override/implement <code>add(T)</code> from <code>List</code> and do what you do in your own <code>add(T)</code> method. Instead, I would suggest that you follow the instructions in the documentation of <code>AbstractList</code> for implementing an unmodifiable <code>List</code>, and then add a separate method for inserting a score as you did in your original code. You could also consider allowing the removal of scores from the <code>List</code> by implementing <code>remove(int)</code>, as described in the documentation of <code>AbstractList</code>.</p>\n<p>This would also eliminate the need for the method <code>getScores()</code>. Nevertheless, here's a suggestion related to this method: I think that <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html#unmodifiableList(java.util.List)\" rel=\"nofollow noreferrer\"><code>Collections.unmodifiableList(List)</code></a> would be more useful here than <code>new ArrayList(List)</code>, because the former returns a read-only &quot;view&quot; of the original <code>List</code> rather than a completely new, independent <code>List</code>, meaning that changes to the original <code>List</code> will be reflected in the <code>List</code> returned by <code>Collections.unmodifiableList(List)</code>, so the caller only needs to call the method <code>getScores()</code> once in the lifetime of the <code>ScoreList</code> in order to always have a read-only reference to the scores.</p>\n</li>\n<li><p>Your insertion mechanism is more complicated than it needs to be, because at every insertion, it sorts a <code>List</code> that is already sorted except for the last inserted element. Instead, you could find out the prospective position of the element to be added in advance with one of the two <code>binarySearch</code> methods in <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collections.html\" rel=\"nofollow noreferrer\"><code>Collections</code></a>, and then insert the new element at this position without sorting the <code>List</code> again.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:13:27.797", "Id": "222206", "ParentId": "222144", "Score": "2" } } ]
{ "AcceptedAnswerId": "222147", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:27:31.670", "Id": "222144", "Score": "6", "Tags": [ "java", "beginner", "game", "sorting" ], "Title": "Class for managing a list of scores (game development)" }
222144
<p>I have a WordPress site with multiple custom post types, that all share a common custom taxonomy. Users can also be tagged with terms from this taxonomy.</p> <p>After giving up on <code>JOINS</code>, I managed to conjure the following query to get all of the posts and users based on a <code>term_ID</code>.</p> <pre><code>global $wpdb; $sql = " SELECT P.ID, P.post_type FROM $wpdb-&gt;posts P, $wpdb-&gt;term_relationships TR, $wpdb-&gt;term_taxonomy TT, $wpdb-&gt;terms T WHERE P.ID = TR.object_id AND TR.term_taxonomy_id = TT.term_taxonomy_id AND TT.term_id = T.term_id AND T.term_id = %d AND NOT P.post_status = 'trash' UNION SELECT U.ID, U.user_email FROM $wpdb-&gt;users U, $wpdb-&gt;term_relationships TR, $wpdb-&gt;term_taxonomy TT, $wpdb-&gt;terms T WHERE U.ID = TR.object_id AND TR.term_taxonomy_id = TT.term_taxonomy_id AND TT.term_id = T.term_id AND T.term_id = %d "; $query = $wpdb-&gt;get_results( $wpdb-&gt;prepare( $sql, $term_id, $term_id ), OBJECT ); </code></pre> <p>This works and gets the job done, but I have a feeling that there's room for improvement (<em>performance-/efficiency-wise, mostly</em>). Any suggestions?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T10:32:46.713", "Id": "222145", "Score": "1", "Tags": [ "php", "sql", "wordpress" ], "Title": "Custom WordPress SQL query to get posts and users using term_id" }
222145
<p>I am creating a Expense Tracking Application in C# and right now I am trying to build its building blocks in a console app. I Would like to know your feedback if it is in a Object Oriented Design/Structure.</p> <pre><code>namespace ExpenseTrackerOOP { class ExpenseTracker { static void Main(string[] args) { Account expense = new Expenses(); expense.Initialize(); Account earnings = new Earnings(); earnings.Initialize(); } } public enum ExpenseType { Food, Transportation, Utitlities } public enum AccountTypes { Expenses, Earnings } public class AccountType { public AccountTypes Type; } public abstract class Account { public decimal Value { get; set; } public AccountType Type; public abstract void Initialize(); } public class Expenses : Account { public List&lt;Expenses&gt; Expenses_list { get; set; } public override void Initialize() { Expenses_list = new List&lt;Expenses&gt;(){ new Expenses() { Value = 10, Type = (new AccountType{Type = AccountTypes.Expenses}) }, new Expenses() { Value = 20, Type = (new AccountType{Type = AccountTypes.Expenses}) }, new Expenses() { Value = 30, Type = (new AccountType{Type = AccountTypes.Expenses}) } }; } } public class Earnings : Account { public List&lt;Earnings&gt; Earnings_list { get; set; } public override void Initialize() { Earnings_list = new List&lt;Earnings&gt;(){ new Earnings() { Value = 10, Type = (new AccountType{Type = AccountTypes.Earnings}) }, new Earnings() { Value = 20, Type = (new AccountType{Type = AccountTypes.Earnings}) }, new Earnings() { Value = 30, Type = (new AccountType{Type = AccountTypes.Earnings}) } }; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:42:07.453", "Id": "429851", "Score": "2", "body": "Please tell us more about how it works, what each block is supposed to do etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T18:30:41.607", "Id": "429914", "Score": "2", "body": "`ExpenseType` isn't being used in this code. Why does an `Expenses` account have a list of `Expenses` accounts? Are you confusing your expense accounts class with actual expenses? You'll need two separate classes to represent those (at least normally)." } ]
[ { "body": "<p>There are several aspects about your code worth reviewing: OO-principles, code conventions, functional design. Since you specifically requested to review OO-design and your question lacks context to review functional design, I'll focus on the former.</p>\n<hr />\n<h3>Inheritance</h3>\n<p><code>Expenses</code> and <code>Earnings</code> both derive from <code>Account</code> to provide their specific implementation of <code>Initialze</code>. Because of a lack of context, I can't make a call about this design. The implementation of both classes does seem off. I don't think you want each instance of these classes to create and store the same fixed list of presets.</p>\n<hr />\n<h3>Polymorphism</h3>\n<p>This is proper use of polymorphism. The declaring type <code>Account</code> is the closest fit to enable the use case <code>Initialize</code>. The instance type <code>Expenses</code> provides the specific implementation of that method.</p>\n<blockquote>\n<pre><code>Account expense = new Expenses();\nexpense.Initialize();\n</code></pre>\n</blockquote>\n<hr />\n<h3>Composition</h3>\n<p>You have been a bit too diligent in the composition of some of your classes. <code>AccountType</code> is a redundant class, which acts only as a wrapper for <code>AccountTypes</code> Type. Get rid of it and use <code>AccountTypes</code> directly in <code>Account</code>.</p>\n<blockquote>\n<pre><code>public class AccountType\n{\n public AccountTypes Type;\n}\n</code></pre>\n</blockquote>\n<hr />\n<h3>Encapsulation</h3>\n<p><code>Account</code> is an abstract class that does not provide an explicit constructor. A public default constructor is implied. It is impossible for derived classes to reduce the scope of the access modifier, hence it's a breach in encapsulation. Consider providing a protected constructor for abstract classes.</p>\n<pre><code>public abstract class Account\n{\n protected Account() {}\n}\n</code></pre>\n<p>All your properties and fields are mutable. This might be as desiged, but at least think about whether this is a requirement or just lazy design.</p>\n<blockquote>\n<p><code>public decimal Value { get; set; }</code></p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T06:51:18.917", "Id": "429937", "Score": "1", "body": "Thanks a lot for your code review. Appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T18:48:09.543", "Id": "222173", "ParentId": "222151", "Score": "5" } }, { "body": "<p>You should consider the possibility to make paradoxical objects. The below is actually possible and valid according to your classes and their properties but makes no sense:</p>\n\n<pre><code>Account account = new Expenses { Value = 100.00m, Type = new AccountType { Type = AccountTypes.Earnings } }\n</code></pre>\n\n<p>In other words: When you have a class hierarchy that defines the data types, there is no need to and it can lead to paradoxical objects having a property that defines the same as the containing class. So an Expenses account is an expenses account by it own definition as subclass to Account and doesn't need the Type property. So get rid of that completely. If you stand on it, you'll have to make it read only and hard code the Type Property on each of the subclasses:</p>\n\n<pre><code>public abstract class Account\n{\n public abstract AccountTypes Type { get; }\n}\n\npublic class Expenses\n{\n public override AccountTypes Type =&gt; AccountTypes.Expenses;\n etc...\n</code></pre>\n\n<p>Alternatively you can remove the subclasses to Account and have an <code>AccountTypes</code> member as defining property, but then it isn't much of a class hierarchy.</p>\n\n<hr>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T20:42:04.373", "Id": "222177", "ParentId": "222151", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T12:53:03.900", "Id": "222151", "Score": "1", "Tags": [ "c#", "beginner", "object-oriented", ".net" ], "Title": "Object-oriented implementation on Expense Tracking App" }
222151
<p>This method shows the list of manufacturers' offered products based on the slug and sidebar filters.</p> <p>Most of the time I have to write the same query with only some changes: you can say I am repeating myself. I want my code more readable and short. How can i refactor and reduce the lines of code?</p> <pre><code>public function colabrativetwo(Request $request, $slug = 0, $division_id = 0, $section_id = 0, $manufacturer_id = 0, $list="") { $cookieId = $this-&gt;setInitialCookie($request); if (!empty($cookieId)) $cookieExists = true; $manufacturerArr = array(); $prodFeatured = array(); $geting=DB::table('product_category')-&gt;select('name')-&gt;get(); $filterArray=array(); foreach( $geting as $get){ $localarray=array(); $localarray['name']=$get-&gt;name; $filterArray[]=$localarray; } if ($slug !== 0 || $division_id != 0 || $section_id != 0 || $manufacturer_id != 0) { $where = array(); $slug_colum = array(); if ($slug !== 0 &amp;&amp; $slug != '') { if ($slug == 'low-emitting-material-prerequisite') { $slug_colum[] = 'products.low_emitting_material_prerequisite_expiry_date'; $slug_colum[] = 'products.low_emitting_material_prerequisite_file'; } elseif ($slug == 'low-emitting-material-credit') { $slug_colum[] = 'products.low_emitting_material_credit_expiry_date'; $slug_colum[] = 'products.low_emitting_material_credit_file'; } /*else{ $slug_colum[]='products.low_emitting_material_prerequisite_expiry_date'; // $slug_colum[] = 'products.low_emitting_material_prerequisite_file'; }*/ } if ($division_id != 0) { $where['products.division_id'] = $division_id; } if ($section_id != 0) { $where['products.section_id'] = $section_id; } if ($manufacturer_id != 0) { $where['manufacturers.id'] = $manufacturer_id; } if (isset($slug_colum[1])) { $productsFeatured = Product::select('products.id','products.low_emitting_material_prerequisite_file', 'products.specs_file','products.specs_file_url','products.low_emitting_material_credit_file', 'products.name', 'products.logo', 'products.division_id', 'products.section_id', 'products.manufacturer_id', 'divisions.name as division_name', 'divisions.code as division_code', 'sections.name as section_name', 'sections.code') -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) use ($slug_colum) { if($slug_colum[0] = 'products.low_emitting_material_prerequisite_expiry_date') { $query-&gt;where($slug_colum[1], '!=', ''); } else { $query-&gt;where($slug_colum[0], '&gt;=', date('Y-m-d')) -&gt;where($slug_colum[1], '!=', ''); } }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('divisions.code', 'asc') -&gt;orderBy('sections.code', 'asc') -&gt;groupBy('products.id') -&gt;get(); $divisionsFeatured = Product::select('divisions.id', 'divisions.name as name', 'divisions.code as division_code', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) use ($slug_colum) { if($slug_colum[0] = 'products.low_emitting_material_prerequisite_expiry_date') { $query-&gt;where($slug_colum[1], '!=', ''); } else { $query-&gt;where($slug_colum[0], '&gt;=', date('Y-m-d')) -&gt;where($slug_colum[1], '!=', ''); } }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;groupBy('divisions.id') -&gt;get(); $sectionsFeatured = Product::select('sections.id', 'sections.name as name', 'sections.code', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) use ($slug_colum) { if($slug_colum[0] = 'products.low_emitting_material_prerequisite_expiry_date') { $query-&gt;where($slug_colum[1], '!=', ''); } else { $query-&gt;where($slug_colum[0], '&gt;=', date('Y-m-d')) -&gt;where($slug_colum[1], '!=', ''); } }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('sections.code', 'asc') -&gt;groupBy('sections.id') -&gt;get(); $manufacturersFeatured = Product::select('manufacturers.id AS id', 'manufacturers.name AS name', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) use ($slug_colum) { if($slug_colum[0] = 'products.low_emitting_material_prerequisite_expiry_date') { $query-&gt;where($slug_colum[1], '!=', ''); } else { $query-&gt;where($slug_colum[0], '&gt;=', date('Y-m-d')) -&gt;where($slug_colum[1], '!=', ''); } }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('name', 'asc') -&gt;groupBy('manufacturers.id') // -&gt;limit(3) -&gt;get(); } else { // dd($productsFeatured); $productsFeatured = Product::select('products.id','products.low_emitting_material_prerequisite_file', 'products.specs_file','products.specs_file_url','products.low_emitting_material_credit_file', 'products.name', 'products.logo', 'products.division_id', 'products.section_id', 'products.manufacturer_id', 'divisions.name as division_name', 'divisions.code as division_code', 'sections.name as section_name', 'sections.code') -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('divisions.code', 'asc') -&gt;orderBy('sections.code', 'asc') -&gt;groupBy('products.id') -&gt;get(); $divisionsFeatured = Product::select('divisions.id', 'divisions.name as name', 'divisions.code as division_code', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;groupBy('divisions.id') // -&gt;limit(3) -&gt;get(); $sectionsFeatured = Product::select('sections.id', 'sections.name as name', 'sections.code', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('sections.code', 'asc') -&gt;groupBy('sections.id') // -&gt;limit(3) -&gt;get(); $manufacturersFeatured = Product::select('manufacturers.id AS id', 'manufacturers.name AS name', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;where($where) -&gt;whereIn('products.status', ['active']) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('name', 'asc') -&gt;groupBy('manufacturers.id') // -&gt;limit(2) -&gt;get(); } } else { // dd('oan di siri'); $productsFeatured = Product::select('products.id', 'products.name','products.low_emitting_material_prerequisite_file', 'manufacturers.phone','manufacturers.address','manufacturers.linkedin_url','manufacturers.city', 'products.specs_file','products.specs_file_url','products.low_emitting_material_credit_file', 'products.logo', 'products.division_id', 'products.section_id', 'products.manufacturer_id', 'divisions.name as division_name', 'divisions.code as division_code', 'sections.name as section_name', 'sections.code') -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) { $query-&gt;where('products.low_emitting_material_prerequisite_file', '!=', ''); }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('divisions.code', 'asc') -&gt;orderBy('sections.code', 'asc') -&gt;groupBy('products.id'); // -&gt;limit(3) // -&gt;get() if($request-&gt;ajax() &amp;&amp; $request-&gt;manufacturer){ $productsFeatured-&gt;whereIn('products.manufacturer_id', $request-&gt;manufacturer); $productsFeatured = $productsFeatured-&gt;get(); } else{ $productsFeatured = $productsFeatured-&gt;get(); } // dd($productsFeatured); $divisionsFeatured = Product::select('divisions.id', 'divisions.name as name', 'divisions.code as division_code', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) { $query-&gt;where('products.low_emitting_material_prerequisite_file', '!=', ''); }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;groupBy('divisions.id'); // -&gt;get(); if($request-&gt;ajax() &amp;&amp; $request-&gt;manufacturer){ $divisionsFeatured-&gt;whereIn('products.manufacturer_id', $request-&gt;manufacturer); $divisionsFeatured = $divisionsFeatured-&gt;get(); } else{ $divisionsFeatured = $divisionsFeatured-&gt;get(); } $sectionsFeatured = Product::select('sections.id', 'sections.name as name', 'sections.code', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) { $query-&gt;where('products.low_emitting_material_prerequisite_file', '!=', ''); }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('sections.code', 'asc') -&gt;groupBy('sections.id'); // -&gt;get(); if($request-&gt;ajax() &amp;&amp; $request-&gt;manufacturer){ $sectionsFeatured-&gt;whereIn('products.manufacturer_id', $request-&gt;manufacturer); $sectionsFeatured = $sectionsFeatured-&gt;get(); } else{ $sectionsFeatured = $sectionsFeatured-&gt;get(); } $manufacturersFeatured = Product::select('manufacturers.id AS id', 'manufacturers.id AS id', 'manufacturers.name', 'manufacturers.address', 'manufacturers.city', 'manufacturers.state', 'manufacturers.state', 'manufacturers.phone', DB::raw('COUNT(DISTINCT products.id) as products_count')) -&gt;whereIn('products.status', ['active']) -&gt;where(function ($query) { $query-&gt;where('products.low_emitting_material_prerequisite_file', '!=', ''); }) -&gt;where('users.user_type', 'manufacturer_paid') -&gt;leftJoin('products_selected_leeds', 'products.id', '=', 'products_selected_leeds.product_id') -&gt;leftJoin('sections', 'products.section_id', '=', 'sections.id') -&gt;leftJoin('divisions', 'products.division_id', '=', 'divisions.id') -&gt;join('manufacturers', 'products.manufacturer_id', '=', 'manufacturers.id') -&gt;join('users', 'manufacturers.user_id', '=', 'users.id') -&gt;orderBy('name', 'asc') -&gt;groupBy('manufacturers.id'); // -&gt;limit(3) // -&gt;get(); if($request-&gt;ajax() &amp;&amp; $request-&gt;manufacturer){ $manufacturersFeatured-&gt;whereIn('products.manufacturer_id', $request-&gt;manufacturer); $manufacturersFeatured = $manufacturersFeatured-&gt;get(); } else{ $manufacturersFeatured = $manufacturersFeatured-&gt;get(); } } // dd($productsFeatured ); foreach ($productsFeatured as $productFeatured) { $recSecFeatured['fav_yes'] = ''; $recSecFeatured['id'] = $productFeatured-&gt;id; $recSecFeatured['name'] = $productFeatured-&gt;name; $recSecFeatured['logo'] = $productFeatured-&gt;logo; $recSecFeatured['div_id'] = $productFeatured-&gt;division_id; $recSecFeatured['division_name'] = $productFeatured-&gt;division_name; $recSecFeatured['division_code'] = $productFeatured-&gt;division_code; $recSecFeatured['low_emitting_material_prerequisite_file'] = $productFeatured-&gt;low_emitting_material_prerequisite_file; $recSecFeatured['specs_file'] = $productFeatured-&gt;specs_file; $recSecFeatured['specs_file_url'] = $productFeatured-&gt;specs_file_url; $mfg = Manufacturer::where('id', $productFeatured-&gt;manufacturer_id)-&gt;first(); // Manufacturere information $mfgArr = array(); $mfgArr['id'] = $mfg['id']; $mfgArr['name'] = $mfg['name']; $mfgArr['logo'] = $mfg['logo']; $mfgArr['address'] = $mfg['address']; $mfgArr['city'] = $mfg['city']; $mfgArr['phone'] = $mfg['phone']; $mfgArr['websiteurl'] = $mfg['websiteurl']; $mfgArr['linkedin_url'] =$mfg['linkedin_url']; if (!$this-&gt;find_key_value($manufacturerArr, 'id', $mfgArr['id'])) { $chkFav = DB::table('user_list_details_temp') -&gt;where('type', 'manufacturer') -&gt;where('unique_id', $cookieId) -&gt;where('reference_id', $mfg['id']) -&gt;select('id as fav_yes') -&gt;first(); $mfgArr['fav_yes'] = ""; if (!empty($chkFav)) $mfgArr['fav_yes'] = $chkFav-&gt;fav_yes; // Check if this product exists in non-logged in fav list $manufacturerArr[] = $mfgArr; } $recSecFeatured['address'] = $mfg['address']; $recSecFeatured['city'] = $mfg['city']; $recSecFeatured['phone'] = $mfg['phone']; $recSecFeatured['websiteurl'] = $mfg['websiteurl']; $recSecFeatured['linkedin_url'] = $mfg['linkedin_url']; $recSecFeatured['mfg_id'] = $mfg['id']; $recSecFeatured['mfg_name'] = $mfg['name']; $recSecFeatured['mfg_logo'] = $mfg['logo']; $productSection = Section::where('id', $productFeatured-&gt;section_id)-&gt;first(); $recSecFeatured['sec_id'] = $productSection['id']; $recSecFeatured['sec_code'] = $productSection['code']; $recSecFeatured['sec_name'] = $productSection['name']; $recSecFeatured['slug'] = str_slug($productFeatured-&gt;name); // Check if this product exists in non-logged in fav list $chkFav = DB::table('user_list_details_temp') -&gt;where('type', 'product') -&gt;where('unique_id', $cookieId) -&gt;where('reference_id', $productFeatured-&gt;id) -&gt;select('id as fav_yes') -&gt;first(); $recSecFeatured['fav_yes'] = ""; if (!empty($chkFav)) $recSecFeatured['fav_yes'] = $chkFav-&gt;fav_yes; // Check if this product exists in non-logged in fav list $featuredProductsIdsArr[] = $productFeatured-&gt;id; $prodFeatured[] = $recSecFeatured; } //echo "&lt;pre&gt;";print_r( $prodFeatured );exit; /*** * * @author Muneeb Faruqi * @todo grouped prodFeatured on division name to each product under its certain division... **/ $new_test = collect($prodFeatured)-&gt;groupBy('division_name')-&gt;toArray(); $data['leedProducts'] = $new_test; $data['filterArray']=$filterArray; /*$data['leedProducts'] = $prodFeatured;*/ /*@Muneeb Faruqi Changes Ends*/ $data['leedManufacturer'] = $manufacturerArr; //$data['leedDivision'] = $divisionsArr; $data['leedDivision'] = $divisionsFeatured-&gt;toArray(); $data['leedSection'] = $sectionsFeatured-&gt;toArray(); $data['leedManufacturers'] = $manufacturersFeatured-&gt;toArray(); // dd($manufacturersFeatured-&gt;toArray()); // SEO Code for this page // $data['seoPageTitle'] = "Collaborative for High Performance Schools (CHPS.net) product database - Zero Docs"; $data['seoPageDescription'] = "Pre-Approved low-emitting collaborative for high performance schools CHPS products for construction projects, schools, office and healthcare."; $data['seoPageKeywords'] = "Collaborative for high performance schools, LEEDv4 low emitting products, California Department of Public Health CDPH low-emission testing method for CA Specification 01350"; // SEO Code for this page // // Start Cookie End Code $data['cookieId'] = $cookieId; $data['slug'] = $slug; $data['division_id'] = $division_id; $data['section_id'] = $section_id; $data['manufacturer_id'] = $manufacturer_id; $data['class'] = ''; if (!empty($list) &amp;&amp; $list === 'list') { $data['layout'] = 'list'; $data['class'] = 'library-list-view'; } else { $data['layout'] = 'card'; } $data['showTooltipHelpText'] = "No"; $showTooltipChpsPage = $request-&gt;session()-&gt;get('tooltip_chps_page', 'No'); if($showTooltipChpsPage == 'Yes') { $request-&gt;session()-&gt;put('tooltip_chps_page', 'No'); $data['showTooltipHelpText'] = "Yes"; } //Code by abdullah for sidebar filters data of manufacturers, products, leeds // $data['manufacturers'] = Manufacturer::where('status','active')-&gt;select('id','name')-&gt;orderBy('name', 'asc')-&gt;get(); // dd($data['manufacturers']); $agent = new Agent(); if($agent-&gt;isDesktop()) { $data['isDesktop'] = true; } else { $data['isDesktop'] = false; } $data['leed_records'] = DB::table('leed_tags')-&gt;where('leed_tags.status', 'active') -&gt;whereIn('products.status', ['active']) -&gt;where('products.division_id', '&gt;', 0) -&gt;where('products.section_id', '&gt;', 0) -&gt;where('products.manufacturer_id', '&gt;', 0) -&gt;join('products_selected_leeds', 'leed_tags.id', '=', 'products_selected_leeds.leed_id') -&gt;join('products', 'products_selected_leeds.product_id', '=', 'products.id') -&gt;orderBy('leed_tags.description', 'asc') -&gt;select('leed_tags.description', 'leed_tags.id', 'leed_tags.parent_id', DB::raw('COUNT(DISTINCT products_selected_leeds.product_id) as products_count')) -&gt;groupBy('leed_tags.id') -&gt;get(); /*** * * @author Muneeb Faruqi * @todo Manipulated the below array according to $new_test */ foreach($data['leedProducts'] as $all_manufacturers){ foreach($all_manufacturers as $manufacturer_new){ $list_all_manufacturers[] = array('mfgg_name' =&gt; $manufacturer_new['mfg_name'], 'mfgg_id' =&gt;$manufacturer_new['mfg_id'], 'product_name' =&gt; $manufacturer_new['name'], 'product_id' =&gt; $manufacturer_new['id']); } // $list_all_manufacturers[] = $all_manufacturers['mfg_name']; } /*@Muneeb Faruqi Changes Ends*/ $data['list_all_active_manufacturers'] = array_unique($list_all_manufacturers, SORT_REGULAR); // dd($data['list_all_active_manufacturers']); // unique by mfgg_name $data['manufacturers'] = $this-&gt;unique_multidim_array($data['list_all_active_manufacturers'],'mfgg_name'); if($request-&gt;ajax()){ $data['checkedManufactureArray'] = $request-&gt;manufacturer; }else{ $data['checkedManufactureArray'] = array(); } if ($cookieExists) { if($request-&gt;ajax()){ // dd($checkedManufactureArray); // return view('guest::new_design_frontend.ajax',$data); return view('guest::new_design_frontend.product-library')-&gt;with($data); }else{ return view('guest::new_design_frontend.product-library')-&gt;with($data); } // return view('guest::newcollaborative', $data); // dd($data); } else { // $this-&gt;sendResponseWithCookie('guest::newcollaborative', $data, $cookieId); $this-&gt;sendResponseWithCookie('guest::new_design_frontend.product-library', $data, $cookieId); } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>If statements without brackets work but it's hard to read and will trip you up eventually.</p>\n\n<pre><code>if (!empty($cookieId))\n $cookieExists = true;\n</code></pre>\n\n<p>This code is redundant </p>\n\n<pre><code>if($agent-&gt;isDesktop()) {\n $data['isDesktop'] = true;\n } else {\n $data['isDesktop'] = false;\n }\n</code></pre>\n\n<p>and can be replaced with</p>\n\n<pre><code>$data['isDesktop'] = $agent-&gt;isDesktop();\n</code></pre>\n\n<p>This variable is created and only used to be reassigned,</p>\n\n<pre><code>$new_test = collect($prodFeatured)-&gt;groupBy('division_name')-&gt;toArray();\n$data['leedProducts'] = $new_test;\n</code></pre>\n\n<p>change to </p>\n\n<pre><code>$data['leedProducts'] = collect($prodFeatured)-&gt;groupBy('division_name')-&gt;toArray()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-26T04:57:40.237", "Id": "222956", "ParentId": "222153", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:06:48.000", "Id": "222153", "Score": "3", "Tags": [ "php", "database", "laravel" ], "Title": "List products based on slug and sidebar filters" }
222153
<p>this is my first time on this stack exchange :)</p> <p>I created a little script to check for the latest version of specified API version available, but I am wondering if I am using the best way possible for checking regex and includes?</p> <p>The <code>var arr</code> will be filled dynamically with version folders using fs.readdir, but for simplicity I wrote them in the array manually and the <code>var pattern</code> will come from <code>req.params.v</code> using nodejs express router middleware.</p> <p>Just looking for an approval or if there is a better way, thank you!</p> <pre><code>var arr = ['v1.0.0', 'v5.2.4', 'v5.2.9', 'v5.20.4', 'v6.4.0']; var pattern = 'v5.2'; const regex = /^v[0-9](\.[0-9]{1,2})?(\.[0-9])?$/; if (regex.test(pattern) &amp;&amp; (arr.filter(s =&gt; s.includes(pattern)) != 0)) { if (pattern.match(/\./g) == null) { console.log('major version'); console.log(pattern); } else if (pattern.match(/\./g).length == 1) { console.log('minor version'); console.log(pattern); pattern = pattern + '.'; } else { console.log('patch version'); console.log(pattern); } const matches = arr.filter(s =&gt; s.includes(pattern)); console.log(matches[matches.length - 1]); } else { console.log('Specify correct API version!'); } </code></pre> <p>Thank you in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:14:25.273", "Id": "430004", "Score": "2", "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 6 → 3" } ]
[ { "body": "<h2>Likely logic flaw</h2>\n\n<p>In the first conditional:</p>\n\n<blockquote>\n<pre><code>if (regex.test(pattern) &amp;&amp; (arr.filter(s =&gt; s.includes(pattern)) != 0)) {\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\"><code>Array.filter()</code></a> \"creates a new array\"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">1</a></sup> so the second conditional expression compares an array with zero. Those two should never be loosely equal so that conditional always evaluates to <code>true</code>. Perhaps you intended to check the <code>length</code> property of the array.</p>\n\n<h2>Improving efficiency</h2>\n\n<p>The code has repeated operations - e.g. <code>arr.filter(s =&gt; s.includes(pattern))</code> appears twice, and then there are multiple calls to <code>pattern.match()</code>. The call to <code>arr.filter()</code> could be stored in a variable and then used whenever needed instead of re-filtering. </p>\n\n<p>Also, the regular expression stored in <code>regex</code> could be used with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match\" rel=\"nofollow noreferrer\"><code>String.match()</code></a> to get an array of matches. Because the regular expression has capturing groups, those capturing groups can be used instead of calling <code>pattern.match(/\\./g)</code> multiple times to check for the number of dots. Instead, check if the array returned by <code>String.match()</code> isn't <code>null</code> and then if the 2nd and 3rd elements are <code>undefined</code>.</p>\n\n<p>See a comparison in <a href=\"https://jsperf.com/repeat-tests-vs-match\" rel=\"nofollow noreferrer\">this jsPerf</a>.</p>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter</a></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:19:51.817", "Id": "429977", "Score": "0", "body": "There is a flaw in your code, namely specifying v5.2 should return the latest of minor version 2, namely v5.2.9 and not v5.20.4 (minor version 20)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:38:50.447", "Id": "429983", "Score": "0", "body": "I have updated my code, see edit. According to jsperf (thank for you that website!) it is the fastest way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T15:35:58.433", "Id": "430025", "Score": "0", "body": "Darn I missed that part about updating the pattern when there is a minor version detected. I have removed that snippet since it isn't the same." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T23:40:55.620", "Id": "222182", "ParentId": "222154", "Score": "3" } }, { "body": "<pre><code>// const fs = require('fs');\n// const folder = \"../api/\";\nconst regex = /^v[0-9](\\.[0-9]{1,2})?(\\.[0-9])?$/;\n\n// let files = fs.readdirSync(folder);\nlet pattern = \"v5.2\"; // let pattern = req.params.v;\n\nvar arr = ['v1.0.0', 'v5.2.4', 'v5.2.9', 'v5.20.4', 'v6.4.0']; // var arr = [];\n\n/** Function **/\n/*\nfunction naturalSort(a, b) {\n var ax = [],\n bx = [];\n\n a.replace(/(\\d+)|(\\D+)/g, function (_, $1, $2) {\n ax.push([$1 || Infinity, $2 || \"\"])\n });\n b.replace(/(\\d+)|(\\D+)/g, function (_, $1, $2) {\n bx.push([$1 || Infinity, $2 || \"\"])\n });\n\n while (ax.length &amp;&amp; bx.length) {\n var an = ax.shift();\n var bn = bx.shift();\n var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);\n if (nn) return nn;\n }\n\n return ax.length - bx.length;\n}\n\nfiles.forEach(file =&gt; {\n let dirStat = fs.statSync(folder + '/' + file).isDirectory();\n if (dirStat) {\n arr.push(file);\n }\n});\n\narr.sort(naturalSort);\n*/\n/**/\n\nif (regex.test(pattern)) {\n\n pattern = (function () {\n let patternRegexMatches = pattern.match(regex);\n\n if (patternRegexMatches[1] === undefined) {\n console.log('major version');\n console.log(pattern);\n } else if (patternRegexMatches[2] === undefined) {\n console.log('minor version');\n console.log(pattern);\n pattern = pattern + '.';\n } else {\n console.log('patch version');\n console.log(pattern);\n }\n\n return pattern;\n })();\n\n let matches = arr.filter(s =&gt; s.includes(pattern));\n\n if (matches.length != 0) {\n console.log(matches[matches.length - 1]);\n } else {\n console.log('Specify correct API version!');\n }\n\n} else {\n console.log('Specify correct API version!');\n}\n</code></pre>\n\n<p>Thanks to the review, I updated my code with the following improvements:</p>\n\n<ol>\n<li>let patternRegexMatches = pattern.match(regex);\nOnly match 1x and only if there is a pattern submitted</li>\n<li>pattern = (function() ...\nreturn pattern</li>\n<li>Only 1x arr.filter(s => s.includes(pattern));</li>\n</ol>\n\n<p>Additionally, in javascript the folder structure is not \"naturally sorted\" as with ls -v on linux, so I added an additional function to make sure the version folders are sorted correctly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:28:10.437", "Id": "222219", "ParentId": "222154", "Score": "0" } } ]
{ "AcceptedAnswerId": "222219", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:13:14.040", "Id": "222154", "Score": "4", "Tags": [ "javascript", "strings", "node.js", "regex", "ecmascript-6" ], "Title": "RegEx version control" }
222154
<p>I'm working on a Django project and I'm wondering if there is any way to improve the process time to export my data to xls format.</p> <p>Actually, it takes between 43 seconds and 49 seconds to create the file and download it. I would like to know if my code could be improved in order to save time.</p> <p>This is my function:</p> <pre><code>def get(self, request): output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet('Competence List') row = 0 worksheet.write(row, 0, 'ID') worksheet.set_column('A:B', 8) worksheet.write(row, 1, 'OMCL ID') worksheet.write(row, 2, 'OMCL Code') worksheet.set_column('C:C', 25) worksheet.write(row, 3, 'OMCL Name') worksheet.set_column('D:D', 80) worksheet.write(row, 4, 'Country Code') worksheet.set_column('E:E', 12) worksheet.write(row, 5, 'Last Name') worksheet.set_column('F:G', 15) worksheet.write(row, 6, 'First Name') worksheet.write(row, 7, 'Email') worksheet.set_column('H:H', 40) worksheet.write(row, 8, 'Title') worksheet.set_column('I:I', 8) worksheet.write(row, 9, 'Test Method ID') worksheet.set_column('J:J', 15) worksheet.write(row, 10, 'Name') worksheet.set_column('K:K', 65) worksheet.write(row, 11, 'Type') worksheet.set_column('L:L', 6) worksheet.write(row, 12, 'Sub Method ID') worksheet.set_column('M:M', 14) worksheet.write(row, 13, 'Group Name') worksheet.set_column('N:N', 20) worksheet.write(row, 14, 'Name') worksheet.set_column('O:O', 60) worksheet.write(row, 15, 'Ref Gen Chap Ph.Eur.') worksheet.set_column('P:T', 20) worksheet.write(row, 16, 'Competence Level') worksheet.write(row, 17, 'Competence Level') worksheet.write(row, 18, 'Frequency Level') worksheet.write(row, 19, 'Frequency Level') worksheet.set_column('U:Z', 15) worksheet.write(row, 20, 'Animals') worksheet.write(row, 21, 'Product Class') worksheet.write(row, 22, 'Manufacturer') worksheet.write(row, 23, 'BSP') worksheet.write(row, 24, 'CAP') worksheet.write(row, 25, 'MSS') worksheet.write(row, 26, 'QMS Covered') worksheet.write(row, 27, 'Last PTS Year') worksheet.write(row, 28, 'OCABR') worksheet.write(row, 29, 'Run Acc Ph.Eur.') worksheet.write(row, 30, 'Comment') worksheet.write(row, 31, 'Subcontracted') worksheet.set_column('AA:AA', 35) worksheet.write(row, 32, 'Counterfeit/Illegal Medicine Testing') worksheet.set_column('AB:AB', 15) worksheet.write(row, 33, '3R programme') worksheet.set_column('AC:AF', 20) worksheet.write(row, 34, 'Created') worksheet.write(row, 35, 'Created By') worksheet.write(row, 36, 'Modified') worksheet.write(row, 37, 'Modified By') objects = Competence.objects.filter( id__in=self.request.session['result_recordset'] ).select_related( 'omcl', 'method', 'sub_method', 'sub_method__sub_method', 'sub_method__group', 'created_by', 'omcl__country' ).annotate( concat_animals=StringAgg('animals__name', ';', True), concat_products=StringAgg('product_classes__name', ';', True), concat_manufacturers=StringAgg('manufacturers__name', ';', True), concat_bsp=StringAgg('bsp_items__code', ';', True), concat_cap=StringAgg('cap_items__code', ';', True), concat_mss=StringAgg('mss_items__code', ';', True), concat_pts=StringAgg(Cast('pts_years__pts_year', CharField(max_length=4)), ';', True)) contacts = Contact.objects.filter(type='OMCL') omcl_contacts = {x.omcl_id: x for x in contacts} row += 1 for item in objects: omcl_contact = omcl_contacts.get(item.omcl.id, None) worksheet.write(row, 0, item.pk) worksheet.write(row, 1, item.omcl.id) worksheet.write(row, 2, item.omcl.code) worksheet.write(row, 3, item.omcl.name) worksheet.write(row, 4, item.omcl.country.code) if omcl_contact: last = omcl_contact.last_name if omcl_contact.last_name else '' first = omcl_contact.first_name if omcl_contact.first_name else '' worksheet.write(row, 5, last) worksheet.write(row, 6, first) worksheet.write(row, 7, omcl_contact.email) worksheet.write(row, 8, omcl_contact.title) worksheet.write(row, 9, item.method.pk) worksheet.write(row, 10, item.method.name) worksheet.write(row, 11, item.method.type) if item.sub_method: worksheet.write(row, 12, item.sub_method.id) worksheet.write(row, 13, item.sub_method.group.name) worksheet.write(row, 14, item.sub_method.sub_method.name) worksheet.write(row, 15, item.method.reference_pheur) worksheet.write(row, 16, item.level) worksheet.write(row, 17, item.get_level()) worksheet.write(row, 18, item.frequency) worksheet.write(row, 19, item.get_frequency()) worksheet.write(row, 20, item.concat_animals) worksheet.write(row, 21, item.concat_products) worksheet.write(row, 22, item.concat_manufacturers) worksheet.write(row, 23, item.concat_bsp) worksheet.write(row, 24, item.concat_cap) worksheet.write(row, 25, item.concat_mss) worksheet.write(row, 26, item.qms_covered) worksheet.write(row, 27, item.concat_pts) worksheet.write(row, 28, item.ocabr) worksheet.write(row, 29, item.run_acc_pheur) worksheet.write(row, 30, item.comment) worksheet.write(row, 31, item.is_subcontracted) worksheet.write(row, 32, item.is_illegal_med_test) worksheet.write(row, 33, item.is_three_r) locale = timezone.localtime(item.creation_date) worksheet.write(row, 34, date_format(locale, 'DATETIME_FORMAT')) worksheet.write(row, 35, six.u(str(item.created_by))) locale = timezone.localtime(item.modification_date) worksheet.write(row, 36, date_format(locale, 'DATETIME_FORMAT')) worksheet.write(row, 37, six.u(str(item.modified_by))) row += 1 workbook.close() output.seek(0) response = HttpResponse(output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="competence_list.xlsx"' return response </code></pre> <p>Maybe by using xlwt library ?</p>
[]
[ { "body": "<p>You have a lot of lines like this:</p>\n\n<blockquote>\n<pre><code>worksheet.write(row, 0, item.pk)\n</code></pre>\n</blockquote>\n\n<p>This means you should use a for loop. Take:</p>\n\n<pre><code>for i, attr in enumerate(...):\n worksheet.write(row, i, item???attr)\n</code></pre>\n\n<p>But what should <code>item???attr</code> be? With <code>operator.attrgetter</code> it's pretty simple.</p>\n\n<p>Take the following example:</p>\n\n<pre><code>&gt;&gt;&gt; class Test:\n value = '{} world!'\n\n&gt;&gt;&gt; Test.value.format('Hello')\n'Hello world!'\n&gt;&gt;&gt; operator.attrgetter('value.format')(Test)('Hello')\n'Hello world!'\n</code></pre>\n\n<p>From this it's easy to see that the loop can be:</p>\n\n<pre><code>for i, attr in enumerate(...):\n worksheet.write(row, i, operator.attrgetter(attr)(item))\n</code></pre>\n\n<hr>\n\n<p>Assuming that <code>worksheet.set_column</code> can be called after all the <code>worksheet.write</code>s your code can be simplified.</p>\n\n<pre><code>TITLES = [\n 'ID',\n 'OMCL ID',\n ...\n]\n\nCOLUMNS = [\n ('A:B', 8),\n ('C:C', 25),\n ...\n]\n\nATTRS = [\n (1, 'pk'),\n (2, 'ocml.id'),\n ...\n]\n\ndef get(self, request):\n\n output = io.BytesIO()\n\n workbook = xlsxwriter.Workbook(output)\n worksheet = workbook.add_worksheet('Competence List')\n\n row = 0\n for i, name in enumerate(TITLES):\n worksheet.write(row, i, 'ID')\n\n for column, value in COLUMNS:\n worksheet.set_column(column, value)\n\n objects = Competence.objects.filter(\n id__in=self.request.session['result_recordset']\n ).select_related(\n 'omcl', 'method', 'sub_method', 'sub_method__sub_method', 'sub_method__group', 'created_by',\n 'omcl__country'\n ).annotate(\n concat_animals=StringAgg('animals__name', ';', True),\n concat_products=StringAgg('product_classes__name', ';', True),\n concat_manufacturers=StringAgg('manufacturers__name', ';', True),\n concat_bsp=StringAgg('bsp_items__code', ';', True),\n concat_cap=StringAgg('cap_items__code', ';', True),\n concat_mss=StringAgg('mss_items__code', ';', True),\n concat_pts=StringAgg(Cast('pts_years__pts_year', CharField(max_length=4)), ';', True))\n\n contacts = Contact.objects.filter(type='OMCL')\n omcl_contacts = {x.omcl_id: x for x in contacts}\n\n attrs = [(i, operator.attrgetter(a)) for i, a in ATTRS]\n\n for row, item in enumerate(objects, start=1):\n for i, attr_getter in attrs:\n worksheet.write(row, i, attr_getter(item))\n\n omcl_contact = omcl_contacts.get(item.omcl.id, None)\n if omcl_contact:\n worksheet.write(row, 5, omcl_contact.last_name or '')\n worksheet.write(row, 6, omcl_contact.first_name or '')\n worksheet.write(row, 7, omcl_contact.email)\n worksheet.write(row, 8, omcl_contact.title)\n\n worksheet.write(row, 17, item.get_level())\n worksheet.write(row, 19, item.get_frequency())\n\n locale = timezone.localtime(item.creation_date)\n worksheet.write(row, 34, date_format(locale, 'DATETIME_FORMAT'))\n worksheet.write(row, 35, six.u(str(item.created_by)))\n\n locale = timezone.localtime(item.modification_date)\n worksheet.write(row, 36, date_format(locale, 'DATETIME_FORMAT'))\n worksheet.write(row, 37, six.u(str(item.modified_by)))\n\n workbook.close()\n\n output.seek(0)\n response = HttpResponse(output.read(),\n content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')\n response['Content-Disposition'] = 'attachment; filename=\"competence_list.xlsx\"'\n return response\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T15:10:40.903", "Id": "429882", "Score": "0", "body": "First, thank you very much with your answer !\nNow I have an issue: `'Competence' object is not subscriptable` on this line: `worksheet.write(row, i, attr_getter(item)) `" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T15:22:29.183", "Id": "429884", "Score": "0", "body": "@Essex Please see the updated code. `itemgetter` -> `attrgetter`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:18:23.617", "Id": "429945", "Score": "0", "body": "I updated the code : `'Competence' object has no attribute 'item'` in `worksheet.write(row, i, attr_getter(item))`. I have to see what doesn't work." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:56:48.957", "Id": "222159", "ParentId": "222155", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:24:51.393", "Id": "222155", "Score": "1", "Tags": [ "python", "excel", "django" ], "Title": "Django export to xls format" }
222155
<p>I'm still new in web development and I am trying to develop a website with free access to doctors listing with option of booking. This is a personal project that my local community can benefit.</p> <p>I want to get an opinion or recommendation from you experts whether the logic for my register functionality is correct.</p> <p>Before I ask any question on this platform, please note that I have done extensive research and trials on web development.</p> <p>Let me just explain the logic I implemented point wise.</p> <ol> <li>Call DB Connection file</li> <li>Check for DB Connection errors</li> <li>Assign form input to variables</li> <li>Use prepared statements to retrieve current user accounts info</li> <li>Check if account exists</li> <li>Insert user details in database using prepared statement</li> <li>Direct to confirmation page + Send email to activate account</li> <li>Close connection</li> </ol> <pre><code>&lt;?php require_once("dblogin.php"); // Connection error to database if ($conn-&gt;connect_error) { trigger_error('No database connection', E_USER_WARNING);; } if (isset($_POST['submit'])) { $firstname = mysqli_real_escape_string($conn, $_POST['firstname']); $lastname = mysqli_real_escape_string($conn, $_POST['lastname']); $email = mysqli_real_escape_string($conn, $_POST['email']); $password1 = password_hash(mysqli_real_escape_string($conn, $_POST['password1']),PASSWORD_BCRYPT); $terms_flag = 'Approved'; $user_type = 'user'; $status = 'Active'; $account_verified = '0'; $str = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM!@#$%&amp;*'; $otp = '0123456789'; $str = str_shuffle($str); $otp = str_shuffle($otp); $str = substr($str,0,10); $otp = substr($otp,0,6); $user_check_query = $conn -&gt; prepare("SELECT count(email) as count_num FROM user_account WHERE username=? LIMIT 1"); $user_check_query -&gt; bind_param("ss", $email); $user_check_query-&gt;execute(); $user_check_query-&gt;store_result(); if($user_check_query-&gt;execute() == true) { $user_check_query -&gt; bind_result($count_num); $user_check_query -&gt; fetch(); $user_check_query-&gt;close(); if ($count_num) { // if user exists $message = "Username already exists. Please use another Email Address or Phone Number"; }elseif (strlen($email) &gt; 0) { $stmt = $conn-&gt;prepare("INSERT INTO user_account (first_name,last_name,email,password1,account_verified,token) VALUES (?,?,?,?,?,?,?)"); $stmt-&gt;bind_param("sssssssssssssss", $firstname,$lastname,$email, $email,$password1,$account_verified,$str); $stmt-&gt;execute(); $stmt-&gt;close(); $to = 'test@gmail.com'; $subject = "Activate your account - Find A Doctor"; //* ========== Start Activate Account Email Layour ======== *// $message .= '&lt;html&gt;&lt;body&gt;'; $message .= 'Please Activate your account'; $message .= '&lt;p align="center" style="font-size:25px; color:#3f4079;"&gt;Username: &lt;strong&gt;'.$email.'&lt;/strong&gt;&lt;/p&gt; &lt;br&gt;'; $message .= '&lt;p align="center" style="font-size:25px; color:#3f4079;"&gt;Kindly&lt;a href="http://www.test.com/login.php? confirmemail='.$email.'&amp;token='.$str.'"&gt;&lt;strong&gt; confirm&lt;/strong&gt;&lt;/a&gt; your registration.&lt;/p&gt;'; $message .= "&lt;/body&gt;&lt;/html&gt;"; //* ========== Start Activate Account Email Layout ======== *// // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: &lt;test@gmail.com&gt;' . "\r\n"; mail($to,$subject,$message,$headers); $_SESSION['username'] = $username; header('location: confirm-register.php? confirmemail='.$email.'&amp;p='.$phonenumber); exit(); } } } $conn-&gt;close(); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:46:18.510", "Id": "429880", "Score": "1", "body": "There seems to be some disputes here. In order to give me time to understand the situation, I am locking this post for one hour. Please hold on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T18:24:24.100", "Id": "429911", "Score": "3", "body": "Alright, here's what we do, the answer will be invalidated if we edit the question, so let's close this question off as broken, not working (it is broken, and not working), and, @PhilStamp - open up a new question with the working code (you can edit this question to get the raw content - and pasted it in to the new question, and then use the correct code for the new question). This will clear up any confustion and start the new question with a clear slate." } ]
[ { "body": "<p>After a cursory read, this jumped out at me:</p>\n\n<pre><code>$user_check_query -&gt; bind_param(\"ss\", $email);\n</code></pre>\n\n<p>You’re binding 1 string parameter, but have two <code>s</code> codes. </p>\n\n<p>You do it again here:</p>\n\n<pre><code>$stmt-&gt;bind_param(\"sssssssssssssss\", \n\n$firstname,$lastname,$email,\n$email,$password1,$account_verified,$str); \n</code></pre>\n\n<p>15 <code>s</code>’s but only 7 parameters. </p>\n\n<hr>\n\n<p>It appears you are storing the password as clear text in the database. <strong>Never</strong> do that. Don’t even store an encrypted password; use a one-way hash. </p>\n\n<hr>\n\n<p>Your confirmation email is not being sent to <code>$email</code>. It is sent unconditionally to <code>test@gmail.com</code>. Your newly registered user will be waiting a long time for their verification code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:45:22.580", "Id": "429853", "Score": "0", "body": "My apologies. You are perfectly right. While editing the code, I missed updating the bind parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:46:31.930", "Id": "429854", "Score": "4", "body": "Remove the checkmark, please. The question is 17 minutes old, and I’ve looked at only 2 lines of code. There is plenty more to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:46:34.390", "Id": "429855", "Score": "0", "body": "@PhilStamp this is not a code review. If this is all you were looking for it means your question is off topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:03:07.137", "Id": "429857", "Score": "0", "body": "@YourCommonSense What does a code review mean? I explained clearly the logic for development and I provided my script for reference. I am just looking for recommendation or things I missed so that the functionality works fine. How is it off topic as StackExchange is for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:05:05.610", "Id": "429858", "Score": "0", "body": "@PhilStamp if your present code doesn't work, it means it is off topic for this site. Only a working code is accepted for the review" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:16:47.427", "Id": "429866", "Score": "0", "body": "Full Working PHP code posted. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:23:42.223", "Id": "429870", "Score": "0", "body": "@AJNeufeld Any link on how to implement one-way hash. Indeed im storing my password in clear text but is it encrypted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T14:28:41.090", "Id": "429873", "Score": "0", "body": "https://www.php.net/manual/en/faq.passwords.php or https://dev.mysql.com/doc/refman/5.7/en/password-hashing.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T18:25:47.030", "Id": "429912", "Score": "0", "body": "I have closed off this (not-working-code version) question. Also asking the OP to start a new question with the corrected code. Expect a new post to come in with that new code, and I recommend reviewing it in that post when it arrives.... with the additional content you want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T05:26:42.083", "Id": "429936", "Score": "0", "body": "To whoever wants to upvote this answer: Basically it points at some errors in the code and a single improvement suggestion is already implemented in the OP. Which by no means can be qualified as a code review according to the site rules." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:43:19.817", "Id": "222158", "ParentId": "222156", "Score": "1" } } ]
{ "AcceptedAnswerId": "222158", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:27:36.290", "Id": "222156", "Score": "-1", "Tags": [ "php", "html", "mysql", "css" ], "Title": "Register Script for a website" }
222156
<p>I've attempted to make a small PHP library for styling terminal output using ANSI escape sequences. The repo is located <a href="https://github.com/tdtrung17693/php-chalk" rel="nofollow noreferrer">here</a>.</p> <p>To be honest, I am not really satisfied with the current structure of my code. It seems to be "not good". But I don't know any better ways to structure it.</p> <p><strong>Chalk.php</strong></p> <pre><code>&lt;?php namespace TdTrung\Chalk; use TdTrung\OSRecognizer\OSRecognizer; class Chalk { const RESET = "\033[0m"; private $styles = [ 'reset' =&gt; 0, 'bold' =&gt; 1, 'dim' =&gt; 2, 'italic' =&gt; 3, 'underscore' =&gt; 4, 'blink' =&gt; 5, 'inverse' =&gt; 7, 'strikethrough' =&gt; 9, 'black' =&gt; 30, 'red' =&gt; 31, 'green' =&gt; 32, 'yellow' =&gt; 33, 'blue' =&gt; 34, 'magenta' =&gt; 35, 'cyan' =&gt; 36, 'lightGray' =&gt; 37, 'darkGray' =&gt; 90, 'lightRed' =&gt; 91, 'lightGreen' =&gt; 92, 'lightYellow' =&gt; 93, 'lightBlue' =&gt; 94, 'lightMagenta' =&gt; 95, 'lightCyan' =&gt; 96, 'white' =&gt; 97 ]; private $twoStageFns = ["rgb"]; private $osRecognizer; private $supportLevel = 0; private $enableColor = true; public function __construct() { $this-&gt;initSeqBuilders(); $this-&gt;osRecognizer = new OSRecognizer; $this-&gt;checkColorSupport(); } private function initSeqBuilders() { foreach ($this-&gt;styles as $name =&gt; $code) { $this-&gt;styles[$name] = function ($offset) use ($code) { if ($code &gt; 0) $code = $offset + $code; return "\033[{$code}m"; }; } $this-&gt;styles["rgb"] = function ($r, $g, $b, $offset) { // TODO: Fallback to ANSI 256 if possible if (!$this-&gt;has16mSupport()) return ""; $type = 38 + $offset; return "\033[{$type};2;{$r};{$g};{$b}m"; }; } private function checkColorSupport() { if (getenv('TERM') === 'dumb') { return 0; } else if (strpos($this-&gt;osRecognizer-&gt;getPlatform(), 'win') !== false) { // get os version and build $release = explode('.', $this-&gt;osRecognizer-&gt;getRelease()); if (intval($release[0]) &gt;= 10 &amp;&amp; intval($release[1]) &gt;= 10586) { $this-&gt;supportLevel = intval($release[2]) &gt;= 14931 ? 3 : 2; return; } $this-&gt;supportLevel = 1; } else if (strpos(getenv('COLORTERM'), 'truecolor') !== false) { $this-&gt;supportLevel = 3; } else if (function_exists('posix_isatty') &amp;&amp; @!posix_isatty(STDOUT)) { $this-&gt;supportLevel = 1; } else if (preg_match('/-256(color)?$/i', getenv('TERM'))) { $this-&gt;supportLevel = 2; } else if (preg_match('/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i', getenv('TERM'))) { $this-&gt;supportLevel = 1; } else { $this-&gt;supportLevel = 0; } } private function is256Color($styleName) { return preg_match('/^color\d+/i', $styleName); } private function isValidStyle($styleName) { if (!(strpos($styleName, 'bg') === false)) { preg_match('/^bg(\w+)$/', $styleName, $match); $styleName = lcfirst($match[1]); } return array_key_exists($styleName, $this-&gt;styles) || $this-&gt;is256Color($styleName); } private function parseStyleName($styleName) { $offset = 0; if (!(strpos($styleName, 'bg') === false)) { $offset = 10; preg_match('/^bg(\w+)$/', $styleName, $match); $styleName = lcfirst($match[1]); } return [$offset, $styleName]; } private function get256Sequence($styleName, $offset) { preg_match('/^color(\d+)/i', $styleName, $match); $offset += 38; return "\033[{$offset};5;{$match[1]}m"; } public function isTwoStageFns($styleName) { return array_search($styleName, $this-&gt;twoStageFns) !== false; } public function disableColor() { $this-&gt;enableColor = false; } public function hasColorSupport() { return $this-&gt;supportLevel &gt;= 1; } public function has256Support() { return $this-&gt;supportLevel &gt;= 2; } public function has16mSupport() { return $this-&gt;supportLevel &gt;= 3; } public function __get($styleName) { if (!$this-&gt;isValidStyle($styleName)) { throw new InvalidStyleException($styleName); } list($offset, $styleName) = $this-&gt;parseStyleName($styleName); if ($this-&gt;is256Color($styleName)) { $style = $this-&gt;get256Sequence($styleName, $offset); } else { $style = $this-&gt;styles[$styleName]($offset); } return new StyleChain($style, $this); } public function __call($styleName, $arguments) { if (!$this-&gt;isValidStyle($styleName)) { throw InvalidStyleException($styleName); } list($offset, $styleName) = $this-&gt;parseStyleName($styleName); if ($this-&gt;isTwoStageFns($styleName)) { array_push($arguments, $offset); return new StyleChain( call_user_func_array($this-&gt;styles[$styleName], $arguments), $this ); } else if ($this-&gt;is256Color($styleName)) { $style = $this-&gt;get256Sequence($styleName, $offset); } else { $style = $this-&gt;styles[$styleName]($offset); } array_unshift($arguments, [$style]); return call_user_func_array([$this, 'apply'], $arguments); } public function apply() { if (func_num_args() &lt; 2) throw new InvalidArgumentException('Insufficient arguments (at least 2 are required)'); $styles = func_get_arg(0); $strings = func_get_args(); array_shift($strings); $text = implode(" ", $strings); if (!$this-&gt;enableColor || !$this-&gt;hasColorSupport()) return $text; return array_reduce($styles, function ($carry, $style) { return "{$style}{$carry}" . Chalk::RESET; }, $text); } } </code></pre> <p><strong>StyleChain.php</strong></p> <pre><code>&lt;?php namespace TdTrung\Chalk; class StyleChain { public $styles = []; private $colorInstance; public function __construct($style, Chalk $colorInstance) { array_push($this-&gt;styles, $style); $this-&gt;colorInstance = $colorInstance; } public function __invoke() { $arguments = func_get_args(); array_unshift($arguments, $this-&gt;styles); return call_user_func_array( [$this-&gt;colorInstance, 'apply'], $arguments ); } public function __get($prop) { $other = $this-&gt;colorInstance-&gt;{$prop}; $this-&gt;merge($other); return $this; } public function __call($method, $arguments) { if ($this-&gt;colorInstance-&gt;isTwoStageFns($method)) { $result = call_user_func_array( [$this-&gt;colorInstance, $method], $arguments ); $this-&gt;merge($result); return $this; } $other = $this-&gt;colorInstance-&gt;{$method}; $this-&gt;merge($other); return call_user_func_array([$this, '__invoke'], $arguments); } private function merge(StyleChain $other) { $this-&gt;styles = array_merge($this-&gt;styles, $other-&gt;styles); } } </code></pre>
[]
[ { "body": "<h2>General Feedback</h2>\n\n<p>The library looks useful and the code appears to adhere to style guides like <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2</a> for the most part. </p>\n\n<p>I don't see docblocks in the code. Each method should have a description of what it does, along with any parameters and the return type. Then anyone reading or contributing will be able to know how methods are implemented without having to read through them.</p>\n\n<p>Are there any unit tests for the library? It would be wise to have those defined, especially since you invite others to fork the repository and contribute to it. Minimum tests would likely include testing all styles supported, as well as chaining calls and cases where an exception is expected to be thrown.</p>\n\n<p>The <a href=\"https://php.net/manual/en/migration56.new-features.php#migration56.new-features.splat\" rel=\"nofollow noreferrer\">splat operator</a> (i.e. <code>...</code>) could likely be used to simplify some of the calls that utilize <code>call_user_func_array()</code>, unless PHP versions prior to 5.6 need to be supported. </p>\n\n<h2>Suggestion about the styles array</h2>\n\n<p>Instead of making dynamic functions for each style in <code>$style</code>, use a method that accepts the color and offset. This would mean that the <code>__get()</code> method would need to be updated to conditionally handle <code>rgb</code> with that method. </p>\n\n<p>Then the array stored in <code>$style</code> could be declared as a constant. </p>\n\n<pre><code>class Chalk\n{ \n const RESET = \"\\033[0m\";\n\n const STYLES = [\n 'reset' =&gt; 0,\n 'bold' =&gt; 1,\n 'dim' =&gt; 2,\n</code></pre>\n\n<p>That way each instance of the class wouldn't need to have that data tied to it, and there wouldn't be a need to call the <code>initSeqBuilders()</code> method.</p>\n\n<p>And then define new methods for getting the styles from that array as well as the RGB colors:</p>\n\n<pre><code>public function getStyle($name, $offset) {\n $code = self::STYLES[$name];\n if ($code &gt; 0)\n $code = $offset + $code;\n return \"\\033[{$code}m\";\n}\npublic function getRgbStyle ($r, $g, $b, $offset) {\n // TODO: Fallback to ANSI 256 if possible\n if (!$this-&gt;has16mSupport()) return \"\";\n\n $type = 38 + $offset;\n return \"\\033[{$type};2;{$r};{$g};{$b}m\";\n}\n</code></pre>\n\n<p>There would obviously need to be updates to any place that <code>$this-&gt;styles</code> is used.</p>\n\n<h2>Error when throwing exception</h2>\n\n<p>In the <code>__call()</code> method of <code>Chalk</code> there is a possibility that an exception will be thrown:</p>\n\n<blockquote>\n<pre><code>public function __call($styleName, $arguments)\n{\n if (!$this-&gt;isValidStyle($styleName)) {\n throw InvalidStyleException($styleName);\n }\n</code></pre>\n</blockquote>\n\n<p>Instead of instantiating a <code>InvalidStyleException</code> object, that code calls <code>InvalidStyleException()</code> as if it is a function, which causes an error because that is not a function. Add the <code>new</code> operator to instantiate the exception:</p>\n\n<pre><code>public function __call($styleName, $arguments)\n{\n if (!$this-&gt;isValidStyle($styleName)) {\n throw new InvalidStyleException($styleName);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T20:38:48.623", "Id": "222490", "ParentId": "222157", "Score": "2" } } ]
{ "AcceptedAnswerId": "222490", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T13:28:34.070", "Id": "222157", "Score": "4", "Tags": [ "php", "console", "formatting", "library", "user-interface" ], "Title": "A small PHP library for styling terminal output" }
222157
<p>My goal is to generate a large sparse matrix with majority (~99%) zeros and ones. Ideally, I would be working with 10,000 rows and 10,000,000 columns. Additionally, each column is generated as a sequence of Bernoulli samples with a <strong>column-specific</strong> probability. So far, I've implemented 3 ways to generate the data:</p> <p><strong>Function 1</strong></p> <p>Creating basic dense matrix of 0/1:</p> <pre><code>spMat_dense &lt;- function(ncols,nrows,col_probs){ matrix(rbinom(nrows*ncols,1,col_probs), ncol=ncols,byrow=T) } </code></pre> <p><strong>Function 2</strong></p> <p>Using <code>Rcpp</code>:</p> <pre><code>#include &lt;RcppArmadillo.h&gt; // [[Rcpp::depends(RcppArmadillo)]] using namespace std; using namespace Rcpp; using namespace arma; // [[Rcpp::export]] arma::sp_mat spMat_cpp(const int&amp; ncols, const int&amp; nrows, const NumericVector&amp; col_probs){ IntegerVector binom_draws = no_init(nrows); IntegerVector row_pos; IntegerVector col_pos; int nz_counter=0; //Generate (row,cell)-coordinates of non-zero values for(int j=0; j&lt;ncols; ++j){ binom_draws = rbinom(nrows,1,col_probs[j]); for(int i=0; i&lt;nrows; ++i){ if(binom_draws[i]==1){ row_pos.push_back(i); col_pos.push_back(j); nz_counter += 1; } } } //Create a 2 x N matrix - indicates row/col positions for N non-zero entries arma::umat loc_mat(2,nz_counter); for(int i=0;i&lt;nz_counter; ++i){ loc_mat(0,i) = row_pos[i]; loc_mat(1,i) = col_pos[i]; } IntegerVector x_tmp = rep(1,nz_counter); arma::colvec x = Rcpp::as&lt;arma::colvec&gt;(x_tmp); //sparse matrix constructor arma::sp_mat out(loc_mat,x); return out; } </code></pre> <p><strong>Function 3</strong></p> <p>Using <code>dgCMatrix</code> construction in <code>Matrix</code> package:</p> <pre><code>spMat_dgC &lt;- function(ncols,nrows,col_probs){ #Credit to Andrew Guster (https://stackoverflow.com/a/56348978/4321711) require(Matrix) mat &lt;- Matrix(0, nrows, ncols, sparse = TRUE) #blank matrix for template i &lt;- vector(mode = "list", length = ncols) #each element of i contains the '1' rows p &lt;- rep(0, ncols) #p will be cumsum no of 1s by column for(r in 1:nrows){ row &lt;- rbinom(ncols, 1, col_probs) #random row p &lt;- p + row #add to column identifier if(any(row == 1)){ for (j in which(row == 1)){ i[[j]] &lt;- c(i[[j]], r-1) #append row identifier } } } p &lt;- c(0, cumsum(p)) #this is the format required i &lt;- unlist(i) x &lt;- rep(1, length(i)) mat@i &lt;- as.integer(i) mat@p &lt;- as.integer(p) mat@x &lt;- x return(mat) } </code></pre> <p><strong>Benchmarking</strong></p> <pre><code>ncols = 100000 nrows = 1000 col_probs = runif(ncols, 0.001, 0.002) microbenchmark::microbenchmark(generate_SpMat1(ncols=ncols,nrows=nrows,col_probs=col_probs), generate_SpMat2(ncols=ncols,nrows=nrows,col_probs = col_probs), generate_spMat(ncols=ncols,nrows=nrows,col_probs=col_probs), times=5L) Unit: seconds expr spMat_dense(ncols = ncols, nrows = nrows, col_probs = col_probs) spMat_cpp(ncols = ncols, nrows = nrows, col_probs = col_probs) spMat_dgC(ncols = ncols, nrows = nrows, col_probs = col_probs) min lq mean median uq max neval 6.527836 6.673515 7.260482 7.13241 7.813596 8.155053 5 56.726238 57.038976 57.841693 57.24435 58.325564 59.873333 5 6.541939 6.599228 6.938952 6.62452 7.402208 7.526867 5 </code></pre> <p>Interestingly, my <code>Rcpp</code> code is not as optimal as I thought it would be. I'm not entirely sure why it's not as efficient as the basic, dense construction. The advantage however in the <code>Rcpp</code> and <code>dgCMatrix</code> construction is that they don't create a dense matrix first. The memory used is much less:</p> <pre><code>ncols = 100000 nrows = 1000 col_probs = runif(ncols, 0.001, 0.002) mat1 &lt;- spMat_dense(ncols=ncols,nrows=nrows,col_probs=col_probs) mat2 &lt;- spMat_cpp(ncols=ncols,nrows=nrows,col_probs = col_probs) mat3 &lt;- spMat_dgC(ncols=ncols,nrows=nrows,col_probs=col_probs) object.size(mat1) object.size(mat2) object.size(mat3) &gt; object.size(mat1) 400000216 bytes &gt; object.size(mat2) 2199728 bytes &gt; object.size(mat3) 2205920 bytes </code></pre> <p><strong>Question</strong></p> <p>What is it about my <code>Rcpp</code> code that makes it slower than the other two? Is it possible to optimize or is the well-written R code with <code>dgCMatrix</code> as good as it gets?</p>
[]
[ { "body": "<p>This seems faster in <code>r</code>:</p>\n\n<pre><code>minem2 &lt;- function(ncols, nrows, col_probs){\n r &lt;- lapply(1:ncols, function(x) {\n p &lt;- col_probs[x]\n i &lt;- sample.int(2L, size = nrows, replace = T, prob = c(1 - p, p))\n which(i == 2L)\n })\n rl &lt;- lengths(r)\n nc &lt;- rep(1:ncols, times = rl) # col indexes\n nr &lt;- unlist(r) # row index\n ddims &lt;- c(nrows, ncols)\n sparseMatrix(i = nr, j = nc, dims = ddims)\n}\n</code></pre>\n\n<p>Andrew Guster commented on this approach (<a href=\"https://stackoverflow.com/a/56348978/4321711\">link</a>)</p>\n\n<p>Maybe using this logic <code>Rcpp</code> code could be written faster...</p>\n\n<p>Generally, we do not need to generate all values, but just get the indexes where value is 1.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:00:36.053", "Id": "222190", "ParentId": "222164", "Score": "2" } } ]
{ "AcceptedAnswerId": "222190", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T15:32:44.827", "Id": "222164", "Score": "4", "Tags": [ "matrix", "r", "rcpp" ], "Title": "Generating random sparse matrix" }
222164
<p>I'm making a program which fits a piecewise linear regression with up to 4-5 breakpoints in the data, and then deciding how many breakpoints is best to prevent over and underfitting. However, my code is extremely slow to run, due to how ungraceful and brute force it is. However, I'm not sure how to code it in any other less laborious way then like so:</p> <p>A rough draft I have of my code suiting my aim is this:</p> <pre><code>import numpy as np import pandas as pd from scipy.optimize import curve_fit, differential_evolution import matplotlib.pyplot as plt import warnings def segmentedRegression_two(xData,yData): def func(xVals,break1,break2,slope1,offset1,slope_mid,offset_mid,slope2,offset2): returnArray=[] for x in xVals: if x &lt; break1: returnArray.append(slope1 * x + offset1) elif (np.logical_and(x &gt;= break1,x&lt;break2)): returnArray.append(slope_mid * x + offset_mid) else: returnArray.append(slope2 * x + offset2) return returnArray def sumSquaredError(parametersTuple): #Definition of an error function to minimize model_y=func(xData,*parametersTuple) warnings.filterwarnings("ignore") # Ignore warnings by genetic algorithm return np.sum((yData-model_y)**2.0) def generate_genetic_Parameters(): initial_parameters=[] x_max=np.max(xData) x_min=np.min(xData) y_max=np.max(yData) y_min=np.min(yData) slope=10*(y_max-y_min)/(x_max-x_min) initial_parameters.append([x_max,x_min]) #Bounds for model break point initial_parameters.append([x_max,x_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([-y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([-y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([y_max,y_min]) result=differential_evolution(sumSquaredError,initial_parameters,seed=3) return result.x geneticParameters = generate_genetic_Parameters() #Generates genetic parameters fittedParameters, pcov= curve_fit(func, xData, yData, geneticParameters) #Fits the data print('Parameters:', fittedParameters) model=func(xData,*fittedParameters) absError = model - yData SE = np.square(absError) MSE = np.mean(SE) RMSE = np.sqrt(MSE) Rsquared = 1.0 - (np.var(absError) / np.var(yData)) return Rsquared def segmentedRegression_three(xData,yData): def func(xVals,break1,break2,break3,slope1,offset1,slope2,offset2,slope3,offset3,slope4,offset4): returnArray=[] for x in xVals: if x &lt; break1: returnArray.append(slope1 * x + offset1) elif (np.logical_and(x &gt;= break1,x&lt;break2)): returnArray.append(slope2 * x + offset2) elif (np.logical_and(x &gt;= break2,x&lt;break3)): returnArray.append(slope3 * x + offset3) else: returnArray.append(slope4 * x + offset4) return returnArray def sumSquaredError(parametersTuple): #Definition of an error function to minimize model_y=func(xData,*parametersTuple) warnings.filterwarnings("ignore") # Ignore warnings by genetic algorithm return np.sum((yData-model_y)**2.0) def generate_genetic_Parameters(): initial_parameters=[] x_max=np.max(xData) x_min=np.min(xData) y_max=np.max(yData) y_min=np.min(yData) slope=10*(y_max-y_min)/(x_max-x_min) initial_parameters.append([x_max,x_min]) #Bounds for model break point initial_parameters.append([x_max,x_min]) initial_parameters.append([x_max,x_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([-y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([-y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([y_max,y_min]) result=differential_evolution(sumSquaredError,initial_parameters,seed=3) return result.x geneticParameters = generate_genetic_Parameters() #Generates genetic parameters fittedParameters, pcov= curve_fit(func, xData, yData, geneticParameters) #Fits the data print('Parameters:', fittedParameters) model=func(xData,*fittedParameters) absError = model - yData SE = np.square(absError) MSE = np.mean(SE) RMSE = np.sqrt(MSE) Rsquared = 1.0 - (np.var(absError) / np.var(yData)) return Rsquared def segmentedRegression_four(xData,yData): def func(xVals,break1,break2,break3,break4,slope1,offset1,slope2,offset2,slope3,offset3,slope4,offset4,slope5,offset5): returnArray=[] for x in xVals: if x &lt; break1: returnArray.append(slope1 * x + offset1) elif (np.logical_and(x &gt;= break1,x&lt;break2)): returnArray.append(slope2 * x + offset2) elif (np.logical_and(x &gt;= break2,x&lt;break3)): returnArray.append(slope3 * x + offset3) elif (np.logical_and(x &gt;= break3,x&lt;break4)): returnArray.append(slope4 * x + offset4) else: returnArray.append(slope5 * x + offset5) return returnArray def sumSquaredError(parametersTuple): #Definition of an error function to minimize model_y=func(xData,*parametersTuple) warnings.filterwarnings("ignore") # Ignore warnings by genetic algorithm return np.sum((yData-model_y)**2.0) def generate_genetic_Parameters(): initial_parameters=[] x_max=np.max(xData) x_min=np.min(xData) y_max=np.max(yData) y_min=np.min(yData) slope=10*(y_max-y_min)/(x_max-x_min) initial_parameters.append([x_max,x_min]) #Bounds for model break point initial_parameters.append([x_max,x_min]) initial_parameters.append([x_max,x_min]) initial_parameters.append([x_max,x_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([-y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([-y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([y_max,y_min]) initial_parameters.append([-slope,slope]) initial_parameters.append([y_max,y_min]) result=differential_evolution(sumSquaredError,initial_parameters,seed=3) return result.x geneticParameters = generate_genetic_Parameters() #Generates genetic parameters fittedParameters, pcov= curve_fit(func, xData, yData, geneticParameters) #Fits the data print('Parameters:', fittedParameters) model=func(xData,*fittedParameters) absError = model - yData SE = np.square(absError) MSE = np.mean(SE) RMSE = np.sqrt(MSE) Rsquared = 1.0 - (np.var(absError) / np.var(yData)) return Rsquared r2s=[segmentedRegression_two(xData,yData),segmentedRegression_three(xData,yData),segmentedRegression_four(xData,yData)] best_fit=np.max(r2s) best_fit np.where(r2s==best_fit) r2s </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T16:15:43.723", "Id": "429894", "Score": "0", "body": "@AlexV I don't see any issues with indentations for the code. Can you point out to me where the issues are?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T16:16:30.993", "Id": "429895", "Score": "0", "body": "Ah, I see what you mean. I'll look into this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T16:26:44.147", "Id": "429896", "Score": "0", "body": "I've fixed it as well as I can to my knowledge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-22T09:56:26.320", "Id": "446312", "Score": "0", "body": "The paper kinked below deals with this kind of problems. But the cases of \"up to 4-5 breakpoints\" isn't specifically treated. Nevertheless, the method shown in the paper might give you an hint. https://fr.scribd.com/document/380941024/Regression-par-morceaux-Piecewise-Regression-pdf" } ]
[ { "body": "<p>First of all you should definitely clean up your code. There are a lot of unused variables and duplicate code, likely caused by copy and paste.\nSince you did not provide test data, there is no chance to tell how much time would be gained simply by removing [R[M]]SE computation from the functions.</p>\n\n<p>Apart from that, its likely that the different <code>func</code>s are the main reason for the bad performance. In your current implementation your basically throwing everything away that allows NumPy to be fast: the ability to perform loops in C instead of in Python. For a more detailed introduction to this topic I would highly recommend to watch <a href=\"https://www.youtube.com/watch?v=EEUXKG97YRw\" rel=\"nofollow noreferrer\"><em>Losing your Loops Fast Numerical Computing with NumPy</em></a> and <a href=\"https://www.youtube.com/watch?v=zQeYx87mfyw\" rel=\"nofollow noreferrer\"><em>Performance Python: Seven Strategies for Optimizing Your Numerical Code</em></a> by Jake VanderPlas. There is also an online version of the <a href=\"https://jakevdp.github.io/PythonDataScienceHandbook/index.html\" rel=\"nofollow noreferrer\"><em>Python Data Science Handbook</em></a> also by Jake VanderPlas.</p>\n\n<p>So how you could <code>func</code> (I chose the first one) be rewritten to allow NumPy to play out its strenghts? (Note: this code is untested since you did not provide test data)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def func(x_vals, break1, break2, slope1, offset1, slope_mid, offset_mid, slope2, offset2):\n \"\"\"Regression fit function\"\"\"\n y = np.zeros_like(x_vals)\n mask = x_vals &lt; break1\n y[mask] = slope1 * x_vals[mask] + offset1\n mask = np.logical_and(x_vals &gt;= break1, x_vals &lt; break2)\n y[mask] = slope_mid * x_vals[mask] + offset_mid\n mask = x_vals &gt;= break2\n y[mask] = slope2 * x_vals[mask] + offset2\n return y\n</code></pre>\n\n<p>This implementation uses <a href=\"https://jakevdp.github.io/PythonDataScienceHandbook/02.06-boolean-arrays-and-masks.html\" rel=\"nofollow noreferrer\">masks</a> to compute the piecewise function for a whole range of values instead of value by value.</p>\n\n<hr>\n\n<p>Apart from that you should clearly structure your code in a more consistent way so that it gets easier to read. Maybe the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (often abbreviated as PEP8) can lead you in the right direction.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:52:31.310", "Id": "222326", "ParentId": "222165", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T15:51:52.563", "Id": "222165", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "numpy", "statistics" ], "Title": "Select optimal piecewise regression fit" }
222165
<p>I use this method to get either Customer or Account. The server will determine which type it is.</p> <p>The response will have a property <code>"Type": "Customer"</code> or <code>"Type": "Account"</code>.</p> <p>I first deserialize to Client (supertype) to check the Type property. Then deserialize to either Customer or Account.</p> <pre class="lang-cs prettyprint-override"><code>public async Task&lt;Models.Entities.Client&gt; GetClient(int clientId) { var getClientRequest = new RestRequest("client/details", Method.GET); getClientRequest.AddQueryParameter("ClientId", clientId); var jsonResponse = await _requestService.DoRequest(getClientRequest); var client = JsonConvert.DeserializeObject&lt;Models.Entities.Client&gt;(jsonResponse); switch (client.Type) { case ClientKind.Account: var account = JsonConvert.DeserializeObject&lt;Account&gt;(jsonResponse) return account; default: var customer = JsonConvert.DeserializeObject&lt;Customer&gt;(jsonResponse); return customer; } } </code></pre> <p>Example responses:</p> <pre><code>{ "ClientId": 1, "Type": "Account", "Name": "Company Inc." } </code></pre> <pre><code>{ "ClientId": 2, "Type": "Customer", "Name": { "First": "John", "Last": "Smith" }, "DateOfBirth": "1960-12-01" } </code></pre> <p>DTOs:</p> <pre class="lang-cs prettyprint-override"><code>public class Client { public int ClientId { get; set; } public ClientType Type { get; set; } } public class Account : Client { public string Name { get; set; } } public class Customer : Client { public PersonalName Name { get; set; } public DateTime DateOfBirth { get; set; } } </code></pre>
[]
[ { "body": "<p>Your code could be rewritten:</p>\n\n<pre><code>var settings = new JsonSerializerSettings { \n TypeNameHandling = TypeNameHandling.All,\n SerializationBinder = knownTypesBinder // &lt;- see security risk below\n};\nvar client = JsonConvert.DeserializeObject&lt;Models.Entities.Client&gt;(jsonResponse);\nreturn client; // &lt;- strongly-typed\n</code></pre>\n\n<ul>\n<li>Make sure both server and client use the <code>settings</code></li>\n<li>If you have declared <code>public ClientType Type { get; set; }</code> just to enable two-phase serialisation (base entity - concrete entity), you should remove it from the code.</li>\n<li>The two-phase serialisation hack can be replaced with a strongly-typed serialisation using <code>TypeNameHandling = TypeNameHandling.All</code>. <a href=\"http://gigi.nullneuron.net/gigilabs/deserializing-derived-types-with-json-net/\" rel=\"nofollow noreferrer\">Example</a></li>\n</ul>\n\n<hr>\n\n<p>As suggested in the comments, we need to address the security aspect also. Hence, <code>knownTypesBinder</code> is used to mitigate a <a href=\"https://www.alphabot.com/security/blog/2017/net/How-to-configure-Json.NET-to-create-a-vulnerable-web-API.html\" rel=\"nofollow noreferrer\">security risk</a>.</p>\n\n<pre><code>// based on https://www.newtonsoft.com/json/help/html/SerializeSerializationBinder.htm\nvar knownTypesBinder = new KnownTypesBinder\n{\n KnownTypes = new List&lt;Type&gt; { typeof(Customer), typeof(Account) }\n};\n\npublic class KnownTypesBinder : ISerializationBinder\n{\n public IList&lt;Type&gt; KnownTypes { get; set; }\n\n public Type BindToType(string assemblyName, string typeName)\n {\n return KnownTypes.SingleOrDefault(t =&gt; t.Name == typeName);\n }\n\n public void BindToName(Type serializedType, out string assemblyName, \n out string typeName)\n {\n assemblyName = null;\n typeName = serializedType.Name;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:18:54.510", "Id": "429946", "Score": "1", "body": "While none of the statements in this answer are false, the omission of any mention of the massive security flaws of the example code is a big problem. If using `TypeNameHandling` you **must** also use `SerializationBinder` and white-list the types which can be loaded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:22:31.280", "Id": "429947", "Score": "1", "body": "@PeterTaylor what kind of _massive security flaws_ do you mean and where did you get this info that the `SerializationBinder` must be used? It's not like the serializer throws when you don't... the examples on newtonsoft don't mention it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T08:01:32.943", "Id": "429951", "Score": "1", "body": "@t3chb0t, I followed the link in the answer, read the comments, and followed the links there. In brief, if you don't white-list then an attacker can craft a serialised class which calls the public constructor of any class which can be loaded and then calls any sequence of public property setters on it. The precise implications depend on what libraries are available, but you can e.g. cause side-effects on the filesystem by creating a `FileInfo` and then manipulating properties like `IsReadOnly`. The worst case, seen in a similar Java vuln due to an Apache lib, is execution of arbitrary code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T08:04:53.677", "Id": "429952", "Score": "0", "body": "@PeterTaylor It does make sense to me to consider the security implications. As a comparison, System.ServiceModel has foreseen this in their API: https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-contract-known-types" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T17:37:43.473", "Id": "222171", "ParentId": "222170", "Score": "1" } } ]
{ "AcceptedAnswerId": "222171", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T17:06:15.073", "Id": "222170", "Score": "2", "Tags": [ "c#", "inheritance", "serialization", "xamarin" ], "Title": "Deserializing response to correct type" }
222170
<p>I wrote a simple program to encode a local text file with password and decode it back. There is one text file and it is either encoded with a password or is in plain text.</p> <p>I had a <a href="https://github.com/epogrebnyak/vault/blob/master/vault.py" rel="nofollow noreferrer">version in Python</a> for this, but nim compiles to an executable, so I gave it a try.</p> <p>I'm not perfectly happy with command line argument handling, as well as with some repeated code in <code>case</code> statement, but maybe there are other things to improve too.</p> <pre><code>import os import system import strutils import terminal import xxtea const FILENAME = "passwords.txt" const USAGE = """Encrypt and decrypt a file using a password. Usage: vault open [file] vault close [file] Default file: passwords.txt WARNING: this program may overwrite or delete file content without a possibilty of recovery. Passwords cannot be recovered. Information can be destroyed by repeated attempts of encryption/decryption. Use at you own risk. """ proc getpass(message: string = "Password: "): string = return terminal.readPasswordFromStdin(message) proc getpass2(): string = let key = getpass() let key2 = getpass("Repeat password: ") if key == key2: return key else: quitWithMessage("Passwords do not match") proc write(content: string): void = writeFile(filepath(), content) proc notify(message: string): void = echo message, " ", filepath() # cli args helpers proc filepath(): string = try: return paramStr(2) except IndexError: return FILENAME proc command(): string = try: return paramStr(1).toLowerAscii() except IndexError: quitWithMessage(USAGE) # flow control proc quitWithMessage(message: string): void = echo message quit(1) # main if command() notin ["open", "close", "help"]: quitWithMessage(USAGE) let existingContent = readFile(filepath()) case command() of "open": let key = getpass() let newContent = xxtea.decrypt(existingContent, key) write(newContent) notify("Decoded") of "close": let key = getpass2() let newContent = xxtea.encrypt(existingContent, key) write(newContent) notify("Encoded") of "help": quitWithMessage(USAGE) </code></pre>
[]
[ { "body": "<p>An improvement in <code>case</code> statement:</p>\n\n<pre><code>if command() notin [\"open\", \"close\"]:\n quitWithMessage(USAGE) \n\nlet existingContent = readFile(filepath())\ncase command() \n of \"open\": \n let key = getpass()\n notify(\"Decoding\")\n let newContent = xxtea.decrypt(existingContent, key)\n of \"close\":\n let key = getpass2()\n notify(\"Encoding\")\n let newContent = xxtea.encrypt(existingContent, key)\nwrite(newContent)\nnotify(\"Finished processing\")\n</code></pre>\n\n<p>I wish I knew how to declare and assign <code>f = xxtea.decrypt</code> and <code>f = xxtea.encrypt</code> and call <code>f</code> in nim - would have same even more repeated code. </p>\n\n<p>Also documentation is not immediately clear about a dictionary in nim, even though <a href=\"https://github.com/nim-lang/Nim/wiki/Nim-for-Python-Programmers\" rel=\"nofollow noreferrer\">some light here</a>. A dictionary can be used to encode <code>notify()</code> messages by command names.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:32:27.330", "Id": "222193", "ParentId": "222172", "Score": "1" } }, { "body": "<p>As long as the encoding and decoding are so similar you could use a template</p>\n\n<pre><code>template doCmd(gp: untyped, encdec: untyped, msg: string): void =\n let key = gp()\n let newContent = encdec(existingContent, key)\n write(newContent)\n notify(msg)\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>of \"open\":\n doCmd getpass, xxtea.decrypt, \"Decoded\"\nof \"close\":\n doCmd getpass2, xxtea.encrypt, \"Encoded\"\n</code></pre>\n\n<p>You can also use a proc that accepts proc as arguments, more safe for checking the types of arguments passed, but at that point either getpass and getpass2 are declared with the same arguments or you have to pass an argument for each variant.</p>\n\n<p>To pass a function as an argument just use <code>proc</code> and<code>{.closure}</code></p>\n\n<pre><code>proc doCmd(gp: proc(m: string = \"Password: \"): string {.closure}, encdec: proc(b: string, k: string): string {.closure}, msg: string): void =\n let key = gp()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T11:15:40.330", "Id": "437896", "Score": "0", "body": "Like the template idea, thanks for sugesting! Woukd need to familiarise with nim syntax behind it, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-04T12:57:02.180", "Id": "437902", "Score": "1", "body": "@Evgeny, nim templates are powerful, an old but still valid post [Introduction to Metaprogramming in Nim#templates](https://hookrace.net/blog/introduction-to-metaprogramming-in-nim/#templates)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-03T21:45:53.293", "Id": "225488", "ParentId": "222172", "Score": "2" } } ]
{ "AcceptedAnswerId": "225488", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T18:06:11.807", "Id": "222172", "Score": "4", "Tags": [ "console", "cryptography", "nim" ], "Title": "File encoder/decoder in Nim" }
222172
<p>I need a menu with buttons of months previous and after a given month, something like this:</p> <p>| month | month | month | <em>current month</em> | month | month | month |</p> <p>Can this function further be improved?</p> <pre><code>/** * Generates array of months previous and after given date * @param $p_base_data - array of base year and months, if not provided current date is used ['year'=&gt;false, 'month'=&gt;0] * @param $p_nr_prev_months - number of previous mounts to calculate * @param $p_nr_post_months - number of upcoming mounts to calculate * @return populated array */ function buildListOfMonths( array $p_base_date = ['year'=&gt;false, 'month'=&gt;0], int $p_nr_prev_months = 5, int $p_nr_post_months = 6) : array { // init var $months_list = []; // setting base year and date if parameter not passed $base_year = $p_base_date['year'] ? $p_base_date['year'] : date('Y'); $base_month = $p_base_date['month'] &gt; 0 ? (int)$p_base_date['month'] : date('n'); // looping through prev to post number of months for ($i = -$p_nr_prev_months; $i &lt;= $p_nr_post_months; $i++) { // creating date object of actual date $date_obj = strtotime(date($base_year.'-'.$base_month.'-01')." +$i months"); // building array of months $months_list[] = [ 'year' =&gt; date('Y', $date_obj), 'nr_month' =&gt; date('n', $date_obj), 'month_name' =&gt; date("M", $date_obj), 'current' =&gt; (date('n', $date_obj) == $base_month) ? true : false ]; } // end for return $months_list; } // end func. </code></pre>
[]
[ { "body": "<p>Be aware that in some scenarios, <a href=\"https://stackoverflow.com/a/9153048/2943403\">strtotime() may have a limitation</a>. Furthermore using property DateTime objects will provide greater utility if you decide to extend functionality in the future.</p>\n\n<p>This task is well-suited for <code>DatePeriod</code>. It will serve you up a collection of date objects that you can format however you wish.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/C1Egc\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>function rangeOfMonths($prior, $ahead, $baseYear = null, $baseMonth = null) {\n $baseYear = $baseYear ?: date('Y');\n $baseMonth = $baseMonth ?: date('m');\n\n $rangeStart = new DateTime($baseYear . '-' . $baseMonth . '-01 23:59:59');\n $rangeEnd = clone($rangeStart);\n\n $rangeStart-&gt;modify(\"-{$prior} month\");\n $rangeEnd-&gt;modify(\"+{$ahead} month +1 day\");\n\n $period = new DatePeriod($rangeStart, new DateInterval('P1M'), $rangeEnd);\n $monthsList = [];\n foreach ($period as $i =&gt; $dateObject) {\n $monthsList[] = [\n 'year' =&gt; $dateObject-&gt;format('Y'), \n 'nr_month' =&gt; $dateObject-&gt;format('n'), \n 'month_name' =&gt; $dateObject-&gt;format('M'),\n 'current' =&gt; $i == $prior\n ]; \n }\n return $monthsList;\n}\n\nvar_export(rangeOfMonths(5, 6));\n</code></pre>\n\n<ul>\n<li><p>Instead of bloating the function declaration syntax with an array type argument which has two elements (with potentially falsey / non-date-oriented values), write these optional values as individually served arguments and write them as the final arguments. This will allow you to call this function without needing to pass the array structure. If your incoming data is already an indexed array with upto two elements, just <code>...</code> (splat operator) the array when calling the function.</p></li>\n<li><p>Either way, using any falsey default values will benefit your script by allowing you to leverage the brief <code>?:</code> (<a href=\"https://stackoverflow.com/a/1993455/2943403\">elvis operator</a>).</p></li>\n</ul>\n\n<p><code>+1 day</code> is to make the date range inclusive of the final month.</p>\n\n<p>*Timezone impact was not included in my review, you may want to investigate fringe cases and set the timezone per your application's requirements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T22:14:02.587", "Id": "222180", "ParentId": "222174", "Score": "2" } } ]
{ "AcceptedAnswerId": "222180", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T19:25:33.503", "Id": "222174", "Score": "4", "Tags": [ "php", "datetime" ], "Title": "List of previous and upcoming months to a given date (year and month)" }
222174
<p>I have given a series problem 1,2,1,3,2,5,3,7,5.... in which the odd terms forms the Fibonacci series and even terms form the prime number series. I have to write a code in which I have to find the nth term. Following is the code for finding the nth term, I want to know whether it can be written more efficiently or not and how?</p> <pre><code> def fib(n): t1=0 t2=1 for i in range(1,n+1): add = t1+t2 t1 = t2 t2 = add print(t1) def prime(n): count =1 for i in range(2,100): flag =0 for j in range(2,i): if (i%j==0): flag=1 break if (flag==1): continue else: if (count==n): print(i) break else: count = count+1 n= int(input('enter the positive number: ' )) if (n%2==0): prime(int(n/2)) else: fib(int(n/2)+1) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T21:06:40.520", "Id": "429925", "Score": "1", "body": "Welcome to Code Review! Since your question has been migrated from Stack Overflow, I invite you to take the [tour](https://codereview.stackexchange.com/tour) here. And also have a look at [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), especially *Titling your question*. At the moment, the title is very generic." } ]
[ { "body": "<p>You could use a few tricks to implement the two sequences more efficiently, but the short version of my answer is that most significant performance improvements you could make involve some relatively advanced math, and the smaller improvements do more to improve your code's readability than its performance.</p>\n\n<hr>\n\n<h1>Useful improvements to <code>prime</code></h1>\n\n<p>If you keep a list of the primes you find, you only need to check if those divide the new numbers you are checking, rather than checking every number up to the number you are looking at.</p>\n\n<p>You could also skip over even numbers in the outer loop (use <code>range(3, max, 2)</code>), thus avoiding checking even numbers that you can be sure aren't prime (you would need to add a special case for 2).</p>\n\n<p>The inner loop (<code>j</code>) can stop at <code>i/2</code>, because no number can be evenly divided by a number more than half its size. Similarly, you can stop the loop at when you pass the square root of <code>n</code>, but you would have to implement that by squaring the factors because <code>sqrt</code> is limited by the inaccuracy of floating-point numbers.</p>\n\n<p>Using all of these suggestions, the code might look a little like this:</p>\n\n<pre><code>def nth_prime(n):\n if n == 1:\n return 2\n primes = [2]\n for candidate_prime in range(3, MAX, 2):\n for p in primes:\n if (p ** 2 &gt; candidate_prime):\n break # candidate is prime\n if (candidate_prime % p == 0)\n break # p divides candidate; candidate is not prime\n if no primes divided candidate_prime:\n primes.append(candidate_prime)\n if len(primes) == n:\n return candidate_prime\n</code></pre>\n\n<p>Additional optimizations for determining whether a number is prime are discussed on <a href=\"https://en.wikipedia.org/wiki/Primality_test\" rel=\"nofollow noreferrer\">the Wikipedia page on the subject</a>.</p>\n\n<p>These improvements will only start to have noticeable effects when you start looking at very large primes, so you might also want to use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"nofollow noreferrer\"><code>itertools.count</code></a> to look at all numbers instead of stopping at 100.</p>\n\n<p>(If you really want to stop at 100, you could also just make a list of the prime numbers up to 100 and index that for maximum efficiency.)</p>\n\n<hr>\n\n<h1>Links to mathematical solutions</h1>\n\n<p>To really improve efficiency, <a href=\"https://stackoverflow.com/a/14661740/7389264\">this answer</a> suggests the solution in <a href=\"http://fusharblog.com/solving-linear-recurrence-for-programming-contest/\" rel=\"nofollow noreferrer\">this blog post</a>, but this is probably overkill unless you really want to be able to calculate very large fibonacci numbers very fast (I can't tell that there's a delay in your function until somewhere far above <code>n=10000</code>).</p>\n\n<p><a href=\"https://stackoverflow.com/questions/9625663/calculating-and-printing-the-nth-prime-number/9704912#9704912\">This question</a> goes into depth about how to find the nth prime number, but the final point is important to note:</p>\n\n<blockquote>\n <p><strong>tl;dr:</strong> Finding the nth prime can be efficiently done, but the more efficient you want it, the more mathematics is involved.</p>\n</blockquote>\n\n<hr>\n\n<h1>Other suggestions</h1>\n\n<p>The following suggestions aren't really about efficiency (if they change the efficiency of your code, the difference will be immeasurably small), but they might make your code a little cleaner.</p>\n\n<ol>\n<li><p>In the loop you're using for the Fibonacci sequence, you can just write <code>t1, t2 = t2, t1 + t2</code> to update both values in one line.</p></li>\n<li><p>When creating the nth Fibonacci number, you can just loop over <code>range(n)</code>; there's no need to adjust the ends of the loop. And if you're not using the index <code>i</code> in that loop, Python convention is call it <code>_</code>, so you end up with <code>for _ in range(n)</code>.</p></li>\n<li><p>Using Python's less-than-well-known <code>for</code>/<code>else</code> feature might let you eliminate the flag variable. If you put an <code>else</code> block after a loop in Python, it will run only if you do <em>not</em> <code>break</code> out of the loop, which allows you to avoid flag variables.</p>\n\n<pre><code>for i in some_list:\n if condition(i):\n break\nelse:\n do_this_if_condition_was_never_true()\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T06:59:32.417", "Id": "429938", "Score": "0", "body": "Thank you so much sir!!!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T21:46:13.090", "Id": "222179", "ParentId": "222178", "Score": "6" } }, { "body": "<p>A tiny improvement to the part that chooses which sequence is required:</p>\n\n<blockquote>\n<pre><code> if (n%2==0):\n prime(int(n/2))\n else:\n fib(int(n/2)+1)\n</code></pre>\n</blockquote>\n\n<p>Since <code>n</code> is already <code>int</code>, we can use simple integer division:</p>\n\n<pre><code>if n % 2:\n print(fib((n+1)//2)\nelse:\n print(prime(n//2))\n</code></pre>\n\n<p>(I've assumed the obvious improvement of making your functions <em>pure</em>, and moving the side-effect to the call site).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T08:16:41.310", "Id": "222195", "ParentId": "222178", "Score": "2" } }, { "body": "<p>This is my first post for suggesting improvements so I may be way off the mark but I think you should</p>\n\n<ol>\n<li>Use docstrings in each function and preferably have an overall docstring</li>\n<li>Use a helper function (in my case <code>find_n_term</code>) so this module can be re-used by other programmers</li>\n<li>Use the guard <code>if __name__ == \"__main__\"</code> so others users can import the module and it won't run automatically </li>\n</ol>\n\n<pre><code>\"\"\"Problem:\n Odd terms in a sequence are of the Fibonacci series\n Even terms in a sequence are of the prime number series\n e.g:\n 1,2,1,3,2,5,3,7,5\n Find the nth term in the series\"\"\"\n\n\ndef fib(n):\n \"\"\"Return the nth fibonacci number\"\"\"\n fib_numbers = [1, 1]\n if n in (1, 2):\n return 1\n for i in range(2, n):\n fib_numbers.append(fib_numbers[i - 1] + fib_numbers[i - 2])\n return fib_numbers[-1]\n\n\ndef prime(n):\n \"\"\"Return the nth prime number\"\"\"\n prime_number = 2\n counter = 3\n prime_count = 1\n if n == 1:\n return 2\n while prime_count &lt; n:\n is_prime = True\n for i in range(2, counter):\n if counter % i == 0:\n is_prime = False\n break\n if is_prime:\n prime_count += 1\n prime_number = counter\n counter += 1\n return prime_number\n\n\ndef find_n_term(n):\n \"\"\"Return the nth term in a sequence where odd terms are from the\n fibonacci sequence and even terms from the primer number sequence\"\"\"\n if n % 2 == 0:\n output = prime(n // 2)\n print(\"Prime number:\", output)\n else:\n output = fib((n + 1) // 2)\n print(\"Fib number:\", output)\n\n\nif __name__ == \"__main__\":\n for i in range(1,10):\n find_n_term(i)\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:52:52.887", "Id": "429988", "Score": "1", "body": "Hi @EML, this a great answer for your first time! You can keep up the good job my making a detailed review of the whole program, places you think could be improved and places you think are unnecessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T04:18:25.230", "Id": "430245", "Score": "0", "body": "The parity is of this rework is inconsistent with the OP's code. Inputs 1 and 2 produce outputs 1 (fib) and 2 (prime) in the OP's code whose sequence starts with the 1st element. This example does the reverse with a sequence that starts with the zeroth element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T04:21:47.207", "Id": "430246", "Score": "0", "body": "The prime number code in this solution is flawed performance-wise. It keeps a list of primes found, but only uses it to return the final element -- no need to allocate a list in this case. However, if it has this list of primes, it should be using it for the divisor tests instead of `range(2, counter)` by 1 (which is flawed for not treating even early on and looping only over odd divisors.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T05:49:56.557", "Id": "430250", "Score": "0", "body": "Thanks. Have updated the code" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T10:19:05.790", "Id": "222202", "ParentId": "222178", "Score": "3" } }, { "body": "<p>I'd take a slightly different approach. Rather than include the n/2 loop in both the Fibonacci and prime code, I'd make it external and turn these two programs into simpler, infinite generators that are easier to debug:</p>\n\n<pre><code>'''\nGiven a series in which the odd terms forms the Fibonacci series and even\nterms form the prime number series, this program finds the nth term.\n'''\n\ndef fibonacci():\n ''' Generator that continuously yields fibonacci numbers. '''\n\n a, b = 0, 1\n\n while True:\n a, b = b, a + b\n\n yield a\n\ndef primes(known_odd_primes=[3]): # dangerous default value\n ''' Generator that continuously yields prime numbers. '''\n\n yield 2\n\n for prime in known_odd_primes:\n yield prime\n\n odd = known_odd_primes[-1] + 2\n\n while True:\n for divisor in known_odd_primes:\n\n if divisor * divisor &gt; odd:\n yield odd\n known_odd_primes.append(odd)\n break\n\n if odd % divisor == 0:\n break\n\n odd += 2\n\ndef sequence(n):\n\n '''\n Find nth element of sequence whose odd terms are from the Fibonacci\n series and whose even terms are from the prime number series.\n '''\n\n if n % 2:\n fibonacci_generator = fibonacci()\n\n for _ in range(n // 2):\n nth = next(fibonacci_generator)\n else:\n prime_generator = primes()\n\n for _ in range((n + 1) // 2):\n nth = next(prime_generator)\n\n return nth\n\nif __name__ == \"__main__\":\n n = int(input('Enter a positive number: '))\n\n print(sequence(n))\n</code></pre>\n\n<p>EXAMPLE:</p>\n\n<pre><code>&gt; python3 test.py\nEnter a positive number: 100000\n611953\n&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T04:15:17.947", "Id": "222341", "ParentId": "222178", "Score": "3" } } ]
{ "AcceptedAnswerId": "222179", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T19:19:46.483", "Id": "222178", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "primes", "fibonacci-sequence" ], "Title": "Find the nth term of a sequence that consists of Fibonacci and prime numbers interleaved" }
222178
<p>Here is my solution to the Tower of Hanoi problem using Python</p> <hr> <pre><code>def helper(number_rings: int, origin: int, target: int, spare: int, list_result=[])-&gt;list: """Helper function works out which ring to move""" if number_rings == 1: list_result.append([origin, target]) else: #Move all but 1 ring from ORIGIN tower to SPARE tower helper(number_rings - 1, origin=origin, target=spare, spare=target) #MOVE the last ring from ORIGIN tower to TARGET tower helper(1, origin=origin, target=target, spare=spare) #MOVE the remaining rings from the SPARE tower to TARGET tower helper(number_rings - 1, origin=spare, target=target, spare=origin) return list_result def move_rings(number_rings: int)-&gt;int: """Function prints the ring move required""" dict_rings = {0: "A", 1: "B", 2: "C"} if number_rings == 1: print("Move from A to C") return 1 list_result = helper(number_rings, 0, 2, 1) for item in list_result: print("Move from", dict_rings[item[0]], "to", dict_rings[item[1]]) return len(list_result) if __name__ == "__main__": counter = move_rings(1) print(f"Solution possible in {counter} moves") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-11T12:00:36.907", "Id": "444737", "Score": "0", "body": "So.... what is the question ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-16T14:07:39.977", "Id": "445428", "Score": "0", "body": "@Jacco - the question is (as always), \"How could I make this code better?\"" } ]
[ { "body": "<p>Overall your implementation is fine, I would just suggest a few things:</p>\n\n<ol>\n<li>Naming - <code>move_rings</code> and <code>helper</code> are not very descriptive. Give them better names, and give them good docstrings (I like <a href=\"https://numpydoc.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">NumpyDoc</a>, but personal preference is fine)</li>\n<li><code>move_rings</code> shouldn't both do calculations and print to <code>stdout</code>. Instead, <code>move_rings</code> should return the information, and the caller should decide what to do with it</li>\n<li><code>move_rings</code> doesn't need the <code>number_rings == 1</code> special case; your API handles it just fine</li>\n<li>Instead of the hard-coded number approach, you can make a little <code>Peg</code> class that makes things a bit cleaner - subclassing <code>namedtuple</code> is a nice way to do this</li>\n<li>Using <code>f</code>-strings makes printing easier</li>\n<li>You can <code>yield from</code> instead of appending to the default argument list, which is easier to read and doesn't waste time reallocating space for the list</li>\n<li>I added a (honestly pretty bad) visualization function to see the movements as well.</li>\n</ol>\n\n<p>This is what I came up with (didn't do all of the things I mentioned above)</p>\n\n<pre><code>from math import ceil\nfrom collections import defaultdict, namedtuple\nfrom typing import Iterable, Generator, List, Tuple\n\n\nclass Peg(namedtuple(\"Peg\", \"id name\")):\n pass\n\n\nSOURCE_PEG = Peg(0, \"A\")\nTARGET_PEG = Peg(2, \"C\")\nWORKER_PEG = Peg(1, \"B\")\nPEGS = [SOURCE_PEG, TARGET_PEG, WORKER_PEG]\n\n\ndef helper(\n number_rings: int, origin: Peg, target: Peg, spare: Peg\n) -&gt; Generator[Tuple[Peg, Peg], None, None]:\n \"\"\"\n Helper function for performing the recursive call when solving the tower puzzle.\n\n Parameters\n ----------\n number_rings : int\n Number of rings in the puzzle\n origin : Peg\n The peg that we're moving from\n target : Peg\n The peg that we want to move to\n spare : Peg\n The other peg, that we can use as a helper\n\n Yields\n ------\n move : tuple\n The movement(s) (from-Peg, to-Peg) we determined were ncessary\n \"\"\"\n\n if number_rings == 1:\n yield (origin, target)\n else:\n # Move all but 1 ring from ORIGIN tower to SPARE tower\n yield from helper(\n number_rings - 1,\n origin=origin,\n target=spare,\n spare=target,\n )\n # MOVE the last ring from ORIGIN tower to TARGET tower\n yield from helper(\n 1, origin=origin, target=target, spare=spare\n )\n # MOVE the remaining rings from the SPARE tower to TARGET tower\n yield from helper(\n number_rings - 1,\n origin=spare,\n target=target,\n spare=origin,\n )\n\ndef move_rings(\n number_rings: int\n) -&gt; Iterable[Tuple[Peg, Peg]]:\n \"\"\"\n Finds the optimal number of moves when solving a Tower of Hanoi puzzle\n with `number_rings` rings, starting on the first ring.\n\n Parameters\n ----------\n number_rings : int\n The number of rings in the Tower of Hanoi puzzle\n\n Returns\n -------\n move_list : iterator\n An iterable of the Peg movements\n \"\"\"\n\n return helper(\n number_rings, SOURCE_PEG, TARGET_PEG, WORKER_PEG\n )\n\n\ndef draw_tower_of_hanoi(ring_map: List[int]):\n \"\"\"\n Pretty dumb drawing tool that visualizes current peg state.\n\n Parameters\n ----------\n ring_map : list\n List of rings and their pegs. Format for a 3-ring puzzle start would be\n [0, 0, 0]. The index represents ring size (size = i+1), and the value at\n that index represents the peg (0, 1, or 2).\n \"\"\"\n\n largest_ring = len(ring_map)\n peg_to_ring = defaultdict(list)\n for ring, peg in enumerate(ring_map, 1):\n peg_to_ring[peg].append(ring)\n\n peg_to_ring = {\n peg: sorted(ring_list, reverse=True)\n for peg, ring_list in peg_to_ring.items()\n }\n height_per_ring = {\n peg: len(ring_list)\n for peg, ring_list in peg_to_ring.items()\n }\n\n total_width = largest_ring * 6 + 7\n total_height = len(ring_map) + 2\n\n peg_centers = [\n 1 + largest_ring,\n 3 + largest_ring * 3,\n 5 + largest_ring * 5,\n ]\n\n # fill it out\n drawing = [\n [\" \" for _ in range(total_width)]\n for _ in range(total_height)\n ]\n\n # Draw the pegs\n for i, row in enumerate(drawing):\n for center in peg_centers:\n drawing[i][center] = \"P\"\n\n # Draw the base\n drawing[-1][:] = [\"G\"] * total_width\n\n # Draw the rings\n for peg in peg_to_ring:\n for i, ring in enumerate(peg_to_ring[peg], 2):\n index = -i\n center = peg_centers[peg]\n drawing[index][center - ring : center] = [\n \"R\"\n ] * ring\n drawing[index][\n center + 1 : center + ring + 1\n ] = [\"R\"] * ring\n\n print(\"\\r\\n\".join([\"\".join(row) for row in drawing]))\n\n\n\ndef visualize_tower_movements(\n number_rings: int, moves: Iterable[Tuple[Peg, Peg]]\n):\n \"\"\"\n Visualization tool for drawing the movement of rings in a Tower of Hanoi puzzle.\n\n Parameters\n ----------\n number_rings : int\n The number of rings in the puzzle\n moves : iterable\n The set of moves performed while working on the puzzle\n \"\"\"\n\n visualizer = [0] * number_rings\n draw_tower_of_hanoi(visualizer)\n for move_from, move_to in moves:\n # Get the smallest ring on the peg, as that is the only one that can move\n move_from_index = min(\n ring\n for ring, value in enumerate(visualizer)\n if value == move_from.id\n )\n visualizer[move_from_index] = move_to.id\n draw_tower_of_hanoi(visualizer)\n\n\n\nif __name__ == \"__main__\":\n moves = list(move_rings(5))\n print(f\"Took {len(moves)} moves\")\n for move_from, move_to in moves:\n print(\n f\"Move from {move_from.name} to {move_to.name}\"\n )\n visualize_tower_movements(5, moves)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-12T14:14:02.360", "Id": "228910", "ParentId": "222181", "Score": "3" } } ]
{ "AcceptedAnswerId": "228910", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-12T22:54:52.097", "Id": "222181", "Score": "9", "Tags": [ "python", "algorithm", "python-3.x", "programming-challenge", "recursion" ], "Title": "Tower of Hanoi with helper function" }
222181
<p>I saw <a href="https://puzzling.stackexchange.com/questions/84854/as-easy-as-three-two-one-how-fast-can-you-go-from-five-to-four">this Puzzling problem</a> and thought I would try to write a Python program to solve it. The task is to transform "four" to "five", forming a new four-letter word at each step, replacing one letter at each step, in as few steps as possible.</p> <p>But turns out I don't know how to optimize recursion, so I'm posting here for help. I'm mostly just confused on why the code to change the <code>past</code> needs to be at the top of the function, but I would also like advice on how to speed this up in general. Right now it takes about 10x as long for each step up <code>max_depth</code> gets on my computer.</p> <p>There won't be any matches until you change <code>max_depth</code> - I didn't want anyone copy-pasting and lagging out. There should be a solution at depth 5, according to Puzzling. However, my <code>words</code> file doesn't have the <code>Foud</code> or the word <code>Fous</code>, which that answer uses. Bumping up to <code>max_depth</code> six will take my computer ~10 minutes, which I don't want to try yet.</p> <pre class="lang-py prettyprint-override"><code>def hamming(string1, string2): assert len(string1) == len(string2) return sum(char1 != char2 for char1, char2 in zip(string1, string2)) max_depth = 3 start_word = "five" end_word = "four" all_words = open("/usr/share/dict/words", "r").read().lower().splitlines() all_words = list(filter(lambda word: word.isalpha(), all_words)) all_words = list(filter(lambda word: len(word) == len(start_word), all_words)) sequences = [] def search(current_word, past = []): # Needs to be first to be fast for some reason past = past[:] past.append(current_word) if len(past) &gt; max_depth: sequences.append(past) return for word in all_words: if hamming(word, current_word) == 1 and word not in past: search(word, past) search(start_word) sequences = [sequence[:sequence.index(end_word) + 1] for sequence in sequences if end_word in sequence] if len(sequences) == 0: print("No matches") else: print(min(sequences, key=len)) </code></pre>
[]
[ { "body": "<p>By performing recursion, you are performing a depth-first search of four-letter words. However, this task involves finding a shortest path, and shortest-path problems are generally better done using breadth-first search. With BFS, the first solution you encounter will be an optimal solution — which is not the case with DFS.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T01:48:17.183", "Id": "429928", "Score": "0", "body": "How would I implement that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T01:51:42.883", "Id": "429929", "Score": "0", "body": "There are [plenty of word ladder solutions to study on this site](https://codereview.stackexchange.com/search?q=word+ladder+is%3Aquestion) already. There are also many [tag:breadth-first-search] implementations you can study." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T04:57:55.943", "Id": "429933", "Score": "0", "body": "Thanks, this worked really well. Runs in under 6 seconds now." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T01:34:47.037", "Id": "222185", "ParentId": "222184", "Score": "12" } } ]
{ "AcceptedAnswerId": "222185", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T01:02:22.437", "Id": "222184", "Score": "7", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "pathfinding" ], "Title": "Python program to find a word ladder transforming \"four\" to \"five\"" }
222184
<p>I have a use-case where I need to retrieve all members with specific attributes in the class and interface hierarchy - I usually need the first match and apply its rules to child members. The built-in <code>GetCustomAttributes</code> are too limited becuase they work only for a single member and don't support interfaces.</p> <hr> <h3>Implementation</h3> <p>To solve this I wrote my own extension that returns a collection of <code>AttributeCollection&lt;T&gt;</code> instances. Each one contains the member the attributes are applied to and the matched attributes.</p> <p>There are couple of rules that this needs to follow in order for the results to be useful because attribute settings are then propagated to child members:</p> <ul> <li>properties come before types</li> <li>classes come before interfaces</li> <li>skip duplicate results</li> </ul> <pre><code>public static class Extensions { public static IEnumerable&lt;AttributeCollection&lt;T&gt;&gt; EnumerateCustomAttributes&lt;T&gt;(this MemberInfo member) where T : Attribute { if (member == null) throw new ArgumentNullException(nameof(member)); var queue = new Queue&lt;MemberInfo&gt; { member, }; // Helps to suppress duplicate results when same member is seen multiple times. var seenAttributeCollections = new HashSet&lt;AttributeCollection&lt;T&gt;&gt;(); while (queue.Any()) { var current = queue.Dequeue(); if (current.GetCustomAttributes&lt;T&gt;() is var attributes &amp;&amp; attributes.Any()) { var attributeCollection = new AttributeCollection&lt;T&gt;(current, attributes); if (seenAttributeCollections.Add(attributeCollection)) { yield return attributeCollection; } } if (current is PropertyInfo property) { queue.Enqueue(property.DeclaringType); } if (current is Type type) { // The order matters so enqueue properties before their declaring types and base classes before interfaces. if (type.IsSubclass()) { if (type.BaseType.GetProperty(member.Name) is PropertyInfo otherProperty) { queue.Enqueue(otherProperty); } queue.Enqueue(type.BaseType); } foreach (var interfaceType in type.GetInterfaces()) { if (interfaceType.GetProperty(member.Name) is PropertyInfo otherProperty) { queue.Enqueue(otherProperty); } queue.Enqueue(interfaceType); } } } } public static bool IsSubclass(this Type type) { return type.IsClass &amp;&amp; type.BaseType != typeof(object); } } </code></pre> <p>This class helps handling equality and results:</p> <pre><code>public class AttributeCollection&lt;T&gt; : List&lt;T&gt;, IEquatable&lt;AttributeCollection&lt;T&gt;&gt; where T : Attribute { private static readonly IEqualityComparer&lt;AttributeCollection&lt;T&gt;&gt; Comparer = EqualityComparerFactory&lt;AttributeCollection&lt;T&gt;&gt;.Create ( // When either one is True then we consider both collections equal. equals: (x, y) =&gt; (x.Member == y.Member) || x.SequenceEqual(y) ); public AttributeCollection(MemberInfo member, IEnumerable&lt;T&gt; attributes) : base(attributes) { Member = member; } public MemberInfo Member { get; } public bool Equals(AttributeCollection&lt;T&gt; other) =&gt; Comparer.Equals(this, other); public override bool Equals(object obj) =&gt; obj is AttributeCollection&lt;T&gt; ac &amp;&amp; Equals(ac); public override int GetHashCode() =&gt; 0; // Always use 'equals'. public override string ToString() { return $"{Member.Name}: [{string.Join(", ", this.Select(a =&gt; a))}]"; } } </code></pre> <hr> <h3>Demo</h3> <p>I used this code to test that extension:</p> <pre><code>void Main() { typeof(T3).GetProperty(nameof(T3.P1)).EnumerateCustomAttributes&lt;A0&gt;().Select(x =&gt; x.ToString()).Dump(); // &lt;-- 6 results typeof(T3).GetProperty(nameof(T3.P1)).EnumerateCustomAttributes&lt;A1&gt;().Select(x =&gt; x.ToString()).Dump(); // &lt;-- 5 results typeof(T3).GetProperty(nameof(T3.P1)).EnumerateCustomAttributes&lt;A2&gt;().Select(x =&gt; x.ToString()).Dump(); // &lt;-- 3 results } [A1(V = "I1")] interface I1 { [A1(V = "I1.P1")] string P1 { get; set; } } [A2(V = "T1")] class T1 : I1 { [A1(V = "T1.P1")] public virtual string P1 { get; set; } } class T2 : T1 { } [A1(V = "T3"), A2(V = "T3")] class T3 : T2 { [A1(V = "T3.P1"), A2(V = "T3.P1")] public override string P1 { get; set; } } interface IA { string V { get; set; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] abstract class A0 : Attribute, IA { public abstract string V { get; set; } public override string ToString() =&gt; V; } class A1 : A0 { public override string V { get; set; } } class A2 : A0 { public override string V { get; set; } } </code></pre> <p>Results:</p> <blockquote> <pre><code>IEnumerable&lt;String&gt; (6 items) P1: [T3.P1, T3.P1] T3: [T3, T3] P1: [T1.P1] T2: [T1] P1: [I1.P1] I1: [I1] IEnumerable&lt;String&gt; (5 items) P1: [T3.P1] T3: [T3] P1: [T1.P1] P1: [I1.P1] I1: [I1] IEnumerable&lt;String&gt; (3 items) P1: [T3.P1] T3: [T3] T2: [T1] </code></pre> </blockquote> <p>In this example you'll notice that I use both an interface and an <code>abstract class</code> overriding the <code>V</code> property. It turned out that I cannot use a single property on the base class because the <code>Attribute.Equals</code> method won't see it and will not recognize two different attributes correctly. See <a href="https://stackoverflow.com/questions/56567005/why-are-two-different-instances-of-the-same-attribute-equal-here">this</a> question.</p> <hr> <p>If you're going to try this demo in LINQPad then you'll need this header as I'm using some of my helpers here:</p> <blockquote> <pre><code>&lt;Query Kind="Program"&gt; &lt;NuGetReference&gt;Reusable.Core&lt;/NuGetReference&gt; &lt;Namespace&gt;Reusable.Extensions&lt;/Namespace&gt; &lt;Namespace&gt;Reusable.Collections&lt;/Namespace&gt; &lt;/Query&gt; </code></pre> </blockquote> <hr> <h3>Real-world example</h3> <p>I'll be using it for retrieving <code>UseX</code> attributes in a model like this one:</p> <blockquote> <pre><code>[UsePrefix("app"), UseNamespace, UseType, UseMember] [TrimStart("I")] public interface IDemo : INamespace { [UseType, UseMember] object Greeting { get; } // &lt;-- will use its own attributes [Tag("io")] object ReadFile { get; } // &lt;-- will use type's attributes } </code></pre> </blockquote> <hr> <h3>Questions</h3> <p>So, what do you think about this implementation? Am I missing anything important here? Is there anything you would improve?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:00:20.107", "Id": "429955", "Score": "0", "body": "It is a bit unclear comparing your test results with your specification what the exact order of results should be. It seems the specified order is subordinate to the class hierarchy order. Could you elaborate on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:02:28.207", "Id": "429957", "Score": "1", "body": "@dfhwze exactly! The class hierarchy matters because later attribute-sets can override previous ones. When a base class specifies some properties then all subsequent members inherit them... unless they redefine their own set of attributes. They are not merged, this would be too tricky. I think it's easier to just completely specify a new set of attributes than trying to disable some etc." } ]
[ { "body": "<blockquote>\n<pre><code> public static IEnumerable&lt;AttributeCollection&lt;T&gt;&gt; EnumerateCustomAttributes&lt;T&gt;(this MemberInfo member) where T : Attribute\n</code></pre>\n</blockquote>\n\n<p>I'm surprised that this method doesn't have a docstring, and I don't find its name very descriptive. What differentiates this from <code>GetCustomAttributes</code> is that it inherits, so I'd expect a name like <code>InheritedCustomAttributes</code>. (Perhaps there's an equally succinct name which makes it clear that it includes attributes defined directly on the member).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var queue = new Queue&lt;MemberInfo&gt;\n {\n member,\n };\n</code></pre>\n</blockquote>\n\n<p>Is a queue the right data structure? Bearing in mind that you say</p>\n\n<blockquote>\n <ul>\n <li>properties come before types</li>\n <li>classes come before interfaces</li>\n </ul>\n</blockquote>\n\n<p>I would have thought that you need to fill a priority queue in one pass (properties have priority over classes have priority over interfaces; and for properties and classes the nearer one has priority; priority between interfaces seems rather arbitrary) and then call <code>GetCustomAttributes</code> in a second pass.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> // Helps to suppress duplicate results when same member is seen multiple times.\n var seenAttributeCollections = new HashSet&lt;AttributeCollection&lt;T&gt;&gt;();\n</code></pre>\n</blockquote>\n\n<p>I'm not clear on why duplication is handled at the level of collections of attributes rather than individual attributes.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (type.IsSubclass())\n {\n if (type.BaseType.GetProperty(member.Name) is PropertyInfo otherProperty)\n {\n queue.Enqueue(otherProperty);\n }\n\n queue.Enqueue(type.BaseType);\n }\n\n foreach (var interfaceType in type.GetInterfaces())\n {\n if (interfaceType.GetProperty(member.Name) is PropertyInfo otherProperty)\n {\n queue.Enqueue(otherProperty);\n }\n\n queue.Enqueue(interfaceType);\n }\n</code></pre>\n</blockquote>\n\n<p>Firstly, I think it would be cleaner to extract a method <code>GetSupertypes</code> which returns the base class (if there is one) followed by the interfaces, so that the loops can be combined into one.</p>\n\n<p>Secondly, I think there are a couple of problems with the <code>PropertyInfo</code> handling:</p>\n\n<ol>\n<li><code>member</code> is not necessarily a <code>PropertyInfo</code>. Should the signature of the method be changed? If not, should support be added for <code>MethodInfo</code> too?</li>\n<li><p>Consider</p>\n\n<pre><code>class T4 : T3\n{\n public new string P1 { get; set; }\n}\n</code></pre>\n\n<p>Should <code>T4.P1</code> inherit attributes from <code>T3.P1</code>?</p></li>\n</ol>\n\n<hr>\n\n<blockquote>\n<pre><code>public class AttributeCollection&lt;T&gt; : List&lt;T&gt;, IEquatable&lt;AttributeCollection&lt;T&gt;&gt; where T : Attribute\n{\n private static readonly IEqualityComparer&lt;AttributeCollection&lt;T&gt;&gt; Comparer = EqualityComparerFactory&lt;AttributeCollection&lt;T&gt;&gt;.Create\n (\n // When either one is True then we consider both collections equal.\n equals: (x, y) =&gt; (x.Member == y.Member) || x.SequenceEqual(y)\n );\n</code></pre>\n</blockquote>\n\n<p>To my comment above that I'm not clear on why duplication is handled at the level of collections of attributes rather than individual attributes, I <em>really</em> don't understand why the order would matter. If collections of attributes are the correct level, should they not at least be treated as sets and equality with <code>SetEquals</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:01:09.210", "Id": "429956", "Score": "0", "body": "I treat each set of attributes as a whole so that later attribute-sets can override previous ones. If I treated them individually then I would merge them or would need another mechanism of disabling previous definitions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:32:26.453", "Id": "429981", "Score": "1", "body": "ok, I think this is a dead-end solution. I'll follow only base classes and interfaces not. There is no way to come up with a reasonable set of rules for them as their order can change anytime and could break everything." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T08:32:24.060", "Id": "222196", "ParentId": "222188", "Score": "5" } } ]
{ "AcceptedAnswerId": "222196", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T06:55:08.527", "Id": "222188", "Score": "6", "Tags": [ "c#", "generics", "reflection", "extension-methods" ], "Title": "Enumerate all members and types with specific attributes" }
222188
<blockquote> <p>Implement a multi-threaded stack, with freedom to use existing implementations of stack. On top of being thread-safe, it must block (not busy-wait) a pushing thread when stack is full and a popping thread when stack is empty. It must signal the threads out of sleep when stack has space again or elements to pop. Fairness is optional in this question.</p> </blockquote> <p>How can I implement such a stack in Java? I came up with below implementation. Is this the correct way to solve above problem?</p> <pre><code>public class MyStack&lt;E&gt; { private final Stack&lt;E&gt; stack; private int max = 16; private final ReentrantLock lock = new ReentrantLock(true); private final Condition notEmpty = lock.newCondition(); private final Condition notFull = lock.newCondition(); public MyStack(int size) { this.stack = new Stack&lt;&gt;(); this.max = size; } public void push(E e) { lock.lock(); try { while (stack.size() == max) { notFull.await(); } stack.push(e); notEmpty.signalAll(); } catch (InterruptedException e1) { e1.printStackTrace(); } finally { lock.unlock(); } } public E pop() { lock.lock(); try { while (stack.size() == 0) { notEmpty.await(); } E item = stack.pop(); notFull.signalAll(); return item; } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:35:49.547", "Id": "429948", "Score": "0", "body": "Is your `Stack` a `java.util.Stack`? Isn't `java.util.Stack` already thread-safe?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:38:34.570", "Id": "429949", "Score": "0", "body": "Yes it is thread safe but I need to do some extra things on top of that as mentioned in my problem statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T16:36:38.827", "Id": "434626", "Score": "0", "body": "@200_success It's thread-safe, but not blocking." } ]
[ { "body": "<p>Looks good to me on a cursory glance. It's pretty much the exact same code as in <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Condition.html\" rel=\"nofollow noreferrer\">java.util.concurrent.locks.Condition</a> JavaDoc.</p>\n\n<p>The only definitive problem I see is the catching and logging of <code>InterruptedException</code>. The code acts towards the caller as if the operation succeeded while nothing was done.</p>\n\n<p>Not providing a way to set the maximum wait time will be a limitation in a library intended for generic use.</p>\n\n<p>Stylistically, <code>private int max</code> should be final to emphasize that it must not be changed after initialization (as changing it when threads are waiting would cause serious problems).</p>\n\n<p>Another thing, which may be a matter of taste, is the <code>stack.size() == max</code> comparison. I always like to use <code>&gt;=</code> where a size is compared to a maximum limit (with a comment, of course). This gives an extra safeguard against infinite loops in the case where a programming error causes the collection to exceed maximum size.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:44:29.993", "Id": "222200", "ParentId": "222191", "Score": "1" } }, { "body": "<h3>Guard Arguments</h3>\n\n<ul>\n<li><code>put</code> does not check for <code>e == null</code>. <strong>Are null values allowed?</strong> If not, add an argument guard <code>if (e == null) throw new NullPointerException();</code>.</li>\n</ul>\n\n<hr>\n\n<h3>Naming Conventions</h3>\n\n<ul>\n<li>Call your class <code>BlockingStack</code> to conform to Java naming guidelines concerning concurrent collections.</li>\n<li><code>max</code> should be called <code>capacity</code>. A collection's capacity is its maximum size. As suggested in another answer, make it final. Also, since you set it in the constructor, there is no reason for the magic number <code>16</code>. It will always be overriden.</li>\n<li>The constructor takes a parameter <code>size</code> which you store to <code>max</code>. There is no reason to use different names. Both should be called <code>capacity</code> anyway.</li>\n</ul>\n\n<hr>\n\n<h3>Threading</h3>\n\n<ul>\n<li>You silently catch <code>InterruptedException</code>. <strong>This is bad design</strong>. Exceptions should propagate up the call stack for callers to handle. </li>\n<li>Also, on exception, notify other threads waiting on the condition before throwing the exception up the call stack. </li>\n<li>Prefer <code>lockInterruptibly()</code> over <code>lock()</code>. <a href=\"https://dzone.com/articles/what-are-reentrant-locks\" rel=\"nofollow noreferrer\">Discussed here</a></li>\n<li>The specification dictates fairness is optional. Let the consumer of the class specify a <code>boolean fair</code> in the constructor. </li>\n</ul>\n\n<hr>\n\n<h3>Refactored Code</h3>\n\n<pre><code>public class BlockingStack&lt;E&gt; {\n\n private final Stack&lt;E&gt; stack;\n private final int capacity;\n private final ReentrantLock lock;\n private final Condition notEmpty;\n private final Condition notFull;\n\n public BlockingStack(int capacity) {\n this(capacity, false);\n }\n\n public BlockingStack(int capacity, boolean fair) {\n if (capacity &lt;= 0)\n throw new IllegalArgumentException();\n this.capacity = capacity;\n stack = new Stack&lt;&gt;();\n lock = new ReentrantLock(fair);\n notEmpty = lock.newCondition();\n notFull = lock.newCondition();\n }\n\n public void push(E e) throws InterruptedException {\n if (e == null)\n throw new NullPointerException();\n lock.lockInterruptibly();\n try {\n while (stack.size() == capacity) {\n notFull.await();\n }\n stack.push(e);\n notEmpty.signalAll();\n } catch (InterruptedException error) {\n notFull.signal();\n throw error;\n } finally {\n lock.unlock();\n }\n }\n\n public E pop() throws InterruptedException {\n lock.lockInterruptibly();\n try {\n while (stack.size() == 0) {\n notEmpty.await();\n }\n E item = stack.pop();\n notFull.signalAll();\n return item;\n } catch (InterruptedException error) {\n notEmpty.signal();\n throw error;\n } finally {\n lock.unlock();\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T16:18:39.690", "Id": "224101", "ParentId": "222191", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:26:47.473", "Id": "222191", "Score": "5", "Tags": [ "java", "multithreading", "error-handling", "thread-safety", "stack" ], "Title": "Thread-safe stack in Java with fixed capacity" }
222191
<p>Please review for performance </p> <p><a href="https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/" rel="nofollow noreferrer">https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/</a></p> <blockquote> <p>Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.</p> <p>Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.</p> <p>Example 1:</p> <p>Given nums = [1,1,2],</p> <p>Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.</p> <p>It doesn't matter what you leave beyond the returned length. Example 2:</p> <p>Given nums = [0,0,1,1,1,2,2,3,3,4],</p> <p>Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.</p> <p>It doesn't matter what values are set beyond the returned length.</p> </blockquote> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// Remove Duplicates from Sorted Array /// https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/727/ /// &lt;/summary&gt; [TestClass] public class RemoveDuplicatesfromSortedArray { [TestMethod] public void RemoveDuplicates5() { int[] nums = {0, 0, 1, 1, 1, 2, 2, 3, 3, 4}; int[] excpected = {0, 1, 2, 3, 4}; int res = RemoveDuplicates(nums); Assert.AreEqual(5,res); for (int i = 0; i &lt; res; i++) { Assert.AreEqual(excpected[i], nums[i]); } } public int RemoveDuplicates(int[] nums) { if (nums.Length &lt;= 1) { return nums.Length; } int current = nums[0]; //1 int newLength = 1; //2 for (int i = 1; i &lt; nums.Length; i++) // i = 5 { if (nums[i] != current) { nums[newLength] = nums[i]; //0,1,2 newLength++; current = nums[i]; } //else continue to next item } return newLength; } } } </code></pre>
[]
[ { "body": "<p>There is not much to review here. This algorithm looks to be as good as it gets. I don't know how much value there is in nitpicking, but here I go:</p>\n\n<h3>Review</h3>\n\n<ul>\n<li><em>The summary tag should be used to describe a type or a type member. Use remarks to add supplemental information</em> (<a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/xmldoc/summary\" rel=\"nofollow noreferrer\">xmldoc summary</a>) -> put the challenge URL in a remarks tag, not in the summary.</li>\n<li>The challenge provides an input parameter <code>nums</code> but <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions\" rel=\"nofollow noreferrer\">C# naming conventions</a> don't invite you to use abbreviations. You could/should change its name to <code>numbers</code>.</li>\n<li>Your unit test contains a variable with a typo <code>excpected</code>. </li>\n<li>Your method is declared public, meaning you should check arguments against null to avoid the nasty <code>NullReferenceException</code>.</li>\n<li>You've added alot of inline comments to show how the algorithm works. Considering the simplicity of the algorithm and the presence of unit tests, I feel these comments don't add much value to the code, if any at all <code>//else continue to next item</code> etc.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-07T20:59:22.790", "Id": "227642", "ParentId": "222192", "Score": "1" } } ]
{ "AcceptedAnswerId": "227642", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:27:37.670", "Id": "222192", "Score": "3", "Tags": [ "c#", "programming-challenge", "array" ], "Title": "LeetCode: Remove Duplicates from Sorted Array" }
222192
<p><a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/" rel="nofollow noreferrer">https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/</a></p> <p>Please review for performance.</p> <blockquote> <p>Say you have an array for which the <em>i</em>-th element is the price of a given stock on day i.</p> <p>Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).</p> <p>Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).</p> <pre><code>Example 1: Input: [7,1,5,3,6,4] Output: 7 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4. Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3. Example 2: Input: [1,2,3,4,5] Output: 4 Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. Example 3: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. </code></pre> </blockquote> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/564/ /// &lt;/summary&gt; [TestClass] public class BestTimetoBuyandSellStockII { [TestMethod] public void AnswerIs7() { int[] prices = {7, 1, 5, 3, 6, 4}; Assert.AreEqual(7, MaxProfit(prices)); } public int MaxProfit(int[] prices) { int max = 0; for (int i = 0; i &lt; prices.Length-1; i++) { if (prices[i] &lt; prices[i + 1]) { max += prices[i + 1] - prices[i]; } } return max; } } } </code></pre>
[]
[ { "body": "<h3>Performance</h3>\n\n<p>Your solution is a single pass with time complexity <span class=\"math-container\">\\$O(n)\\$</span>. It's a small variation of the <a href=\"https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/\" rel=\"nofollow noreferrer\">proposed solution</a>. </p>\n\n<h3>Conventions</h3>\n\n<ul>\n<li>use <code>static</code> when no instance state/operations are used</li>\n<li>use a clear, non-abbreviated method name <code>CalculateMaximumProfit</code></li>\n<li>always guard against bad user input in <code>public</code> methods</li>\n<li>prefer the use of <code>var</code> when the type is obvious when reading the code</li>\n<li>prefer whitespace between operands and operators <code>prices.Length - 1</code></li>\n<li>clean up waisted whitespace (in this case, after the <code>return</code> statement)</li>\n</ul>\n\n<p>applied to your code:</p>\n\n<pre><code> public static int CalculateMaximumProfit(int[] prices)\n {\n prices = prices ?? throw new ArgumentNullException(nameof(prices));\n var max = 0;\n for (var i = 0; i &lt; prices.Length - 1; i++)\n {\n if (prices[i] &lt; prices[i + 1])\n {\n max += prices[i + 1] - prices[i];\n }\n }\n return max;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-21T18:24:17.827", "Id": "222725", "ParentId": "222194", "Score": "2" } } ]
{ "AcceptedAnswerId": "222725", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T07:56:36.043", "Id": "222194", "Score": "3", "Tags": [ "c#", "programming-challenge", "array", "complexity" ], "Title": "LeetCode: Best Time to Buy and Sell Stock II" }
222194
<p>I developed this group of scripts to validate users againts a LDAP server and presenting the appropiate message to the user after sending the information.</p> <p>I wonder if I'm handling everything properly according to best practices. I'll appreciate any advice on how to improve the code in order for it to be easier to maintain in the future.</p> <p>LDAP connection script:</p> <pre><code> &lt;?php session_start(); unset($_SESSION["error"]); $ldaprdn = 'mydomain\\' . trim($_POST["user"]); // will always be set coming from login form. $ldappass = $_POST["pass"]; $ldapserver = 'aest-dc4.xxxxxxx.xxx.xxxxxxxx.xxx.xxx'; $ldapconn = ldap_connect($ldapserver); if ($ldapconn) { $ldapbind = ldap_bind($ldapconn, $ldaprdn, $ldappass); $_SESSION["logged-in"] = $ldapbind; if (!$ldapbind) { $_SESSION["error"] = 2; } else { $_SESSION["error"] = 3; } } else { $_SESSION["error"] = 4; } header("Location: http://" . $_SERVER["HTTP_HOST"] . "?/php/views/portal.php"); </code></pre> <p>Login.php</p> <pre><code>&lt;div id="form-container"&gt; &lt;form action="/php/scripts/ldap_connect.php" onsubmit="return validateLoginForm(this);" method="POST" class="form-login"&gt; &lt;h1&gt;Login&lt;/h1&gt; &lt;label for="user"&gt;Usuario&lt;/label&gt; &lt;input type="text" name="user" id="user"&gt; &lt;label for="password"&gt;Password&lt;/label&gt; &lt;input type="password" name="pass" id="pass"&gt; &lt;button type="text" class="form-login-submit" name="form-login-submit"&gt;Login&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;script&gt; function validateLoginForm(form) { let input = [form["user"], form["pass"]]; let $submit = true; input.forEach(element =&gt; { if (element.value.length === 0) { if (!element.className.includes("input-error")) { element.className += " input-error"; element.className = element.className.trim(); } element.addEventListener("keyup", function() { element.className = element.className.replace("input-error", ""); if (element.className.length === 0) element.removeAttribute("class"); }); $submit = false; } }); return $submit; } &lt;/script&gt; </code></pre> <p>error-codes.php</p> <pre><code>&lt;?php $error_codes = [ 0 =&gt; "!Usuario incorrecto.", 1 =&gt; "!Password incorrecta.", 2 =&gt; "!Credenciales inválidas.", 3 =&gt; "Logueado correctamente.", 4 =&gt; "!No se pudo conectar al servidor LDAP para validar las credenciales." ]; /** * Looks up error in error code table and returns the appropriate message * * @param [int] $error the id of the error. * @return array(string, bool) the error message and true if it is an error or false if it a success. */ function getError($error) { global $error_codes; foreach ($error_codes as $key =&gt; $value) { if ($key === $error) { $is_error = $value[0] === '!'; $msg = $is_error ? substr($value, 1) : $value; return array($msg, $is_error); } } return array("Error desconocido", true); } </code></pre> <p>Where I show the error:</p> <pre><code>&lt;?php session_start(); $link = isset($_GET["link"]) ? $_GET["link"] : "php/views/portal.php"; include("php/error-codes.php"); ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;link rel="stylesheet" href="/css/normalize.css"&gt; &lt;link rel="stylesheet" href="/css/style.css"&gt; &lt;link rel="icon" href="favicon.png"&gt; &lt;script src="js/php_file_tree.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="js/jquery.js"&gt;&lt;/script&gt; &lt;title&gt;TecoDB&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="app"&gt; &lt;?php if (isset($_SESSION["error"])) : $error = getError($_SESSION["error"]); $type = $error[1] ? "error" : "success"; unset($_SESSION["error"]); echo ("&lt;span class=\"error-msg $type\"&gt;" . $error[0] . "&lt;/span&gt;"); endif; ?&gt; &lt;?php include "php/views/header.php" ?&gt; &lt;div id="search-box"&gt; &lt;section id="search-breadcrumbs"&gt; &lt;?php if (substr($link, 0, 5) === 'docs/') { // if it's not a doc, don't show path echo "&lt;p id=\"search-breadcrumbs-result\"&gt;$link&lt;/p&gt;"; } ?&gt; &lt;/section&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:10:26.170", "Id": "429975", "Score": "1", "body": "Your javascript doesn't look Hungarian. Is there a significance to the `$` on the `$submit` variable? What business does a correct login have being in the list of error codes?" } ]
[ { "body": "<p>My attention is really drawn to your error-codes script. I love a good lookup array, and you almost have one, but it needs some polishing.</p>\n\n<ul>\n<li>Rather than declaring the lookup variable with <code>global</code> to put it in the function's scope, realize that you probably aren't going to be modifying the data during processing, so it is a perfect candidate for being a constant. A constant does not suffer scoping issues -- it is globally available.</li>\n<li>Construct your lookup array to instantly deliver exactly what you need. Don't bother with performing string manipulations to the first character. Spend the few more characters in the array and just name boolean values in the second element of each subarray in the lookup.</li>\n<li><code>error_codes</code> is a strange name for data that contains both positive and negative responses. I wouldn't be saving any positive messages, but if you truly need to store the positive message, then it would be better to rename the file, the lookup, and the custom function.</li>\n<li>The beauty of writing a lookup array with identifiable keys is that you can leverage a key check (<code>isset()</code> or similar) which will always perform better than an iterative process (even with an early <code>break</code>/<code>return</code>). This is purely a matter of how php arrays are designed and processed. See my snippet for how simple the function call can be after the lookup array is sweetened up.</li>\n</ul>\n\n<p>Code: (<a href=\"https://3v4l.org/NpPUX\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>const response_codes = [\n [\"Usuario incorrecto.\", false],\n [\"Password incorrecta.\", false],\n [\"Credenciales inválidas.\", false],\n [\"Logueado correctamente.\", true],\n [\"No se pudo conectar al servidor LDAP para validar las credenciales.\", false]\n];\n\nfunction interpretResponse($id)\n{\n return response_codes[$id] ?? [\"Error desconocido\", false];\n}\n</code></pre>\n\n<p>With <a href=\"https://www.php.net/manual/en/migration70.new-features.php\" rel=\"nofollow noreferrer\">null coalescing operator</a> in play, it's almost not worth declaring the custom function.</p>\n\n<p>Beyond that...</p>\n\n<ul>\n<li><p>I don't see the point in writing <code>unset($_SESSION[\"error\"]);</code> near the top of your LDAP connection script because no matter which outcome is reached, the value will be overwritten.</p></li>\n<li><p>When you want to check if a string begins with specific characters use:</p>\n\n<pre><code>if (strpos($link, 'docs/') === 0) {\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>if (substr($link, 0, 5) === 'docs/') {\n</code></pre>\n\n<p>because you don't need the string, you only need to check the location. It's not going to be a major performance booster, but I consider it to be more deliberate in coding intent. I have seen other cases where the substring is a bit longer (say 20 or more characters) and the developer would have to go to the trouble to count the characters each time the substring was changed -- increasing the risk of human error. <code>strpos()</code> -- when finding a substring from the start of the string (or near the start) spares that irritation.</p></li>\n<li><p>You might also consider the slight shorting of conditional syntax from <code>variable.length === 0</code> to <code>!variable.length</code>. They are equivalent.</p></li>\n<li><p>Finally, you might like to check out this handy javascript feature: <a href=\"https://stackoverflow.com/a/14101453/2943403\">https://stackoverflow.com/a/14101453/2943403</a> <code>element.classList.add(\"input-error\");</code> This will spare you having the concat and trim stuff as you go.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T06:35:24.367", "Id": "430669", "Score": "0", "body": "Thank you so much for your time. I learned a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:50:22.620", "Id": "222213", "ParentId": "222199", "Score": "4" } } ]
{ "AcceptedAnswerId": "222213", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T09:07:12.073", "Id": "222199", "Score": "2", "Tags": [ "php", "error-handling", "form" ], "Title": "PHP LDAP credentials validation and error handling" }
222199
<p>I have completed an university assignment on C. While the code is fully functional based on the specifications of the exercise, I like high-quality code and would like to ask for opinions on how can certain parts of it be improved. Be advised that I cannot change any function signature.</p> <ul> <li>The first part is the below <code>load()</code> function whose job is to create and fill a linked list based on entries of a file. If the specified file doesn't exist then a new file must be created. Unfortunately, due to the structure of the signature, I am forced to <code>fclose()</code> the file (opening / closing files are expensive operations) as I don't have any way to store the file pointer. </li> </ul> <p>I don't quite like the double <code>fopen()</code> call there. Also, while I've found a way to detect when a file is blank or when it has wrong format, I still have the feeling that there are cases where undefined behavior can occur.</p> <pre><code>studentList* load(char *filename) { studentList *list = newList(); FILE *f = fopen(filename, "r"); if (f == NULL) { f = fopen(filename, "w"); fclose(f); printf("File %s not found. A new blank file has been created.\n",filename); return list; } fseek(f, 0, SEEK_END); if (ftell(f) != 0) { rewind(f); while (!feof(f)) { student st; int res = fscanf(f, "%d%s", &amp;st.id, st.name); if (res == 2) add(list, st); } fflush(f); fclose(f); } printf("File %s loaded successfully.\n",filename); return list; } </code></pre> <ul> <li>The second part is more generic and has to do with the way status messages are printed to the console for the user. Excluding <code>load()</code> where I don't have any other option due to the nature of the signature , the other functions that provide basic functionalities of a linked list like <code>add()</code> , <code>delete()</code> , <code>find()</code> etc. don't have any <code>printf()</code> or <code>puts()</code> as I consider that method a dirty code style and besides that, I want to have full control of when a status message is printed. </li> </ul> <p>Instead, these functions return an status code <code>int</code> where then an other function takes that status message and prints the corresponding status message to the console. I have not found a better method to achieve this result. Any ideas in this part would be highly appreciated.</p> <p>Example of my code:</p> <pre><code>int res = add(list, st); printAddStudentResult(res); </code></pre>
[]
[ { "body": "<p>The first thing that strikes me is that you're writing error and status messages to the <em>standard output</em> stream, when usually these go to <code>stderr</code>, the <em>standard error</em> stream.</p>\n\n<p>I'm not sure it makes much sense to attempt to create an empty file if the file opening fails - why not leave this until it's time to save? What if the reason it failed is because the file doesn't have read permission for the process? And how do you know whether creating a new file succeeded or not?</p>\n\n<p>I'd argue that it's better to return a null pointer if the file opening fails, so that client code can distinguish this from a successful load of an empty list:</p>\n\n<pre><code>if (f == NULL)\n{\n /* NULL return signifies nothing could be read */\n return NULL;\n}\n\nstudentList *list = newList();\n</code></pre>\n\n<p>I'm assuming <code>newList()</code> is an allocation function that returns a null pointer if the allocation fails; that means we shouldn't attempt to use it until we've checked it's a valid pointer.</p>\n\n<p><code>while (!eof)</code> is <a href=\"//stackoverflow.com/q/5431941\">a common anti-pattern</a>; what we want to do instead is more like <code>while (fscanf(...)==2)</code> - and that removes the need to measure the file size before reading the contents.</p>\n\n<p>This line is clearly wrong</p>\n\n<blockquote>\n<pre><code> fflush(f);\n</code></pre>\n</blockquote>\n\n<p><code>f</code> is an <em>input stream</em>, so <code>fflush(f)</code> is Undefined Behaviour. Just remove this call.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:47:13.417", "Id": "429995", "Score": "0", "body": "The solution with the fscanf() as the loop condition is something I should have thought in the first place, very nice touch. I'm aware of the stderr stream but that's something we haven't seen yet in class. Let's keep it simple. You may have misunderstood how I use the term status message eg. When a student is successfully added the message \"Student added.\" appears. It's an informative message for the user not something we wouldn't want if we stored the stdout stream to a file. Concerning fflush() you are correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:50:46.247", "Id": "429996", "Score": "0", "body": "A lot of the C programs I write are filters or short utilities, so separating data output and messages is an instinctive thing. If those messages *are* the data for output, then yes, clearly `stdout` is appropriate. I had to make an assumption with limited context." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:22:51.760", "Id": "222215", "ParentId": "222203", "Score": "2" } } ]
{ "AcceptedAnswerId": "222215", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T10:22:30.250", "Id": "222203", "Score": "3", "Tags": [ "c", "file", "console", "user-interface" ], "Title": "Filling A Linked List With Data From File And Handling User Status Messages" }
222203
<p>I am attempting to do object oriented programming in right way, and appreciate any review to see if my approach is correct.</p> <p><code>class_blogpost.php</code> as below:</p> <pre><code>&lt;?php class BlogPosts { function __construct() { # code... } public function ListAllBlogPosts() { $DB = DatabaseFactory::getFactory()-&gt;Connect(); $query = $DB-&gt;prepare("SELECT * FROM posts ORDER BY date DESC"); $query-&gt;execute(); $list_all = $query-&gt;fetchAll(PDO::FETCH_ASSOC); return $list_all; } public function ShowABlogPost($post_id) { if (isset((int)$_GET["id"];)) { $post_id = (int)$_GET["id"]; $DB = DatabaseFactory::getFactory()-&gt;Connect(); $query = $DB-&gt;prepare("SELECT * FROM posts WHERE id = :post_id"); $query-&gt;bindParam(':post_id', $post_id, PDO::PARAM_INT); $query-&gt;execute(); $show_post = $query-&gt;fetchAll(PDO::FETCH_ASSOC); return $show_post[0]; } else { echo "Post not found."; } } } $blogposts = new BlogPosts; </code></pre> <p>Below is code for <code>home.php</code> which uses <code>ListAllBlogPosts()</code> function:</p> <pre><code>&lt;?php include_once 'connect.php'; $title = "Home"; include_once 'header.php'; $list_all = $blogposts-&gt;ListAllBlogPosts(); ?&gt; &lt;!-- col starts --&gt; &lt;div&gt; &lt;?php foreach ($list_all as $r) { $id = $r["id"]; $title = $r["title"]; $post = $r["post"]; $date = $r["date"]; ?&gt; &lt;h1&gt;&lt;?php echo $title; ?&gt;&lt;/h1&gt; &lt;p&gt;&lt;?php echo $post; ?&gt;&lt;/p&gt; &lt;a href="post.php?id=&lt;?php echo $id; ?&gt;"&gt;more&lt;/a&gt; &lt;?php } #ends foreach loop ?&gt; &lt;/div&gt; </code></pre> <p>And finally <code>post.php</code> below, user reaches as <code>post.php?id=1</code> like that:</p> <pre><code>&lt;?php include_once 'connect.php'; $id = $blogposts-&gt;ShowABlogPost($_GET["id"])["id"]; $title = $blogposts-&gt;ShowABlogPost($id)["title"]; $date = $blogposts-&gt;ShowABlogPost($id)["date"]; $post = $blogposts-&gt;ShowABlogPost($id)["post"]; include_once 'header.php'; ?&gt; &lt;div&gt; &lt;h1&gt;&lt;?php echo $title; ?&gt;&lt;/h1&gt; &lt;p&gt;&lt;?php echo $post; ?&gt;&lt;/p&gt; &lt;/div&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:04:26.540", "Id": "429974", "Score": "1", "body": "Given your code is not OOP, would you still do things like `$blogposts->ShowABlogPost($id)[\"title\"];,$date = $blogposts->ShowABlogPost($id)[\"date\"];`? Or you would just fetch a single row and use its contents? What makes you think that fetching the same record from database four times in a row is a good OOP?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:13:14.500", "Id": "429976", "Score": "0", "body": "Thank you @YourCommonSense, I haven't realized I was fetching 4 times, thanks for pointing out this murder. :) Surely, I would just fetch a single row and use its contents." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:20:01.307", "Id": "429978", "Score": "0", "body": "Why would it be important to cast `(int)$_GET[\"id\"]` before checking if it `isset()`?" } ]
[ { "body": "<p>That's a good start but the structure is overall inefficient, that leads to code duplication.</p>\n\n<p>the main problem is the violation of the Single responsibility principle. The ShowABlogPost does four things at a time:</p>\n\n<ul>\n<li>connects to the database</li>\n<li>checks the HTTP data</li>\n<li>fetches a certain record from the database</li>\n<li>displays some error</li>\n</ul>\n\n<p>it should be doing only one thing, what it's intended for - fetching a record from a database. </p>\n\n<p>Another issue is multiple calls to ShowABlogPost(). It would be, like, if you have to pay a cab driver 44.50 and you got this exact amount in your pocket, but would fetch the notes and coins one by one instead of taking them all at once.</p>\n\n<p>You already have an array that contains all the data from the first call. So just use this array.</p>\n\n<p>Other issues are:</p>\n\n<ul>\n<li><code>$DB = DatabaseFactory::getFactory()-&gt;Connect();</code> is duplicated in every method. Why not to make a database connection a class variable? So it will be available in all class methods by default.</li>\n<li><code>PDO::FETCH_ASSOC</code> could be made the default fetch option so you won't have to call it every time explicitly</li>\n<li>when no variables are going to be used in the query, there is no use for the prepared statements. </li>\n<li>when you need to fetch only one row, then you have to use fetch() method, not fetchAll()</li>\n</ul>\n\n<p>So let's rewrite your class</p>\n\n<pre><code>&lt;?php\nclass BlogPosts {\n\n protected $db;\n\n function __construct($db) {\n $this-&gt;db = $db;\n }\n\n public function ListAllBlogPosts() {\n $sql = \"SELECT * FROM posts ORDER BY date DESC\";\n $return $this-&gt;db-&gt;query($sql)-&gt;fetchAll();\n }\n\n public function ShowABlogPost($post_id) {\n $query = $this-&gt;db-&gt;prepare(\"SELECT * FROM posts WHERE id = :post_id\");\n $query-&gt;bindParam(':post_id', $post_id, PDO::PARAM_INT);\n $query-&gt;execute();\n return $query-&gt;fetch();\n }\n}\n</code></pre>\n\n<p>And now we can rewrite post.php</p>\n\n<pre><code>&lt;?php\ninclude_once 'connect.php';\ninclude_once 'class_blogpost.php';\n\n$db = DatabaseFactory::getFactory()-&gt;Connect();\n$blogposts = new BlogPosts($db);\n\nif (!isset($_GET[\"id\"]) {\n die( \"Empty request\");\n} else {\n $post = $blogposts-&gt;ShowABlogPost($_GET[\"id\"]);\n}\n?&gt;\n\n&lt;?php if ($post) : ?&gt;\n &lt;div&gt;\n &lt;h1&gt;&lt;?= $post['title']; ?&gt;&lt;/h1&gt;\n &lt;p&gt;&lt;?= $post['post']; ?&gt;&lt;/p&gt;\n &lt;/div&gt;\n&lt;?php else : ?&gt;\n Post not found.\n&lt;?php endif ?&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:22:06.440", "Id": "222208", "ParentId": "222204", "Score": "4" } } ]
{ "AcceptedAnswerId": "222208", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T10:37:07.140", "Id": "222204", "Score": "3", "Tags": [ "php", "object-oriented" ], "Title": "OOP in PHP. Exercising on creating a blog" }
222204
<p>Here is a very simple solution to the 100 doors challenge</p> <blockquote> <p>You are in a hotel with 100 doors. Initially every door is closed. On the first round, you change the state of every door (if it is open, close it. If it is closed, open it). On the second round, you change the state of every second door. On the third round, every third door etc... Find the state of all 100 hundred doors after n rounds</p> </blockquote> <pre><code>"""Check which doors are open and which are closed after n rounds""" def check_doors_round(n): """Check which door is open after n rounds""" doors = [False] * 100 for step in range(n): for (index, door) in enumerate(doors): if (index+1) % (step+1) == 0: doors[index] = not door print(doors) if __name__ == "__main__": check_doors_round(100) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:40:08.173", "Id": "430193", "Score": "0", "body": "Does it mean n < 100?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:41:58.420", "Id": "430194", "Score": "0", "body": "Sorry. I don't understand the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:44:22.253", "Id": "430195", "Score": "0", "body": "If \"Find the state of all 100 hundred doors after n rounds\" and there're 100 doors, it means that n cannot be bigger than 100? Or there are n doors, and n rounds?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:45:22.027", "Id": "430196", "Score": "0", "body": "I see. Good point. Yes. For n<=100" } ]
[ { "body": "<ul>\n<li><p>It would be better if you merged <code>(index+1) % (step+1) == 0</code> into the preceding <code>for</code> loop.</p>\n\n<p>Whilst it's easy to understand what it means, it's even easier to understand what <code>range(start, stop, step)</code> means.</p></li>\n<li><p>You should return <code>doors</code> and print outside the function.</p></li>\n<li>I'd prefer to be able to specify how many doors to use. This can be a default argument.</li>\n</ul>\n\n<pre><code>def check_doors_round(n, doors_=100):\n doors = [False] * doors_\n for step in range(n):\n for index in range(step, doors_, step + 1):\n doors[index] = not doors[index]\n return doors\n\n\nif __name__ == \"__main__\":\n print(check_doors_round(100))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:25:01.327", "Id": "429980", "Score": "0", "body": "True. The ```step``` argument in the for loop is more elegant. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:48:23.820", "Id": "430022", "Score": "4", "body": "To make the function marginally nicer to use, the parameter should probably by `doors` and the local variable `doors_`, or the parameter could be `num_doors` or the like." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:54:43.427", "Id": "430023", "Score": "0", "body": "@jirassimok That could be an improvement, but since it's a positional and keyword argument I don't think many will use `check_door_round(1, doors_=2)` over `check_door_round(1, 2)`, :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:19:11.283", "Id": "222207", "ParentId": "222205", "Score": "14" } }, { "body": "<p><strong>Mathematical observation</strong></p>\n\n<p>Let's consider the <code>i-th</code> door after <code>n</code> rounds and see when its state changes.</p>\n\n<p>This boils down to considering the divisors of <code>i</code> smaller than n. In particular, we could try to handle them by pair <code>(p, q)</code> such than <code>i = p * q</code>. Without limitation, we can assume <code>p &lt;= q</code>.</p>\n\n<ul>\n<li>If <code>0 &lt; p &lt; q &lt; n</code> (\"usual situation\"), the door will change its state at step p and q => these divisors cancel each other</li>\n<li>If <code>0 &lt; p = q &lt; n</code> (\"perfect square root\"), the door will change its state once => the door state changes</li>\n<li>If <code>0 &lt; n &lt; p &lt;= q</code> (\"both are too big\"), the door will not be changed</li>\n<li>If <code>0 &lt; p &lt; n &lt;= q</code> (\"one is too big\"), the door will change its state once => the door state changes</li>\n</ul>\n\n<p>The last cases are a bit tedious to consider but using the first 2 cases, we can see than once n gets big enough, we'll have only 2 different situations:</p>\n\n<ul>\n<li><p>i is a perfect square: all pairs of divisors cancel each other except for one: the door ends up open</p></li>\n<li><p>i is not a perfect square: all pairs of divisors cancel each other: the door ends up closed.</p></li>\n</ul>\n\n<p>Changing details in your code, this can become very obvious:</p>\n\n<pre><code>def check_doors_round(n):\n \"\"\"Check which door is open after n rounds\"\"\"\n doors = [False] * 100\n for step in range(n):\n for (index, door) in enumerate(doors):\n if (index+1) % (step+1) == 0:\n doors[index] = not door\n return doors\n\ndef pretty_print_doors(doors):\n print([i+1 for i, d in enumerate(doors) if d])\n\nif __name__ == \"__main__\":\n pretty_print_doors(check_doors_round(100))\n</code></pre>\n\n<p>Which return [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].</p>\n\n<p>Thus, we can rewrite the function:</p>\n\n<pre><code>import math\n\ndef check_doors_round(n):\n \"\"\"Check which door is open after n rounds\"\"\"\n doors = [False] * 100\n for i in range(int(math.sqrt(100))):\n doors[i*i -1] = True\n return doors\n</code></pre>\n\n<p>This still needs to be generalised for various values of n...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:22:16.213", "Id": "430005", "Score": "0", "body": "I like the ```pretty_print_doors``` function. Certainly makes the output easier to read. I was keen to keep the function completely generalisable for any value of ```n```, however small. Thanks though for your insight" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:56:56.937", "Id": "430009", "Score": "1", "body": "Bugs in your rewrite: you loop starting at 0, and set `doors[i*i-1]`, or `doors[-1]` (the last door), to `True`. And the argument `n` is unused." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T15:50:24.670", "Id": "430029", "Score": "0", "body": "@AJNeufeld The argument n is unused because I've covered the case where \"n gets big enough\" and I plan to let OP perform the adaptation for other values of n based on the insight provided. As for the other point, good catch. I'll need to update my answer asap (but the idea is worth more than the actual code using it)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:17:27.670", "Id": "222218", "ParentId": "222205", "Score": "12" } }, { "body": "<p>One thing I would add would be to describe what your inputs should be, and to check if they are indeed the correct input type. For small scripts it's not that pressing, but in my experience it can make debugging much easier in the future.</p>\n\n<p>I've also copied @Peilonrayz suggestion because I agree with it.</p>\n\n<pre><code>def check_doors_round(n, number_doors=100):\n \"\"\"\n Check which doors are open and which are closed after n rounds\n\n :param int n: number of rounds\n :param int number_doors: number of doors to check\n :return: list of doors, with states of open (True) or closed (False)\n \"\"\"\n\n if not isinstance(n, int):\n raise TypeError (f\"n Should be an integer, not {type(n)}\")\n if n &lt; 0:\n raise ValueError (\"n Should be larger than 0.\")\n if not isinstance(number_doors, int):\n raise TypeError (f\"number_doors Should be an integer, not {type(number_doors)}\")\n if number_doors &lt; 0:\n raise ValueError (\"number_doors Should be larger than 0.\")\n\n doors = [False] * number_doors\n for step in range(n):\n for (index, door) in enumerate(doors):\n if (index+1) % (step+1) == 0:\n doors[index] = not door\n return doors\n\nif __name__ == \"__main__\":\n print(check_doors_round(100))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:10:53.633", "Id": "430108", "Score": "0", "body": "Thanks for this. Is it better to ```raise exception``` when dealing with type errors then? I usually just print a message to the terminal?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:16:28.957", "Id": "430111", "Score": "2", "body": "If you raise an exception, you can let the caller decide how to handle it. Also if you use any code somewhere the user can not see the terminal, printing to the terminal is not really useful. I would use a less generic `Exception` like `TypeError` or `ValueError`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:39:27.970", "Id": "430115", "Score": "0", "body": "@MaartenFabré thank you, I've updated it!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T07:32:03.673", "Id": "222263", "ParentId": "222205", "Score": "4" } }, { "body": "<p>Apart from the remarks already given about returning instead of printing, and an argument for the number of doors, this code looks good.</p>\n\n<p>Instead of looping over the list, you can also use slicing:</p>\n\n<pre><code>def check_doors_round_splice(n, num_doors=100):\n \"\"\"Check which door is open after n rounds\"\"\"\n doors = [False] * num_doors\n for step in range(min(n, num_doors)):\n my_slice = slice(step, None, step + 1)\n doors[my_slice] = [not door for door in doors[my_slice]]\n return doors\n</code></pre>\n\n<h1>Timing</h1>\n\n<p>This is a lot faster:</p>\n\n<pre><code>%timeit check_doors_round(100)\n</code></pre>\n\n<blockquote>\n<pre><code>1.01 ms ± 40.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n</blockquote>\n\n<pre><code>%timeit check_doors_round_splice(100)\n</code></pre>\n\n<blockquote>\n<pre><code>66 µs ± 4.65 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:09:50.990", "Id": "430107", "Score": "0", "body": "That's a really smart idea! Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T07:50:48.510", "Id": "222264", "ParentId": "222205", "Score": "4" } } ]
{ "AcceptedAnswerId": "222207", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T10:41:44.780", "Id": "222205", "Score": "14", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "100-doors puzzle" }
222205
<p>I'm toggling the class of an element with this code but I'm pretty sure it can be written more efficiently.</p> <pre><code>$('.expandable_header').click(function() { toggle_expandable_icon($(this).find('i')[0]); $(this).nextUntil('tr.expandable_header').slideToggle(100, function(){ }); }); function toggle_expandable_icon(elem) { var toOpen = 'fa-plus-circle'; var toClose = 'fa-minus-circle'; if (elem.classList.contains(toOpen)) { elem.classList.replace(toOpen, toClose); } else { elem.classList.replace(toClose, toOpen); }}; </code></pre> <p>Not pointless to say js is not my mother tongue.</p>
[]
[ { "body": "<h2>Use toggle methods</h2>\n\n<p>Presuming that you are just toggling those two classes, you could just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods\" rel=\"nofollow noreferrer\"><code>classList.toggle()</code></a> with those two class names:</p>\n\n<pre><code>function toggle_expandable_icon(elem) {\n elem.classList.toggle('fa-plus-circle');\n elem.classList.toggle('fa-minus-circle');\n}\n</code></pre>\n\n<p>And it appears jQuery is used, so the <a href=\"https://api.jquery.com/toggleClass\" rel=\"nofollow noreferrer\"><code>.toggleClass()</code></a> method could be used on a jQuery collection (i.e. remove the <code>[0]</code> in <code>toggle_expandable_icon($(this).find('i')[0]);</code>):</p>\n\n<pre><code>function toggle_expandable_icon(collection) {\n collection.toggleClass('fa-plus-circle').toggleClass('fa-minus-circle');\n}\n</code></pre>\n\n<p>Those class names could also be added together in a single <code>toggleClass()</code> call:</p>\n\n<pre><code>function toggle_expandable_icon(collection) {\n collection.toggleClass('fa-plus-circle fa-minus-circle');\n}\n</code></pre>\n\n<h2>Demo</h2>\n\n<p>Without knowing the HTML structure it was challenging to know exactly how the toggles operated, but it wasn't very difficult to generate something.</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>$('.expandable_header').click(function() {\n toggle_expandable_icon($(this).find('i'));\n $(this).nextUntil('tr.expandable_header').slideToggle(\"slow\");\n});\n\nfunction toggle_expandable_icon(collection) {\n collection.toggleClass('fa-plus-circle fa-minus-circle');\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n&lt;link href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.8.2/css/all.css\" rel=\"stylesheet\" /&gt;\n&lt;table&gt;\n &lt;tr class=\"expandable_header\"&gt;\n &lt;td&gt;\n &lt;i class=\"fa fa-plus-circle\"&gt;&lt;/i&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr style=\"display: none;\" height=\"250px\"&gt;\n &lt;td&gt; \n &lt;a href=\"https://codereview.meta.stackexchange.com/a/1511/120114\" target=\"_blank\"&gt; Zombies exist! &lt;/a&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n&lt;/table&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T07:54:18.883", "Id": "430100", "Score": "0", "body": "Excellent ! And neither I was aware for the zombies..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T18:40:56.507", "Id": "222240", "ParentId": "222209", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:23:08.093", "Id": "222209", "Score": "2", "Tags": [ "javascript", "beginner", "jquery", "event-handling" ], "Title": "Toggling a class in JS" }
222209
<p>I would like to change row names values from a first data frame if these rows names are present in another data frame, and change it to a corresponding value (defined in the second data frame). I could do it with a <code>for</code> loop, but I wonder what would be some other more suitable ways to do it in R. </p> <p>Here is a toy dataset (my real dataset has 10^5 rows):</p> <pre><code>df &lt;- data.frame("sample_1" = rep(0,3), "sample_2" = rep(0,3), row.names = paste0('gene_', seq(1, 3)), stringsAsFactors = FALSE) annotation &lt;- data.frame("gene" = paste0('gene_', seq(1, 2)), 'name' = paste0('name_', seq(1, 2)), stringsAsFactors = FALSE) df$gene &lt;- rownames(df) </code></pre> <p>Initial data frames: </p> <pre><code>df sample_1 sample_2 gene gene_1 0 0 gene_1 gene_2 0 0 gene_2 gene_3 0 0 gene_3 annotation gene name 1 gene_1 name_1 2 gene_2 name_2 </code></pre> <p>Solution found:</p> <pre><code>for (x in rownames(df)){ if (x %in% annotation$gene){ df[x,]$gene &lt;- annotation$name[which(annotation$gene == x)] } } rownames(df) &lt;- df$gene df$gene &lt;- NULL </code></pre> <p>Resulting data frame:</p> <pre><code>df sample_1 sample_2 name_1 0 0 name_2 0 0 gene_3 0 0 </code></pre>
[]
[ { "body": "<h3>Code Review</h3>\n\n<p>One change I would make to your solution is to directly modify the row names as below (instead of modifying <code>gene</code> and then setting the row names equal to <code>gene</code>).</p>\n\n<pre><code>for (i in 1:nrow(df)){\n if (rownames(df)[i] %in% annotation$gene) {\n\n rownames(df)[i] = annotation$name[which(annotation$gene == rownames(df)[i])]\n\n }\n}\ndf$gene &lt;- NULL\n\ndf\n# sample_1 sample_2\n# name_1 0 0\n# name_2 0 0\n# gene_3 0 0\n</code></pre>\n\n<p>This solution is similar to the original, but iterates over row numbers (1-3 in this case) instead of row names. This allows direct modification of the row names and makes the code slightly more concise. This version doesn't use <code>gene</code> at all.</p>\n\n<p>That's how I'd modify the existing solution, but overall I wouldn't use a <code>for</code> loop. <code>for</code> loops can be slow since they iterate over every element (and your data set has 10^5 rows). Below is another approach using the <code>dplyr</code> library.</p>\n\n<h3>Another Approach</h3>\n\n<pre><code>library(dplyr)\nlibrary(tibble)\n\ndf &lt;- left_join(df, annotation, by = \"gene\") %&gt;% # Join \"annotation\" and \"df\"\nmutate(gene = if_else(is.na(name), gene, name)) %&gt;% # Convert \"gene\" to \"name\" when \"name\" is valid\ncolumn_to_rownames(var = \"gene\") %&gt;% # Set row names to \"gene\"\nselect(-name) # Remove \"name\"\n\ndf\n# sample_1 sample_2\n# name_1 0 0\n# name_2 0 0\n# gene_3 0 0\n</code></pre>\n\n<p>This syntax may look unfamiliar but it's doing 3 main things:<br>\n - left-joining <code>df</code> and <code>annotation</code> by the <code>gene</code> field. It has to be a left-join so all rows of <code>df</code> are preserved!<br>\n - changing the value of <code>gene</code> to <code>name</code> only when <code>name</code> is non-null<br>\n- setting the row names equal to <code>gene</code> </p>\n\n<p>The pipe operator <code>%&gt;%</code> passes the data through these operations without needing to repeatedly type <code>df &lt;-</code>. These are all vectorized operations and so are faster than a <code>for</code> loop, especially for large data sets.</p>\n\n<p><code>dplyr</code> syntax can be intimidating at first, but it's an extremely popular (and I believe intuitive) paradigm to manipulate data. <a href=\"https://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html\" rel=\"nofollow noreferrer\">Here</a> is a handy intro on <code>dplyr</code> syntax.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-12T00:58:03.687", "Id": "225953", "ParentId": "222211", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T11:38:56.813", "Id": "222211", "Score": "1", "Tags": [ "iterator", "r" ], "Title": "Replace values in R data frame according to values in other data frame" }
222211
<p>I find it irritating that in standard C++ I can't do <code>std::max(a, b) = x</code> when it's possible and that it can't handle more than 2 arguments. For the second concern I found <a href="https://www.youtube.com/watch?v=z_fnMdzfWAQ&amp;t=266s" rel="noreferrer">this <code>std::min</code> tutorial</a> and it looks interesting but the usage of pointers confuses me because I don't understand why they are needed here. Since I want to learn more about c++ I wanted to try to create my own version of <code>std::max</code> while making use of the latest c++ features that I know of.</p> <p>First I want to make use of concepts to let the user know when the types of arguments are invalid at compilation time:</p> <pre class="lang-cpp prettyprint-override"><code>namespace std1 { // Helper concept for static_assert template&lt;typename&gt; concept False = false; template&lt;typename T&gt; concept Boolean = std::is_same_v&lt;T, bool&gt;; template&lt;typename T&gt; concept TypeLessThanComparable = requires(T a, T b) { { a &lt; b } -&gt; Boolean; }; template&lt;typename T&gt; concept TypeLessThanEqComparable = requires(T a, T b) { { a &lt;= b } -&gt; Boolean; }; template&lt;typename T&gt; concept TypeGreaterThanComparable = requires(T a, T b) { { a &gt; b } -&gt; Boolean; }; template&lt;typename T&gt; concept TypeGreaterThanEqComparable = requires(T a, T b) { { a &gt;= b } -&gt; Boolean; }; </code></pre> <p>These are the functions themselves:</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;typename T&gt; constexpr decltype(auto) max(T&amp;&amp; a) noexcept { return std::forward&lt;T&gt;(a); } template&lt;typename T&gt; constexpr decltype(auto) max(T&amp;&amp; a, T&amp;&amp; b) noexcept { if constexpr(TypeLessThanComparable&lt;T&gt;) { return a &lt; b ? std::forward&lt;T&gt;(b) : std::forward&lt;T&gt;(a); } else if constexpr(TypeLessThanEqComparable&lt;T&gt;) { return a &lt;= b ? std::forward&lt;T&gt;(b) : std::forward&lt;T&gt;(a); } else if constexpr(TypeGreaterThanComparable&lt;T&gt;){ return a &gt; b ? std::forward&lt;T&gt;(a) : std::forward&lt;T&gt;(b); } else if constexpr(TypeGreaterThanEqComparable&lt;T&gt;) { return a &gt;= b ? std::forward&lt;T&gt;(a) : std::forward&lt;T&gt;(b); } else { // if I just put false in static_assert it gives a compilation error no matter what static_assert(False&lt;void&gt;, "You called max with invalid arguments, cannot find comparison operators for their type"); } } template&lt;typename T, typename...Ts&gt; constexpr decltype(auto) max(T&amp;&amp; a, T&amp;&amp; b, T&amp;&amp; c, Ts&amp;&amp;...d) noexcept { return max(a, max(b, max(c, d...))); } } // namespace std1 </code></pre> <p>And some tests:</p> <pre class="lang-cpp prettyprint-override"><code> struct A{}; struct B { bool operator&lt;(B const&amp;) const noexcept = delete; bool operator&lt;=(B const&amp;) const noexcept = delete; bool operator&gt;(B const&amp;) const noexcept = delete; bool operator&gt;=(B const&amp;) const noexcept; }; int main() { static_assert(std1::max(1, 2) == 2); int a = 1; int b = 5; int c = 3; int d = 2; assert(std1::max(a, b, c, d) == b); std1::max(b, c, d) = 4; assert(b == 4); // This gives a compilation error because the static assertion failed // (void)std1::max(A{}, A{}); // This works std1::max(B{}, B{}, B{}, B{}, B{}); } </code></pre> <p>I want to know if the code is well written and could replace <code>std::max</code> in c++20, maybe it has bugs that I'm not aware of since I am inexperienced in c++. You could also check the compiler explorer link: <a href="https://godbolt.org/z/5urgqR" rel="noreferrer">https://godbolt.org/z/5urgqR</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T15:54:05.017", "Id": "430032", "Score": "0", "body": "What's wrong with [`constexpr T std::max( std::initializer_list<T> ilist );`](https://en.cppreference.com/w/cpp/algorithm/max#top)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:01:11.567", "Id": "430034", "Score": "0", "body": "@TobySpeight Can it do `std::max({a, b, c}) = 4`? It also doesn't pass my test with `B{}` when not all comparison operators are implemented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:06:40.423", "Id": "430038", "Score": "0", "body": "Ah, I missed that you wanted an `lvalue` return type. Thanks for the clarification. There might be a way to use `std::reference_wrapper` to get that behaviour; as for types that don't implement `<` - I'd call that a bug in the type (but it's easy to pass a custom comparator). I'll write this in an answer." } ]
[ { "body": "<p>I think this function is unnecessary.</p>\n\n<p>We can deal with defective classes (that don't properly implement the standard <code>LessThanComparable</code> concept) by either fixing them (preferable) or by providing a comparator argument to <code>std::max</code>:</p>\n\n<pre><code>auto const b_lessthan = [](const B&amp; a, const B&amp; b){ return !(a&gt;=b); };\n\nstd::max({B{}, B{}, B{}, B{}, B{}}, b_lessthan);\n</code></pre>\n\n<p>Sure, you could make a generic adapter using the same <code>if constexpr</code> chain as in this code, but are the defective types really that common?</p>\n\n<hr>\n\n<p>We can arrange for <code>std::max()</code> to return an lvalue by passing it an initialiser list of <code>std::reference_wrapper</code> for its arguments:</p>\n\n<pre><code>template&lt;typename... T&gt;\nconstexpr auto&amp; ref_max(T... args)\n{\n return std::max({std::ref(args)...,}).get();\n}\n</code></pre>\n\n<hr>\n\n<p>We now have</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;functional&gt;\n#include &lt;cassert&gt;\n\nint main()\n{\n static_assert(std::max(1, 2) == 2);\n\n int a = 1;\n int b = 5;\n int c = 3;\n int d = 2;\n\n assert(std::max({a, b, c, d}) == b);\n\n ref_max(b, c, d) = 4;\n\n assert(b == 4);\n\n // This gives a compilation error because the static assertion failed\n // (void)std1::max(A{}, A{});\n\n // This works\n auto const b_lessthan = [](const B&amp; a, const B&amp; b){ return !(a&gt;=b); };\n\n std::max({B{}, B{}, B{}, B{}, B{}}, b_lessthan);\n}\n</code></pre>\n\n<p>Which isn't so very different than the <code>main()</code> in the question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:33:41.927", "Id": "430046", "Score": "0", "body": "You are right. Only now did I realize I should have added the possibility to provide a custom comparator so that the function can be useful. What I would add is an extra constraint, for example `Callable<T, F>`, so that the comparator is actually valid so that the compiler won't give cryptic error messages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:37:19.983", "Id": "430049", "Score": "0", "body": "Or do what `std::max()` does, and pass an iterator list and a comparator as the two arguments (but I'm not quite sure whether we can combine that with the fold expression for reference-wrapping)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:27:39.333", "Id": "222233", "ParentId": "222216", "Score": "8" } } ]
{ "AcceptedAnswerId": "222233", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T12:52:32.117", "Id": "222216", "Score": "6", "Tags": [ "c++", "beginner", "variadic", "c++20" ], "Title": "Max function with variable number of arguments" }
222216
<p>I can do this in one line in Python:</p> <pre><code>sum([i for i in range(9,9999999) if i == sum([int(x)**5 for x in str(i)])]) </code></pre> <p>Not very fast, but works nicely. I thought it might be quicker to do it in Haskell, a language I'm quite new to:</p> <pre><code>-- helper func toDigits :: Int -&gt; [Int] toDigits 0 = [] toDigits x = toDigits (x `div` 10) ++ [x `mod` 10] isSumofFifth n = n == sum (map (^5) (toDigits n)) sum (filter isSumofFifth [9..9999999]) </code></pre> <p>But it seems as slow, or even slower (I haven't done exact profiling).</p> <p>I realise I could optimise it with a more refined upper bound, but aside from that, is there a better way to write this in Haskell?</p>
[]
[ { "body": "<p>I'm not familiar with either Haskell or Python, but I'd like to challenge the way you're tackling this problem.</p>\n\n<p>First of all, seven 9s will give you a sum of 7 * 9<sup>5</sup> = 413343. That's six digits, so searching up to one million (instead of ten million) would already be enough.</p>\n\n<p>But we can do better. Instead of analyzing all million numbers, you can reduce that number by realizing that 123456 will give the same sum as 654321. The order of the digits doesn't matter. The sums you <em>actually</em> need to compute are the <a href=\"https://en.wikipedia.org/wiki/Combination#Number_of_combinations_with_repetition\" rel=\"noreferrer\">combinations with repetition</a>; there are 'only' <a href=\"https://www.wolframalpha.com/input/?i=10+multichoose+6\" rel=\"noreferrer\">5005</a> of them. Python has a standard function to list them in the <a href=\"https://docs.python.org/3.4/library/itertools.html#itertools.combinations_with_replacement\" rel=\"noreferrer\">itertools</a> package, e.g. <code>combinations_with_replacement('0123456789', 6)</code>.</p>\n\n<p>When you have computed the sum of the combination, you need to sort its digits and check if they match the combination. If so, the sum is a true positive and can be added to the list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:45:53.543", "Id": "430021", "Score": "0", "body": "Ah, quite correct. I usually go about these things in the lazy way, so thanks for the feedback. Going to leave it open for a bit in case anyone has insight on the code itself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:35:42.383", "Id": "222227", "ParentId": "222221", "Score": "8" } }, { "body": "<p>I agree with Glorfindel that the best result is achieved by thinking of the problem in a different way. Still, improvements can be made to the code that speed it up by about a factor of 3:</p>\n\n<pre><code>toDigits :: Int -&gt; [Int]\ntoDigits 0 = []\ntoDigits x = let (d, m) = x `divMod` 10\n in d `seq` m : toDigits d\n\nisSumofFifth n = n == sum (map (^5) (toDigits n))\n\nmain :: IO ()\nmain = do\n let result = sum (filter isSumofFifth [9..9999999])\n putStrLn $ \"Result is: \" ++ show result\n</code></pre>\n\n<p>First the <code>divMod</code> function is used to compute the quotient and modulus in a single step rather than separately, which saves time, as they are expensive operations.</p>\n\n<p>More importantly, the <code>toDigits</code> function can be changed to generate the digits in reverse order, which is fine for this problem, and thereby avoid a series of concatenations. In this code, each digit is generated as needed, while in the original, the first digit can't be read until all of the others are generated and then concatenated together from a series of single-element lists. This causes a lot of copying.</p>\n\n<p>Another small speed-up is achieved by the <code>seq</code> operator, which insures that d is fully calculated when m is returned, avoiding extra processing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T04:49:32.130", "Id": "222258", "ParentId": "222221", "Score": "4" } }, { "body": "<p>Actually, you did a much better job with your first version than you seem to think.</p>\n\n<p>Your Python version takes about 23 seconds (Python 3) on my desktop. If I take your original program:</p>\n\n<pre><code>toDigits :: Int -&gt; [Int]\ntoDigits 0 = []\ntoDigits x = toDigits (x `div` 10) ++ [x `mod` 10]\n\nisSumofFifth n = n == sum (map (^5) (toDigits n))\nmain = print $ sum (filter isSumofFifth [9..9999999])\n</code></pre>\n\n<p>and, remembering that Haskell is a <strong>compiled</strong> language, take care to compile it with optimizations <code>ghc -O2 FindFives.hs</code> (using GHC 8.6.4), I find the executable runs in about 2.7 seconds, so <strong>about ten times faster than the Python version.</strong></p>\n\n<p><em>So, Important Note:</em> Never benchmark Haskell code with the GHCi interpreter or using <code>runghc</code>! The performance results will be completely meaningless.</p>\n\n<p>Also, since this is Code Review, let me point out that you can write your Haskell version in much the same form as the Python version:</p>\n\n<pre><code>answer :: Int\nanswer = sum [i | i &lt;- [9..9999999], i == sum [d^5 | d &lt;- toDigits i]]\n-- Python: sum([i for i in range(9,9999999) if i == sum([int(x)**5 for x in str(i)]\n</code></pre>\n\n<p>Using your original <code>toDigits</code>, this still runs in about 2.7 seconds, but it's probably easier to read.</p>\n\n<p>@Truman has covered the main ways to speed up your <code>toDigits</code>. The version in that answer gives a runtime of about 1 second.</p>\n\n<p>You can do a little better. The version:</p>\n\n<pre><code>toDigits :: Int -&gt; [Int]\ntoDigits = unfoldr go\n where go 0 = Nothing\n go x = Just $ swap $ x `quotRem` 10\n</code></pre>\n\n<p>gets it down to about 700ms because <code>unfoldr</code> allows the creation of the actual digits list to be optimized away.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-01T07:20:49.663", "Id": "432590", "Score": "0", "body": "Several really helpful points here, thanks a lot!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-01T00:26:31.603", "Id": "223266", "ParentId": "222221", "Score": "3" } } ]
{ "AcceptedAnswerId": "222258", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T13:39:53.657", "Id": "222221", "Score": "7", "Tags": [ "haskell", "mathematics" ], "Title": "Check if an integer equals the sum of its digits to the fifth power" }
222221
<p>I'm experimenting how a Relation (a cartesian product's subset) can be implemented in Haskell using different data classes.</p> <p>Forest and Tree allow to keeps together in a single data structure different relations each one of different n-arity.</p> <p>This set of functions require only the Eq constraint and a simple Normal Form. (The two show functions require the additional Show constraint.)</p> <p>The examples allow to quick test the functions.</p> <pre><code>module RelationT (isTreeInNormalForm ,isForestInNormalForm ,toTreeNormalForm ,toForestNormalForm ,equTrees ,equForests ,unionOfTwoTrees ,unionOfTwoForests ,unionOfForests ,addTreeToTree ,addForestToTree ,addForestToForest ,addTreeToForest ,appendTreeToTree ,appendForestToTree ,appendForestToForest ,growthTree ,growthForest ,fmapLeafsOfTree ,fmapLeafsOfForest ,showF ,showT) where import Data.Tree import Data.List -- -------------------- CAVEAT -------------------- -- Forests and subforests must be in NORMAL FORM. -- (Node values of th same level must all be different.) -- ============================== NORMAL FORM ============================== -- Each tree and forest must result True. isTreeInNormalForm :: Eq a =&gt; Tree a -&gt; Bool isTreeInNormalForm (Node _ subforest) = isForestInNormalForm subforest isForestInNormalForm :: Eq a =&gt; Forest a -&gt; Bool isForestInNormalForm [] = True isForestInNormalForm [Node _ subfrst] = isForestInNormalForm subfrst isForestInNormalForm (Node x _ : ndxs) = let (oks,others) = partition (\(Node w _) -&gt; w == x) ndxs in case oks of [] -&gt; isForestInNormalForm others _ -&gt; False -- "Fusion" of the nodes in the same level that have the same value toTreeNormalForm :: Eq a =&gt; Tree a -&gt; Tree a toTreeNormalForm (Node x subforest) = Node x $ toForestNormalForm subforest toForestNormalForm :: Eq a =&gt; Forest a -&gt; Forest a toForestNormalForm [] = [] toForestNormalForm [Node x subfrst] = [Node x (toForestNormalForm subfrst)] toForestNormalForm (Node x subfrst : ndxs) = let (oks,others) = partition (\(Node w _) -&gt; w == x) ndxs in if null oks then Node x (toForestNormalForm subfrst) : toForestNormalForm others else Node x (unionOfForests $ map (\(Node _ subf) -&gt; subf) oks) : toForestNormalForm others -- ============================== EQUIVALENCE ============================== -- Forests and subforests are CONSIDERED equivalent if differs only by the order of nodes in the same level. equTrees :: Eq a =&gt; Tree a -&gt; Tree a -&gt; Bool equTrees (Node x subfrstX) (Node y subfrstY) | x == y = equForests subfrstX subfrstY | otherwise = False equForests :: Eq a =&gt; Forest a -&gt; Forest a -&gt; Bool equForests [] [] = True equForests [] _ = False equForests _ [] = False equForests (Node x subfrstX : ndxs) ndys = let (oks,others) = partition (\(Node w _) -&gt; w == x) ndys in case oks of [] -&gt; False [Node _ subfrstZ] -&gt; equForests subfrstX subfrstZ &amp;&amp; equForests ndxs others _ -&gt; error "NOT in Normal Form" -- ============================== COMBINE ============================== unionOfTwoTrees :: Eq a =&gt; Tree a -&gt; Tree a -&gt; [Tree a] unionOfTwoTrees nd (Node _ []) = [nd] unionOfTwoTrees (Node _ []) nd = [nd] unionOfTwoTrees ndx@(Node x subforestX) ndy@(Node y subforesty) | x == y = [Node x (unionOfTwoForests subforestX subforesty)] | otherwise = [ndx, ndy] unionOfTwoForests :: Eq a =&gt; [Tree a] -&gt; [Tree a] -&gt; [Tree a] unionOfTwoForests [] frst = frst unionOfTwoForests frst [] = frst unionOfTwoForests (ndy@(Node y subfrstY) : ndys) ndxs = let (oks,others) = partition (\(Node w _) -&gt; w == y) ndxs in case oks of [] -&gt; ndy : unionOfTwoForests ndys others [Node z subfrstZ] -&gt; Node z (unionOfTwoForests subfrstY subfrstZ) : unionOfTwoForests ndys others _ -&gt; error "NOT in Normal Form" unionOfForests :: (Foldable t, Eq a) =&gt; t [Tree a] -&gt; [Tree a] unionOfForests frsts = foldr unionOfTwoForests [] frsts -- -------------------- Addition -------------------- -- Addition is non-commutative. -- The first tree is "added" to the second only if the "root" values are the same. -- The following functions behaves similarly. addTreeToTree :: Eq a =&gt; Tree a -&gt; Tree a -&gt; Tree a addTreeToTree (Node _ []) nd = nd addTreeToTree (Node y subfrstY) ndx@(Node x []) | y == x = Node x subfrstY | otherwise = ndx addTreeToTree (Node y subfrstY) ndx@(Node x subfrstX) | y == x = Node x $ addForestToForest subfrstY subfrstX | otherwise = ndx addTreeToForest :: Eq a =&gt; Tree a -&gt; [Tree a] -&gt; [Tree a] addTreeToForest (Node _ []) frst = frst addTreeToForest _ [] = [] addTreeToForest ndy@(Node y _) frst = let (oks,others) = partition (\(Node w _) -&gt; w == y) frst in case oks of [] -&gt; frst [ndz] -&gt; addTreeToTree ndz ndy : others _ -&gt; error "The forest is NOT in Normal Form" addForestToTree :: Eq a =&gt; [Tree a] -&gt; Tree a -&gt; Tree a addForestToTree [] nd = nd addForestToTree ndys nd@(Node x subforestX) = case filter (\(Node w _) -&gt; w == x) ndys of [] -&gt; nd [Node _ subfrstZ] -&gt; Node x $ appendForestToForest subfrstZ subforestX _ -&gt; error "The forest is NOT in Normal Form" addForestToForest :: Eq a =&gt; [Tree a] -&gt; [Tree a] -&gt; [Tree a] addForestToForest [] frst = frst addForestToForest _ [] = [] -- !!! addForestToForest (Node y subfrstY : ndys) ndxs = let (oks,others) = partition (\(Node w _) -&gt; w == y) ndxs in case oks of [] -&gt; addForestToForest ndys ndxs [Node z subfrstZ] -&gt; Node z (unionOfTwoForests subfrstY subfrstZ) : addForestToForest ndys others _ -&gt; error "The second forest is NOT in Normal Form" -- -------------------- Append -------------------- -- Thees functions appends trees or forests to the leaves of the target forest. -- For each target leaf the condition is that the value of the leaf have to be equal to the value of the "root" of what would be appended. appendTreeToTree :: Eq a =&gt; Tree a -&gt; Tree a -&gt; Tree a appendTreeToTree (Node _ []) nd = nd appendTreeToTree (Node y subfrstY) ndx@(Node x []) | y == x = Node x subfrstY | otherwise = ndx appendTreeToTree ndy (Node x subfrstX) = Node x $ map (\nd -&gt; appendTreeToTree ndy nd) subfrstX appendForestToTree :: Eq a =&gt; [Tree a] -&gt; Tree a -&gt; Tree a appendForestToTree [] nd = nd appendForestToTree frst ndx@(Node x []) = case filter (\(Node y _) -&gt; y == x) frst of [] -&gt; ndx [Node _ subforest] -&gt; Node x subforest _ -&gt; error "The forest is NOT in Normal Form" appendForestToTree frst (Node x subforestX) = Node x $ appendForestToForest frst subforestX appendForestToForest :: Eq a =&gt; [Tree a] -&gt; [Tree a] -&gt; [Tree a] appendForestToForest [] frst = frst appendForestToForest frst [] = frst appendForestToForest frstY frstX = map (\ndx -&gt; appendForestToTree frstY ndx) frstX -- ============================== CONSTRUCTION ============================== -- These functions can selectively add nodes to the leaves of the target. growthTree :: (t -&gt; Forest t) -&gt; Tree t -&gt; Tree t growthTree f (Node x []) = Node x (f x) growthTree f (Node x subfrst) = Node x $ growthForest f subfrst growthForest :: (t -&gt; Forest t) -&gt; [Tree t] -&gt; [Tree t] growthForest f [] = [] growthForest f frst = map (growthTree f) frst -- ============================== LEAF'S VALUE MODIFICATION ============================== -- Thees functions nodify only the leaves of the target. fmapLeafsOfTree :: (a -&gt; a) -&gt; Tree a -&gt; Tree a fmapLeafsOfTree f (Node x []) = Node (f x) [] fmapLeafsOfTree f (Node x subfrst) = Node x $ fmapLeafsOfForest f subfrst fmapLeafsOfForest :: (a -&gt; a) -&gt; Forest a -&gt; Forest a fmapLeafsOfForest f [] = [] fmapLeafsOfForest f frst = map (fmapLeafsOfTree f) frst -- ============================== PRETTY PRINT ============================== -- Functions that are useful for values other than strings. showF :: Show a =&gt; [Tree a] -&gt; IO () showF = putStr . drawForest . map (fmap show) showT :: Show a =&gt; Tree a -&gt; IO () showT = putStr . drawTree . fmap show -- ============================== EXAMPLES ============================== tr1 = Node "John" [Node "friends" [Node "John" [], Node "Sally"[]] ,Node "cars" [Node "Laputa" [], Node "Pinto"[]] ,Node "motorbikes" [Node "Thunderbird"[]]] tr2 = Node "Mary" [Node "motorbikes" [Node"Varadero" []] ,Node "past holidays" [Node "Rome" [],Node "Sydney" []]] tr3 = Node "John" [Node "motorbikes" [Node"Vespa" []] ,Node "past holidays" [Node "Rome" [],Node "Paris" []]] tr4 = Node "John" [Node "friends" [Node "Mary" [], Node "Rick"[]] ,Node "past holidays" [Node "Rome" [], Node "London" []]] tr5 = Node "Frank" [Node "home" [Node "New York" []]] tr6 = Node "Sally" [Node "phone numbers" [Node "345-25-33" [], Node "898-38-234" []]] tr7 = Node "Rose" [Node "phone numbers" [Node "525-33-425" []]] tr8 = Node "Thunderbird" [Node "manufacturing company" [Node "Triumph Engineering"[]]] tr9 = Node "Varadero" [Node "manufacturing company" [Node "Honda" []]] fr1 = [tr1, tr2] fr2 = [tr4, tr5] fr3 = [tr6, tr7] fr4 = [tr8,tr9] ------------------------- ex1 = showF $ unionOfTwoForests fr1 fr2 ex2 = showF $ unionOfTwoForests fr1 fr2 ex3 = showF $ unionOfForests [fr1,fr2,fr3,fr4] ex4 = showF $ addForestToForest fr2 fr1 ex5 = showF $ addForestToForest fr1 fr2 ex6 = showF $ appendForestToForest fr4 fr1 ex7 = showF $ appendForestToForest fr3 fr1 ex10 = showF $ appendForestToForest (unionOfForests [fr3,fr4]) (unionOfForests [fr1,fr2]) ex11 = showF $ appendForestToForest (unionOfForests [fr3,fr4]) (unionOfForests [fr1,fr2,fr3,fr4]) countryOf x = case x of "Rome" -&gt; [Node "country" [Node "Italy" []]] "Paris" -&gt; [Node "country" [Node "France" []]] _ -&gt; [] ex20 = showT $ growthTree countryOf tr3 </code></pre>
[]
[ { "body": "<p>It looks like you might need some more testing. The function <code>isForestInNormalForm</code> is wrong, since it thinks the following forest is in normal form:</p>\n\n<pre><code>badfr1 = [Node \"x\" [Node \"y\" [], Node \"y\" []], Node \"z\" []]\n</code></pre>\n\n<p>and the function <code>toForestNormalForm</code> is wrong since if you apply it to:</p>\n\n<pre><code>badfr2 = [Node \"x\" [Node \"y\" [], Node \"y\" []], Node \"x\" [], Node \"z\" []]\n</code></pre>\n\n<p>you get a normalized forest with no <code>\"y\"</code> nodes.</p>\n\n<p>In general, a recursive function on a list structure that handles the singleton case specially:</p>\n\n<pre><code>foo [] = ...\nfoo [x] = ...\nfoo (x:xs) = ...\n</code></pre>\n\n<p>increases the change of making an error. In both of these broken functions, you are mishandling <code>x</code> in the <code>(x:xs)</code> case (forgetting to recurse in <code>isForestInFormalForm</code>, and forgetting it entirely in the <code>else</code> branch of your <code>toForestNormalForm</code>).</p>\n\n<p>For <code>isForestInNormalForm</code>, you should be able to drop the singleton case entirely and move its check into the general recursive case:</p>\n\n<pre><code>isForestInNormalForm :: Eq a =&gt; Forest a -&gt; Bool\nisForestInNormalForm [] = True\nisForestInNormalForm (Node x f : ndxs) =\n let (dups,others) = partition (\\(Node w _) -&gt; w == x) ndxs\n in case dups of\n [] -&gt; isForestInNormalForm f &amp;&amp; isForestInNormalForm others\n _ -&gt; False\n</code></pre>\n\n<p>However, <code>partition</code> isn't really necessary here. You just want to know if there are any duplicates. If there aren't then <code>ndxs</code> and <code>others</code> are equal anyway, so you don't need <code>partition</code> to create <code>others</code>. This gives an even clearer version:</p>\n\n<pre><code>isForestInNormalForm :: Eq a =&gt; Forest a -&gt; Bool\nisForestInNormalForm [] = True\nisForestInNormalForm (Node x f : ndxs) =\n if any (\\(Node w _) -&gt; w == x) ndxs\n then False\n else isForestInNormalForm f &amp;&amp; isForestInNormalForm ndxs\n</code></pre>\n\n<p>or simplified to:</p>\n\n<pre><code>isForestInNormalForm :: Eq a =&gt; Forest a -&gt; Bool\nisForestInNormalForm [] = True\nisForestInNormalForm (Node x f : ndxs) =\n all (\\(Node w _) -&gt; w /= x) ndxs &amp;&amp; isForestInNormalForm f &amp;&amp; isForestInNormalForm ndxs\n</code></pre>\n\n<p>But I favor writing a version that more directly implements the definition: a forest is in normal form if there are no duplicates in its top-most labels and all of the subtrees is in normal form. (At least, I <em>think</em> that's the definition you intend.) You can do this by first checking for duplicates and then recursively making sure the subtrees are in normal form:</p>\n\n<pre><code>isForestInNormalForm' :: Eq a =&gt; Forest a -&gt; Bool\nisForestInNormalForm' ts\n = noDuplicates (map rootLabel ts) &amp;&amp; all isTreeInNormalForm ts\n</code></pre>\n\n<p>You can write a <code>noDuplicates</code> that requires only <code>Eq</code> using <code>nub</code>:</p>\n\n<pre><code>noDuplicates :: Eq a =&gt; [a] -&gt; Bool\nnoDuplicates xs = nub xs == xs\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-04T18:48:57.853", "Id": "223522", "ParentId": "222223", "Score": "2" } } ]
{ "AcceptedAnswerId": "223522", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:21:27.133", "Id": "222223", "Score": "3", "Tags": [ "haskell", "tree", "api" ], "Title": "Haskell API for manipulating Tree/Forest" }
222223
<p>On an Internet forum a person came with their homework, to write Arkanoid in a console - it seemed they wanted someone to do their homework for them so I did not respond. However, I found the task interesting, especially when I broadened the scope of the assignment - so I wrote such arkanoid for my own entertainment. However, I don't really know C coding patterns so I'd be interested to know what more experienced devs think about my code.</p> <pre><code>#include &lt;curses.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;signal.h&gt; #include &lt;math.h&gt; const short brick_color = 1; const short other_color = 2; #define board_y_size 21 #define board_x_size 78 typedef enum { EMPTY, BRICK, BALL } content; typedef struct { unsigned lv; unsigned balls_left; bool running; content board[board_y_size][board_x_size]; int ball_y, ball_x; int racket_pos; int delta_y, delta_x; unsigned score; } game_data; void init_new_level(game_data* gd) { gd-&gt;lv++; if(gd-&gt;lv % 3 == 0) gd-&gt;balls_left++; gd-&gt;running = false; gd-&gt;racket_pos = 39; for(int y = 0; y &lt; board_y_size; y++) for(int x = 0; x &lt; board_x_size; x++) gd-&gt;board[y][x] = EMPTY; for(int y = 2; y &lt; board_y_size - 4; y++) for(int x = 2; x &lt; board_x_size - 2; x++) gd-&gt;board[y][x] = BRICK; gd-&gt;ball_y = board_y_size-1; gd-&gt;ball_x = gd-&gt;racket_pos; gd-&gt;board[gd-&gt;ball_y][gd-&gt;ball_x] = BALL; } void advance_ball(game_data* gd, int new_y, int new_x) { gd-&gt;board[gd-&gt;ball_y][gd-&gt;ball_x] = EMPTY; gd-&gt;board[new_y][new_x] = BALL; gd-&gt;ball_y = new_y; gd-&gt;ball_x = new_x; } void recover_from_miss(game_data* gd) { gd-&gt;racket_pos = 39; ball_found: advance_ball(gd, board_y_size-1, gd-&gt;racket_pos); } int start_level(game_data* gd, int input) { gd-&gt;delta_y = -1; if(input == KEY_LEFT) gd-&gt;delta_x = -1; else gd-&gt;delta_x = 1; gd-&gt;running = true; return (int)round(1000.0/pow(1.25, gd-&gt;lv-1)); } void y_bounce(game_data* gd) { gd-&gt;delta_y *= -1; } void x_bounce(game_data* gd) { gd-&gt;delta_x *= -1; } void flip(game_data* gd) { y_bounce(gd); x_bounce(gd); } void crush_bricks(game_data* gd, int y, int x) { if(y &gt;= 0 &amp;&amp; y &lt; board_y_size &amp;&amp; x &gt;= 0 &amp;&amp; x &lt; board_x_size &amp;&amp; gd-&gt;board[y][x] == BRICK) { gd-&gt;board[y][x] = EMPTY; gd-&gt;score++; } } bool is_out_of_board(int y) { return y &gt;= board_y_size; } bool is_blocked(game_data* gd, int y, int x) { if(y &lt; 0 || x &lt; 0 || x &gt;= board_x_size) return true; return gd-&gt;board[y][x] == BRICK; } bool normal_move(game_data* gd) { int old_y = gd-&gt;ball_y, old_x = gd-&gt;ball_x; int new_y = old_y + gd-&gt;delta_y; int new_x = old_x + gd-&gt;delta_x; if(is_out_of_board(new_y)) { gd-&gt;running = false; gd-&gt;balls_left--; return false; } else { int actual_new_x = new_x, actual_new_y = new_y; if(is_blocked(gd, old_y, new_x) &amp;&amp; is_blocked(gd, new_y, old_x) || is_blocked(gd, new_y, new_x) &amp;&amp; !is_blocked(gd, old_y, new_x) &amp;&amp; !is_blocked(gd, new_y, old_x)) { flip(gd); actual_new_x = old_x; actual_new_y = old_y; } else if(is_blocked(gd, old_y, new_x)) { actual_new_x = old_x; x_bounce(gd); } else if(is_blocked(gd, new_y, old_x)) { actual_new_y = old_y; y_bounce(gd); } advance_ball(gd, actual_new_y, actual_new_x); crush_bricks(gd, old_y, new_x); crush_bricks(gd, new_y, old_x); crush_bricks(gd, new_y, new_x); } return true; } bool collide_with_racket(game_data* gd) { int old_y = gd-&gt;ball_y, old_x = gd-&gt;ball_x; int new_y = old_y + gd-&gt;delta_y; int new_x = old_x + gd-&gt;delta_x; if(old_y != board_y_size-1 || new_y != board_y_size) return false; if(new_x == gd-&gt;racket_pos-1 || new_x == gd-&gt;racket_pos-2 &amp;&amp; gd-&gt;delta_x &lt; 0) { y_bounce(gd); new_x = gd-&gt;racket_pos+1; gd-&gt;delta_x = 1; new_y = old_y-1; advance_ball(gd, new_y, new_x); return true; } else if(new_x == gd-&gt;racket_pos+1 || new_x == gd-&gt;racket_pos + 2 &amp;&amp; gd-&gt;delta_x &gt; 0) { y_bounce(gd); new_x = gd-&gt;racket_pos-1; gd-&gt;delta_x = -1; new_y = old_y-1; advance_ball(gd, new_y, new_x); return true; } else if(new_x == gd-&gt;racket_pos) { y_bounce(gd); new_x += gd-&gt;delta_x; new_y = old_y-1; advance_ball(gd, new_y, new_x); return true; } return false; } bool no_bricks_left(game_data* gd) { for(int y = 0; y &lt; board_y_size; y++) for(int x = 0; x &lt; board_x_size; x++) if(gd-&gt;board[y][x] == BRICK) return false; gd-&gt;running = false; return true; } bool process_turn(game_data* gd) { if(!collide_with_racket(gd)) { if(!normal_move(gd)) return false; return no_bricks_left(gd); } return false; } void move_racket(game_data* gd, int racket_move) { if(gd-&gt;racket_pos + racket_move &gt;= 1 &amp;&amp; gd-&gt;racket_pos + racket_move &lt; board_x_size-1) { gd-&gt;racket_pos+=racket_move; } } void print_game_data(game_data const* gd) { for(int x = 0; x &lt; 80; x++) { mvaddch(0, x, ' '); mvaddch(23, x, ' '); } mvprintw(0, 3, "Lv: %u", gd-&gt;lv); mvprintw(0, 65, "Balls: %u", gd-&gt;balls_left); mvprintw(0, 52, "Score: %u", gd-&gt;score); if(!gd-&gt;running) { attron(A_BLINK); if(gd-&gt;balls_left) mvprintw(0, 16, "PRESS LEFT OR RIGHT TO START"); else mvprintw(0, 25, "GAME OVER"); attroff(A_BLINK); } mvaddch(1, 0, ACS_ULCORNER); mvaddch(1, 79, ACS_URCORNER); for(int y = 2; y &lt; 24; y++) { mvaddch(y, 0, ACS_VLINE); mvaddch(y, 79, ACS_VLINE); } for(int x = 1; x &lt; 79; x++) mvaddch(1, x, ACS_HLINE); const int y_offset = 2; const int x_offset = 1; for(int y = 0; y &lt; board_y_size; y++) for(int x = 0; x &lt; board_x_size; x++) { chtype char_to_print; switch(gd-&gt;board[y][x]) { case EMPTY: char_to_print = ' '; break; case BRICK: char_to_print = ACS_CKBOARD | COLOR_PAIR(brick_color); break; case BALL: char_to_print = 'O'; break; } mvaddch(y+y_offset, x+x_offset, char_to_print); } const int racket_print_pos = gd-&gt;racket_pos+x_offset; mvaddch(23, racket_print_pos-1, ACS_HLINE); mvaddch(23, racket_print_pos, ACS_TTEE); mvaddch(23, racket_print_pos+1, ACS_HLINE); refresh(); } void game_loop(game_data* gd) { int sleep_time; bool advance_lv = true; while(true) { if(!gd-&gt;running) { nodelay(stdscr, FALSE); if(gd-&gt;balls_left) if(advance_lv) init_new_level(gd); else recover_from_miss(gd); print_game_data(gd); int input; do input = getch(); while(!(gd-&gt;balls_left &amp;&amp; (input == KEY_LEFT || input == KEY_RIGHT))); sleep_time = start_level(gd, input); nodelay(stdscr, TRUE); process_turn(gd); } else { print_game_data(gd); napms(sleep_time); int racket_move = 0; int input; while((input = getch()) != ERR) if(input == KEY_LEFT) racket_move = -1; else if(input == KEY_RIGHT) racket_move = 1; else if(input == KEY_DOWN) racket_move = 0; move_racket(gd, racket_move); advance_lv = process_turn(gd); } } } void cleanup(int signal) { endwin(); exit(0); } int main() { struct sigaction cleanup_action = { .sa_handler = cleanup, .sa_flags = 0 }; sigfillset(&amp;cleanup_action.sa_mask); sigaction(SIGINT, &amp;cleanup_action, NULL); initscr(); cbreak(); keypad(stdscr, TRUE); noecho(); nonl(); curs_set(0); start_color(); nodelay(stdscr, TRUE); init_pair(brick_color, COLOR_RED, COLOR_WHITE); init_pair(other_color, COLOR_BLACK, COLOR_WHITE); attrset(COLOR_PAIR(other_color)); game_data gd = {.lv = 0, .balls_left = 3, .score = 0}; game_loop(&amp;gd); return 0; } </code></pre> <p>I did spot two flaws in my code (DRY violations) and hopefully corrected them before posting it here - so I did take time to make it (reasonably) clean. Still, I'm sure the code is not ideal - what are the flaws I did not spot? (the game seems to be working)</p> <p>There is still one flaw I'm aware of but that I consciously chose not to fix - namely, I'm not checking if the functions I call do not return errors. However, I think that error-checking in C is so tedious and the probability that these calls return errors is so low on any 'reasonable' platform that I thought it was simply not practical to do error-checking: the benefits would not justify cluttering the code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:27:51.300", "Id": "430017", "Score": "0", "body": "Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Could you add some context or description about your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:31:28.053", "Id": "430019", "Score": "2", "body": "@dfhwze This is the context: On an Internet forum a person came with their homework, to write Arkanoid in a console - it seemed they wanted someone to do their homework for them so I did not respond. However, I found the task interesting, especially when I broadened the scope of the assignment - so I wrote such arkanoid for my own entertainment. However, I don't really know C coding patterns so I'd be interested to know what more exprienced devs think about my code. This is kind of the whole context" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:33:25.240", "Id": "430020", "Score": "0", "body": "@dfhwze edited Q...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-27T16:56:17.360", "Id": "486818", "Score": "0", "body": "You might want to fix your `SIGINT` handler to not call `exit` but instead [raise `SIGINT` anew](https://www.cons.org/cracauer/sigint.html). This improves the behaviour when your program is called from a script or similar and is just good programming style." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:16:33.327", "Id": "504602", "Score": "0", "body": "For those of us who don't know the game, can you summarise it for us? I see `enum { EMPTY, BRICK, BALL }` and wonder if it's a Breakout-style game?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T01:38:18.767", "Id": "504633", "Score": "0", "body": "@TobySpeight The way I understand terminology \"breakout\" and \"arkanoid\" are synonymous." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-07T09:41:46.470", "Id": "504651", "Score": "0", "body": "Thanks @gaazkam - that helps." } ]
[ { "body": "<p>Enable more compiler warnings. With <code>gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion</code> I see, amongst others:</p>\n<pre class=\"lang-none prettyprint-override\"><code>222224.c: In function ‘recover_from_miss’:\n222224.c:57:1: warning: label ‘ball_found’ defined but not used [-Wunused-label]\n ball_found:\n ^~~~~~~~~~\n222224.c: In function ‘cleanup’:\n222224.c:331:18: warning: unused parameter ‘signal’ [-Wunused-parameter]\n void cleanup(int signal)\n ~~~~^~~~~~\n222224.c: At top level:\n222224.c:337:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n int main()\n ^~~~\n222224.c: In function ‘main’:\n222224.c:339:10: error: variable ‘cleanup_action’ has initializer but incomplete type\n struct sigaction cleanup_action = { .sa_handler = cleanup, .sa_flags = 0 };\n ^~~~~~~~~\n</code></pre>\n<p>Fixing these would immediately improve the program. (That last one requires us to set <code>_POSIX_C_SOURCE</code> to an appropriate value before including <code>&lt;signal.h&gt;</code>; that's easiest done as a command-line argument such as <code>-D_POSIX_C_SOURCE</code> or <code>-D_GNU_SOURCE</code>).</p>\n<p>Please use <code>ALL_CAPS</code> for macros. Macros need to be immediately recognisable so that we can treat them with extra caution, as they don't act like variables.</p>\n<p>There's a lot of naked constants sprinkled over the code. For example,</p>\n<blockquote>\n<pre><code>gd-&gt;racket_pos = 39;\n</code></pre>\n</blockquote>\n<p>Is it coincidental that this is <code>board_x_size / 2</code>? Or is it intrinsically related?</p>\n<p>And:</p>\n<blockquote>\n<pre><code> if(gd-&gt;lv % 3 == 0)\n gd-&gt;balls_left++;\n</code></pre>\n</blockquote>\n<p>That's baking the game's parameters into its code; a more flexible game would allow such things to be set up as gameplay configuration.</p>\n<p>We could do with some targeted comments to help readers (including future-you) to understand what values mean. For example, we have:</p>\n<blockquote>\n<pre><code>int start_level(game_data* gd, int input)\n{\n /* ... */\n return (int)round(1000.0/pow(1.25, gd-&gt;lv-1));\n}\n</code></pre>\n</blockquote>\n<p>It's not obvious why <code>start_level()</code> should even return a value, and completely opaque as to what the value might mean. I had to find the calling code to discover that it's a time delay, and then look up the documentation of <code>napms()</code> to discover the units. I'd argue that would be better obtained by a separate function, e.g.</p>\n<pre><code>int millis_per_frame(const game_data *game);\n</code></pre>\n<p>That immediately documents what it does, rather than hiding in a return value from an unrelated function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-06T16:40:10.140", "Id": "255693", "ParentId": "222224", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:25:34.017", "Id": "222224", "Score": "8", "Tags": [ "beginner", "c", "game", "console", "posix" ], "Title": "Console arkanoid in C" }
222224
<p>Im trying to access the attribute directly in the parent component, that why Im using the <code>ref</code> method. here an example of why Im trying to achieve: <a href="https://stackblitz.com/edit/react-lupsr2" rel="nofollow noreferrer">https://stackblitz.com/edit/react-lupsr2</a> Im accessing it using some <code>for in</code> loop currently, so far it works, although I think there is probably more efficient way to do the job. to me, using a <code>for in</code> loop is probably very expensive, and there is probably other way, more ecologic to achieve the end. </p> <p>Here my react snippet: </p> <pre><code>class App extends Component { constructor(prop) { super(prop); this.children=React.createRef() this.state = { name: 'React' }; } componentDidMount(){ for (var key in this.children.current) { if(key.includes("__reactEventHandlers")) // ACCESS OBJECT HERE return console.log("in componentdidmount for in:", this.children.current[key].test) } } render() { console.log("this.children in render: ", this.children) return ( &lt;div&gt; &lt;Hello name={this.state.name} /&gt; &lt;button onClick= {()=&gt; console.log("children: ", this.children)} &gt; click to display children&lt;/button&gt; &lt;p&gt; Start editing to see some magic happen :) &lt;/p&gt; &lt;div ref={this.children} test={awesomeObject} /&gt; &lt;/div&gt; ); } } </code></pre> <p>any hint would be great, thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T14:56:23.390", "Id": "430291", "Score": "0", "body": "In React data is passed from Parent to Child. A child component should **not** have direct access to its parent. It's anti-pattern. That being said, I do not understand what you're attempting to achieve. Could you elaborate more please ? There is always a better way than via the Parent (Provider/Context, Mobx, etc..)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T15:05:47.680", "Id": "430781", "Score": "0", "body": "@kemicofa hi and thanks you for your answer. Im trying to make a component having a specific style inside the parent. So I would register some variable to allow them to work with parent. Using a sub-component could be an option" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:33:47.580", "Id": "222226", "Score": "2", "Tags": [ "javascript", "html", "react.js", "jsx" ], "Title": "Access object in an custom attribute efficiently" }
222226
<p>I am <strong>not</strong> looking for a detailed review of this code as I am aware it is very inefficient. The main reason for posting this is to see if there is a better way to achieve my goal (I am certain there must be)</p> <p>I have created code to find the fewest number of dice rolls that would permit someone to move from the first to last square on a snakes and ladders board. The player wins if they land on or go beyond the final square on the board. They start off the board at position -1.</p> <p>My approach uses recursion so is OK for small boards. The moment the board reaches a size of 30+ it takes far too long to generate the solution. </p> <p>Is there a better way to solve this problem</p> <pre><code>"""Module works out fastest way to traverse a snakes and ladders board""" def roll_dice(position, roll_number, number_squares, snakes, ladders, list_moves=[]): """Roll the dice and then work out if the player can climb a ladder / has won""" if position in ladders: position = ladders[position] if position &gt;= number_squares - 1: list_moves.append(roll_number) return for i in range(1, 7): #For each position roll the dice 6 times if position + i in snakes: continue # Forbid a dice-roll that lands on a snake roll_dice(position + i, roll_number + 1, number_squares, snakes, ladders) return list_moves def minimum_moves(number_squares, snakes={}, ladders={}): """Returns the minimum number of moves starting from position 0 for a board of size n snakes and ladders are both dictionaries containing the starting point as the key and end point as the value""" # Initialise board # The player starts off the board at position -1 list_moves = roll_dice(-1, 0, number_squares, snakes, ladders) print(f"Board is traversable in {min(list_moves)} moves") if __name__ == "__main__": NUMBER_SQUARES = 25 SNAKES = {21:0, 19:9, 14: 2, 18:5} LADDERS = {2: 21, 4:9, 10:20, 17:23} minimum_moves(NUMBER_SQUARES, SNAKES, LADDERS) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:18:11.613", "Id": "430042", "Score": "2", "body": "Here is my solution if need be - https://repl.it/repls/StainedMonthlyOutput. (By the way, nice question!)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:24:44.160", "Id": "430045", "Score": "0", "body": "It's okay. I have provided a link to my first solution above if need be. I'm glad it helped you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T21:55:24.633", "Id": "430070", "Score": "0", "body": "[Follow-up question](https://codereview.stackexchange.com/q/222248)" } ]
[ { "body": "<p>Don't use mutable default arguments. If you need to default to a list then default to <code>None</code> and then change to an empty list.</p>\n\n<p>Take the following example code:</p>\n\n<pre><code>&gt;&gt;&gt; def example_list_builder(value, list_=[]):\n list_.append(value)\n return list_\n\n&gt;&gt;&gt; example_list_builder(1)\n[1]\n&gt;&gt;&gt; example_list_builder(2)\n[1, 2]\n</code></pre>\n\n<p>This makes <code>list_</code> a really poorly defined singleton variable, that can't be accessed globally.</p>\n\n<hr>\n\n<p>Your code looks like it's something like <span class=\"math-container\">\\$O(6^n)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the size of the board.</p>\n\n<p>You can instead make it <span class=\"math-container\">\\$O(l^2)\\$</span> where <span class=\"math-container\">\\$l\\$</span> is <code>LADDERS</code> and <code>SNAKES</code>.</p>\n\n<p>To improve your code, you should remove the simulation and instead only work with the <code>LADDERS</code> and <code>SNAKES</code> variables.</p>\n\n<p>For each snake and ladder you should traverse it, and then traverse the snake or ladder after this. You should note the distance, there are two ways to do this:</p>\n\n<ol>\n<li>Least tiles visited.</li>\n<li>Least turns taken.</li>\n</ol>\n\n<p>For the latter, you'll have to check for collisions with other snakes and ladders.</p>\n\n<p>You should take snakes into account, as the fastest path for the following is 4 turns:</p>\n\n<pre><code>NUMBER_SQUARES = 1000\nLADDERS = {1: 502, 501: 999}\nSNAKES = {503: 500}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:05:46.690", "Id": "430037", "Score": "2", "body": "Thanks for the suggestions. I will see if I can come up with a faster solution using these ideas." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:35:43.640", "Id": "430047", "Score": "0", "body": "How would you code the ```list_moves``` then so it isn't mutable but still returns all the values to the ```minimum_moves``` function? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:37:05.087", "Id": "430048", "Score": "2", "body": "@EML `def fn(value=None): if value is None: value = []; ...` or `def fn(value=None): value = value or []; ...`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:43:24.040", "Id": "430050", "Score": "0", "body": "After implementing this, I got ```ValueError: min() arg is an empty sequence```. I pass the list_moves between stacks" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:02:08.153", "Id": "222231", "ParentId": "222228", "Score": "7" } }, { "body": "<blockquote>\n<pre><code> continue # Forbid a dice-roll that lands on a snake\n</code></pre>\n</blockquote>\n\n<p>This may prevent finding the shortest path - it's possible to imagine a board with two long ladders, where the first ladder passes the bottom of the second ladder, but a snake descends from after the top of the first ladder to before the bottom of the second ladder. Be careful: if you do follow snakes, you'll need some logic to get you out of loops.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>if __name__ == \"__main__\":\n</code></pre>\n</blockquote>\n\n<p>This is great - good work!</p>\n\n<hr>\n\n<p>What you probably want to do is to convert the board to a <em>directed graph</em> whose edges are straight runs of board and whose nodes are the destinations of the snakes and ladders.</p>\n\n<p>It might be possible to work with a map of the board, with all the squares containing the number of moves until the end:</p>\n\n<ul>\n<li>Initially, all squares contain <code>None</code>.</li>\n<li>Now work backwards from the end position, marking how many die throws are necessary to reach the end from there (the first few squares will be <code>1</code>, for example). But don't write anything at the top of a snake or bottom of a ladder.</li>\n<li>Whenever you reach a square that's already marked, check to see if it's already the same or less than you're about to write to it; if so, then stop exploring that branch.</li>\n<li>If you reach the top of a ladder, you can mark the bottom square with the same number as the top square.</li>\n<li>If you reach the bottom of a snake, the converse applies - mark the top of it with the same number as the bottom.</li>\n<li>When you've completed exploring all branches, the number in the beginning square will be the minimum number of turns needed to reach the top.</li>\n</ul>\n\n<p>It should become obvious that the distinction between snakes and ladders is unimportant here - they just have beginnings and ends, so can be combined into a single list, or just be properties of their beginning and end squares.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:35:40.820", "Id": "430064", "Score": "0", "body": "Thanks. Yes that was one of the reasons I avoided snakes all together. I could imagine an infinite loop developing and had no idea how I would avoid this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:36:28.520", "Id": "430065", "Score": "0", "body": "Having said this, I think the above method is very bad. I agree that a directed graph is actually a really smart idea and I have, in fact, been trying to build one as I realised this would be a really smart way to solve the problem. Thanks for suggesting this too as it supports my hypothesis" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:43:55.643", "Id": "430066", "Score": "1", "body": "To be honest, I mentioned the directed graph and then realised that just labelling the squares is going to be easier, given that we need to deal with moves that skip over the starts of shortcuts. I'd go with the latter option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T21:29:38.740", "Id": "430069", "Score": "0", "body": "Thanks for this. I had basically finished my directed graph code and as this is actually something I am not used to writing, I think getting feedback on this would be most helpful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:30:05.840", "Id": "430112", "Score": "0", "body": "I'm curious, how did you simplify `position >= number_squares - 1` to `position > number_squares`? Is there extra logic somewhere in the given code that's being rolled into this case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:55:21.440", "Id": "430118", "Score": "2", "body": "@muru: In a word: *mistakenly* :-( I've edited to remove my error!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:18:11.473", "Id": "222244", "ParentId": "222228", "Score": "5" } } ]
{ "AcceptedAnswerId": "222231", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:56:28.240", "Id": "222228", "Score": "5", "Tags": [ "python", "algorithm", "time-limit-exceeded", "pathfinding" ], "Title": "Fastest path on a snakes and ladders board" }
222228
<p>Below is a segment of a game I am writing to stay in practice with my Java. </p> <p><strong>EDIT</strong> The class this method is in is the Encounter class. This class just manages the encounter between the player and an enemy, and the other methods are victory() and defeat(), which add gold/experience when player wins, and removes gold when player loses.</p> <p>There are two ways I am thinking of implementing a combat system, but I am not sure which path is more efficient. The code works perfectly fine; I am only inquiring about the efficiency:</p> <p><strong>EDIT 2</strong> Included the entire class</p> <p><strong>Option 1</strong></p> <pre><code>import java.util.Scanner; public class Encounter { private static Scanner sc; private static Player player; private static Enemy enemy; public static void manage(Player p, Enemy e) { player = p; enemy = e; sc = new Scanner(System.in); System.out.println("You are fighting a " + enemy.getName() + "!"); while(player.getHealth() &gt; 0 &amp;&amp; enemy.getHealth() &gt; 0) { System.out.println(player.getName() + "'s Health/Mana: " + player.getHealth() + "/" + player.getMana()); System.out.println(enemy.getName() + "'s' Health/Mana: " + enemy.getHealth() + "/" + enemy.getMana()); Ability playerAbility = selectAbility(); //Player attacks enemy =&gt; Enemy loses health =&gt; player loses mana enemy.subtractHealth(playerAbility.getDamage()); player.subtractMana(playerAbility.getManaCost()); //Enemy attacks player =&gt; Player loses health player.subtractHealth(enemy.attackPlayer()); } if(player.getHealth() &lt;= 0) { defeat(); } else if(enemy.getHealth() &lt;= 0) { victory(); } } private static void defeat() { System.out.println("======================="); System.out.println("You died to " + enemy.getName() + "!"); System.out.println("======================="); //Handle death here player.deathSubtraction(); player.resetHealthMana(); } private static void victory() { System.out.println("You defeated " + enemy.getName() + "!"); //Handle experience/gold/item(s) here player.addExperience(enemy.getExperience()); player.addGold(enemy.getGold()); player.checkLevelUp(player); displayStats(); player.resetHealthMana(); System.out.println("Press enter to continue"); sc.nextLine(); } private static Ability selectAbility() { player.displayMoves(); while(true) { String input = sc.nextLine(); for(Ability ability : player.getAbilities()) { if(input.equalsIgnoreCase(ability.getName()) &amp;&amp; ability.getManaCost() &lt; player.getMana()) { return ability; } } System.out.println("Not a valid move/Not enough mana! Select again!"); } } private static void displayStats() { System.out.println("============================"); System.out.println("Current Level: " + player.getLevel()); System.out.println("Current Experience: " + player.getExperience() + "/100"); System.out.println("Current Gold: " + player.getGold()); System.out.println("============================"); } } </code></pre> <p><strong>Option 2</strong></p> <pre><code>import java.util.Scanner; public class Encounter { private static Scanner sc; private static Player player; private static Enemy enemy; public static void manage(Player p, Enemy e) { player = p; enemy = e; sc = new Scanner(System.in); System.out.println("You are fighting a " + enemy.getName() + "!"); while(true) { System.out.println(player.getName() + "'s Health/Mana: " + player.getHealth() + "/" + player.getMana()); System.out.println(enemy.getName() + "'s' Health/Mana: " + enemy.getHealth() + "/" + enemy.getMana()); Ability playerAbility = selectAbility(); //Player attacks enemy =&gt; Enemy loses health =&gt; player loses mana enemy.subtractHealth(playerAbility.getDamage()); player.subtractMana(playerAbility.getManaCost()); //Enemy attacks player =&gt; Player loses health player.subtractHealth(enemy.attackPlayer()); if(player.getHealth() &lt;= 0) { defeat(); break; } else if(enemy.getHealth() &lt;= 0) { victory(); break; } } } private static void defeat() { System.out.println("======================="); System.out.println("You died to " + enemy.getName() + "!"); System.out.println("======================="); //Handle death here player.deathSubtraction(); player.resetHealthMana(); } private static void victory() { System.out.println("You defeated " + enemy.getName() + "!"); //Handle experience/gold/item(s) here player.addExperience(enemy.getExperience()); player.addGold(enemy.getGold()); player.checkLevelUp(player); displayStats(); player.resetHealthMana(); System.out.println("Press enter to continue"); sc.nextLine(); } private static Ability selectAbility() { player.displayMoves(); while(true) { String input = sc.nextLine(); for(Ability ability : player.getAbilities()) { if(input.equalsIgnoreCase(ability.getName()) &amp;&amp; ability.getManaCost() &lt; player.getMana()) { return ability; } } System.out.println("Not a valid move/Not enough mana! Select again!"); } } private static void displayStats() { System.out.println("============================"); System.out.println("Current Level: " + player.getLevel()); System.out.println("Current Experience: " + player.getExperience() + "/100"); System.out.println("Current Gold: " + player.getGold()); System.out.println("============================"); } } </code></pre> <p>I am unsure if I should just break when the conditions are met, or have the condition be evaluated in the <code>while</code> loop. I feel that having <code>while(true)</code> can avoid any bugs, and a simple <code>break</code> will ensure that it exits the loop. Any and all suggestions are appreciated and considered.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T17:44:37.650", "Id": "430054", "Score": "0", "body": "Please provide some more context to this code. What class does it appear in, and what else does the class do? (The `player = p` stuff at the top of the function looks suspiciously bad.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T19:33:10.257", "Id": "430058", "Score": "0", "body": "@200_success Added more clarification" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T19:36:33.027", "Id": "430059", "Score": "0", "body": "I would prefer that you actually show the code. I believe that the design of the class is fundamentally flawed. As @Martin's answer says, `static` shouldn't be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:12:30.893", "Id": "430073", "Score": "0", "body": "@200_success Included entire class" } ]
[ { "body": "<ul>\n<li>You've used a readable idiomatic Java naming convention.</li>\n<li>There is no point reassign p to player and e to enemy, use the full name on entry, make the parameters <code>final</code>.</li>\n<li>Static methods are a code smell in OO programming, they will result is tightly coupled code. They should be studiously avoided until you know the specific circumstances that make them necessary.</li>\n<li>Follow the <em><a href=\"https://martinfowler.com/bliki/TellDontAsk.html\" rel=\"nofollow noreferrer\">tell don't ask idiom</a></em>, tell the player to attack the enemy and tell the enemy to attack the player which will minimise coupling if you use an interface.</li>\n<li>Never use <code>while(true)</code>. In this case I would use a <code>do { .. } while(...)</code> loop since you always want this loop to be performed once. Use <code>while(...)</code> when it could be <code>0..N</code> and <code>do { .. } while(...)</code> when the loop is <code>1..N</code>.\n\n<ul>\n<li>Use a single condition, probably the player's input or battling continues for your loop control for clarity.</li>\n</ul></li>\n<li>Put the health display inside the <code>Player</code> and <code>Enemy</code> classes (or a common base class) and show it during players and enemy turn.</li>\n<li>Pass the gold &amp; experience as a parameter to the victory method on the player.</li>\n</ul>\n\n<p>Something like this:</p>\n\n<pre><code>public void manage(Player player, Enemy enemy) {\n boolean battling = true; \n do {\n player.turn(enemy);\n enemy.turn(player);\n battling = player.isAlive() &amp;&amp; enemy.isAlive();\n } while(battling);\n }\n}\n</code></pre>\n\n<ul>\n<li>In the <code>Player</code> and <code>Enemy</code> classes have a <code>Opponent</code> interface (follow the <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Interface Segregation Principle</a>) that includes a turn method to makes attack and takes damage. The instances of Player and Enemy sends damage to the opponent and reduces their karma. Getting and Setting is a code smell that increases coupling.</li>\n</ul>\n\n<p>e.g.</p>\n\n<pre><code>public turn(Opponent character) { \n displayStatus();\n attack = chooseAttack();\n reduceMana(attack);\n character.damage(attack);\n}\n\npublic damage(Attack attack) { \n hp - hp - attack.damage;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T19:38:28.803", "Id": "430060", "Score": "0", "body": "There should be no need for your `battling` flag variable, if you structure the loop properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-26T13:03:58.870", "Id": "431888", "Score": "0", "body": "I regard clarity as a first class nfr of my team members." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T18:38:46.320", "Id": "222239", "ParentId": "222229", "Score": "3" } } ]
{ "AcceptedAnswerId": "222239", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T15:43:54.727", "Id": "222229", "Score": "5", "Tags": [ "java", "performance", "comparative-review", "battle-simulation" ], "Title": "Two ways of implementing a combat system" }
222229
<p>I am trying to write a method that takes in a <code>String</code> and returns an <code>Object</code>. The catch is I want to parse it to one of a few different data-types, and if that fails, return the original <code>String</code>. I currently have the code below. Is this the best way to handle what I want or is there something obvious that I'm missing?</p> <pre><code>private static Object tryParse(String str) { try { return Long.parseLong(str); } catch (NumberFormatException ex1) { try { return Double.parseDouble(str); } catch (NumberFormatException ex2) { return str; } } } </code></pre> <p>EDIT: I made a tweak that I think should improve performance a bit since I only need to check for longs, doubles, and Strings.</p> <pre><code>private static Object tryParse(String str) { try { Double d = Double.parseDouble(str); if (d % 1 == 0) { return d.longValue(); } return d; } catch (NumberFormatException ex1) { return str; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T19:20:26.147", "Id": "430057", "Score": "1", "body": "Your second implementation will return a wrong value for `\"1e30\"`, which is an integer number, but too large for `long`." } ]
[ { "body": "<p>Your second code, while might be slightly more efficient than the first due to the avoidance of the second <code>try ... catch</code> inside the first, has two bugs:</p>\n\n<p>First, if <code>str</code> contains a value greater than <span class=\"math-container\">\\$2^{63}-1\\$</span> or less than <span class=\"math-container\">\\$-2^{63}\\$</span>, while it is an integer value (<code>d % 1 == 0</code> will be <code>true</code>), it cannot be expressed as a <code>long</code>, so <code>d.longValue()</code> will discard the upper bits.</p>\n\n<p>Second, if <code>str</code> contains a value which can be parsed as a <code>Long</code>, but has a magnitude greater than <span class=\"math-container\">\\$2^{52}\\$</span>, parsing it as a <code>Double</code> will discard some of the low-order bits.</p>\n\n<pre><code>jshell&gt; Double d = Double.parseDouble(\"10000000000000123\");\nd ==&gt; 1.0000000000000124E16\n\njshell&gt; d.longValue()\n$2 ==&gt; 10000000000000124\n\njshell&gt; Long.parseLong(\"10000000000000123\");\n$3 ==&gt; 10000000000000123\n</code></pre>\n\n<hr>\n\n<p>The statements <code>return Long.parseLong(str)</code> and <code>return Double.parseDouble(str)</code> may be doing more work than necessary. These methods return a <code>long</code> and a <code>double</code>, respectively, which then need to be auto-boxed into <code>Long</code> and <code>Double</code>. You should instead use <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Long.html#valueOf(java.lang.String)\" rel=\"nofollow noreferrer\"><code>Long.valueOf(str)</code></a> and <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Double.html#valueOf(java.lang.String)\" rel=\"nofollow noreferrer\"><code>Double.valueOf(str)</code></a> which return already boxed values.</p>\n\n<hr>\n\n<p>I would write this code like:</p>\n\n<pre><code>private static Object tryParse(String str) {\n try {\n return Long.valueOf(str);\n } catch (NumberFormatException ex) { /* no-op */ }\n\n try {\n return Double.valueOf(str);\n } catch (NumberFormatException ex) { /* no-op */ }\n\n return str;\n}\n</code></pre>\n\n<p>... which avoids the nested <code>try-catch</code> blocks, so can easily be extended to several other types, possibly even looping over a collection of parsers:</p>\n\n<pre><code>private static Object tryParse(String str) {\n for (Parser parser : parsers) { \n try {\n return parser.valueOf(str);\n } catch (NumberFormatException ex) {\n /* no-op */\n }\n }\n\n return str;\n}\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>private static Object tryParse(String str) {\n for (Parser parser : parsers) { \n Optional&lt;Object&gt; value = parser.valueOf(str);\n if (!value.empty()) {\n return value.get();\n }\n }\n\n return str;\n}\n</code></pre>\n\n<p>Implementation of <code>Parser</code>, and its instances, left as exercise to student.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:49:30.150", "Id": "430067", "Score": "0", "body": "Oh wow, thanks a ton for the detailed answer. I didn't consider either of those bugs as possibilities, but now that you mention them it does make perfect sense. I'm probably going to go with the first of your three recommended solutions just because my co-workers often complain about my over-engineering of things and that Parser system might get some complaints (even though it's definitely the most elegant system). Thank you so much!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T19:23:32.513", "Id": "222241", "ParentId": "222234", "Score": "3" } } ]
{ "AcceptedAnswerId": "222241", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T16:33:58.293", "Id": "222234", "Score": "5", "Tags": [ "java", "parsing" ], "Title": "Try Parse Multiple Types" }
222234
<p>In F# the <a href="https://fsharpforfunandprofit.com/rop/" rel="nofollow noreferrer">Railway Oriented Programming</a> pattern can be implemented synchronously using the <code>Result&lt;'t,'terr&gt;</code> type as result value for functions, so they can be foreward piped like:</p> <pre><code>let result = func1 |&gt; Result.bind func2 |&gt; Result.bind func3 |&gt; Result.bind func4 </code></pre> <p>I would like to implement the same pattern for functions returning <code>Async&lt;Result&lt;'t,'terr&gt;&gt;</code>, so I can pipe them like</p> <pre><code>let resultAsync = func1Async |&gt; Result.bindAsync func2Async |&gt; Result.bindAsync func3Async |&gt; Result.bindAsync func4Async </code></pre> <p>and execute that in a non blocking manner like</p> <pre><code>let result = resultAsync |&gt; Async.RunSynchronously match result with | Ok(value) -&gt; todoHandleOk values | Error(msg) -&gt; todoHandleError msg </code></pre> <p>To accomplish that I have implemented <code>Result.bindAsync</code> as an extension:</p> <pre><code>module Result = let bindAsync&lt;'t,'s,'terr&gt; (binder:'t -&gt; Async&lt;Result&lt;'s,'terr&gt;&gt;) (result:Async&lt;Result&lt;'t,'terr&gt;&gt;) : Async&lt;Result&lt;'s,'terr&gt;&gt; = async { let! res = result match res with | Ok(value) -&gt; return! binder value | Error(err) -&gt; return Error(err) } </code></pre> <p>As shown it mimic the "normal" <code>bind</code> operation for a computational expression but encapsulated in a <code>async</code> workflow expression and hence returning an <code>Async&lt;Result&lt;'s,'terr&gt;&gt;</code>. The <code>result</code> argument is the Async "result" from the previous function which is executed to get its materialized result (<code>res</code>) before it can be used either as argument to the <code>binder</code> which is the next step on the successful track or returned as an error if unsuccessful.</p> <hr> <p><strong>Test Case</strong></p> <p>The below is a console test case with some functions that can be bound using <code>Result.bindAsync</code> as shown above.</p> <pre><code>module AsyncBindTests = let anotherProcAsync = async { for i in 1..Int32.MaxValue do printfn "Another Proc is at: %d" i do! Async.Sleep 800 } let rand = new Random(); let collectValuesAsync = async { printfn "Collecting Values..." let count = rand.Next(10, 15) let values = List.init count ( fun i -&gt; async { let x = rand.Next(1, 1000) printfn "Value Collected: %d" x do! Async.Sleep 500 return x } |&gt; Async.RunSynchronously ) printfn "Values Collected" match (values |&gt; List.sum) % 3 with | 0 -&gt; return Error("Values sum is a multiple of 3") | _ -&gt; return Ok(values) } let groupValuesAsync values = async { printfn "Grouping Values..." let sizeSum = values |&gt; List.groupBy (fun v -&gt; v % 3) |&gt; List.sumBy (fun (k, lst) -&gt; lst |&gt; List.length) do! Async.Sleep 2000 match sizeSum % 3 with | 0 -&gt; return Error("Sum of Group Sizes is a multiple of 3") | _ -&gt; return Ok (sizeSum, values) } let crossSum value = let rec cs v sum = if v = 0 then sum else cs (v / 10) (sum + (v % 10)) cs value 0 let getCrossSumAsync (sizeSum, values) = async { printfn "Checking Cross Sum..." let result = values |&gt; List.fold (fun csum value -&gt; csum + (crossSum value)) (crossSum sizeSum) do! Async.Sleep 2000 match result % 3 with | 0 -&gt; return Error "Crosssum is a multiple of 3" | _ -&gt; return Ok(values) } let runValuesFunctions = collectValuesAsync |&gt; Result.bindAsync groupValuesAsync |&gt; Result.bindAsync getCrossSumAsync let run () = printfn "AsyncBindTests" Async.Start anotherProcAsync let result = runValuesFunctions |&gt; Async.RunSynchronously match result with | Ok(values) -&gt; values |&gt; List.iter (printfn "Value: %d") | Error(msg) -&gt; printfn "ERROR: %s" msg Console.ReadLine() |&gt; ignore Async.CancelDefaultToken() </code></pre> <hr> <p>Any feedback on the use of Async/async are welcome, but I'm especially interested in your thoughts about the Result.bindAsync. Am I violating something or are there better ways to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T17:38:35.100", "Id": "430181", "Score": "0", "body": "This post has been [mentioned on Meta](https://codereview.meta.stackexchange.com/q/9205/9357)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T17:32:53.043", "Id": "222235", "Score": "3", "Tags": [ "functional-programming", "error-handling", "asynchronous", "f#", "railway-oriented" ], "Title": "Async in Railway Oriented Programming in F#" }
222235
<p>When I was looking to use <code>std::bitset</code> instead of GCC's <code>__uint128</code> in my <a href="/q/214240">RDS error-corrector</a>, I found that it was hard to use, because there's no way to widen or truncate a bitset to one of another size. Nor is there any ability to do bitwise arithmetic (<code>&amp;</code>, <code>|</code>, <code>^</code>) or comparison (<code>==</code>, <code>!=</code>) with a bitset of different width.</p> <p>I've identified the functions that I believe ought to be part of <code>std::bitset</code> and implemented them by wrapping the standard class. To convert between different widths, I've had to go via <code>std::string</code>, but (as written in comment), an update to <code>std::bitset</code> would have a more direct (and exception-free) path.</p> <p>I could have composed rather than inherited <code>std::bitset</code> - that's not really of concern here. Please ignore the mechanics that deal with <code>my::bitset</code> being different to <code>std::bitset</code> and imagine that they are a single, larger class. I'm most interested in whether the function signatures are correct and complete.</p> <p>Note that (like the integers), widening can be implicit, but narrowing operations need to be explicit. Most of the apparent duplication is to handle this distinction.</p> <pre><code>#include &lt;bitset&gt; #include &lt;climits&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; namespace my { template&lt;std::size_t N&gt; struct bitset : public std::bitset&lt;N&gt; { // forwarding of std::bitset constructors bitset() : std::bitset&lt;N&gt;{} {} template&lt;typename T&gt; requires std::is_unsigned_v&lt;T&gt; bitset(T n) : std::bitset&lt;N&gt;{n} {} template&lt; class CharT, class Traits, class Alloc &gt; explicit bitset(const std::basic_string&lt;CharT,Traits,Alloc&gt;&amp; str, typename std::basic_string&lt;CharT,Traits,Alloc&gt;::size_type pos = 0, typename std::basic_string&lt;CharT,Traits,Alloc&gt;::size_type n = std::basic_string&lt;CharT,Traits,Alloc&gt;::npos) : std::bitset&lt;N&gt;{str, pos, n} {} // Widening and narrowing constructors, to be added to std::bitset // Although this user implementation round-trips through // std::string (which can throw std::bad_alloc), library // implementation can, and should, just copy the internal // representation. // widening conversion template&lt;std::size_t P&gt; requires P &lt;= N bitset(const std::bitset&lt;P&gt;&amp; n) noexcept : std::bitset&lt;N&gt;{n.to_string()} {} // narrowing conversion template&lt;std::size_t P&gt; requires P &gt; N explicit bitset(const std::bitset&lt;P&gt;&amp; n) noexcept : std::bitset&lt;N&gt;{n.to_string()} {} }; // Deduction guide for my::bitset template&lt;std::size_t N&gt; bitset(std::bitset&lt;N&gt;) -&gt; bitset&lt;N&gt;; // Free functions to be added to namespace std // Deduction guide template&lt;typename T&gt; requires std::is_unsigned_v&lt;T&gt; bitset(T) -&gt; bitset&lt;sizeof (T) * CHAR_BIT&gt;; // comparisons - widen as necessary template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator==(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N != Q { if constexpr (N &gt; Q) return a == bitset&lt;N&gt;{b}; else return bitset&lt;Q&gt;{a} == b; } template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator!=(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) { return ! (a == b); } // bitwise-and produces the narrower type // (a specific exception to "doing as the integers do") template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator&amp;(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N!=Q { if constexpr (N &gt; Q) return bitset&lt;Q&gt;(a) &amp; b; else return a &amp; bitset&lt;N&gt;(b); } template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator&amp;(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N&lt;Q { return a &amp; bitset&lt;N&gt;(b); } // bitwise-and assignment accepts a wider type template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator&amp;=(bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N != Q { return a &amp;= bitset&lt;N&gt;(b); } // bitwise-or produces the wider type template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator|(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N&lt;Q { return bitset&lt;Q&gt;{a} | b; } template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator|(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N&gt;Q { return a | bitset&lt;N&gt;{b}; } template&lt;std::size_t N, std::size_t Q&gt; constexpr auto&amp; operator|=(bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N&gt;=Q { return a = a | bitset&lt;N&gt;{b}; } // bitwise-xor produces the wider type template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator^(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N&lt;Q { return bitset&lt;Q&gt;{a} ^ b; } template&lt;std::size_t N, std::size_t Q&gt; constexpr auto operator^(const bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N&gt;Q { return a ^ bitset&lt;N&gt;{b}; } template&lt;std::size_t N, std::size_t Q&gt; constexpr auto&amp; operator^=(bitset&lt;N&gt;&amp; a, const bitset&lt;Q&gt;&amp; b) requires N&gt;=Q { return a = a ^ bitset&lt;N&gt;{b}; } template&lt;std::size_t N, typename T&gt; requires std::is_unsigned_v&lt;T&gt; constexpr auto operator^(const bitset&lt;N&gt;&amp; a, const T&amp; b) { return a ^ bitset&lt;N&gt;{b}; } template&lt;std::size_t N, typename T&gt; requires std::is_unsigned_v&lt;T&gt; constexpr auto operator^(const T&amp; a, const bitset&lt;N&gt;&amp; b) { return bitset&lt;N&gt;{a} ^ b; } } </code></pre> <p>I've used Concepts Lite, which needs to be enabled when compiling as C++17. My compiler invocation is</p> <blockquote> <pre class="lang-sh prettyprint-override"><code>g++ -std=c++17 -fconcepts \ -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic \ -Warray-bounds -Wno-unused -Weffc++ </code></pre> </blockquote> <p>I have a simple compilation test for the above code. None of the mixed-width operations marked <code>// new</code> will compile with <code>std::bitset</code>; all the uncommented statements are fine with <code>my::bitset</code>. The commented-out statements are intended to be errors (because they have a narrowing conversion without a cast).</p> <pre><code>#define NEW_BITSET int main() { #ifdef NEW_BITSET using my::bitset; #else using std::bitset; #endif // Lower-case variables are narrow; upper-case are wide bitset&lt;32&gt; a{0xFFFF0000u}; bitset&lt;64&gt; B{a ^ 0xFFFF00u}; //bitset&lt;32&gt; b = B; // error bitset&lt;32&gt; b{B}; // explicit conversion //auto b = bitset&lt;32&gt;{B}; // error bitset c = a &amp; B; // new; c is bitset&lt;32&gt; bitset D = a | B; // new; D is bitset&lt;64&gt; bitset E = a ^ B; // new; E is bitset&lt;64&gt; c &amp;= b; // no change c &amp;= B; // new (unlike |= and ^=) B &amp;= c; // new c |= b; // no change //c |= B; // error D |= b; // new c ^= b; // no change //c ^= B; // error D ^= b; // new } </code></pre> <p>Perhaps there's a way to <code>static_assert()</code> that something shouldn't be valid, but I resorted to uncommenting the <code>// error</code> lines one at a time to prove them wrong.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T04:50:23.110", "Id": "430086", "Score": "0", "body": "Why do you have to go through `std::string`? Can't you copy bit by bit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T07:22:39.060", "Id": "430097", "Score": "1", "body": "Bit-by-bit would work too, and would be `noexcept`. The point really is that if this were part of `std::bitset`, the implementation would be able to use its underlying representation, and could likely just `std::memcpy()` the data." } ]
[ { "body": "<p>One aspect that could surprise users is that operator <code>&amp;</code> always <em>narrows</em> types to match. That's a departure from the usual guidance of \"do what the integers do\".</p>\n\n<p>On one hand, it makes sense not to waste resources on bits that will always be zero. One of my own use cases is to extract the some or all of the lower 26 bits from a 130-bit value, so it seems reasonable to expect a 26-bit result.</p>\n\n<p>On the other hand, it could catch users out when shifting the result. These two functions will give different results:</p>\n\n<pre><code>auto fun_i(std::uint32_t a, std::uint16_t b) {\n return (a &amp; b) &lt;&lt; 16;\n}\n\nauto fun_b(my::bitset&lt;32&gt; a, my::bitset&lt;16&gt; b) {\n return (a &amp; b) &lt;&lt; 16;\n}\n</code></pre>\n\n<p>On balance, I think that having to explicitly widen before shifting is a fair price to pay for saving resources when masking large numbers, but that would need to be well documented. And I value dissenting opinions (in comments, please).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T07:31:48.063", "Id": "222262", "ParentId": "222236", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T17:43:51.670", "Id": "222236", "Score": "9", "Tags": [ "c++", "api", "c++17", "bitset" ], "Title": "Mixed-width operations for std::bitset" }
222236
<p>ROP is a way to direct successful and failed results of a function along separate execution path in a chain of function calls.</p> <p>An excellent explanation can be found <a href="https://fsharpforfunandprofit.com/rop/" rel="nofollow noreferrer">here</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T17:53:59.087", "Id": "222237", "Score": "0", "Tags": null, "Title": null }
222237
Should be used for questions about the Railway Oriented Programming pattern mostly used in functional programming.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T17:53:59.087", "Id": "222238", "Score": "0", "Tags": null, "Title": null }
222238
Railway-oriented programming is a design pattern to support error handling with function composition by using a convention where all functions accept a success/error state as input, and return a success/error state as output.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:14:40.567", "Id": "222243", "Score": "0", "Tags": null, "Title": null }
222243
<p><a href="https://leetcode.com/problems/intersection-of-two-arrays-ii/" rel="noreferrer">https://leetcode.com/problems/intersection-of-two-arrays-ii/</a></p> <p>Please review for performance, I am having a problem with using TryGetValue, if someone can explain how this can be used in here.</p> <blockquote> <p>Given two arrays, write a function to compute their intersection.</p> <pre><code>Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note: </code></pre> <p>Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.</p> </blockquote> <pre><code>using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/intersection-of-two-arrays-ii/ /// &lt;/summary&gt; [TestClass] public class IntersectionOfTwoArraysii { [TestMethod] public void IntersectionOfDouble2Test() { int[] nums1 = {1, 2, 2, 1}; int[] nums2 = {2, 2}; CollectionAssert.AreEqual(nums2, Intersect(nums1,nums2)); } public int[] Intersect(int[] nums1, int[] nums2) { if (nums1.Length &gt; nums2.Length) { return Intersect(nums2, nums1); } Dictionary&lt;int, int&gt; nums1Count = new Dictionary&lt;int, int&gt;(); List&lt;int&gt; res = new List&lt;int&gt;(); foreach (var num in nums1) { if (!nums1Count.ContainsKey(num)) { nums1Count.Add(num,1); } else { nums1Count[num]++; } } foreach (var num in nums2) { if (nums1Count.ContainsKey(num) &amp;&amp; nums1Count[num] &gt; 0) { res.Add(num); nums1Count[num]--; } } return res.ToArray(); } } } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code> if (!nums1Count.ContainsKey(num))\n {\n nums1Count.Add(num,1);\n }\n else\n {\n nums1Count[num]++;\n }\n</code></pre>\n</blockquote>\n\n<p>I think it can be written as:</p>\n\n<pre><code>nums1Count.TryGetValue(num, out int count);\nnums1Count[num] = count + 1;\n</code></pre>\n\n<p>You don't have to test the return value of <code>TryGetValue()</code> in this case, because <code>TryGetValue()</code> sets <code>count</code> to default (<code>0</code>) if it returns false.</p>\n\n<p>The loop could also be written as a LINQ sequence as:</p>\n\n<pre><code>var nums1Count = data.GroupBy(i =&gt; i).ToDictionary(gr =&gt; gr.Key, gr =&gt; gr.Count());\n</code></pre>\n\n<hr>\n\n<p>Likewise:</p>\n\n<blockquote>\n<pre><code> if (nums1Count.ContainsKey(num) &amp;&amp; nums1Count[num] &gt; 0)\n {\n res.Add(num);\n nums1Count[num]--;\n }\n</code></pre>\n</blockquote>\n\n<p>can be changed to:</p>\n\n<pre><code>if (nums1Count.TryGetValue(num, out int count) &amp;&amp; count &gt; 0)\n{\n res.Add(num);\n nums1Count[num]--;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T04:03:24.673", "Id": "222257", "ParentId": "222245", "Score": "3" } } ]
{ "AcceptedAnswerId": "222257", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:26:50.147", "Id": "222245", "Score": "4", "Tags": [ "c#", "programming-challenge", "array", "hash-map" ], "Title": "LeetCode: Intersection of two arrays ii C#" }
222245
<p>I'm a few weeks into javascript and had to make a simple "crystals collector" app. The app works as intended, but the code is obtuse and repetitive.</p> <p>I'd like to make the app work using just one on click event, rather than using four for each crystal. I can't make an array of each color crystal and loop through them since the num variables change as well.</p> <p>Here is my code below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () { // Global variables var targetNumber; var num1; var num2; var num3; var num4; var userTotal = 0; var wins = 0; var losses = 0 // Functions function reset() { num1 = Math.floor(Math.random() * 11 + 1); num2 = Math.floor(Math.random() * 11 + 1); num3 = Math.floor(Math.random() * 11 + 1); num4 = Math.floor(Math.random() * 11 + 1); targetNumber = Math.floor(Math.random() * 101 + 19); userTotal = 0; $("#total-score").text(userTotal); $("#target-score").text(targetNumber); } function initialize() { num1 = Math.floor(Math.random() * 11 + 1); num2 = Math.floor(Math.random() * 11 + 1); num3 = Math.floor(Math.random() * 11 + 1); num4 = Math.floor(Math.random() * 11 + 1); targetNumber = Math.floor(Math.random() * 101 + 19); $("#target-score").text(targetNumber); $("#wins").text(wins); $("#losses").text(losses); $("#total-score").text(userTotal); } function logic() { if (userTotal === targetNumber) { alert("You Win!"); reset(); wins++; $("#wins").text(wins); } else if (userTotal &gt; targetNumber) { alert("You lose!"); reset(); losses++; $("#losses").text(losses); } } // Run Game (main) // something like... // var array = ["#blue","#green","#red","#yellow"] // for (var i =0; i &lt; array.length;i++) { // } initialize(); $("#blue").on("click", function () { userTotal = userTotal + num1; $("#total-score").text(userTotal); console.log(userTotal); logic(); }) $("#green").on("click", function () { userTotal = userTotal + num2; $("#total-score").text(userTotal); console.log(userTotal); logic(); }) $("#red").on("click", function () { userTotal = userTotal + num3; $("#total-score").text(userTotal); console.log(userTotal); logic(); }) $("#yellow").on("click", function () { userTotal = userTotal + num4; $("#total-score").text(userTotal); console.log(userTotal); logic(); }) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.img { width: 150px; height: 150px; } #crystal-main { width: 650px; border: 2px solid gray; padding: 25px; background: black; color: whitesmoke; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"&gt; &lt;link rel="stylesheet" href="assets/css/style.css"&gt; &lt;title&gt;Crystal Game&lt;/title&gt; &lt;script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="assets/javascript/game.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Crystals Collector!&lt;/h1&gt; &lt;hr&gt; &lt;div class="container-fluid"&gt; &lt;div class="container" id="crystal-main"&gt; &lt;div class="row"&gt; &lt;h2&gt;Target Score: &lt;span id="target-score"&gt;&lt;/span&gt;&lt;/h2&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;h2&gt;Total Score: &lt;span id="total-score"&gt;&lt;/span&gt;&lt;/h2&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-3-md crystal"&gt; &lt;img src="assets/images/blue.png" alt="blue" class="img" id="blue"&gt; &lt;/div&gt; &lt;div class="col-3-md crystal"&gt; &lt;img src="assets/images/green.png" alt="green" class="img" id="green"&gt; &lt;/div&gt; &lt;div class="col-3-md crystal"&gt; &lt;img src="assets/images/red.png" alt="red" class="img" id="red"&gt; &lt;/div&gt; &lt;div class="col-3-md crystal"&gt; &lt;img src="assets/images/yellow.png" alt="yellow" class="img" id="yellow"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;h4&gt;Wins: &lt;span id="wins"&gt;&lt;/span&gt;&lt;/h4&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;h4&gt;Losses: &lt;span id="losses"&gt;&lt;/span&gt;&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Here's my answer. Note I did not touch the html. We could attack both the javascript and the html and condense them both, but I think that just one file change is necessary right now.</p>\n\n<pre><code>$(document).ready(function () {\n\n // Global variables\n\n var targetNumber;\n var userTotal = 0;\n var wins = 0;\n var losses = 0;\n\n // Functions\n\n function reset() {\n for(var i = 0; i &lt; crystals.length; i++) {\n crystals[i].setAttribute(\"score\", Math.floor(Math.random() * 11 + 1))\n }\n targetNumber = Math.floor(Math.random() * 101 + 19);\n userTotal = 0;\n $(\"#total-score\").text(userTotal);\n $(\"#target-score\").text(targetNumber);\n }\n\n function initialize() {\n crystals = document.getElementsByTagName(\"img\")\n for(var i = 0; i &lt; crystals.length; i++) {\n crystals[i].setAttribute(\"score\", Math.floor(Math.random() * 11 + 1))\n crystals[i].addEventListener(\"click\", (args) =&gt; {\n value = Math.round(args.target.getAttribute(\"score\"))\n userTotal = userTotal + value;\n $(\"#total-score\").text(userTotal);\n console.log(userTotal);\n logic();\n })\n }\n targetNumber = Math.floor(Math.random() * 101 + 19);\n $(\"#target-score\").text(targetNumber);\n $(\"#wins\").text(wins);\n $(\"#losses\").text(losses);\n $(\"#total-score\").text(userTotal);\n }\n function logic() {\n if (userTotal === targetNumber) {\n alert(\"You Win!\");\n reset();\n wins++;\n $(\"#wins\").text(wins);\n }\n else if (userTotal &gt; targetNumber) {\n alert(\"You lose!\");\n reset();\n losses++;\n $(\"#losses\").text(losses);\n }\n }\n\n initialize();\n});\n</code></pre>\n\n<p>You're right when you say it would be difficult to loop through each element and increase the user's score by a preset random value. Instead, we make that random score part of the element. We can get all the crystals by getting all the images in the document (with the <i>document.getElementsByTagName(tagname)</i> function). This returns a list of the html elements.</p>\n\n<p>We can set the random value in the initialize function, with the <i>setAttribute()</i> function. This takes in two parameters: first, the new attribute name; second, the attribute's value. At the outset (and in each reset of the game), we set it to the new random value. </p>\n\n<p>Now we have an iterating loop through the four crystals, and each crystal has a new html attribute which contains its score. Now all we need to do is add the event listeners. We'll do that in the same for loop. Simply use the <i>addEventListener(event, f)</i> function. It takes in a string for what event to activate on, and a function to execute when that event is triggered. When the crystal is clicked, we'll want to get the value in the attribute, add it to the user's total, change the text, log it, and call logic!</p>\n\n<p>That's pretty much it. I also removed the declarations for the 'numx' variables. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:33:14.627", "Id": "430160", "Score": "0", "body": "\"_[Yes , you can have custom attributes.. But your HTML will not be validated.](https://stackoverflow.com/a/13041243/1575353)_\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:57:25.397", "Id": "222250", "ParentId": "222247", "Score": "3" } }, { "body": "<h2>General feedback</h2>\n\n<p>The code is quite redundant so to adhere to the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><em><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</em> principle</a>, there are a couple things that can be done:</p>\n\n<ul>\n<li>Abstract common lines from functions like <code>reset()</code> and <code>initialize()</code> into a separate function that can be called in both places. That way if you need to update logic it can be done in one place instead of multiple.</li>\n<li>Store the numbers representing the crystals in an array, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\">Object</a>\n, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a> etc. that can be indexed into and also iterated over. And you could use an <em>id</em> attribute or <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"nofollow noreferrer\"><em>data attributes</em></a> from the elements to determine which element was clicked. </li>\n</ul>\n\n<p>The function name <code>logic</code> seems quite vague. Somebody reading the code might wonder what \"<em>logic</em>\" it contains. If it had a more descriptive name, like \"<em>checkOutcome</em>\"</p>\n\n<h2>Targeted Feedback</h2>\n\n<p>For constructs like this</p>\n\n<blockquote>\n<pre><code>wins++;\n$(\"#wins\").text(wins);\n</code></pre>\n</blockquote>\n\n<p>You could use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()\" rel=\"nofollow noreferrer\">pre-increment operator</a> instead. That way there is no need to have the first line:</p>\n\n<pre><code>$(\"#wins\").text(++wins);\n</code></pre>\n\n<hr>\n\n<p>For adding a number to a variable:</p>\n\n<blockquote>\n<pre><code>userTotal = userTotal + num4;\n</code></pre>\n</blockquote>\n\n<p>There is a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment_2\" rel=\"nofollow noreferrer\">shorthand Addition assignment operator</a> that can be used here to simplify this:</p>\n\n<pre><code>userTotal += num4;\n</code></pre>\n\n<hr>\n\n<p>The deprecated syntax (as of jQuery 3.0) for the <code>.ready()</code> method:</p>\n\n<blockquote>\n<pre><code>$(document).ready(function() {\n</code></pre>\n</blockquote>\n\n<p>can be changed to </p>\n\n<pre><code>$(function() {\n</code></pre>\n\n<p>Since that is the recommended format<sup><a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">1</a></sup></p>\n\n<hr>\n\n<p>There is little benefit to making a class name <code>img</code>, since your CSS could select the images with a tag name selector:</p>\n\n<pre><code>img {\n width: 150px;\n height: 150px;\n}\n</code></pre>\n\n<p>But in a larger application/page, perhaps a class name like <code>crystal</code> would be more descriptive.</p>\n\n<p><sup>1</sup><sub><a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">http://api.jquery.com/ready/</a></sub></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:40:38.777", "Id": "222301", "ParentId": "222247", "Score": "1" } } ]
{ "AcceptedAnswerId": "222250", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T20:46:59.510", "Id": "222247", "Score": "5", "Tags": [ "javascript", "jquery", "html", "css", "event-handling" ], "Title": "Crystals Collector game with four clickable buttons" }
222247
<p>Earlier I <a href="https://codereview.stackexchange.com/questions/222228/fastest-path-on-a-snakes-and-ladders-board/222244?noredirect=1#comment430066_222244">posted</a> a fairly inefficient recursive solution to the problem of getting across a snakes and ladders board in the smallest number of moves.</p> <p>I have created a much faster solution to this using Dijkstra's algorithm and I believe it is correct. </p> <p>Each square on the board is linked to any square that is between 1-6 larger than it with a weight of one (equivalent of rolling a 1-6 on a dice). All snakes and ladders link squares with a weight of 1. The aim was to have the smallest total cost for the pathway between 1 and 100 (0 and 99 here as I have used list indexes). </p> <p>This is the first time I have implemented Dijkstra's algorithm and the first time I have used <code>namedtuples</code>. I am not sure if using namedtuples was appropriate, but it made it clearer in my head. </p> <p>I think I have massively over-complicated bits of code especially within the <code>for</code> loop under the condition <code>if edge.start == next_item:</code>. I seem to be using list comprehensions far too much and I know this makes the solution slower than it could be. Please could someone help me work out better ways to access the variables in my queue of named-tuples. </p> <pre><code>"""Calculate the shortest path across a snakes and ladders board using Dijkstra's shortest path""" from collections import namedtuple Edge = namedtuple("Edge", ("start", "end", "cost")) Stack = namedtuple("Stack", ("start", "pathcost", "totalcost")) class Graph: """Class generates graph and calculates shortest path""" def __init__(self, edges): """Generate edges in graph""" self.edges = [Edge(*edge) for edge in edges] def dijkstra_path(self, start, end): """Function that calculates the shortest path""" if start &gt;= end or start &lt; 0 or end &gt; 99: return -1 queue = sorted( ( Stack(edge.end, edge.cost, edge.cost) for edge in self.edges if edge.start == start ), key=lambda x: x[2], ) while queue: next_item, _, current_total = queue.pop(0) if next_item == end: return current_total for edge in self.edges: if edge.start == next_item: if edge.end in [item.start for item in queue]: current_cost = [ item.totalcost for item in queue if item.start == edge.end ][0] if not current_cost &lt; edge.cost + current_total: queue = [item for item in queue if item.start != edge.end] queue.append( Stack(edge.end, edge.cost, edge.cost + current_total) ) else: queue.append( Stack(edge.end, edge.cost, edge.cost + current_total) ) queue = sorted(queue, key=lambda x: x[2]) def build_graph(): """Chess Board""" list_board = [[i, i + j, 1] for i in range(100) for j in range(1, 7)] # Ladders list_board.append([1, 37, 1]) list_board.append([19, 59, 1]) list_board.append([28, 63, 1]) list_board.append([55, 99, 1]) # Snakes list_board.append([91, 13, 1]) list_board.append([86, 11, 1]) list_board.append([53, 2, 1]) list_board.append([41, 13, 1]) return list_board if __name__ == "__main__": GRAPH = Graph(build_graph()) FROM = 0 TO = 100 NUMBER_STEPS = GRAPH.dijkstra_path(FROM, TO) if not NUMBER_STEPS == -1: print(f"Can complete game in a minimum of {NUMBER_STEPS} rolls") else: print("Error. Make sure the starting point is between 0 and 99 and less than the end point", "which itself must be than or equal to 99") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:04:26.953", "Id": "430071", "Score": "0", "body": "As Peilonrayz said in response to your first version, you can make a graph without the blank squares on it. You just need to check distances to and between different snakes and ladders (and the start and end square.) The distance between any two special squares is the difference between their numbers, divided by six, and rounded up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:11:30.347", "Id": "430072", "Score": "2", "body": "Nice I hadn't thought about dijkstra's. I see you've included one test, does this example use a snake? Also as @Josiah said you should be able to compute the distance that way, but you'll have to check if it is actually traversable. Say if you have 6 snakes in a row you can't really go that way, or if you're at pos 1, there's a snake at pos 7 and the ladder is at pos 13." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:12:59.270", "Id": "430074", "Score": "0", "body": "Thanks. Yes. I thought that would be far less interesting a coding challenge though as that is basically a mathematical problem. I agree that the aim is in part to compute the outcome as quickly as possible but as I only started getting back into coding a month a go or so, I am very keen to try new techniques and get feedback on them. I hope @Peilonrazy you aren't upset I chose a different technique for my follow-up post.l" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:15:20.723", "Id": "430075", "Score": "0", "body": "@Peilonrayz. I actualy initially tested the code on a very small graph that I wrote by hand and entered the nodes manually. The aim was first to see if the code worked on that before trying it on the snakes and ladders board." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:21:23.113", "Id": "430076", "Score": "0", "body": "Good point about some runs not being traversable with a lucky bunch of sixes. The other point about 6 snakes in a row is in principle, that could make the game unwinnable. (If there isn't a ladder to bypass them) Whether that counts as a game of snakes and ladders is up for debate, but it's probably worth thinking about that edge case. In graph theory terms, it's how should Dijkstra's algorithm handle the shortest path between two disconnected nodes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:23:41.967", "Id": "430077", "Score": "0", "body": "I actually have no background in computer science or mathematics so I actually don't know anything about graph theory. I only came across the algorithm by chance as I was looking up graph traversal on google. Sorry" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:34:00.930", "Id": "430078", "Score": "1", "body": "I'll have you know I'm very upset @EML - that I didn't think of using Dijkstra's before reading this question. This is definitely better than what I was thinking" } ]
[ { "body": "<ul>\n<li><p>Named tuples are a good idea here. If you need to mutate the data you should instead use <code>dataclasses.dataclass</code>. But as there is no need here it's good.</p></li>\n<li><p>I'd suggest changing your nodes to contain snakes, ladders, and the start and end of the board. This is as you don't need to build the empty spaces as they are only used as distances.</p>\n\n<p>Since you need the distance between two nodes, then you need to calculate the distance at creation, not during the calculations.</p></li>\n<li><p>I've simplified calculating the distance between each node. You should take into account the following special cases:</p>\n\n<ul>\n<li>If the distance between two nodes is 12, and there is a snake or ladder halfway between them, it takes 3 rather than 2 turns to travel between the nodes.</li>\n<li>If there are 6 snakes or ladders after a node it's <em>impossible</em> to pass them without visiting those nodes.</li>\n</ul></li>\n<li><p>Currently you have <code>Edge</code> with a start, end and cost. I would suggest you instead split this into a <code>Node</code> with a start, end and edges. And an <code>Edge</code> that has a distance and a node.</p>\n\n<p>It should be noted that the <code>start</code> and <code>end</code> should only be used when creating the graph. The node will then just turn into glorified list.</p></li>\n<li><p>It should be noted that <code>Node</code> should be called <code>Vertex</code> if you want to keep with 'pure' graph theory naming.</p></li>\n<li><p>Please ignore my implementation of Dijkstra's algorithm, it's not great. And half way I came across some hashing problems, hence the <code>path[node[:2]]</code> ickyness. I don't recommend you take inspiration from it - unless it's how not to code.</p>\n\n<p>This means if the graph is setup, incorrectly, to have two ladders over the same space, then some bugs may appear.</p></li>\n</ul>\n\n<p>All of this together can look like:</p>\n\n<pre><code>from collections import namedtuple\nfrom dataclasses import dataclass, field\nfrom typing import * # Against best-practice but shhh\nimport math\n\nEdge = namedtuple('Edge', 'distance node'.split())\n\n\nclass Node(namedtuple('Node', 'start end edges'.split())):\n def __str__(self):\n return f'{self.start} -&gt; {self.end}'\n\n\n@dataclass(order=True)\nclass Path:\n distance: int\n current: Node=field(compare=False)\n previous: Node=field(compare=False)\n\n\n@dataclass\nclass Graph:\n nodes: List[Node]\n\n def shortest_paths(self, start: Node) -&gt; Dict[Node, Path]:\n if start not in self.nodes:\n raise ValueError(\"Graph doesn't contain start node.\")\n paths = {}\n queue = []\n for node in self.nodes:\n path = Path(float('inf'), node, None)\n paths[node[:2]] = path\n queue.append(path)\n\n paths[start[:2]].distance = 0\n queue.sort(reverse=True)\n while queue:\n node = queue.pop()\n for neighbor in node.current.edges:\n alt = node.distance + neighbor.distance\n path = paths[neighbor.node[:2]]\n if alt &lt; path.distance:\n path.distance = alt\n path.previous = node\n queue.sort(reverse=True)\n return paths\n\n def shortest_path(self, start: Node, end: Node) -&gt; List[Tuple[int, Node]]:\n if end not in self.nodes:\n raise ValueError(\"Graph doesn't contain end node.\")\n paths = self.shortest_paths(start)\n node = paths[end[:2]]\n output = []\n while node is not None:\n output.append((node.distance, node.current))\n node = node.previous\n return list(reversed(output))\n\n\ndef build_nodes(snakes: List[Tuple[int, int]], size: int) -&gt; List[Node]:\n return [\n Node(1, 1, []),\n Node(size, size, [])\n ] + [\n Node(start, end, [])\n for start, end in snakes\n ]\n\n\n# There are some edgecases that will need to be handled.\ndef calculate_distance(start: Node, end: Node, nodes: List[Node]):\n distance = int(math.ceil((end.start - start.end) / 6))\n start.edges.append(Edge(distance, end))\n\n\ndef add_edges(nodes: List[Node]):\n for start in nodes:\n for end in nodes:\n if end.start &gt; start.end:\n calculate_distance(start, end, nodes)\n\n\ndef build_graph(edges: List[Tuple[int, int]], size: int):\n nodes = build_nodes(edges, size)\n add_edges(nodes)\n start, end = nodes[:2]\n return Graph(nodes), start, end\n\n\nif __name__ == '__main__':\n graph, start, end = build_graph(\n [\n ( 2, 520),\n (530, 500),\n (510, 999)\n ],\n 1000,\n )\n for dist, node in graph.shortest_path(start, end):\n print(dist, node)\n</code></pre>\n\n<p>This outputs:</p>\n\n<pre><code>0 1 -&gt; 1\n1 2 -&gt; 520\n3 530 -&gt; 500\n5 510 -&gt; 999\n6 1000 -&gt; 1000\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T02:43:38.823", "Id": "430080", "Score": "0", "body": "Wow, a downvote within 5 minutes. I must have really messed something up. If it's fixable it'd be great to know what, so I can improve my answer. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T08:21:07.733", "Id": "430101", "Score": "0", "body": "There's actually quite a few edge cases to handle, like, say, nodes that are 16-18 steps apart with snakes or ladders at 5, 6 and 10 steps from the first node. Writing a reliable distance calculation is not a trivial exercise. I would actually recommend including empty spaces in the search graph, at least at first, just for that reason: it may slow down the search a bit, but it also frees you from having to explicitly consider all those edge cases. If it's too slow, you can later optimize it. But aim for correctness before speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:08:45.327", "Id": "430106", "Score": "0", "body": "Wow thanks. It's really great to get such detailed feedback on this. I'm learning so many new concepts so I really appreciate. Never even heard of ```dataclasses``` before! Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T11:30:29.827", "Id": "430123", "Score": "0", "body": "@IlmariKaronen I'm not sure having white space in the graph makes it correct. Also [it seems pretty trivial to me](https://gist.github.com/Peilonrayz/acf46dfe7e2bf5745736851efb799abc)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:05:22.960", "Id": "430294", "Score": "0", "body": "@Peilonrayz. I am working through your updated solution to try and unpick how everthing works and there is one thing I don't understand. for ```class Node``` you have said ```class Node(namedtuple('Node', 'start end edges'.split()))```. I have never seen anything be defined in the class name parameter before. Please can you let me know what this does? Thank you. This seems different to class inheritance to me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:33:41.627", "Id": "430297", "Score": "1", "body": "@EML If you see the line above that `Edge = namedtuple(...)`. Following PEP 8 we know `Edge` is a class, and `type(Edge) is type` also shows it is. And so we can do `class MyClass(Edge)`. You should be able to see now that all I've done is removed the need to define a class `_Node` - the named tuple - that `Node` inherits from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T16:35:12.517", "Id": "430298", "Score": "0", "body": "I see. thank you. I didn't realise ```Edge``` would have been a class. Good to know! Thanks" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T02:36:09.570", "Id": "222255", "ParentId": "222248", "Score": "2" } } ]
{ "AcceptedAnswerId": "222255", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T21:40:42.500", "Id": "222248", "Score": "5", "Tags": [ "python", "algorithm", "python-3.x", "pathfinding" ], "Title": "Shortest pathway across a snakes and ladders board (Update)" }
222248
<p>There's lots of code out there for basic adapters of <code>std::deque</code> to provide a thread-safe queue. I've adopted that, but wanted to provide a relatively full analog to <code>std::queue</code>, so I've added the whole set of constructors and <code>operator=</code>. The queue works fine. My questions are mainly related to the constructors and <code>operator=</code>:</p> <ol> <li>Have I applied the correct type traits for identifying whether the constructor will be <code>noexcept</code>?</li> <li>I'm using <code>notify_once</code> for <code>push</code> and <code>emplace</code>, and <code>notify_all</code> for <code>operator=</code> overloads. Is that correct?</li> <li>Because I need to acquire a lock before altering the queue, the constructors have to be written a bit differently from the <code>std::queue</code> adapter. For example, the initializer list can't include the data copy/move. Does that code look correct?</li> <li>The conditional <code>noexcept</code> syntax I've added for <code>size</code> and <code>empty</code> looks bizarre. Am I doing that correctly?</li> </ol> <p>Other comments not related to those questions are welcome. One note about the class: I did add some combination methods (e.g., <code>clear_count_push</code>) because that is a common combination of calls that I use—such as at program shutdown when I push a close thread semaphore on the queue so that the thread taking work off the queue will know it's time to shut down.</p> <p><strong>Note: since posting I've updated this significantly. See <a href="https://gist.github.com/rsjaffe/59d22db0649d8276e42aca1061d7c08c" rel="nofollow noreferrer">https://gist.github.com/rsjaffe/59d22db0649d8276e42aca1061d7c08c</a> for the latest version.</strong></p> <pre class="lang-cpp prettyprint-override"><code>template&lt;typename T, class Container = std::deque&lt;T&gt;&gt; class BlockingQueue { public: using container_type = Container; using value_type = typename Container::value_type; using size_type = typename Container::size_type; using reference = typename Container::reference; using const_reference = typename Container::const_reference; static_assert(std::is_same_v&lt;T, value_type&gt;, "container adaptors require consistent types"); // Constructors: see https://en.cppreference.com/w/cpp/container/queue/queue // These are in same order and number as in cppreference /*1*/ BlockingQueue() noexcept(std::is_nothrow_default_constructible_v&lt;Container&gt;){}; /*2*/ explicit BlockingQueue(const Container&amp; cont) noexcept( std::is_nothrow_copy_constructible_v&lt;Container&gt;) : queue_{cont} { } /*3*/ explicit BlockingQueue(Container&amp;&amp; cont) noexcept( std::is_nothrow_move_constructible_v&lt;Container&gt;) : queue_{std::move(cont)} { } /*4*/ BlockingQueue(const BlockingQueue&amp; other) { auto lock{std::scoped_lock(other.mutex_)}; queue_ = other.queue_; } /*5*/ BlockingQueue(BlockingQueue&amp;&amp; other) noexcept( std::is_nothrow_move_constructible_v&lt;BlockingQueue&gt;) { auto lock{std::scoped_lock(other.mutex_)}; queue_ = std::move(other.queue_); } /*6*/ template&lt;class Alloc, class = std::enable_if_t&lt;std::uses_allocator_v&lt;Container, Alloc&gt;&gt;&gt; explicit BlockingQueue(const Alloc&amp; alloc) noexcept( std::is_nothrow_constructible_v&lt;Container, const Alloc&amp;&gt;) : queue_{alloc} { } /*7*/ template&lt;class Alloc, class = std::enable_if_t&lt;std::uses_allocator_v&lt;Container, Alloc&gt;&gt;&gt; BlockingQueue(const Container&amp; cont, const Alloc&amp; alloc) : queue_{cont, alloc} { } /*8*/ template&lt;class Alloc, class = std::enable_if_t&lt;std::uses_allocator_v&lt;Container, Alloc&gt;&gt;&gt; BlockingQueue(Container&amp;&amp; cont, const Alloc&amp; alloc) noexcept( std::is_nothrow_constructible_v&lt;Container, Container, const Alloc&amp;&gt;) : queue_(std::move(cont), alloc) { } /*9*/ template&lt;class Alloc, class = std::enable_if_t&lt;std::uses_allocator_v&lt;Container, Alloc&gt;&gt;&gt; BlockingQueue(const BlockingQueue&amp; other, const Alloc&amp; alloc) : queue_(alloc) { auto lock{std::scoped_lock(other.mutex_)}; queue_ = other.queue_; } /*10*/ template&lt;class Alloc, class = std::enable_if_t&lt;std::uses_allocator_v&lt;Container, Alloc&gt;&gt;&gt; BlockingQueue(BlockingQueue&amp;&amp; other, const Alloc&amp; alloc) noexcept( std::is_nothrow_constructible_v&lt;Container, Container, const Alloc&amp;&gt;) : queue_(alloc) { auto lock{std::scoped_lock(other.mutex_)}; queue_ = std::move(other.queue_); } // operator= BlockingQueue&amp; operator=(const BlockingQueue&amp; other) { { auto lock{std::scoped_lock(mutex_, other.mutex_)}; queue_ = other.queue_; } condition_.notify_all(); return *this; } BlockingQueue&amp; operator=(BlockingQueue&amp;&amp; other) noexcept( std::is_nothrow_move_assignable_v&lt;Container&gt;) { { auto lock{std::scoped_lock(mutex_, other.mutex_)}; queue_ = std::move(other.queue_); } condition_.notify_all(); return *this; } // destructor ~BlockingQueue() = default; // methods void push(const T&amp; value) { { auto lock{std::scoped_lock(mutex_)}; queue_.push_back(value); } condition_.notify_one(); } void push(T&amp;&amp; value) { { auto lock{std::scoped_lock(mutex_)}; queue_.push_back(std::move(value)); } condition_.notify_one(); } template&lt;class... Args&gt; void emplace(Args&amp;&amp;... args) { { auto lock{std::scoped_lock(mutex_)}; queue_.emplace_back(std::forward&lt;Args&gt;(args)...); } condition_.notify_one(); } T pop() { auto lock{std::unique_lock(mutex_)}; condition_.wait(lock, [this]() noexcept(noexcept(std::declval&lt;Container&amp;&gt;().empty())){ return !queue_.empty(); }); T rc{std::move(queue_.front())}; queue_.pop_front(); return rc; } [[nodiscard]] std::optional&lt;T&gt; try_pop() { auto lock{std::scoped_lock(mutex_)}; if (queue_.empty()) return std::nullopt; T rc{std::move(queue_.front())}; queue_.pop_front(); return rc; } void clear() { auto lock{std::scoped_lock(mutex_)}; queue_.clear(); } [[nodiscard]] auto size() const noexcept(noexcept(std::declval&lt;Container&amp;&gt;().size())) { auto lock{std::scoped_lock(mutex_)}; return queue_.size(); } [[nodiscard]] auto clear_count() { auto lock{std::scoped_lock(mutex_)}; auto ret = queue_.size(); queue_.clear(); return ret; } auto clear_count_push(const T&amp; value) { size_type ret; { auto lock{std::scoped_lock(mutex_)}; ret = queue_.size(); queue_.clear(); queue_.push_back(value); } condition_.notify_one(); return ret; } auto clear_count_push(T&amp;&amp; value) { size_type ret; { auto lock{std::scoped_lock(mutex_)}; ret = queue_.size(); queue_.clear(); queue_.push_back(std::move(value)); } condition_.notify_one(); return ret; } template&lt;class... Args&gt; auto clear_count_emplace(Args&amp;&amp;... args) { size_type ret; { auto lock{std::scoped_lock(mutex_)}; ret = queue_.size(); queue_.clear(); queue_.emplace_back(std::forward&lt;Args&gt;(args)...); } condition_.notify_one(); return ret; } [[nodiscard]] bool empty() const noexcept(noexcept(std::declval&lt;Container&amp;&gt;().empty())) { auto lock{std::scoped_lock(mutex_)}; return queue_.empty(); } private: Container queue_{}; mutable std::condition_variable condition_{}; mutable std::mutex mutex_{}; }; </code></pre>
[]
[ { "body": "<pre><code> /*9*/ template&lt;class Alloc, class = std::enable_if_t&lt;std::uses_allocator_v&lt;Container, Alloc&gt;&gt;&gt;\n BlockingQueue(const BlockingQueue&amp; other, const Alloc&amp; alloc) : queue_(alloc)\n {\n auto lock{std::scoped_lock(other.mutex_)};\n queue_ = other.queue_;\n }\n</code></pre>\n\n<p>This doesn't look quite right. <code>queue_ = other.queue;</code> may cause the allocator from <code>other.queue</code> to be used, <a href=\"https://en.cppreference.com/w/cpp/container/deque/operator%3D\" rel=\"nofollow noreferrer\">depending on the allocator traits</a>.</p>\n\n<p>To ensure correct behavior, we probably need to use the relevant <code>Container</code> constructor instead:</p>\n\n<pre><code> /*9*/ template&lt;class Alloc, class = std::enable_if_t&lt;std::uses_allocator_v&lt;Container, Alloc&gt;&gt;&gt;\n BlockingQueue(const BlockingQueue&amp; other, const Alloc&amp; alloc)\n {\n auto lock{std::scoped_lock(other.mutex_)};\n queue_ = Container(other.queue_, alloc);\n }\n</code></pre>\n\n<p>(And the same for <code>/*10*/</code>).</p>\n\n<hr>\n\n<pre><code>[[nodiscard]] auto size() const noexcept(noexcept(std::declval&lt;Container&amp;&gt;().size()))\n[[nodiscard]] auto clear_count()\n... etc.\n</code></pre>\n\n<p>We could use <code>size_type</code> rather than <code>auto</code>.</p>\n\n<hr>\n\n<pre><code>[[nodiscard]] auto clear_count()\n... etc.\n</code></pre>\n\n<p>Perhaps <code>count_clear</code> would better reflect the order that this function does things in. (And the same for the other similar functions).</p>\n\n<hr>\n\n<p>(I'm not very familiar with <code>noexcept</code>, so I haven't checked that aspect).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T15:21:16.660", "Id": "450768", "Score": "0", "body": "Interesting. So operator= may result in the allocator being changed to the same as the source allocator. I'll change #9 and #10 to do what you suggest. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-23T08:46:58.697", "Id": "231180", "ParentId": "222249", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T22:43:42.273", "Id": "222249", "Score": "7", "Tags": [ "c++", "concurrency", "queue", "c++17" ], "Title": "Concurrent Queue Adapter" }
222249
<p>I have two tables:</p> <p><strong>tableA</strong></p> <p><code>aid</code> <code>name</code> <code>age</code> <code>sex</code> <code>email</code> <code>password</code></p> <p><strong>tableB</strong></p> <p><code>bid</code> <code>idno</code> <code>aid</code></p> <p>The steps should be</p> <ul> <li><p>Enter, verify <code>email</code> and <code>password</code></p></li> <li><p>If email and password are correct, insert random number into tableB as <code>idno</code></p></li> <li><p>Select <code>name</code>, <code>age</code>, <code>sex</code>, <code>email</code>, <code>idno</code> from both tables and return an array as result.</p></li> <li><p>If <code>email</code> and <code>password</code> are wrong, do nothing.</p></li> </ul> <p>I wrote the following code in Codeigniter model</p> <pre><code>function login($data) { $email = $data["email"]; $password = $data["password"]; $sql = "select aid from tableA where email='".$email."' and password='".$password."'"; $query = $this-&gt;db-&gt;query($sql); if ($query-&gt;num_rows() &gt; 0) { $ret = $query-&gt;row(); $idno = random(); $aid = $ret-&gt;aid; $sql = "insert into tableB (idno, aid) values('".$idno."','".$aid."')"; $query = $this-&gt;db-&gt;query($sql); if ($query) { $sql = "select '".$idno."' as idno, name, age, sex, email from tableA where aid='".$aid."'"; $query = $this-&gt;db-&gt;query($sql); if ($query-&gt;num_rows() &gt; 0) { return $query-&gt;result_array(); } return $query-&gt;num_rows(); } else { return false; } return false; } return $query-&gt;num_rows(); } </code></pre> <p>The code works, but I think the code is so ugly and not efficient. How can I optimize the code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T05:51:08.417", "Id": "430092", "Score": "0", "body": "Where are your prepared statements or Codeigniter query building methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T06:41:17.993", "Id": "430096", "Score": "1", "body": "1. The function is called `login()`, but it doesn't seem do what it says on the label. 2. You could get rid of the third query if you get all the needed fields with the first query." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T07:25:52.907", "Id": "430098", "Score": "0", "body": "You're not saving unencrypted passwords are you? How can you be sure that you will never have an `$idno` collision?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T07:30:17.130", "Id": "430099", "Score": "3", "body": "Your question title seems to address your chief concern with your code instead of what your code does. You will need to edit your title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:21:55.627", "Id": "430280", "Score": "0", "body": "@mickmackusa Thanks for the reply, and actually I think the so many nestings will result in lower execution efficiency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:22:08.727", "Id": "430281", "Score": "0", "body": "@KIKOSoftware Thanks for the reply, and actually I think the so many nestings will result in lower execution efficiency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-19T09:20:14.970", "Id": "430908", "Score": "1", "body": "`$data[\"email\"] = \"' OR 1 --\"` There I just bypassed your query with SQLInjection, and passed your conditional check of `if ($query->num_rows() > 0)` For example `select aid from tableA where email='' OR 1 --' and password='...'` the `--` is the start of a comment so the tail of the query is ignored. `OR 1` is always true so this returns all the rows from that table." } ]
[ { "body": "<p>The biggest thing I see are the numerous SQL injection vulnerabilities enabled by concatenating variables with SQL together. Use <a href=\"https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow noreferrer\">Prepared Statements</a> instead.</p>\n\n<p>You can reduce nesting in code by <a href=\"https://softwareengineering.stackexchange.com/q/47789/118878\">returning early from the function</a>.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$query = $this-&gt;db-&gt;query($sql);\n\nif ($query-&gt;num_rows() == 0)\n return false;\n\n$sql = \"insert into tableB (idno, aid) values('\".$idno.\"','\".$aid.\"')\";\n$query = $this-&gt;db-&gt;query($sql);\n...\n\nif (!isset($query))\n return false;\n\n$sql = \"select '\".$idno.\"' as idno, name, age, sex, email from tableA where aid='\".$aid.\"'\";\n$query = $this-&gt;db-&gt;query($sql);\n\nif ($query-&gt;num_rows() == 0)\n return false;\n\nreturn $query-&gt;result_array();\n</code></pre>\n\n<p>Pass the e-mail and password values as explicit parameters, instead of an array. You only need two values from this array. That's not too many arguments for a method:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>public function login($email, $password) {\n ...\n}\n</code></pre>\n\n<p>Some code style improvements:</p>\n\n<ul>\n<li>Put a blank line above the <code>if</code> statements</li>\n<li>Put a blank line above the <code>return</code> statements</li>\n</ul>\n\n<p>Whitespace is not just a useful design element for graphic designers. It is useful for code authors as a means for grouping related statements together, or calling out a statement as something more important than the others. A <code>return</code> statement is pretty important in knowing what this method does. Furthermore blank lines above and below code elements give natural \"breaks\" in the look of the code, which guides your eye and mind to realize they are related &mdash; like paragraphs of text.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T19:41:38.380", "Id": "224303", "ParentId": "222253", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T02:21:27.113", "Id": "222253", "Score": "4", "Tags": [ "php", "codeigniter" ], "Title": "Codeigniter models optimization" }
222253
<p>I have the below code to pull messages from a FIFO SQS queue. Using the <code>while (IsRunning)</code> loop makes me feel to question the code design. Is there a pattern I am missing or some SDK that will do this more efficiently with recovery on error and other features for a subscriber that won't need human intervention to restart?</p> <p>From AWS SDK, I haven't seen any other way - like pub/sub - but the only way is polling the SQS queue. </p> <pre><code>namespace Messaging.Services { public class AwsSimpleQueueSubscriber : IMessagingSubscriber { private readonly string _queueUrl; private readonly IAmazonSQS _amazonSqsClient; private readonly ILogger&lt;AwsSimpleQueueSubscriber&gt; _logger; private readonly int _receiveMessageWaitTime; private readonly int _maxNumberOfMessages; private Task _runningSubscriberTask; private CancellationTokenSource _runningSubscriberCancellationTokenSource; public bool IsRunning { get; private set; } public AwsSimpleQueueSubscriber( string queueUrl, IAmazonSQS amazonSqsClient, ILogger&lt;AwsSimpleQueueSubscriber&gt; logger, int receiveMessageWaitTime = 20, int maxNumberOfMessages = 1) { Guard.Argument(queueUrl, nameof(queueUrl)).NotNull().NotEmpty().NotWhiteSpace(); Guard.Argument(amazonSqsClient, nameof(amazonSqsClient)).NotNull(); Guard.Argument(logger, nameof(logger)).NotNull(); _queueUrl = queueUrl; _amazonSqsClient = amazonSqsClient; _logger = logger; _receiveMessageWaitTime = receiveMessageWaitTime; _maxNumberOfMessages = maxNumberOfMessages; } public Task StartAsync(Func&lt;MessagePayload, Task&lt;bool&gt;&gt; func, CancellationToken cancellationToken = default) { if (!IsRunning) { _runningSubscriberCancellationTokenSource = new CancellationTokenSource(); _runningSubscriberCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); _runningSubscriberTask = CheckForMessagesAsync(func, _runningSubscriberCancellationTokenSource.Token); IsRunning = true; } return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken = default) { _runningSubscriberCancellationTokenSource.Cancel(); _runningSubscriberTask = null; IsRunning = false; return Task.CompletedTask; } private async Task CheckForMessagesAsync( Func&lt;MessagePayload, Task&lt;bool&gt;&gt; func, CancellationToken cancellationToken) { _logger.LogInformation("Checking for SQS messages"); while (IsRunning) { try { if (cancellationToken.IsCancellationRequested) { cancellationToken.ThrowIfCancellationRequested(); } var receiveMessageRequest = new ReceiveMessageRequest { QueueUrl = _queueUrl, WaitTimeSeconds = _receiveMessageWaitTime, MaxNumberOfMessages = _maxNumberOfMessages }; var response = await _amazonSqsClient.ReceiveMessageAsync(receiveMessageRequest, cancellationToken); if (response.HttpStatusCode == HttpStatusCode.OK &amp;&amp; response.Messages.Any()) { _logger.LogDebug($"Process {response.Messages.Count} messages from {_queueUrl}"); foreach (var message in response.Messages) { var funcResult = await func(new MessagePayload {Body = message.Body}); if (funcResult) { var deleteMessageRequest = new DeleteMessageRequest { QueueUrl = _queueUrl, ReceiptHandle = message.ReceiptHandle }; var result = await _amazonSqsClient.DeleteMessageAsync(deleteMessageRequest, cancellationToken); if (result.HttpStatusCode != HttpStatusCode.OK) { _logger.LogError( $"Amazon SQS DELETE ERROR: {response.HttpStatusCode}\r\nQueueURL: {_queueUrl}\r\nReceiptHandle: {message.ReceiptHandle}"); } } } } if (response.HttpStatusCode != HttpStatusCode.OK) { _logger.LogError($"Amazon SQS ERROR: {response.HttpStatusCode}\r\n QueueURL: {_queueUrl}"); } } catch (Exception ex) { _logger.LogError(ex, $"Error consuming SQS message from {_queueUrl}"); if (ex is OperationCanceledException) { IsRunning = false; break; } } } } } } </code></pre>
[]
[ { "body": "<h2>Cancellation Token Source</h2>\n\n<p>You create a token source, and then immediately overwrite it with a new instance, disregarding the previously created instance. Surely, you did not mean to instantiate it twice?</p>\n\n<blockquote>\n<pre><code>_runningSubscriberCancellationTokenSource = new CancellationTokenSource();\n_runningSubscriberCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h2>Thread-Safety</h2>\n\n<p><code>StartAsync</code> and <code>StopAsync</code> are not thread-safe. Concurrent access to these methods may result in a partially running and inconsistent state of the instance. You should use a <code>SemaphoreSlim</code> to block concurrent access to these methods.</p>\n\n<hr>\n\n<h2>Task.FromException</h2>\n\n<p><code>StartAsync</code> and <code>StopAsync</code> are async wrappers of synchronous code. You return <code>return Task.CompletedTask;</code>, however if some exception occurs before the return statement, the exception does not get wrapped as an async task. You should catch exceptions and return <code>return Task.FromException(exception);</code>.</p>\n\n<hr>\n\n<h2>Q&amp;A</h2>\n\n<blockquote>\n <p><em>Using the while (IsRunning) loop makes me feel to question the code design.</em></p>\n</blockquote>\n\n<p>If <code>IsRunning</code> would have been declared as <code>private volatile bool IsRunning</code> ,this code would not be such a bad idea. Then at least you are certain the value of the variable is read atomically on each cycle in the loop. Since you did not declare it as such, it is possible that the value gets cached on the first read and never re-read by the same thread (<a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile\" rel=\"nofollow noreferrer\">Volatile keyword in C#</a>). </p>\n\n<p>An important note on the <em>volatile</em> keyword (see link above):</p>\n\n<blockquote>\n <p>The compiler, the runtime system, and even hardware may rearrange\n reads and writes to memory locations for performance reasons. Fields\n that are declared volatile are not subject to these optimizations.</p>\n</blockquote>\n\n<p>As an alternative, you could use <code>while (!cancellationToken.IsCancellationRequested)</code> and perhaps one last call to <code>cancellationToken.ThrowIfCancellationRequested();</code> after the loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-10T15:16:31.470", "Id": "225891", "ParentId": "222254", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T02:28:14.263", "Id": "222254", "Score": "5", "Tags": [ "c#", "thread-safety", "queue", "library", "async-await" ], "Title": "SQS subscriber pattern in background service" }
222254
<p>This is a <a href="https://leetcode.com/problems/snakes-and-ladders/" rel="nofollow noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>On an <span class="math-container">\$N\$</span> x <span class="math-container">\$N\$</span> <code>board</code>, the numbers from <code>1</code> to <code>N * N</code> are written boustrophedonically (<strong>starting from the bottom left of the board</strong>), and alternating direction each row. For example, for a 6 x 6 board, the numbers are written as follows -</em></p> <p><a href="https://i.stack.imgur.com/yis33.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yis33.png" alt="enter image description here"></a></p> <p><em>You start on square <code>1</code> of the board (which is always in the last row and first column). Each move, starting from square <code>x</code>, consists of the following -</em></p> <ul> <li><em>You choose a destination square <code>S</code> with number <code>x+1, x+2, x+3, x+4, x+5</code>, or <code>x+6</code>, provided this number is <code>&lt;= N * N</code>.</em> <ul> <li><em>(This choice simulates the result of a standard 6-sided die roll, ie., there are always <strong>at most 6 destinations, regardless of the size of the board.</strong>)</em></li> </ul></li> <li><em>If <code>S</code> has a snake or ladder, you move to the destination of that snake or ladder. Otherwise, you move to <code>S</code>.</em></li> </ul> <p><em>A board square on row <code>r</code> and column <code>c</code> has a "snake or ladder" if <code>board[r][c] != -1</code>. The destination of that snake or ladder is <code>board[r][c]</code>.</em></p> <p><em>Note that you only take a snake or ladder at most once per move; if the destination to a snake or ladder is the start of another snake or ladder, you do <strong>not</strong> continue moving. (For example, if the board is <code>[[4,-1],[-1,3]]</code>, and on the first move your destination square is <code>2</code>, then you finish your first move at <code>3</code> because you do <strong>not</strong> continue moving to <code>4</code>.)</em></p> <p><em>Return the least number of moves required to reach square <code>N * N</code>. If it is not possible, return <code>-1</code>.</em></p> <p><strong><em>Note -</em></strong></p> <ul> <li><em><code>2 &lt;= board.length = board[0].length &lt;= 20</code></em></li> <li><em><code>board[i][j]</code> is between <code>1</code> and <code>N * N</code> or is equal to <code>-1</code>.</em></li> <li><em>The board square with number <code>1</code> has no snake or ladder.</em></li> <li><em>The board square with number <code>N * N</code> has no snake or ladder.</em></li> </ul> <p><strong><em>Example 1 -</em></strong></p> <pre><code>Input: [ [-1,-1,-1,-1,-1,-1], [-1,-1,-1,-1,-1,-1], [-1,-1,-1,-1,-1,-1], [-1,35,-1,-1,13,-1], [-1,-1,-1,-1,-1,-1], [-1,15,-1,-1,-1,-1]] Output: 4 """ Explanation - At the beginning, you start at square 1 [at row 5, column 0]. You decide to move to square 2, and must take the ladder to square 15. You then decide to move to square 17 (row 3, column 5), and must take the snake to square 13. You then decide to move to square 14, and must take the ladder to square 35. You then decide to move to square 36, ending the game. It can be shown that you need at least 4 moves to reach the N*N-th square, so the answer is 4. """ </code></pre> </blockquote> <p>I would like to have a performance review of my solution and would also like to know whether I could make it more efficient.</p> <p>Here is my solution to this challenge (in Python 3) -</p> <pre><code># Uses Breadth First Search (BFS) def snakes_and_ladders(board): """ :type board: List[List[int]] :rtype: int """ board_2 = [0] rows, cols = len(board), len(board[0]) row = rows - 1 while row &gt;= 0: for col in range(cols): board_2.append(board[row][col]) row -= 1 if row &gt;= 0: for col in range(cols - 1, -1, -1): board_2.append(board[row][col]) row -= 1 visited = [0 for i in range(len(board_2))] stack = collections.deque() stack.append([1,0]) while stack: current_index, current_dist = stack.popleft() for i in range(1,7): next_index = min(rows * cols, current_index + i) if board_2[next_index] != -1: next_index = board_2[next_index] if next_index == rows * cols: return current_dist + 1 if visited[next_index] == 0: visited[next_index] = 1 stack.append([next_index, current_dist + 1]) return -1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-30T09:10:12.527", "Id": "451602", "Score": "1", "body": "Having to travel odd board rows backwards... *shudder* I'd almost factor out your board transformation **just** to be able to call it `sanify(board)`." } ]
[ { "body": "<h1>Type Hinting</h1>\n\n<p>You were halfway there! Good job having the type of values accepted and returned in the method docstring. Now, you can use type hints to show in the header of the method what values are accepted and returned, as follows</p>\n\n<pre><code>from typing import List\n\ndef snakes_and_ladders(board: List[List[int]]) -&gt; int:\n</code></pre>\n\n<h1>Consistent Spacing</h1>\n\n<p>This</p>\n\n<pre><code>for i in range(1,7):\n</code></pre>\n\n<p>should be this</p>\n\n<pre><code>for i in range(1, 7):\n</code></pre>\n\n<p>You have good spacing in the rest of your code, but you should stay consistent and apply this spacing everywhere.</p>\n\n<p>The same for this line</p>\n\n<pre><code>stack.append([1,0]) -&gt; stack.append([1, 0])\n</code></pre>\n\n<h1>Magic Numbers</h1>\n\n<p>We're coming back to this line again</p>\n\n<pre><code>for i in range(1, 7):\n</code></pre>\n\n<p>What is <code>7</code> supposed to represent? The max number of rows or columns? What if you have to change it later on to apply to smaller/bigger snakes and ladders boards? I would advise using a variable to hold this value, naming it accordingly.</p>\n\n<h1>List Comprehension</h1>\n\n<p>You use lots of loops with one line in them. Particularly when appending to lists. Luckily, you can add two lists together and it will merge them.</p>\n\n<p>From this</p>\n\n<pre><code>for col in range(cols):\n board_2.append(board[row][col])\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>board_2 += [board[row][col] for col in range(cols)]\n</code></pre>\n\n<p>You can do the same for the next loop a couple lines down</p>\n\n<p>From this</p>\n\n<pre><code>for col in range(cols - 1, -1, -1):\n board_2.append(board[row][col])\n</code></pre>\n\n<p>to this</p>\n\n<pre><code>board_2 += [board[row][col] for col in range(cols - 1, -1, -1)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-30T07:18:47.840", "Id": "231513", "ParentId": "222256", "Score": "3" } } ]
{ "AcceptedAnswerId": "231513", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T03:42:37.983", "Id": "222256", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "breadth-first-search" ], "Title": "(Leetcode) Snakes and Ladders" }
222256
<p>Follow-up to <a href="https://codereview.stackexchange.com/questions/222184/python-program-to-find-a-word-ladder-transforming-four-to-five">Python program to find a word ladder transforming &quot;four&quot; to &quot;five&quot;</a></p> <p>I'm trying to write a program to solve a word ladder puzzle to brush up on my Python. For those who don't know:</p> <blockquote> <p>A word ladder puzzle begins with two words, and to solve the puzzle one must find a chain of other words to link the two, in which two adjacent words (that is, words in successive steps) differ by one letter. - Wikipedia</p> </blockquote> <p>I've implemented <em>breadth first search</em> as opposed to <em>depth first search</em> for a big performance boost since my last question, as suggested in the answers. I've also added a new mode, that can add and remove letters as well as just swapping them. Additionally, the program now takes user input, and can take more than two words to link together (given <code>a b c</code>, it runs <code>a b</code>, and then runs <code>b c</code>).</p> <p>The program now takes ~6 seconds on my machine to run with input of <code>five four</code> and <code>1</code>. I'm still interested in making this faster, and also would like to know how to make it more Pythonic.</p> <pre class="lang-py prettyprint-override"><code># -------- Data Structures -------- class Queue(): """ FIFO Queue """ def __init__(self, parent = None): self.list = [] self.parent = parent def append(self, value): self.list.append(value) def pop(self): return self.list.pop(0) class Node(): """ Node of a Tree """ def __init__(self, value, parent = None): self.value = value self.parent = parent # -------- Distance Functions -------- def hamming(s1, s2): return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) def levenshtein(s1, s2): if len(s1) &lt; len(s2): return levenshtein(s2, s1) if len(s2) == 0: return len(s1) previous_row = range(len(s2) + 1) for i, c1 in enumerate(s1): current_row = [i + 1] for j, c2 in enumerate(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1] # -------- IO -------- # Print sequence from root to node def print_words(node): values = [] while isinstance(node, Node): values.append(node.value) node = node.parent print(list(reversed(values))) # Get all input all_words = open("/usr/share/dict/words", "r").read().lower().splitlines() input_words = input("Enter list of words, seperated by spaces: ").split() input_mode = int(input("Enter 1 for swap-only mode, or 2 for swap-add-rem mode: ")) # Validate user input if not 1 &lt;= input_mode &lt;= 2: raise ValueError("Invalid mode: " + input_mode) for word in input_words: if word not in all_words: raise ValueError("Invalid word: " + word) # Adapt to mode distance = [hamming, levenshtein][input_mode - 1] if input_mode == 1: all_words = [word for word in all_words if len(word) == len(input_words[0])] # -------- Breadth First Search -------- def fill(node, to_check, checked): checked.add(node.value) for word in all_words: if 1 &gt;= len(word) - len(node.value) &gt;= -1 and distance(word, node.value) == 1: to_check.append(Node(word, node)) for i in range(len(input_words) - 1): root = Node(input_words[i]) checked = set() to_check = Queue() fill(root, to_check, checked) while to_check.list: node = to_check.pop() if node.value == input_words[i + 1]: print_words(node) break if node.value not in checked: fill(node, to_check, checked) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T05:32:31.687", "Id": "430088", "Score": "0", "body": "Side answer: A node that knows both the parent and children is double-linked: https://en.wikipedia.org/wiki/Doubly_linked_list. So a node that knows only one is just 'linked'. Since a tree has a parent-child cardinality of 1..*, it would always be the child that knows the parent when 'linked'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T05:39:38.087", "Id": "430090", "Score": "0", "body": "Never mind - I just found the answer to my confusingly worded question. Apologies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T05:50:47.020", "Id": "430091", "Score": "0", "body": "Feel free to post a self-answer to enlighten us :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T06:08:04.797", "Id": "430093", "Score": "0", "body": "I mean, the answer to the side question was just \"no\"... I just didn't have a good enough understanding of the term \"tree\" so the question didn't make much sense." } ]
[ { "body": "<p>I'm a little bit short on time at the moment, but I'ld like to share a few minor observations with you. Maybe I will also find time to look at performance related optimizations and expand it later.</p>\n\n<hr>\n\n<p>You said you would like your code to be Pythonic. With that in mind you could replace <code>print(list(reversed(values)))</code> by <code>print(values[::-1])</code> which uses slicing (nice <a href=\"https://stackoverflow.com/a/509295/5682996\">explanation on Stack Overflow</a>) to revert the list. Since you need the complete list nevertheless, there is no real advantage in using a reverse iterator instead of a list directly.</p>\n\n<p>Also since \"Explicit is better than implicit.\" (from <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"noreferrer\">Zen of Python</a>) I would prefer to see </p>\n\n<pre><code>distance = hamming if input_mode == 1 else levenshtein\n</code></pre>\n\n<p>or something similar instead of</p>\n\n<pre><code>distance = [hamming, levenshtein][input_mode - 1]\n</code></pre>\n\n<p>The proposed version would also allow you to drop the string to int conversion. It would even work if the user entered something else than the two values presented by the prompt. <code>levenshtein</code> would be assumed to be the default then. Change the <code>if</code> to your liking if you prefer <code>hamming</code> as default. Although this might not be something to think about, since you have an input validation in place (good). However, the way it is written could be improved since you have a really small range (read: two) values that are valid. That makes it possible to list them explicitly:</p>\n\n<pre><code># Validate user input\nif input_mode not in (1, 2):\n raise ValueError(\"Invalid mode: \" + input_mode) \n</code></pre>\n\n<p>This almost reads like normal language.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T08:41:09.527", "Id": "222267", "ParentId": "222260", "Score": "6" } }, { "body": "<p>Your <code>Queue</code> class should be replaced by the builtin <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque</code></a> which offers better performances (<code>list</code>s <code>.pop(0)</code> are <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> since the remainder of the list have to be shifted, but <code>deque.popleft()</code> is <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>).</p>\n\n<p>You should also take the habit of opening files using the <code>with</code> statement to avoid keeping opened file descriptors around:</p>\n\n<pre><code>def read_file(filename='/usr/share/dict/words'):\n with open(filename) as f:\n return set(map(str.lower, map(str.strip, f)))\n</code></pre>\n\n<p>Note that I return a <code>set</code> to accelerate the search <code>if word not in all_words</code>. You could also bring back the <code>isalpha</code> filter from your previous question:</p>\n\n<pre><code>def read_file(filename='/usr/share/dict/words'):\n with open(filename) as f:\n return set(map(str.lower, filter(str.isalpha, map(str.strip, f))))\n</code></pre>\n\n<p>Your code would also largely gain from using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> instead of your various <code>input</code>s.</p>\n\n<p>And <code>print_words</code> could easily be converted to an <code>__iter__</code> method on the <code>Node</code> class.</p>\n\n<p>Example improvements:</p>\n\n<pre><code>\"\"\"Word-Ladder Solver.\n\nblah blah blah\nand blah\n\"\"\"\n\n\nimport sys\nimport enum\nimport argparse\nimport itertools\nfrom collections import deque\n\n\nclass Mode(enum.Enum):\n SWAP = 'swap-only'\n ADD_REM_SWAP = 'add-remove-swap'\n\n\nclass Node:\n \"\"\"Node of a Tree\"\"\"\n def __init__(self, value, parent=None):\n self.value = value\n self.parent = parent\n\n def __iter__(self):\n if self.parent is not None:\n yield from self.parent\n yield self.value\n\n def __reversed__(self):\n node = self\n while node is not None:\n yield node.value\n node = node.parent\n\n\ndef command_line_parser():\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('word', nargs='+')\n parser.add_argument('final_word')\n parser.add_argument(\n '-m', '--mode', type=Mode,\n choices=[m.value for m in Mode], default=Mode.SWAP,\n help='mode of operation to use')\n parser.add_argument(\n '-d', '--dictionnary', '--words-file',\n metavar='PATH', default='/usr/share/dict/words',\n help='path to the list of words to search from')\n return parser\n\n\ndef pairwise(iterable):\n a, b = itertools.tee(iterable)\n next(b, None)\n yield from zip(a, b)\n\n\ndef hamming(s1, s2):\n return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))\n\n\ndef levenshtein(s1, s2):\n if len(s1) &lt; len(s2):\n return levenshtein(s2, s1)\n\n if len(s2) == 0:\n return len(s1)\n\n previous_row = range(len(s2) + 1)\n for i, c1 in enumerate(s1):\n current_row = [i + 1]\n for j, c2 in enumerate(s2):\n insertions = previous_row[j + 1] + 1\n deletions = current_row[j] + 1\n substitutions = previous_row[j] + (c1 != c2)\n current_row.append(min(insertions, deletions, substitutions))\n previous_row = current_row\n\n return previous_row[-1]\n\n\ndef read_words(filename):\n with open(filename) as f:\n return set(map(str.lower, filter(str.isalpha, map(str.strip, f))))\n\n\ndef find_word_ladder(source, target, words, distance):\n checked = set()\n candidates = deque([Node(source)])\n\n while candidates:\n node = candidates.popleft()\n candidate = node.value\n if candidate == target:\n return node\n\n if candidate not in checked:\n checked.add(candidate)\n candidates.extend(\n Node(word, node)\n for word in words\n if distance(word, candidate) == 1)\n\n\ndef main(targets, words, mode):\n if mode is Mode.SWAP:\n distance = hamming\n elif mode is Mode.ADD_REM_SWAP:\n distance = levenshtein\n else:\n return\n\n for source, target in pairwise(targets):\n if source not in words:\n sys.exit('unknown word in dictionnary: {}'.format(source))\n if target not in words:\n sys.exit('unknown word in dictionnary: {}'.format(target))\n chain = find_word_ladder(source, target, words, distance)\n print(list(chain))\n\n\nif __name__ == '__main__':\n parser = command_line_parser()\n args = parser.parse_args()\n\n try:\n words = read_words(args.dictionnary)\n except OSError as e:\n parser.error('unable to read words file: {}'.format(e))\n\n if args.mode is Mode.SWAP:\n length = len(args.final_word)\n words = {w for w in words if len(w) == length}\n\n targets = args.word\n targets.append(args.final_word)\n main(targets, words, args.mode)\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>$ python words_ladder.py -d /usr/share/dict/cracklib-small five four dice\n['five', 'fire', 'fore', 'tore', 'torr', 'tour', 'four']\n['four', 'tour', 'torr', 'tore', 'tire', 'dire', 'dice']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T00:44:54.753", "Id": "430241", "Score": "0", "body": "Thanks for your time! One part of the code that I don't understand is `reversed(list(reversed(self)))`. Why would you reverse something twice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T07:15:16.977", "Id": "430257", "Score": "0", "body": "@AlexF The first is here to call `self.__reversed__()`, the second is the same than in your function and serves to traverse the tree from the root to the `self` node. All in all, this is just hiding your `print_words` as `Node`'s internals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T07:18:54.530", "Id": "430258", "Score": "0", "body": "I contemplated using `deque.extendleft` instead but found it a bit obscure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T10:08:34.470", "Id": "430267", "Score": "1", "body": "@AlexF Changed `__iter__` to provide an alternate implementation and avoid the double `reversed`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T12:11:21.830", "Id": "222276", "ParentId": "222260", "Score": "5" } } ]
{ "AcceptedAnswerId": "222276", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T05:26:56.830", "Id": "222260", "Score": "8", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "tree" ], "Title": "Word-Ladder solver in Python 3" }
222260
<p>My goal is to implement Strongly Connected Components algorithm using python. I have splitted up my code on 3 parts:</p> <ol> <li><p>Data Load:</p> <pre><code>import csv as csv import numpy as np import random as random import copy as copy import math import sys, threading import time sys.setrecursionlimit(800000) threading.stack_size(67108864) start = time.time() num_nodes = 160000 graph = [[] for i in range(num_nodes)] reverse_graph = [[] for i in range(num_nodes)] graph_2_step = [[] for i in range(num_nodes)] file = open("C:\\Users\\yefida\\Desktop\\Study_folder\\Online_Courses\\Algorithms\\Project 5\\test7.txt", "r") data = file.readlines() for line in data: if line.strip(): items = line.split() if int(items[1]) not in reverse_graph[int(items[1]) - 1]: reverse_graph[int(items[1]) - 1].append(int(items[1])) reverse_graph[int(items[1]) - 1].append(int(items[0])) else: reverse_graph[int(items[1]) - 1].append(int(items[0])) if int(items[0]) not in graph[int(items[0]) - 1]: graph[int(items[0]) - 1].append(int(items[0])) graph[int(items[0]) - 1].append(int(items[1])) else: graph[int(items[0]) - 1].append(int(items[1])) for i in range(len(graph)): if len(graph[i]) == 0: graph[i] = [i+1,i+1] if len(reverse_graph[i]) == 0: reverse_graph[i] = [i+1,i+1] end = time.time() time_taken = end - start print('Time: ',time_taken) </code></pre></li> <li><p>Depth-first search algorithm on the reversed graph:</p> <pre><code>#2. Run DFS-loop on reversed Graph: start = time.time() t = 0 # for finishing lines: how many nodes are processed so far s = None # current source vertex explored = set() finish_time = {} def DFS(graph,node): explored.add(node) global s for vertex in graph[node - 1][1:]: if vertex not in explored: DFS(graph,vertex) global t t+= 1 finish_time[node] = t #Nodes starts from n to 1 for i in range(max(reverse_graph)[0],0,-1): if i not in explored: s = i DFS(reverse_graph,i) #Mapping to the new list in increasing order for edge in range(len(graph)): for vertex in range(len(graph[edge])): graph[edge][vertex] = finish_time[graph[edge][vertex]] graph_2_step[graph[edge][0] - 1] = graph[edge] end = time.time() time_taken = end - start print('Time: ',time_taken) </code></pre></li> <li><p>Depth-first-search algortihm on the graph after step 2:</p> <pre><code> #3. Run DFS-loop on Graph with original directions(but with labeled finishing times): all_components = []#Saves all strongly connected components all_comp_elem = set()#check if element is in Strongly Connected Components(already explored) SSC = set() # strongly connected component, that will be saved in "all_components" explored= set() # variables, that are already explored next_elem = 0 # contains information how many elements have to be checked, before making a decision #c)modification of DFS def DFS_2_Path(graph,node): global all_components global SSC global next_elem explored.add(node) #node is explored next_elem += len(graph[node - 1][1:]) # add number elements, that must be explored from the current node #checking one vertex -&gt; minus one element that must be explored for vertex in graph[node - 1][1:]: next_elem -= 1 #check if element is in Strongly Connected Components(already explored) if node not in all_comp_elem: SSC.add(node) #if vertex is not explored, than reccursion and go to the next vertex if vertex not in explored: SSC.add(vertex) DFS_2_Path(graph,vertex) #if vertex is not the last element in the chain(Ex: [6,5,1,7] -&gt; 6 is a main Node, and 7 is the last element, to which #node 6 is connected) elif vertex in explored and vertex != graph[node - 1][1:][len(graph[node - 1][1:]) - 1]: continue #if vertex is the last element in the chain(Ex: [6,5,1,7] -&gt; 6 is a main Node, and 7 is the last element, to which #node 6 is connected) -&gt; update stringly connected components elif vertex in explored and vertex == graph[node - 1][1:][len(graph[node - 1][1:]) - 1] and next_elem == 0: all_components.append(SSC) all_comp_elem.update(SSC) SSC = set() #Main loop for i in range(max(graph_2_step)[0],0,-1): if i not in explored: DFS_2_Path(graph_2_step,i) end = time.time() time_taken = end - start print('Time: ',time_taken) </code></pre></li> </ol> <p>I have tested my algorithm on different test cases -> it works correct. First two parts of the algorithm work fast(on the data set with 160000 nodes). But when I run the third part -> kernel in Jupyter dies.</p> <p>I have improved the speed of the code as much as I could. I definitely need a fresh look on my code.</p> <p>P.S Don't look at first 2 parts of the code. I provided them to you only for the test, if you want to test.</p> <p>P.S.S The link to the file, that I have used for the test: <a href="https://github.com/beaunus/stanford-algs/blob/master/testCases/course2/assignment1SCC/input_mostlyCycles_64_160000.txt" rel="nofollow noreferrer">https://github.com/beaunus/stanford-algs/blob/master/testCases/course2/assignment1SCC/input_mostlyCycles_64_160000.txt</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:12:03.667", "Id": "430109", "Score": "0", "body": "Have you had a look at the [networkx](https://networkx.github.io/) library and especially its [strongly_connected_components](https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.components.strongly_connected_components.html#networkx.algorithms.components.strongly_connected_components) function? Not that I wanted to discourage you from trying it yourself, but depending on your needs that could make it a lot easier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:13:12.217", "Id": "430110", "Score": "0", "body": "What do you mean with reversed graph?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:38:43.183", "Id": "430114", "Score": "0", "body": "@dfhwze By reversed graph I meant, that we reverse all of the arcs in our original graph" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:39:51.060", "Id": "430116", "Score": "0", "body": "@AlexV I know, that special library exists. I am coding this algorithm in order to improve my skills in Python and to understand algorithms better :)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T08:35:38.210", "Id": "222266", "Score": "3", "Tags": [ "python", "performance", "algorithm", "reinventing-the-wheel" ], "Title": "Strongly Connected component algorithm implementation(Python)" }
222266
<p>I have a list of objects and a query. I need to rank the objects, based on how do they match the query. An object would match the query 100% if it contains all properties in the query. My program works correctly, but I have a design issue. From the console input, I have a location of a these objects. In this location I need to find all type of specific objects, and to perform the query on them. Based on the result of this query, I need t prioritize them. So from my App.class I create a <code>Map</code> between a object and set of its properties (I can't use the object directly). Then, again from the console input, I read the query. There can be many queries. For all query I create new <code>RankingSystem</code> object (which, I don't like, I don't think I should create new object for every new query), where <code>RankingSystem</code> has two fields - the query itself and the map between Object and its set of properties. </p> <p>Then, for every query, which I read from the console, I create new <code>RankingSystem</code> object. Again, I don't think this is correct. However, if I put <code>private Set&lt;String&gt; query</code> as a parameter then I have problems with creating a custom comparator. I thought of extracting the comparator in a separate class, yet, I do need to put there the <code>computeRank</code> method. If I do so, then I have to create the comparator with two fields (dictionary and query), because I need them for the <code>computeRank</code> method. Another thing (which stops me from creating the comparator in a separate class), is that I am using <code>computeRank</code> in the <code>findBestMatches</code> method, to print out the percentage of matches. I must print the matching percentage, so I need to have this method (<code>computeRank</code>) in the <code>RankingSystem</code> class. I am using it for my custom comparator as well, so if I extract my custom comparator in a separate class, I will have the same method twice (which is obvious code repetition, which is bad). So I decided to put the comparator inside my <code>RankingSystem</code> class. Is this approach OK, or is there a better approach? Also, is there a way to avoid the creation of an <code>RankingSystem</code> object every time when I have a new query? Here is my <code>RankingSystem</code> class:</p> <pre><code> public class RankingSystem { private Map&lt;File, Set&lt;String&gt;&gt; dictionary; //Q1: is there a way to avoid putting the query as a class field? At the moment it seems as the right solution, because I need it for my custom comparator, but this way I create new object for each query? private Set&lt;String&gt; query; public RankingSystem(Map&lt;File, Set&lt;String&gt;&gt; dictionary, Set&lt;String&gt; query) { this.dictionary = dictionary; this.query = query; } private PriorityQueue&lt;File&gt; compareFiles(){ PriorityQueue&lt;File&gt; queue = new PriorityQueue&lt;File&gt;(10, fileComparator); for(File file: dictionary.keySet()) { if(computeFileRank(file) != 0) { queue.add(file); } } return queue; } public void findBestMatches() { PriorityQueue&lt;File&gt; queue = compareFiles(); if(queue.isEmpty()) { System.out.println("no matches found"); } int counter = 0; while(!queue.isEmpty() &amp;&amp; counter &lt; 10) { File file = queue.poll(); System.out.println(file.getName() + ":" + computeFileRank(file) + "%"); counter++; } } //Q2: is it OK leaving the comparator like this? I tried to extract it into a separate class, but that way I get code repetition (of computeRank method) and I have to pass the dictionary and the query as fields again? private Comparator&lt;File&gt; fileComparator = new Comparator&lt;File&gt;() { public int compare(File f1, File f2) { if (computeFileRank(f1) &gt; computeFileRank(f2)) return -1; if (computeFileRank(f1) &lt; computeFileRank(f2)) return 1; return 0; } }; private double computeFileRank(File file) { int matches = 0; int totalCount = query.size(); Set&lt;String&gt; wordsInFile = dictionary.get(file); for(String word: query) { if(wordsInFile.contains(word)) { matches++; } } return matches*100/totalCount; } } </code></pre> <p>Just for the sake of trying, I tried to move my custom comparator in a separate class and this is how it looks:</p> <pre><code>public class FileComparator implements Comparator&lt;File&gt;{ //I dont like that I need to pass the query and the dictionary again private Set&lt;String&gt; query; private Map&lt;File, Set&lt;String&gt;&gt; dictionary; public FileComparator(Set&lt;String&gt; query, Map&lt;File, Set&lt;String&gt;&gt; dictionary) { this.query = query; this.dictionary = dictionary; } @Override public int compare(File f1, File f2) { if (computeFileRank(f1, query) &gt; computeFileRank(f2, query)) return -1; if (computeFileRank(f1, query) &lt; computeFileRank(f2, query)) return 1; return 0; } //I dont like that I have the same method on 2 places private double computeFileRank(File file, Set&lt;String&gt; query) { int matches = 0; int totalCount = query.size(); Set&lt;String&gt; wordsInFile = dictionary.get(file); for(String word: query) { if(wordsInFile.contains(word)) { matches++; } } return matches*100/totalCount; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T10:36:31.920", "Id": "430544", "Score": "0", "body": "Please don't change a question significantly after answers are available. You can always ask a follow-up question instead. I have rollbacked your changes." } ]
[ { "body": "<p>You are computing a rank 4 times here. Why not store the results in a variable and compute only 2 times?</p>\n\n<blockquote>\n<pre><code>public int compare(File f1, File f2) {\n if (computeFileRank(f1) &gt; computeFileRank(f2))\n return -1;\n if (computeFileRank(f1) &lt; computeFileRank(f2))\n return 1;\n return 0;\n } \n};\n</code></pre>\n</blockquote>\n\n<pre><code>public int compare(File f1, File f2) {\n final int rank1 = computeFileRank(f1);\n final int rank2 = computeFileRank(f2);\n if (rank1 &gt; rank2)\n return -1;\n if (rank1 &lt; rank2)\n return 1;\n return 0;\n } \n};\n</code></pre>\n\n<hr>\n\n<p>Can <code>totalCount</code> be <code>0</code>? Do you want to divide by 0 or have different behavior in such case?</p>\n\n<blockquote>\n<pre><code> private double computeFileRank(File file, Set&lt;String&gt; query) {\n // ..\n int totalCount = query.size();\n // ..\n return matches*100/totalCount;\n }\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:22:53.737", "Id": "222270", "ParentId": "222269", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T09:17:15.800", "Id": "222269", "Score": "2", "Tags": [ "java", "object-oriented", "priority-queue" ], "Title": "Prioritize objects using PriorityQueue and custom comparator in Java" }
222269
<p>I have this image: </p> <p><a href="https://i.stack.imgur.com/t4ApL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t4ApL.jpg" alt="enter image description here"></a></p> <p>I want to whiten the black contours (borders) around it without affecting the image content. Here is the code I used: </p> <pre><code>import cv2 import numpy as np import shapely.geometry as shageo img = cv2.imread('filename.jpg') # get the gray image and do binaryzation gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) gray[gray &lt; 20] = 0 gray[gray &gt; 0] = 255 # get the largest boundry of the binary image to locate the target contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) rect = cv2.minAreaRect(contours[0]) box = cv2.boxPoints(rect) box = np.int0(box) poly = shageo.Polygon(box) h, w = img.shape[:2] ind = np.zeros((h, w), np.bool) # check if the point is inside the target or not for i in range(h): for j in range(w): p = shageo.Point(j, i) if not p.within(poly): ind[i, j] = True # whiten the outside points img[ind] = (255, 255, 255) cv2.imwrite('result.jpg', img) </code></pre> <p>Here is the result: <a href="https://i.stack.imgur.com/55OqS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/55OqS.jpg" alt="enter image description here"></a></p> <p>The code works fine, but it's very slow because of the <code>for</code> loops. </p> <p>Any suggestions how to avoid the for loops or to make them faster?</p>
[]
[ { "body": "<p>After some research, I ended to a better and faster solution. Here is the code: </p>\n\n<pre><code># import packages\nimport numpy\nimport mahotas.polygon\nimport shapely.geometry as shageo\nimport cv2\nimport numpy as np\n\ndef get_mask(dims, pts):\n # create a numpy array of zeros with the same dimensions of the image \n canvas = numpy.zeros((dims[0], dims[1]), dtype=int)\n # the points coords in the form of pt(y, x)\n\n # fill the polygon with ones.\n mahotas.polygon.fill_polygon(pts, canvas)\n return canvas\n\n\ndef find_polygon(img):\n # get the gray image and do binaryzation\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n gray[gray &lt; 20] = 0\n gray[gray &gt; 0] = 255\n\n # get the largest boundry of the binary image to locate the target\n contours, _ = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n rect = cv2.minAreaRect(contours[0])\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n poly = shageo.Polygon(box)\n # return the polygone coords in a list\n return list(poly.exterior.coords)\n\n\ndef main():\n img = cv2.imread('filename.jpg')\n # get the coords of the polygon containing (around) the image.\n coords = find_polygon(img)\n poly_coords = []\n # the coords are floats and sometimes are negaive (-1), so transform them into positive ints.\n for element in coords:\n poly_coords.append(tuple(map(int, map(abs, reversed(element)))))\n\n mask = get_mask(img.shape, poly_coords)\n # convert the mask into array of 0 and 1.\n binary_mask = np.logical_not(mask).astype(int)\n # reshape the array to be similar to the image dimenstions\n binary_mask = binary_mask.reshape(img.shape[0], img.shape[1], -1)\n # sum the binary mask with the image\n cv2.imwrite('res.jpg', img + binary_mask * 255)\n\n\nmain()\n</code></pre>\n\n<p>I am sure this code can be optimized more, any suggestions are welcome. </p>\n\n<p><strong>Credits:</strong><br>\n1- <a href=\"https://stackoverflow.com/questions/5587839/drawing-polygons-in-numpy-arrays\">Drawing polygons in numpy arrays</a><br>\n2- <a href=\"https://stackoverflow.com/a/56592818/8128190\">Whiten black contours around a skewed image opencv</a></p>\n\n<p>Here is the result:<br>\n<a href=\"https://i.stack.imgur.com/TZJRL.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TZJRL.jpg\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T13:07:55.223", "Id": "222524", "ParentId": "222273", "Score": "0" } } ]
{ "AcceptedAnswerId": "222524", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T10:38:23.937", "Id": "222273", "Score": "2", "Tags": [ "python", "performance", "opencv" ], "Title": "Whiten black contours around a skewed image" }
222273
<p>This is a <a href="https://leetcode.com/problems/3sum/" rel="nofollow noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>Given an array <code>nums</code> of <code>n</code> integers, are there elements <span class="math-container">\$a, b, c\$</span> in <code>nums</code> such that <span class="math-container">\$a + b + c\$</span> = <code>0</code>? Find all unique triplets in the array which gives the sum of zero.</em></p> <p><strong><em>Note -</em></strong></p> <p><em>The solution set must not contain duplicate triplets.</em></p> <p><strong><em>Example -</em></strong></p> <p><em>Given array <code>nums</code> = <code>[-1, 0, 1, 2, -1, -4]</code></em>,</p> <p><em>A solution set is -</em></p> <pre><code>[ [-1, 0, 1], [-1, -1, 2] ] </code></pre> <p><strong><em>NOTE -</em></strong> <em><code>[-1, 0, 1]</code> and <code>[1, 0, -1]</code> are considered duplicates.</em></p> </blockquote> <p>Here is my solution to this challenge -</p> <pre><code>def three_sum(nums): if nums == None or len(nums) &lt; 3: return [] res = [] nums.sort() for i in range(len(nums) - 2): if i &gt; 0 and nums[i] == nums[i - 1]: continue j = i + 1 k = len(nums) - 1 while j &lt; k: if nums[i] + nums[j] + nums[k] &gt; 0: k -= 1 while nums[k] == nums[k + 1] and k &gt; j: k -= 1 elif nums[i] + nums[j] + nums[k] &lt; 0: j += 1 while nums[j] == nums[j - 1] and j &lt; k: j += 1 else: res.append([nums[i], nums[j], nums[k]]) j += 1; k -= 1 while nums[k] == nums[k + 1] and k &gt; j: k -= 1 while nums[j] == nums[j - 1] and j &lt; k: j += 1 return res </code></pre> <p>So I would like to know whether I could make my program shorter and more efficient. Also, I would like to know if I could make my code <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">PEP 8</a> compliant (if possible) as I'm having trouble (understanding) with the <a href="http://pep8online.com/checkresult" rel="nofollow noreferrer">PEP 8 checker</a> (I need explanations for <em>why</em> I'm getting these errors) -</p> <p><a href="https://i.stack.imgur.com/lEkcu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lEkcu.png" alt="enter image description here"></a></p> <p>Also, any recommendations for better PEP 8 checkers? I'll be glad to know.</p>
[]
[ { "body": "<p>Have you actually read or at least skimmed PEP8 regarding the aspects mentioned by the style checking tool?</p>\n\n<p>The first error (E711) basically wants you to write <code>if nums is None or ...</code> instead of ``. You can find this at section <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">Programming Recommendations</a>.</p>\n\n<p>The second one (E702) tells you that you are using a semicolon to cram multiple lines into a single one. Simple searching your code for <code>;</code> will bring up <code>j += 1; k -= 1</code>. It is not recommended to have multiple instructions per line, so each of them should be on its own line. This can be found in the section titled <a href=\"https://www.python.org/dev/peps/pep-0008/#other-recommendations\" rel=\"nofollow noreferrer\">Other Recommendations</a>.</p>\n\n<p>As you know, Python can be a bit picky when it comes to whitespace. The explanation why trailing whitespace is frowned upon may also be found under <em>Other Recommendations</em> in PEP8 (see previous link).</p>\n\n<p>As for the missing newline at the end of the file: there is no Python specific reason why you <em>have</em> to do this. It's just that most people <em>tend to</em> do this. pylint's <a href=\"http://pylint-messages.wikidot.com/messages:c0304\" rel=\"nofollow noreferrer\">help page on that message</a> tells you more about it:</p>\n\n<blockquote>\n <p>While Python interpreters typically do not require line end character(s) on the last line, other programs processing Python source files may do, and it is simply good practice to have it. This is confirmed in <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#line-structure\" rel=\"nofollow noreferrer\">Python docs: Line Structure</a> which states that a physical line is ended by the respective line end character(s) of the platform.</p>\n</blockquote>\n\n<p>Which brings us to other tools that can be use to check your code style. Python has a lot of them, e.g. <a href=\"https://pylint.org/\" rel=\"nofollow noreferrer\">pylint</a> (mentioned above - also with a static code checker), <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">flake8</a>, <a href=\"http://pycodestyle.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">pycodestyle</a> (formerly pep8), and <a href=\"https://pypi.org/project/bandit/\" rel=\"nofollow noreferrer\">bandit</a> to name a few. There is a Visual Studio Code <a href=\"https://code.visualstudio.com/docs/python/linting#_specific-linters\" rel=\"nofollow noreferrer\">help page</a> about which linters are supported by that specific IDE with a few more of them. Just pick an code editor (Visual Studio Code, Atom, vim, emacs, ...) or IDE (Eclipse with Python plugin, PyCharm, Spyder, ...) of your choice, type its name into Google search, add \"python linter\"/\"python stylecheck\" to your query and you are more than likely to find something that either describes how to use built-in tools or integrations to do just that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:18:51.583", "Id": "430130", "Score": "0", "body": "Yep. I have read through most of PEP 8 and corrected some errors in my code to adhere to PEP 8. But the thing with this PEP 8 checker is that, even after correcting most of the code, it picks up some error or the other (don't know why). Anyways, thanks for your answer, it was extremely helpful :) +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:12:18.567", "Id": "222282", "ParentId": "222278", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/222282/200133\">AlexV</a> has covered the formatting stuff.</p>\n\n<h3>With regards to the length and efficiency of the code:</h3>\n\n<p>You've clearly put a lot of thought into <em>how</em> to calculate the list of tuples requested. And you've found some good efficiencies! But you're approaching this from the wrong direction: Start with the <em>clearest syntactically legal expression of the desired result</em> you can write, and then add complexity/efficiency as needed.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def three_sum(nums: List[int]) -&gt; Set[Tuple[int,int,int]]: # Type-hints are optional.\n return {\n tuple(sorted([a, b, c]))\n for a in nums\n for b in nums\n for c in nums\n if 0 == (a + b + c)\n }\n</code></pre>\n\n<p>That's pretty concise and pretty clear, but it's just about the least efficient way one could do it. </p>\n\n<ul>\n<li>We should be sorting first, and our inner loops should only cover values greater-than-or-equal-to (or only less than/equal to) the value grabbed by the outer loop.</li>\n<li>We can ignore duplicate values in <code>nums</code>, since each value will be considered alongside itself anyway.</li>\n</ul>\n\n<p>This will reduce the length of our loops. It may actually <em>increase</em> the time we spend sorting/culling, but that will depend on the input data. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def three_sum(nums: List[int]) -&gt; Set[Tuple[int,int,int]]:\n indexed_culled = enumerate(sorted(set(nums)))\n return {\n (a, b, c)\n for (a, i_a) in indexed_culled\n for (b, i_b) in indexed_culled[i_a:]\n for (c, _) in indexed_culled[i_b:]\n if 0 == (a + b + c)\n }\n</code></pre>\n\n<p>This is still lacking in the kind of maximal efficiency your code seems to be striving for. It <em>is</em> the version I'd want to see in most production situations, but if runtime optimization is critical then maybe we should try to shorten/avoid the innermost loop. If the <code>c</code> loop has five items to run, in ascending integer value, and the first <code>a + b + c</code> is 1, then we shouldn't have to do the other four.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def three_sum(nums: List[int]) -&gt; Set[Tuple[int,int,int]]:\n culled = set(nums)\n indexed = enumerate(sorted(culled))\n pairs = {\n (a, b)\n for (a, i_a) in indexed\n for (b, _) in indexed[i_a:]\n }\n return {\n (a, b, 0 - (a + b))\n for (a, b) in pairs\n if 0 - (a + b) in culled\n }\n</code></pre>\n\n<p>Of course if runtime optimization is critical, you'll want someone better versed than me in python's different iterable types to reconsider all my Set/List/Tuple/Generator choices. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:15:45.713", "Id": "430143", "Score": "0", "body": "Amazing answer! +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:14:45.497", "Id": "222289", "ParentId": "222278", "Score": "4" } } ]
{ "AcceptedAnswerId": "222289", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T12:25:09.447", "Id": "222278", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "k-sum" ], "Title": "Leetcode 15 - 3 sum" }
222278
<p>So I have an user which can create his own Locations. <a href="https://i.stack.imgur.com/pE0AI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pE0AI.png" alt="data model"></a></p> <p>I implemented a webservice in order to add and update locations. If the user is not the owner of the location i want to throw an appropriate exception so that the user knows whats wrong.</p> <p>The current method looks like this:</p> <pre><code>private void updateLocation(String loginToken, MapLocation ml) throws Exception{ String username = this.getUsernameBySingInToken(loginToken); //throws exception is wrong token, otherwise returns username PreparedStatement stmt = conn.prepareStatement("SELECT username FROM Location WHERE idLoc=?"); stmt.setInt(1, ml.getLocationId()); ResultSet rs = stmt.executeQuery(); String actuallUsername = null; while (rs.next()) { actuallUsername=rs.getString("username"); } if(actuallUsername==null) throw new Exception("no location found!!"); //appropriate exception if(!username.equals(actuallUsername) || !username.equals(ml.getUsername())) throw new Exception("you are not the creator of this location!"); //appropriate exception PreparedStatement stmtVerification = conn.prepareStatement("UPDATE Location SET positionX=?,positionY=?" + " WHERE idLoc=?"); stmtVerification.setDouble(1, ml.getPosX()); stmtVerification.setDouble(2, ml.getPosY()); stmtVerification.setInt(3, ml.getLocationId()); stmtVerification.executeUpdate(); disconnectFromMySQL(); } </code></pre> <p>The second method I implemented is shorter but the errors are not clear:</p> <pre><code>private void updateLocationV2(String loginToken, MapLocation ml) throws Exception{ String username = this.getUsernameBySingInToken(loginToken); if(!username.equals(ml.getUsername())) throw new Exception("username is not the same as username of maplocation object"); //not sure if neccesary PreparedStatement stmtVerification = conn.prepareStatement("UPDATE Location SET positionX=?,positionY=?" + " WHERE idLoc=? and username=?"); stmtVerification.setDouble(1, ml.getPosX()); stmtVerification.setDouble(2, ml.getPosY()); stmtVerification.setInt(3, ml.getLocationId()); stmtVerification.setString(4, username); int executeUpdate = stmtVerification.executeUpdate(); if(executeUpdate==0) throw new Exception("update failed. either wrong username or idLocation is wrong"); //not clear what is the error BUT shorter disconnectFromMySQL(); } </code></pre> <p>So yeah, now I have two methods which update my location but I am not sure which of them is the best. The first method has the advantage that the errors are clear but its slower since I have two queries (select and update). the second method is faster but the errors are not clear. WHich one of them is better, or is there even a better solution?</p> <p>EDIT: This is my webservice method which calls the update function:</p> <pre><code>@PUT @Path("/update") @Consumes({MediaType.APPLICATION_JSON}) public Response update(String token, MapLocation ml) { Response r = Response.status(Response.Status.OK).entity("location updated").build(); try { isUpdated = db.updateLocation(token,ml); } catch (Exception ex) { r = Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build(); } return r; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T12:40:14.647", "Id": "430274", "Score": "0", "body": "Without seeing the rest of the class it is very hard to tell which is the better of the two functions. It also depends on what the requirements for the implementation are. The question is also unclear because there could be a third way that is best." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:29:21.643", "Id": "430283", "Score": "0", "body": "@pacmaninbw there are no requirements. I am making my own project. So right know I dont know whats the best way to make an update. Yes there could be better solutions but i dont know which is the best" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:36:10.987", "Id": "430803", "Score": "2", "body": "@SavanLuffy even if it's your own project you have requirements. If you don't know them you should think them out :)" } ]
[ { "body": "<p>Soo ... I'm not quite sure how to formulate this without it sounding brash, but... Both of these methods are less than ideal...</p>\n\n<p>Let's follow the behavioural flow to see what issues this code has:</p>\n\n<ul>\n<li>The webservice portion you provide only understands <code>PUT</code> requests.<br>\nConventionally, PUT requests are used to <strong>create</strong> objects, not to update them.\nInstead one would expect a POST endpoint for that.</li>\n<li><p>You first create an OK response and then overwrite it in case something fails.\nThat's somewhat... annoying in comparison to the simpler direct return.</p>\n\n<pre><code>try {\n db.updateLocation(token, ml);\n return Response.status(Status.OK).entity(\"location updated\").build();\n} catch (Exception e) {\n return Response.status(Status.BAD_REQUEST).entity(ex.getMessage()).build();\n}\n</code></pre></li>\n<li><p>All this code assumes that the user gets to see the Exception message.<br>\nThis is a bad assumption. Your webservice method should be responsible for creating useful messages, not your business logic. </p></li>\n<li>Considering that the webservice code does not compile (because the declaration for <code>isUpdated</code> is missing) I hope that you don't actually pretend that every Exception ever is the user's fault by throwing a HTTP 400 to them...</li>\n</ul>\n\n<p>The root cause of your conundrum is that you're not using the power of widely used java sql abstractions. Instead of manually writing SQL statements and performing updates, you should really make use of JPA and Entities.</p>\n\n<p>If you had these, all of this would boil down to the following simplified code:</p>\n\n<pre><code>private void updateLocation(String username, MapLocation update) {\n MapLocation stored = em.find(MapLocation.class, update.getLocationId());\n if (stored == null) {\n throw new LocationDoesNotExistException();\n }\n if (!stored.getUsername().equals(username)) {\n throw new IllegalLocationUpdateException();\n }\n em.persist(update);\n}\n</code></pre>\n\n<p>Note that the codesample above makes some simplifying assumptions about transaction management and the class hierarchy of the Exceptions it throws.</p>\n\n<p>Note that I'm suggesting to rewrite your webservice method to something like:</p>\n\n<pre><code>public Response update(String loginToken, MapLocation request) {\n final String username = getUsernameFromToken(loginToken);\n try {\n db.updateLocation(username, request);\n return Response.ok().build();\n } catch (LocationDoesNotExistException e) {\n return Response.status(Response.Status.NOT_FOUND).build();\n } catch (IllegalLocationUpdateException e) {\n return Response.status(Response.Status.FORBIDDEN).build();\n } catch (Exception e) {\n LOGGER.warn(\"Unexpected exception in updateLocation\", e);\n return Response.serverError().build();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T23:25:58.410", "Id": "430331", "Score": "0", "body": "@Vogel623 thank you for the detailed answer. I never heard of JPA, I will defenitly look it up. As far as I know its bad practise to have more than 1 return value, thats why I only use one response object which gets overwritten if an error occurs. Are you sure that PUT is meant to CREATE update objects and POST to UPDATE them? I thought its the exact opposite?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T22:37:29.500", "Id": "222381", "ParentId": "222279", "Score": "2" } } ]
{ "AcceptedAnswerId": "222381", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T12:27:36.607", "Id": "222279", "Score": "3", "Tags": [ "java", "performance", "comparative-review", "rest", "web-services" ], "Title": "Most efficient way to check if user is allowed to update an object" }
222279
<p>With this algorithm I update an automatically generated verilog-file. The update within this file is done by commenting the assigned wires to specific ports of module instances.</p> <p>Is there a better, more elegant or more optimized way to do this than with this algorithm?</p> <pre><code>file_name = "test.v" # name of the verilog file test = ".test" # port name 1 tezt = ".tezt" # port name 2 dummy = [] # buffer for the updated string with open(file_name, "r+") as f: lines = f.readlines() f.seek(0) f.truncate() # clear the file for line in lines: if test in line or tezt in line: # check if one of the ports is in the line if line[line.index('(')+1] != '/': # check if the assigned wire is already is commented for c in line: # update the line and comment the wire name within the brackets if c == ')': dummy.append("*/") dummy.append(c) if c == '(': dummy.append("/*") line = line.replace(line, "".join(dummy)) # replace the old line with the new string dummy.clear() f.write(line) f.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:15:39.550", "Id": "430129", "Score": "1", "body": "Welcome to Code Review! \"... done by *commenting* the assigned wires ...\" should likely be \" ... *connecting* ...\", no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:26:53.103", "Id": "430136", "Score": "0", "body": "@AlexV Looking at the `dummy.append(\"*/\")`, it looks like the are _commenting_ the wires." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:30:07.427", "Id": "430141", "Score": "0", "body": "@Peilonrayz On the second look that might actually be true :-)" } ]
[ { "body": "<ul>\n<li>You don't need to manually call <code>f.close()</code>, that's what the <code>with</code> is for.</li>\n<li>It looks like <code>line = line.replace(line, \"\".join(dummy))</code> can just be <code>line = \"\".join(dummy)</code>.</li>\n<li><p>It's clearer to define <code>dummy</code> in the if statement:</p>\n\n<ul>\n<li>This means that it's in the correct scope, meaning we don't have to look out for it being used elsewhere.</li>\n<li>It also means that you can remove <code>dummy.clear()</code>.</li>\n</ul></li>\n<li>Personally I would merge your two <code>if</code> statements together, to reduce the arrow anti-pattern.</li>\n<li>It looks like <code>dummy</code> and your <code>for</code> loop can be replaced with <a href=\"https://docs.python.org/3/library/stdtypes.html#str.maketrans\" rel=\"noreferrer\"><code>str.maketrans</code></a> and <a href=\"https://docs.python.org/3/library/stdtypes.html#str.translate\" rel=\"noreferrer\"><code>str.translate</code></a>.</li>\n</ul>\n\n<p><sub>untested</sub></p>\n\n<pre><code>file_name = \"test.v\"\ntest = \".test\"\ntezt = \".tezt\"\ntrans_table = str.maketrans({'(': '(/*', ')': '*/)'})\n\nwith open(file_name, \"r+\") as f:\n lines = f.readlines()\n f.seek(0)\n f.truncate()\n for line in lines:\n if ((test in line or tezt in line)\n and line[line.index('(') + 1] != '/'\n ):\n line = line.translate(trans_table)\n f.write(line)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T05:12:21.600", "Id": "430474", "Score": "0", "body": "Thank you for your improvements. I knew that it could be optimized. The two string methods are new to me, but it's good to know that they exist." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:42:43.503", "Id": "222286", "ParentId": "222280", "Score": "5" } } ]
{ "AcceptedAnswerId": "222286", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T12:43:09.310", "Id": "222280", "Score": "6", "Tags": [ "python", "algorithm", "python-3.x", "file" ], "Title": "Updating generated file" }
222280
<p>I work as an IT intern in a multinational and I was given a tedious task of combing through a 2500+ long multi-column excel report file in search of inactive servers.</p> <p>Here's a sample row from that file:</p> <p><a href="https://i.stack.imgur.com/ABhb2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ABhb2.png" alt="enter image description here"></a></p> <p>Then, I got another excel file but this time with just the DB Codes (80+ of them).</p> <p>My task was:</p> <ul> <li>Go through the big report file</li> <li>Find the company by its DB Code</li> <li>Check if the server is active or not active, and if not active flag it for a decommission</li> </ul> <p>Of course, as you might expect, I was told to return the results in a spreadsheet in the following format:</p> <p><code>Full name: Acme Inc. | Code: ACM | Active?: no | Decomm?: yes</code></p> <p><code>Fulln name:, Code:, etc.</code> are column headers. Here, they are just for readability.</p> <p>If I were to do it manually, I'd most probably die of boredom. But! There's Python, right?</p> <p>So, I exported some of the columns from the report into a tab delimited file and drafted this:</p> <pre><code>def read_file_to_list(file_name): with open(file_name, 'r') as file_handler: stuff = file_handler.readlines() return [line[:-1] for line in stuff] def make_dic(file_name): with open(file_name, 'r') as f: rows = (line.replace('"', "").strip().split("\t") for line in f) return {row[0]:row[1:] for row in rows} def search(dic, ou_codes): counter = 1 with open("output.txt", "w") as output: #writing a header output.write("Full name\tCode\tActive?\tDecomm?\n") for k, v in dic.items(): for code in ou_codes: if v[0] == code: #writing back line by line to a tab delimited file outputline = "{}\t{}\t{}\t{}\n".format(k, *v, "yes" if v[1] == "no" else "no") output.write(outputline) print("{}. Full name: {} | Code: {} | Active?: {} | Decomm?: {}".format(counter, k, *v, "yes" if v[1] == "no" else "no")) counter += 1 decomm_codes = read_file_to_list('t1.txt') all_of_it = make_dic('t2.txt') search(all_of_it, decomm_codes) </code></pre> <p>That spits out:</p> <pre><code>1. Full name: Random, Inc | Code: RNDM | Active?: yes | Decomm?: no 2. Full name: Acme Inc.| Code: ACM | Active?: no | Decomm?: yes 3. Full name: Fake Bank, Ltd. | Code: FKBNK | Active?: yes | Decomm?: no </code></pre> <p>Is there a way refactor the <code>search</code> method?</p> <p>Finally, here's the contents of the <code>decomm_codes.txt</code> and <code>big_report.txt</code> files.</p> <p>decomm_codes.txt:</p> <pre><code>RNDM ACM FKBNK </code></pre> <p>big_report.txt:</p> <pre><code>"Random, Inc" RNDM yes Acme Inc. ACM no "Fake Bank, Ltd. " FKBNK yes </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:24:58.653", "Id": "430134", "Score": "5", "body": "\"... but how do I write the results back into a tab-delimited text file?\" is likely [off-topic](https://codereview.stackexchange.com/help/dont-ask) here, since only existing and working code can be reviewed. Apart from that it seems like a good question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:02:58.367", "Id": "222281", "Score": "5", "Tags": [ "python", "python-3.x", "parsing", "excel" ], "Title": "Parsing Long Excel Report Files for Predefined Results" }
222281
<p>I am learning to work with OOP design patterns and so I challenged myself with the idea of creating a way to generate a pdf invoice based on some information entered. So, this is what I have done so far and would like to have some review on my approach and design. </p> <p>Invoice.py </p> <pre><code>import fpdf from datetime import datetime class Creator: def __init__(self,first_name,last_name,email,phone_num,address,city,country): self.first_name = first_name self.last_name = last_name self.email = email self.phone_num = phone_num self.address = address self.city = city self.country = country class Organization: def __init__(self,name,address,city,country): self.name = name self.address = address self.city = city self.country = country class BankAccountDetail: def __init__(self,account_name,account_num,currency,bank_name,branch,branch_addr): self.account_name = account_name self.account_num = account_num self.currency = currency self.bank_name =bank_name self.branch = branch self.branch_addr = branch_addr class Project: def __init__(self,name,description,amount): self.name = name self.description = description self.amount = amount class Invoice: ''' Invoice class used to model a invoice object which is a composition of 1. Creator Object 2. Organization Object 3. Project Object 4. BankDetail Object ''' def __init__(self,invoice_num,creator,organization,project,bankaccountdetail): self.invoice_num = invoice_num self.creator = creator self.organization = organization self.project = project self.bankaccountdetail = bankaccountdetail class File: def __init__(self,filename,font_size,line_height,orientation): self.filename = filename self.font_size = font_size self.line_height = line_height self.orientation = orientation class PdfInvoice(Invoice): ''' Inherits from the Parent Invoice class and has an extra feature 1. File Object : Used to specify some basic details about the file ''' def __init__(self,invoice_num,creator,organization,project,bankaccountdetail,file): super().__init__(invoice_num,creator,organization,project,bankaccountdetail) self.file = file def generate_pdf(self): dt = datetime.now() date = dt.date() pdf = fpdf.FPDF(format=self.file.orientation) pdf.add_page() pdf.set_font("Arial", size=self.file.font_size) pdf.write(self.file.line_height,"Invoice Number #") pdf.write(self.file.line_height,self.invoice_num) pdf.ln() pdf.write(self.file.line_height,"Date Invoiced #") pdf.write(self.file.line_height,str(date)) pdf.ln() pdf.write(self.file.line_height, "Billed By #") pdf.write(self.file.line_height,"{}{}".format(self.creator.first_name,self.creator.last_name)) pdf.ln() pdf.write(self.file.line_height,"Address #") pdf.write(self.file.line_height,self.creator.address) pdf.ln() pdf.write(self.file.line_height, "City #") pdf.write(self.file.line_height, self.creator.city) pdf.ln() pdf.write(self.file.line_height,"Country #") pdf.write(self.file.line_height,self.creator.country) pdf.ln() pdf.write(self.file.line_height, "Email #") pdf.write(self.file.line_height, self.creator.email) pdf.ln() pdf.write(self.file.line_height, "Phone Number #") pdf.write(self.file.line_height, self.creator.phone_num) pdf.ln() pdf.write(self.file.line_height,"Billed To #") pdf.ln() pdf.write(self.file.line_height,"Organization Name #") pdf.write(self.file.line_height,self.organization.name) pdf.ln() pdf.write(self.file.line_height, "Organization Address #") pdf.write(self.file.line_height, self.organization.address) pdf.ln() pdf.write(self.file.line_height, "Organization City #") pdf.write(self.file.line_height, self.organization.city) pdf.ln() pdf.write(self.file.line_height, "Organization Country #") pdf.write(self.file.line_height, self.organization.country) pdf.ln() pdf.write(self.file.line_height, "Comments #") pdf.write(self.file.line_height, self.project.description) pdf.ln() pdf.write(self.file.line_height, "Amount #") pdf.write(self.file.line_height,str(self.project.amount)) pdf.ln() pdf.write(self.file.line_height,'Account details ') pdf.ln() pdf.write('Account Name #') pdf.write(self.file.line_height,self.bankaccountdetail.account_name) pdf.ln() pdf.write('Account Number #') pdf.write(self.file.line_height,self.bankaccountdetail.account_num) pdf.ln() pdf.write('Account Currency #') pdf.write(self.file.line_height, self.bankaccountdetail.currency) pdf.ln() pdf.write('Bank Name #') pdf.write(self.file.line_height, self.bankaccountdetail.bank_name) pdf.ln() pdf.write('Branch Address #') pdf.write(self.file.line_height, self.bankaccountdetail.branch_addr) pdf.ln() pdf.output(self.file.filename) creator = Creator('Test','User','test@gmail.com', '099006789','Joans Apartment, 123 Test road','Nairobi','Kenya') organization = Organization('Test Org','Ndemi Road Kilimani', 'Nairobi','Kenya') bank_detail = BankAccountDetail('Test User','999999678','KES', 'Test Bank','Kenya','BRANCH Way, ABC Place') file = File("Invoice.pdf",12,5,"letter") project = Project('Ecommerce site','Worked on the ecommerce site',10.900) pdf_inv = PdfInvoice('1393939',creator,organization,project,bank_detail,file) pdf_inv.generate_pdf() </code></pre> <p><a href="https://i.stack.imgur.com/3oHBm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3oHBm.png" alt="UML diagram"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:03:45.430", "Id": "430142", "Score": "0", "body": "Welcome to Code Review! Is this supposed to work in Python 2 or Python 3? Please add the according tag to your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:18:34.337", "Id": "430144", "Score": "0", "body": "@AlexV:- Thank you. I have added the tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:09:28.747", "Id": "430188", "Score": "1", "body": "Rendering text onto the PDF using one statement per string is quite tedious. Consider using a higher-level library or templating language such as [ReportLab](https://www.reportlab.com)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T22:21:42.037", "Id": "430233", "Score": "0", "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 5 → 4" } ]
[ { "body": "<h2>Data classes</h2>\n\n<p>Since you are using the classes as immutable data containers, it would be possible to significantly cut down the amount of code you have to write to create all of them using <code>namedtuple</code> from the <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"noreferrer\"><code>collections</code></a> module:</p>\n\n<pre><code>from collections import namedtuple\n\nCreator = namedtuple(\"Creator\", [\"first_name\", \"last_name\", \"email\", \"phone_num\",\n \"address\", \"city\", \"country\"])\n\n\nOrganization = namedtuple(\"Organination\", [\"name\", \"address\", \"city\", \"country\"])\n\n\nBankAccountDetail = namedtuple(\"BankAccountDetail\", [\"account_name\", \"account_num\",\n \"currency\", \"bank_name\", \"branch\", \"branch_addr\"])\n\n\nProject = namedtuple(\"Project\", [\"name\", \"description\", \"amount\"])\n\n\nFile = namedtuple(\"File\", [\"filename\", \"font_size\", \"line_height\", \"orientation\"])\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"noreferrer\"><code>dataclasses</code></a> might also be used to get a similar result.</p>\n\n<hr>\n\n<h2>Code duplication</h2>\n\n<p>There is a massive amount of duplicate code in <code>generate_pdf</code>. You could layout the document using a list and string formatting and then iterate over that list to finally write it to a file. Let me give you a sketch of what I mean (Note: the code below is untested):</p>\n\n<pre><code>def generate_pdf(self):\n dt = datetime.now()\n date = dt.date()\n pdf = fpdf.FPDF(format=self.file.orientation)\n pdf.add_page()\n pdf.set_font(\"Arial\", size=self.file.font_size)\n\n pdf_content = [\n f\"Invoice Number #{self.invoice_num}\", \n f\"Date Invoiced #{date}\",\n # and so on and so forth\n ]\n\n for line in pdf_content:\n pdf.write(self.file.line_height, line)\n pdf.ln()\n\n pdf.output(self.file.filename)\n</code></pre>\n\n<p>The code uses f-string, which are available since Python 3.6. If you are using an older version of Python you will have to use <code>.format</code> instead such as you do in several places already.</p>\n\n<p>There might be even better ways to do this, but I have no specific knowledge about that special library.</p>\n\n<hr>\n\n<h2>Misc</h2>\n\n<p>It might be a good idea to have a look at the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">official Style Guide for Python Code</a> (often just called PEP8) for short. It's a collection of style recommendations and other paradigms that allow you to write compelling and visually appealing Python code.</p>\n\n<p><code>file</code> in <code>file = File(\"Invoice.pdf\", 12, 5, \"letter\")</code> is not a good variable name since you overwrite Python's <code>file</code> command with this. At least append a <code>_</code> to make it <code>file_</code> or choose another name altogether.</p>\n\n<p>Maybe it would also be worth to have a look at <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"noreferrer\"><code>if __name__ == \"__main__\":</code></a> to separate the \"library part\" from the example code.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from datetime import datetime\nfrom collections import namedtuple\n\nimport fpdf\n\n\nCreator = namedtuple(\"Creator\", [\"first_name\", \"last_name\", \"email\", \"phone_num\",\n \"address\", \"city\", \"country\"])\n\n# all the other code ...\n\nif __name__ == \"__main__\":\n creator = Creator('Test', 'User', 'test@gmail.com', '099006789',\n 'Joans Apartment, 123 Test road', 'Nairobi', 'Kenya')\n\n organization = Organization('Test Org', 'Ndemi Road Kilimani', 'Nairobi',\n 'Kenya')\n\n bank_detail = BankAccountDetail('Test User', '999999678', 'KES', 'Test Bank',\n 'Kenya', 'BRANCH Way, ABC Place')\n\n file = File(\"Invoice.pdf\", 12, 5, \"letter\")\n\n project = Project('Ecommerce site', 'Worked on the ecommerce site', 10.900)\n\n pdf_inv = PdfInvoice('1393939', creator, organization, project, bank_detail,\n file)\n pdf_inv.generate_pdf()\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:53:09.640", "Id": "430210", "Score": "0", "body": "@AlexV- This is so helpful. I really appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:46:49.783", "Id": "222303", "ParentId": "222285", "Score": "7" } }, { "body": "<p>Might want to look at LaTex. It's a lot less code and it IS possible to add comments in, so it's definetly possible to use it as both a template and a way to generate a pdf!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T21:43:58.423", "Id": "222328", "ParentId": "222285", "Score": "1" } } ]
{ "AcceptedAnswerId": "222303", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T13:34:04.357", "Id": "222285", "Score": "6", "Tags": [ "python", "python-3.x", "object-oriented", "pdf" ], "Title": "Class to generate a pdf invoice" }
222285
<p>I've made a section of my site to have two grids side by side. On the left-hand side is one big static (sticky in my case) image, on the right-hand side is a (grid) long column of several other images, that is scrollable. So as the user scrolls the grid on the right-hand side of the page, the grid on the left remains 'stuck' until the user has reached the end of the grid on the right. </p> <p>My code below works, but I was wondering if there a more elegant way of doing this?</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-css lang-css prettyprint-override"><code>html, body, p, ol, ul, li { background-color: #1A1A1A; margin: 0; padding: 0; } .container { height: 100vh; width: 95%; margin: auto; position: relative; } #tattoos { width: 95%; display: flex; justify-content: space-between; height: 2000px; position: relative; } #sectionOne { display: grid; height: 100vh; grid-template-rows: repeat(1, 1fr); grid-template-columns: repeat(1, 1fr); grid-gap: 15px; width: 60%; position: sticky; top: 0; } .gallery-item { display: flex; justify-content: center; align-items: center; opacity: 1; text-transform: uppercase; font-family: 'Lora'; font-weight: 700; color: white; font-size: 9vw; } #image-one { background-image: url("https://i.ibb.co/HXfG735/tattoo.jpg"); background-size: cover; background-position: 0% 80%; box-shadow: inset 0 0 0 2000px rgba(0, 0, 0, 0.8); margin: 4% 0; } .sectionTwo { width: 37%; display: grid; height: 1940px; grid-template-rows: repeat(7, 1fr); grid-template-columns: repeat(1, 1fr); grid-gap: 30px; margin: 2.5% 0; } #image-two { background-image: url("https://i.ibb.co/kBJrryt/7ab34470-9318-4fc1-a6da-656ca31399c5.jpg"); background-size: cover; background-position: 0% 80%; } #image-three { background-image: url("https://i.ibb.co/SKCnT4d/b19aaf2a-84cf-42b4-9ccd-6205ca1be395.jpg"); background-size: cover; background-position: 0% 50%; } #image-four { background-image: url("https://i.ibb.co/xF4Qv50/b5d6695b-2142-42cc-8eef-2963311edfd6.jpg"); background-size: cover; background-position: 0% 60%; } #image-eight { background-image: url("https://i.ibb.co/0nY3VDG/d1ecf205-6b1b-4a1a-b94b-7d75aa177464.jpg"); background-size: cover; background-position: 0% 60%; } #image-nine { background-image: url("https://i.ibb.co/QYf6vDY/48a63fe2-066b-42d1-9211-040c6977ceff.jpg"); background-size: cover; background-position: 0% 40%; } #image-ten { background-image: url("https://i.ibb.co/7RdJqgP/ce30fff2-1679-403f-8431-c6be4f8b1466.jpg"); background-size: cover; background-position: 0% 80%; } #image-twelve { background-image: url("https://i.ibb.co/BtJxDc7/24b54530-710f-4173-a32a-36bd24a496e0.jpg"); background-size: cover; background-position: 0% 50%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="tattoos" class="container"&gt; &lt;section id="sectionOne"&gt; &lt;div id="image-one" class="gallery-item"&gt; tatujes &lt;/div&gt; &lt;/section&gt; &lt;section class="sectionTwo"&gt; &lt;div id="image-two" class="gallery-item"&gt;&lt;/div&gt; &lt;div id="image-three" class="gallery-item"&gt;&lt;/div&gt; &lt;div id="image-four" class="gallery-item"&gt;&lt;/div&gt; &lt;div id="image-eight" class="gallery-item slide"&gt;&lt;/div&gt; &lt;div id="image-nine" class="gallery-item slide"&gt;&lt;/div&gt; &lt;div id="image-ten" class="gallery-item slide"&gt;&lt;/div&gt; &lt;div id="image-twelve" class="gallery-item slide"&gt;&lt;/div&gt; &lt;/section&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T12:01:10.770", "Id": "435001", "Score": "0", "body": "Why did you decide to make sectionOne an ID and sectionTwo a class? Does it have any specific reason or was it by accident. I think as a naming convention this is a bit confusing." } ]
[ { "body": "<p>Although this is not a full answer It will shorten your code,\nYou could remove 'background-size:cover;' &amp; replace it with a class of bGCov,\n(As your declaring this multiple times &amp; if your application grows larger With many more Images, this will save many, many lines of code) \nAswell as Use Bitly URL shortener, to shorten all of your Image URL links, make sure to name them something farely short but related to the actual image as it makes keeping track of them easier later on.\nAlso if you started using scss background-position and a few other things could be made into variables.\nthis would shorten you code for a few lines... </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-17T17:02:06.903", "Id": "224356", "ParentId": "222287", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:03:03.433", "Id": "222287", "Score": "3", "Tags": [ "html", "css" ], "Title": "Two CSS grids side by side, one is scrollable, the other isn't" }
222287
<p>Everytime a new visitor comes to my webshop I write a cookie (1d) which sets a session entry with mt_rand(1,2) to A or B group.</p> <pre><code>if(empty($_GET["cltestuser"])) { if(empty($_COOKIE['cl_customergroup_test'])) { $cookieValue = "cl_use_default"; if(mt_rand(1, 2) == 1) { $cookieValue = "A"; } else { $cookieValue = "B"; } setcookie("cl_customergroup_test", $cookieValue, time() + (86400 * 30)); //1 day $_COOKIE['cl_customergroup_test'] = $cookieValue; } $_SESSION["Customergroup"]-&gt;cl_testuser = $_COOKIE['cl_customergroup_test']; } else { $cookieValue = strtoupper($_GET["cltestuser"]); setcookie("cl_customergroup_test", $cookieValue, time() + (86400 * 30)); //1 day $_COOKIE['cl_customergroup_test'] = $cookieValue; $_SESSION["Customergroup"]-&gt;cl_testuser = $_COOKIE['cl_customergroup_test']; } </code></pre> <p>So the site is the same now for A and B visitors. The testing sample is 15,000 visitors where 150 people bought goods. </p> <p>(Note: 15,000 times in a for loop with the mt_rand(1,2) is nearly even (7500/7500))</p> <p><strong>But the conversion for B is about 30% higher then A.</strong></p> <p>When you have cookies blocked you cannot buy. There are no returning customers.</p> <p>Is this breaking the law of the great numbers? Where does this come from?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T16:14:30.697", "Id": "430173", "Score": "0", "body": "Welcome to Code Review. Is the code working as expected or not, we can only review working code and can't help debug issues. Please see https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T17:51:02.827", "Id": "430186", "Score": "3", "body": "I don't understand. You did an A-B test and came to a conclusion. Now you're doubting the experiment just because the null hypothesis was rejected? So why do the experiment at all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T08:26:37.530", "Id": "430262", "Score": "1", "body": "@200_success in OP's defense, the null hypothesis (\"_buying decisions are not influenced by invisible cookie values_\") appears airtight. @Thomas-z you have a sample size problem. Run `mt_rand(100,299)` 15000 times. `100` and `200` are conversions. Examine their distribution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T05:54:23.217", "Id": "430476", "Score": "0", "body": "@OhMyGoodness could you explain that a little bit more? Why do I have a sample size problem? Is the 15,000 visitors the problem, it appears enough for me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T09:28:13.167", "Id": "430526", "Score": "0", "body": "@ThomasZ. you didn't run the `mt_rand(100,299)` experiment that I described. Suppose you sold 15,000,000 lotto tickets to A and B, and then A wins two jackpots and B wins one — a difference of 100%! How is that possible with a sample size of 15M? Is the sample size actually 15M?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:21:04.993", "Id": "222290", "Score": "1", "Tags": [ "php", "e-commerce" ], "Title": "Webshop Conversion - Binary testing is not even" }
222290
<p>I have a water reservoir with input and output rates. I want to determine when the input is exceeding the output by a certain constant. To accomplish this, I need to cumulatively sum all cases where the inflow exceeds the outflow. Thus, I've written this function:</p> <pre class="lang-py prettyprint-override"><code>def pos_diff_cum_sum(flow_in: np.ndarray, flow_out: np.ndarray) -&gt; np.ndarray: sums = [] cum_sum = 0 diff = list(flow_in - flow_out) for dd in diff: cum_sum += dd if cum_sum &lt; 0: cum_sum = 0 sums.append(cum_sum) return np.array(sums) </code></pre> <p>It sums up the periods where the inflow exceeds the outflow while ignoring periods where the opposite is true. Basically, <code>numpy.cumsum</code> with a corner case.</p> <h2>Tests with plots</h2> <pre class="lang-py prettyprint-override"><code>t_steps = 9 fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8)) in_flow = np.linspace(1., 0., t_steps) out_flow = np.linspace(0., 1., t_steps) ax1.plot(in_flow, label="in") ax1.plot(out_flow, label="out") ax1.legend() pos_diff = pos_diff_cum_sum(in_flow, out_flow) ax2.plot(pos_diff) pos_diff # =&gt; array([1. , 1.75, 2.25, 2.5 , 2.5 , 2.25, 1.75, 1. , 0. ]) </code></pre> <p><a href="https://i.stack.imgur.com/X3WMB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/X3WMB.png" alt="first example"></a></p> <pre class="lang-py prettyprint-override"><code>t_steps = 9 fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(4, 8)) in_flow = np.linspace(0., 1., t_steps) out_flow = np.linspace(1., 0., t_steps) ax1.plot(in_flow, label="in") ax1.plot(out_flow, label="out") ax1.legend() pos_diff = pos_diff_cum_sum(in_flow, out_flow) ax2.plot(pos_diff) pos_diff # =&gt; array([0. , 0. , 0. , 0. , 0. , 0.25, 0.75, 1.5 , 2.5 ]) </code></pre> <p><a href="https://i.stack.imgur.com/DHShx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DHShx.png" alt="enter image description here"></a></p> <p>This code isn't vectorized, but it's going to be called very frequently, so is there some way I should speed it up? Is there any way to make this more elegant?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:01:35.193", "Id": "430154", "Score": "0", "body": "Can these graphs only go below zero at the beginning/end - like in the example? Can they go below zero half way through?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:10:11.553", "Id": "430157", "Score": "0", "body": "I'm pretty sure you can iterate over a Numpy 1D array just as if it was a list. So converting it to a list seems unnecessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:56:34.843", "Id": "430167", "Score": "0", "body": "@Peilonrayz none of the graphs ever go below zero? Flows are always positive. The difference I calculate is explicitly made positive." } ]
[ { "body": "<p>There's two steps I think you could leave out:</p>\n\n<ol>\n<li>Casting the diff as a list, you can iterate over a numpy array just fine</li>\n<li><p>Checking if cum_sum is smaller than zero, you can check this using max()</p>\n\n<pre><code>def pos_diff_cum_sum(flow_in: np.ndarray, flow_out: np.ndarray) -&gt; np.ndarray:\n\n sums = []\n cum_sum = 0\n diff = flow_in - flow_out\n\n for dd in diff:\n cum_sum = max(cum_sum + dd, 0)\n sums.append(cum_sum)\n\n return np.array(sums)\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:45:57.387", "Id": "430162", "Score": "0", "body": "Surprisingly, replacing the `if` with `max` makes the function slightly slower, according to my benchmarking." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:19:44.900", "Id": "222298", "ParentId": "222291", "Score": "2" } }, { "body": "<p>You can use <code>np.cumsum</code> and <code>np.minimum.accumulate</code> (which I <a href=\"https://stackoverflow.com/a/41526917\">found from this post</a>).</p>\n\n<p>Another way to look at what you want is you want the cumsum.</p>\n\n<p>If the value goes below zero then you want to subtract a value to get it to zero, this value is itself. This means that you just need a running minimum. This is as you've subtracted the value from an earlier value so the effect propagates in your version but not in <code>np.cumsum</code>.</p>\n\n<p>You also want to start this <code>minumum</code> from <code>0</code>.</p>\n\n<pre><code>def pos_diff_cum_sum(flow_in, flow_out):\n delta = np.cumsum(flow_in - flow_out)\n return delta - np.minimum.accumulate(np.append([0], delta))[1:]\n</code></pre>\n\n<hr>\n\n<p>For reference below.</p>\n\n<pre><code>def fn(in_, out):\n delta = np.cumsum(np.array(in_) - np.array(out))\n print(delta)\n output = delta - np.minimum.accumulate(np.append([0], delta))[1:]\n print(np.minimum.accumulate(np.append([0], delta))[1:])\n print(output)\n</code></pre>\n\n<p>If you have an input that only increases then you can just use use <code>np.cumsum</code>:</p>\n\n<pre><code>&gt;&gt;&gt; fn([1, 1, 1, 1, 1], [0, 0, 0, 0, 0])\n[1 2 3 4 5]\n[0 0 0 0 0]\n[1 2 3 4 5]\n</code></pre>\n\n<p>However if the number goes negative you must subtract all values after it goes negative by that value. This is as the single <code>-=</code> affects the rest of the input in the OP:</p>\n\n<pre><code>&gt;&gt;&gt; fn([1, 0, 0, 0, 0], [0, 1, 1, 0, 0])\n[ 1 0 -1 -1 -1]\n[ 0 0 -1 -1 -1]\n[1 0 0 0 0]\n</code></pre>\n\n<p>This means you must subtract them even if the value becomes positive again:</p>\n\n<pre><code>&gt;&gt;&gt; fn([1, 0, 0, 1, 1], [0, 1, 1, 0, 0])\n[ 1 0 -1 0 1]\n[ 0 0 -1 -1 -1]\n[1 0 0 1 2]\n</code></pre>\n\n<p>If more numbers go negative then you have to decrease by these amounts too:</p>\n\n<pre><code>&gt;&gt;&gt; fn([1, 0, 0, 0, 0], [0, 1, 1, 1, 1])\n[ 1 0 -1 -2 -3]\n[ 0 0 -1 -2 -3]\n[1 0 0 0 0]\n</code></pre>\n\n<p>This allows the value to go positive again if it needs to:</p>\n\n<pre><code>&gt;&gt;&gt; fn([1, 0, 0, 0, 1], [0, 1, 1, 1, 0])\n[ 1 0 -1 -2 -1]\n[ 0 0 -1 -2 -2]\n[1 0 0 0 1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:54:43.407", "Id": "430166", "Score": "0", "body": "I'm a bit confused by your explanation. I understand subtract a value to get zero. However, hows does it follow that I need a running minimum?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:58:07.370", "Id": "430168", "Score": "1", "body": "Because you need to subtract that from ever value afterwards. Because if you subtract at any point in the cumsum you have to subtract every point after this. You also need to subtract different amounts for different positions, so the subtractions only get larger." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:46:51.927", "Id": "222304", "ParentId": "222291", "Score": "4" } } ]
{ "AcceptedAnswerId": "222304", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:23:42.703", "Id": "222291", "Score": "6", "Tags": [ "python", "performance", "numpy" ], "Title": "Positive cumulative sum of difference" }
222291
<p>Regarding the Character picture exercise located at the end the following page: <a href="https://automatetheboringstuff.com/chapter4/" rel="nofollow noreferrer">https://automatetheboringstuff.com/chapter4/</a></p> <blockquote> <p>Say you have a list of lists where each value in the inner lists is a one-character string, like this:</p> <pre><code>grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] </code></pre> <p>You can think of <code>grid[x][y]</code> as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The <code>(0, 0)</code> origin will be in the upper-left corner, the x-coordinates increase going right, and the y-coordinates increase going down.</p> <p>Copy the previous grid value, and write code that uses it to print the image.</p> <pre><code>..OO.OO.. .OOOOOOO. .OOOOOOO. ..OOOOO.. ...OOO... ....O.... </code></pre> </blockquote> <p>I wrote the following code, any feedback is appreciated.</p> <pre><code>grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] for i in range(6): for a in range(9): if a &lt; 8: print(grid[a][i], end="") else: print(grid[a][i]) </code></pre>
[]
[ { "body": "<p>Your code is pretty good. It's what I'd expect the author of the book to have wanted their readers to write.</p>\n\n<p>Good job!</p>\n\n<hr>\n\n<p>In terms of making the code more understandable/maintainable you can get the same functionality using <a href=\"https://docs.python.org/3.5/library/functions.html#zip\" rel=\"noreferrer\"><code>zip</code></a>, <a href=\"https://docs.python.org/dev/tutorial/controlflow.html#arbitrary-argument-lists\" rel=\"noreferrer\"><code>*args</code></a>, <a href=\"https://docs.python.org/3/library/stdtypes.html#str.join\" rel=\"noreferrer\"><code>''.join</code></a> and a single <code>print</code>.</p>\n\n<pre><code>for column in zip(*grid):\n print(''.join(column))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:16:29.770", "Id": "430159", "Score": "0", "body": "That's actually pretty cool! I had to think a moment to see what's going on here. But it's really clever. Basically a matrix transpose in plain Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:45:55.437", "Id": "430206", "Score": "0", "body": "Now that is short. Thanks for the answer. I will have to take a look at those functions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:41:20.287", "Id": "222293", "ParentId": "222292", "Score": "7" } }, { "body": "<p>As @Peilonrayz said - your code is well built and according to me, unexpectedly short which is certainly a good job as most people tend to write long programs for short tasks like this.</p>\n\n<hr>\n\n<p>But you could make it much shorter (a single line perhaps) -</p>\n\n<pre><code>&gt;&gt;&gt; print('\\n'.join(map(''.join, zip(*grid))))\n\n..OO.OO..\n.OOOOOOO.\n.OOOOOOO.\n..OOOOO..\n...OOO...\n....O....\n</code></pre>\n\n<p>The <a href=\"https://www.geeksforgeeks.org/zip-in-python/\" rel=\"nofollow noreferrer\"><code>zip</code></a><code>(*grid)</code> effectively transposes the matrix (flip it on the main diagonal), then each row is <a href=\"https://www.geeksforgeeks.org/join-function-python/\" rel=\"nofollow noreferrer\"><code>joined</code></a> into one string, then the rows are joined with newlines so the whole thing can be printed at once.</p>\n\n<p>Here's what <code>map()</code> in Python is -</p>\n\n<blockquote>\n <p><em>The <strong><code>map()</code></strong> function returns a list of the results after applying the given\n function to each item of a given iterable (list, tuple, etc.)</em></p>\n</blockquote>\n\n<p><sup><sup>Source - <a href=\"https://www.geeksforgeeks.org/python-map-function/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/python-map-function/</a></sup></sup></p>\n\n<p><strong><em>BUT</em></strong></p>\n\n<p><strong><em><code>map()</code></strong> is a built-in function which focuses on functional programming. It may be useful for hacks and tricks since it shortens the code, but can be a bad idea for large projects in use.</em></p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T20:55:36.517", "Id": "430211", "Score": "2", "body": "Map's semi-depricated, defiantly discouraged. IIRC the Google code style also discourages it too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:36:17.440", "Id": "430284", "Score": "1", "body": "@Peilonrayz - I used `map()` because of this - https://stackoverflow.com/questions/1247486/list-comprehension-vs-map - for a more elegant solution. But I agree with your comment." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:55:13.030", "Id": "222307", "ParentId": "222292", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:27:06.750", "Id": "222292", "Score": "7", "Tags": [ "python", "python-3.x", "programming-challenge", "formatting" ], "Title": "Character Picture Grid exercise - automatetheboringstuff" }
222292
<p>This is a <a href="https://leetcode.com/problems/valid-parentheses/" rel="nofollow noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>Given a string containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</em></p> <p><em>An input string is valid if -</em></p> <ul> <li><em>Open brackets must be closed by the same type of brackets.</em></li> <li><em>Open brackets must be closed in the correct order.</em></li> </ul> <p><em>Note that an empty string is also considered valid.</em></p> <p><strong><em>Example 1 -</em></strong></p> <pre><code>Input: "()" Output: True </code></pre> <p><strong><em>Example 2 -</em></strong></p> <pre><code>Input: "()[]{}" Output: True </code></pre> <p><strong><em>Example 3 -</em></strong></p> <pre><code>Input: "(]" Output: False </code></pre> <p><strong><em>Example 4 -</em></strong></p> <pre><code>Input: "([)]" Output: False </code></pre> <p><strong><em>Example 5 -</em></strong></p> <pre><code>Input: "{[]}" Output: True </code></pre> </blockquote> <hr> <p>Here is my solution to this challenge -</p> <pre><code>def is_valid(s): if len(s) == 0: return True parentheses = ['()', '[]', '{}'] flag = False while len(s) &gt; 0: i = 0 while i &lt; 3: if parentheses[i] in s: s = s.replace(parentheses[i], '') i = 0 flag = True else: i += 1 if len(s) == 0: return True else: flag = False break return False </code></pre> <p>So I would like to know whether I could improve performance and make my code shorter.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T00:37:53.487", "Id": "430338", "Score": "0", "body": "Is there a reason you are using flags? I removed the flags and it still seems to work, unless I made a mistake. Thank you." } ]
[ { "body": "<p>You can make your code shorter and much faster by using <code>stack</code> -</p>\n\n<blockquote>\n <p><em>Stack works on the principle of <span class=\"math-container\">\\$“\\$</span>Last-in, first-out <span class=\"math-container\">\\$”\\$</span>. Also, the inbuilt functions in Python make the code short and simple. To add an\n item to the top of the list, i.e., to push an item, we use the\n <strong><code>append()</code></strong> function and to pop out an element we use the <strong><code>pop()</code></strong> function. These functions work quite efficiently and fast in end operations.</em></p>\n</blockquote>\n\n<p>Here's a visual representation -</p>\n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/F7dIU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/F7dIU.png\" alt=\"enter image description here\"></a></p>\n</blockquote>\n\n<p><sup><sup>Source - <a href=\"https://www.geeksforgeeks.org/stack-data-structure/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/stack-data-structure/</a></sup></sup></p>\n\n<p>Here's a shorter and faster version of your program using <code>stack</code> -</p>\n\n<pre><code>def is_valid(s):\n stack = []\n mapping = {\n \")\" : \"(\",\n \"}\" : \"{\",\n \"]\" : \"[\"\n }\n\n if len(s) != 0: \n for char in s: \n if char in mapping: \n if len(stack) == 0: \n return False\n else: \n top_element = stack.pop() \n if top_element != mapping[char]:\n return False\n else:\n stack.append(char)\n return len(stack) == 0\n return True\n</code></pre>\n\n<p>Let's compare Leetcode timings (76 test cases) -</p>\n\n<p>Your Leetcode result -</p>\n\n<p><a href=\"https://i.stack.imgur.com/NFsNz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NFsNz.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>Leetcode result for <code>stack</code> solution (76 test cases) -</p>\n\n<p><a href=\"https://i.stack.imgur.com/L1EgK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L1EgK.png\" alt=\"enter image description here\"></a></p>\n\n<p>Also, you don't need <em>any</em> <code>flag</code> here (Thanks to @moondra for pointing it out) -</p>\n\n<pre><code>parentheses = ['()', '[]', '{}']\nflag = False\nwhile len(s) &gt; 0:\n # rest of the code\n</code></pre>\n\n<p>Or here -</p>\n\n<pre><code>s = s.replace(parentheses[i], '')\ni = 0\nflag = True\n</code></pre>\n\n<p>Or here -</p>\n\n<pre><code> else:\n flag = False\n break\nreturn False\n</code></pre>\n\n<p>The program will work without the <code>flag</code>s.</p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T16:08:03.523", "Id": "430171", "Score": "1", "body": "There is no need to check for `len(s) == 0` as, if it is the case, the for loop wouldn't execute and `len(stack)` would be `0`. Also, `if not stack:` inside the loop feels more pythonic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T17:33:14.443", "Id": "430179", "Score": "0", "body": "@MathiasEttinger - Could you include this in an answer? This seems interesting." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:58:57.580", "Id": "222296", "ParentId": "222295", "Score": "2" } }, { "body": "<p>Not a performance suggestion, but you can make use of the fact that an empty collection is Falsey.</p>\n\n<pre><code>if len(s) == 0:\n</code></pre>\n\n<p>Is functionally the same as just:</p>\n\n<pre><code>if not s:\n</code></pre>\n\n<p>And similarly, </p>\n\n<pre><code>while len(s) &gt; 0:\n</code></pre>\n\n<p>Can be just:</p>\n\n<pre><code>while s:\n</code></pre>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#id51\" rel=\"nofollow noreferrer\">Relevant PEP entry</a> (search for \"For sequences\" under the linked heading).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T17:29:49.147", "Id": "430178", "Score": "0", "body": "Thanks for your answer! Really helped a lot. I never realized this. Thanks for pointing this out. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T16:57:30.773", "Id": "222311", "ParentId": "222295", "Score": "3" } } ]
{ "AcceptedAnswerId": "222311", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T14:58:57.580", "Id": "222295", "Score": "0", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "balanced-delimiters" ], "Title": "(Leetcode) Valid parentheses" }
222295
<p>When handling errors in C#, is it acceptable/appropriate to re-throw exceptions that are caught in a <code>try/catch</code>?</p> <p>My scenario is that I am making an HTTP request and then checking the content of the response for a specific key (<code>access_token</code>). If that key is missing, I throw an error.</p> <p>However, as all of the code within the method is in a <code>try/catch</code> block (just in case HTTP requests go awry), the exception that I throw is being caught. The solution that I've settled on for now is to re-throw the error that is caught, to ensure that I don't lose additional detail that was included with the custom exception. You can see a full example of my code at the bottom of this question.</p> <p>I've found a number of other possibilities though, and I'd be interested to know what the C# community thinks is the best way to handle such scenarios (even if it turns out that none of them are appropriate!). There are of course other questions/resources that are similar to this, but some of the information is ambiguous and being a novice at C#, I'd like get a bit of extra context with a real-life example.</p> <h1>Possibilities</h1> <ol> <li>A separate <code>catch</code> block to re-throw the known error (see example 1).</li> <li>Check for the type of exception in a single <code>catch</code> block (see example 2).</li> <li>Return an exception should 'access_token' not be present (as opposed to throwing it).</li> <li>Don't wrap all the code in a <code>try\catch</code>.</li> </ol> <h3>Example 1</h3> <pre><code>catch (WhException ex) { // Capture and rethrow a 'WhException', ensurig that the detail is not lost. throw ex; } catch (Exception ex) { // Capture any generic exception and retrhow it as a 'WhException'. throw new WhException("An error occurred whilst attempting to generate a bearer access token.", ex.Message, ex); } </code></pre> <h3>Example 2</h3> <pre><code>catch (Exception ex) { if (ex is WhException) // Capture and rethrow a 'WhException', ensurig that the detail is not lost. throw ex; else // Capture any generic exception and retrhow it as a 'WhException'. throw new WhException("An error occurred whilst attempting to generate a bearer access token.", ex.Message, ex); } </code></pre> <h1>Full working example</h1> <pre><code>public static async Task&lt;string&gt; GetAzureAccessTokenAsync(this HttpClient http, WhConfigRaw config) { try { Dictionary&lt;string, string&gt; form = new Dictionary&lt;string, string&gt;() { { "grant_type", "client_credentials" }, { "client_id", config.ServicePrincipalId }, { "client_secret", config.ServicePrincipalKey }, { "resource", AppSettings.Get("AzureCoreUri") } }; FormUrlEncodedContent requestContent = new FormUrlEncodedContent(form); string uri = string.Format(AppSettings.Get("ClientCredentialsUri"), config.TenantId); // Query the Azure management API to get client credentials. HttpResponseMessage response = await http.PostAsync(uri, requestContent); // Read the content of the response for the Azure management API. JObject content = await response.Content.ReadAsJsonAsync&lt;JObject&gt;(); // Check whether or not the content of the response contains and 'access_token'. if (!content.ContainsKey("access_token")) { throw new WhException("An error occurred whilst attempting to generate a bearer access token.", content); } return content["access_token"].ToString(); } catch (WhException ex) { // Capture and rethrow a 'WhException', ensurig that the detail is not lost. throw ex; } catch (Exception ex) { // Capture any generic exception and retrhow it as a 'WhException'. throw new WhException("An error occurred whilst attempting to generate a bearer access token.", ex.Message, ex); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T16:48:49.580", "Id": "430176", "Score": "0", "body": "Do you do anything with the exception besides catch it? If not, then there's no point catching it in the first place." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:31:40.163", "Id": "430591", "Score": "0", "body": "Thanks for your comment. Exceptions are bubbled up so that they may be handled gracefully. The bottom `catch (Exception ex)` would only really be for informational purposes, as an error there would likely mean a configuration error. But the other exception contains error messages which must be presented to the users, hence my uncertainty as to whether or not I'm handling this correctly." } ]
[ { "body": "<p>Deciding which exceptions to handle, rethrow, wrap in other exceptions is a design decision. Some exceptions might be caught to branch to a different flow. Naively catching all exceptions is a bad call. <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/exceptions/\" rel=\"nofollow noreferrer\">Guidelines for handling and throwing exceptions</a></p>\n\n<hr>\n\n<p>Some exceptions should be propagated all the way up, because of the integrity of the application or even your machine cannot be preserved. Be careful when encountering <code>OutOfMemoryException</code>, <code>BadImageFormatException</code>, <code>StackOverflowException</code>.</p>\n\n<p>Would you really want to wrap/hide the aforementioned exceptions in a custom exception?</p>\n\n<blockquote>\n<pre><code>catch (Exception ex)\n{\n // Capture any generic exception and retrhow it as a 'WhException'.\n throw new WhException(\"An error occurred whilst ..\", ex.Message, ex);\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Keep in mind that detail is lost when you catch and <code>throw ex;</code>. A new stacktrace is created.</p>\n\n<blockquote>\n<pre><code>catch (WhException ex)\n{\n // Capture and rethrow a 'WhException', ensurig that the detail is not lost.\n throw ex;\n}\n</code></pre>\n</blockquote>\n\n<p>Use <code>throw;</code> to preserve stacktrace.</p>\n\n<pre><code>catch (WhException ex)\n{\n throw; // preserves stacktrace\n}\n</code></pre>\n\n<p>If you want to rethrow outside the catch block you could use <code>ExceptionDispatchInfo</code>. Suppose <code>Exception error</code> is declared before the try:</p>\n\n<pre><code>catch (WhException ex)\n{\n error = ExceptionDispatchInfo.Capture(ex);\n}\n\nerror?.Throw(); // preserves stacktrace\n</code></pre>\n\n<hr>\n\n<p>Consider throwing these well-known exceptions for common situations:</p>\n\n<ul>\n<li>ArgumentNullException : when a mandatory argument is not provided</li>\n<li>ArgumentException: when an argument does not meet the preconditions to run</li>\n<li>AggregateException: when packing multiple exceptions together</li>\n</ul>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:32:12.440", "Id": "430593", "Score": "1", "body": "Thanks for your response. I didn't know about the lose of the stack trace when using `throw ex`, so that's def something I'll change." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:29:49.867", "Id": "222299", "ParentId": "222297", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:16:30.287", "Id": "222297", "Score": "2", "Tags": [ "c#", ".net", "error-handling" ], "Title": "Should I re-throw exceptions within a method, or is there a better way to handle it?" }
222297
<p>Is there a way to speed this guy up? The code is designed to go into a directory, open up all of the .xlsm files in the folder, and copy specific data into a target file. This code works as is, but it is extremely slow. Is there a way to speed it up?</p> <pre><code> Const FOLDER_PATH = "C:\Users\maxd\OneDrive - Nortek, Inc\Coil Test Data\coils_35_and_36\36\WET\Testing\" 'REMEMBER END BACKSLASH Sub ImportWorksheets() '============================================= 'Process all Excel files in specified folder '============================================= Dim sFile As String 'file to process Dim wsTarget As Worksheet Dim wbSource As Workbook Dim wsSource As Worksheet Dim rowTarget As Long 'output row rowTarget = 11 'check the folder exists If Not FileFolderExists(FOLDER_PATH) Then MsgBox "Specified folder does not exist, exiting!" Exit Sub End If 'reset application settings in event of error On Error GoTo errHandler Application.ScreenUpdating = False 'set up the target worksheet Set wsTarget = Sheets("Sheet1") 'loop through the Excel files in the folder sFile = Dir(FOLDER_PATH &amp; "*.xlsm*") Do Until sFile = "" 'open the source file and set the source worksheet - ASSUMED WORKSHEET(1) Set wbSource = Workbooks.Open(FOLDER_PATH &amp; sFile) Set wsSource = wbSource.Worksheets("Report") 'import the data With wsTarget .Range("A" &amp; rowTarget).Value = wsSource.Range("E9").Value 'Year .Range("B" &amp; rowTarget).Value = wsSource.Range("D30").Value 'CFM '.Range("D" &amp; rowTarget).Value = wsSource.Range("D30/(30*30/144)").Value 'Face Velocity .Range("E" &amp; rowTarget).Value = wsSource.Range("D36").Value 'AVG Capacity .Range("F" &amp; rowTarget).Value = wsSource.Range("D29").Value 'APD .Range("G" &amp; rowTarget).Value = wsSource.Range("D34").Value 'WPD .Range("H" &amp; rowTarget).Value = wsSource.Range("D22").Value 'Inlet db .Range("I" &amp; rowTarget).Value = wsSource.Range("D23").Value 'Inlet wb '.Range("J" &amp; rowTarget).Value = wsSource.Range("").Value 'Inlet dp .Range("K" &amp; rowTarget).Value = wsSource.Range("L16").Value 'Inlet WT .Range("L" &amp; rowTarget).Value = wsSource.Range("L17").Value 'Outlet WT .Range("M" &amp; rowTarget).Value = wsSource.Range("L22").Value 'Heat Balance 'optional source filename in the last column .Range("N" &amp; rowTarget).Value = sFile End With 'close the source workbook, increment the output row and get the next file wbSource.Close SaveChanges:=False rowTarget = rowTarget + 1 sFile = Dir() Loop 'Loop for face velocity Dim r As Integer Dim i As Integer i = Cells(Rows.Count, 1).End(xlUp).Row For r = 11 To i Cells(r, 4) = "=RC[-2]/(30*30/144)" Next r errHandler: On Error Resume Next Application.ScreenUpdating = True 'tidy up Set wsSource = Nothing Set wbSource = Nothing Set wsTarget = Nothing End Sub Private Function FileFolderExists(strPath As String) As Boolean If Not Dir(strPath, vbDirectory) = vbNullString Then FileFolderExists = True End Function </code></pre>
[]
[ { "body": "<p>It's been a while since I wrote VBA, but I seem to remember <code>Application.Calculation = xlCalculationManual</code> often sped up my programs considerably. This prevents formulae from being evaluated while you're updating cell values, and can be reversed via <code>Application.Calculation = xlCalculationAutomatic</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:15:05.487", "Id": "222315", "ParentId": "222306", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T15:48:21.287", "Id": "222306", "Score": "4", "Tags": [ "performance", "vba", "excel" ], "Title": "Collecting all relevant data from xlsm files" }
222306
<p>I am sharing this function I wrote with the community to provide an alternative to slow <code>VLOOKUP</code> and/or <code>Index</code>-<code>Match</code> functions. Also, if you have any feedback/suggestions to make this better please let me know. I tested this function using a lookup of just under 160,000 rows and it returned results in 2 seconds. This surpasses the native <code>VLOOKUP</code> and or <code>Index</code>-<code>Match</code> by a <strong>very large margin</strong>. </p> <p><strong>Usage:</strong> </p> <ol> <li><p>Can be used in a worksheet as an array formula (i.e. must be entered using <code>Ctrl+Shift+Enter</code>). </p></li> <li><p>Can be used in VBA as well. </p></li> </ol> <p><strong>Original Post:</strong> </p> <pre><code> Public Function FastLookUp(ByRef rngLookUpVals As Range, ByRef rngLookUpTable As Range, _ ByVal lngLookUpValCol As Long, ByVal lngSearchCol As Long, _ ByVal lngReturnCol As Long, _ Optional ByVal boolBinaryCompare As Boolean = True) As Variant Dim i As Long Dim dictLooUpTblData As Object Dim varKey As Variant Dim arryLookUpVals() As Variant, arryLookUpTable() As Variant, _ arryOut() As Variant arryLookUpVals() = rngLookUpVals.Value2 arryLookUpTable() = rngLookUpTable.Value2 Set dictLooUpTblData = CreateObject("Scripting.Dictionary") If boolBinaryCompare Then dictLooUpTblData.CompareMode = vbBinaryCompare Else dictLooUpTblData.CompareMode = vbTextCompare End If 'add lookup table's lookup column to 'dictionary For i = LBound(arryLookUpTable, 1) To UBound(arryLookUpTable, 1) varKey = Trim(arryLookUpTable(i, lngSearchCol)) If Not dictLooUpTblData.Exists(varKey) Then 'this is called a silent add with is faster 'than the standard dictionary.Add Key,Item 'method dictLooUpTblData(varKey) = arryLookUpTable(i, lngReturnCol) End If varKey = Empty Next i i = 0: varKey = Empty ReDim arryOut(1 To UBound(arryLookUpVals, 1), 1 To 1) For i = LBound(arryLookUpVals, 1) To UBound(arryLookUpVals, 1) varKey = Trim(arryLookUpVals(i, lngLookUpValCol)) 'if the lookup value exists in the dictionary 'at this index of the array, then return 'its correspoding item If dictLooUpTblData.Exists(varKey) Then arryOut(i, 1) = dictLooUpTblData.Item(varKey) End If varKey = Empty Next i FastLookUp = arryOut End Function </code></pre> <p><strong>Note:</strong> You could change the parameters to arrays instead of ranges and use this function to execute lookups on arrays in memory as well. You could also use Early-Binding for another increase in speed. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-15T13:21:14.783", "Id": "430279", "Score": "0", "body": "How large a margin? I ask because I think you can quantify this, and indeed identify any areas of your code that can be improved, with some profiling. Worth noting also that built in formulae can leverage Excel's multithreading capabilities IIRC, while VBA cannot (easily), so I'd be interested to see how your approach compares over large numbers of calls, as well as large search ranges." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T20:01:07.943", "Id": "430443", "Score": "1", "body": "@Greedo I ran several tests a using a VLOOKUP (exact match = True) on 158,000 rows, and compared the times to my function. It wasn’t even a contest. VLOOKUP to around 2 minutes while the function above took 2 seconds. As for large numbers of calls to the function, I plan to run some formal unit test and post my results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:28:37.770", "Id": "430553", "Score": "0", "body": "If you can sort the data first, you can probably speed this up more by using binary search. See: https://fastexcel.wordpress.com/2012/03/29/vlookup-tricks-why-2-vlookups-are-better-than-1-vlookup/. This approach would be `nlogn` complexity I believe. If you are looking for optimization on this method, you could use the built in `.Items` method on the dictionary to return an array of values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T15:36:14.443", "Id": "430594", "Score": "0", "body": "@RyanWildry If you mean sorting to perform a binary search via the standard VLOOKUP, then I agree. However, for the `FastLookUp` function, the lookup to the dictionary is `O(1)` (constant time), so a `b-tree` built from sorting the `dictionary` by key would be unnecessary overhead. Though, the `FastLookUp` is `n^2' where `n` = number of rows. It annoys me that I have to loop twice.....(right I after I wrote this line a realized something, check my edit for more)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T16:01:17.637", "Id": "430603", "Score": "0", "body": "@RyanWildry false alarm on checking my edit. I realized that my \"realization\" was useless, lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T11:26:04.787", "Id": "430722", "Score": "0", "body": "Yup, I meant using a double vlookup with the last parameter set as true. This would be even faster, I think, than this approach." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T17:17:53.673", "Id": "222312", "Score": "3", "Tags": [ "performance", "array", "vba", "excel", "hash-map" ], "Title": "Alternative for VLOOKUP/Index-Match in VBA" }
222312