body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>can you give me some feedback about my approach to remove an idential element from following data structure?</p>
<pre class="lang-js prettyprint-override"><code>const items = {
'Sun Mar 07 2021': [
{ id: 2 },
{ id: 1 }
],
'Sat Mar 06 2021': [
{ id: 1 } // remove me
]
}
const id = 1 // filter by id 1
const newDate = 'Sun Mar 07 2021' // filter by newDate
let oldDate = ''
// Find the duplicate date and
// save it in oldDate to splice it afterwards
Object.keys(items).forEach(date => {
items[date].forEach(item => {
const match = item.id === id
if (match && date !== newDate) {
oldDate = date
}
})
})
const idx = items[oldDate].findIndex(el => el.id === id)
// remove the old item from matched array
if (oldDate) items[oldDate].splice(idx, 1)
</code></pre>
<p>I think it can be simplified or solved differently. Unfortunately I can't get any further, do you have any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T02:18:30.363",
"Id": "506853",
"Score": "1",
"body": "@radarbob I believe this question is appropriate for Code Review. Any reason it should be moved to StackExchange? Especially, which SE site will it belong to instead of Code Review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T07:27:21.053",
"Id": "506879",
"Score": "1",
"body": "You code does not work, your example works only due to luck.. `Array.splice` does not take a function as an argument. Because you have not included the delete count argument the line `items[oldDate].splice(item => item.id === id)` will delete all items in the array `items[oldDate]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T09:59:59.660",
"Id": "506974",
"Score": "0",
"body": "@Blindman67 Thanks for pointing that out, I hadn't noticed."
}
] |
[
{
"body": "<blockquote>\n<p>I think it can be simplified or solved differently.</p>\n</blockquote>\n<p>That's good intuition. That's called a <em>code smell</em>. Something "smells" funny, off, or wrong but not sure what it is. Pay attention to that feeling!!</p>\n<blockquote>\n<p>Unfortunately I can't get any further</p>\n</blockquote>\n<p>This is an even stronger code smell.</p>\n<blockquote>\n<p>do you have any ideas?</p>\n</blockquote>\n<ul>\n<li>Re-examine the <code>date</code> object design.\n<ul>\n<li><code>date</code> and <code>IDs</code> should be in one object</li>\n<li>Put the date objects into an array. Array is designed for easy handling of multiple objects.</li>\n<li>Using Array's provided methods should eliminate external variables and functions.</li>\n</ul>\n</li>\n</ul>\n<hr />\n<p>This code demonstrates overall structural changes after fixing the objects. Algorithm details not shown.</p>\n<pre><code>const dates = [\n { date : 'Sun Mar 07 2021',\n IDs : [ 1, 2 ]\n },\n { date : 'Sat Mar 06 2021',\n IDs : [ 1 ]\n }\n]\n\nconst dupeDate = { date : 'Sun Mar 07 2021', IDs : [ 1 ] }\n\ndates.forEach( date => {\n\n if( date.date === dupeDate.date ) return;\n\n if( date.IDs.includes( dupeDate.IDs[0] )) { \n // algorithm details here. Should be function calls as much as possible, \n // not dozens of lines of nested, nested code.\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T12:04:40.507",
"Id": "507745",
"Score": "0",
"body": "Thank you for your constructive feedback. I have the freedom to change the data structure and I am ready to do so."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T00:22:04.920",
"Id": "256703",
"ParentId": "256698",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256703",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T22:18:25.453",
"Id": "256698",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Clean way to remove an identical nested object in javascript"
}
|
256698
|
<p>I am trying to analyze a number of companies using financial data I gathered from Yahoo Finance. I am also using the yfinance API to get some more details about the company using functions. Since I am trying to do this for a number of companies Each Iteration needs to be quick. Currently, 1 Company takes about 3 seconds.</p>
<p>Is it because of the API calls or requests? Can I increase the below code efficiency?</p>
<pre><code>import pandas as pd
import numpy as np
from pandas import ExcelWriter
import requests
import timeit
import yfinance as yf
def get_industry(stock):
tickerdata = yf.Ticker(stock)
return tickerdata.info['industry']
def get_symbol(symbol):
url = "http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={}&region=1&lang=en".format(symbol)
result = requests.get(url).json()
for x in result['ResultSet']['Result']:
if x['symbol'] == symbol:
return x['name']
def get_currency(stock):
tickerdata = yf.Ticker(stock)
return tickerdata.info['currency']
quarters = ['Q4-2020','Q3-2020','Q2-2020','Q1-2020','Q4-2019','Q3-2019','Q2-2019','Q1-2019','Q4-2018','Q3-2018','Q2-2018','Q1-2018']
start_time = timeit.default_timer()
r = []
for i in stock[:1]:
try:
df = pd.read_csv(i+'_quarterly_balance-sheet.csv')
df = df.drop('ttm',axis=1,errors='ignore')
df['name'] = df['name'].str.replace('\t','')
df = df.iloc[:,:13].T
df.columns = df.iloc[0]
df = df[1:]
df.insert(0,'Q',quarters)
try:
df.insert(0,'Currency',get_currency(i))
except:
df.insert(0,'Currency','Not Found')
df.insert(0,'Ticker',i)
df.insert(0,'Company',get_symbol(i))
try:
df.insert(0,'Industry',get_industry(i))
except:
df.insert(0,'Industry','Unknown')
df = df.loc[:,df.columns.isin(['Q','Currency','Ticker','Company','Industry','TotalRevenue'])]
r.append(df)
except:
continue
df = pd.concat(r)
# code you want to evaluate
elapsed = timeit.default_timer() - start_time
elapsed
</code></pre>
<p>3.041297 Seconds</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T06:47:10.463",
"Id": "506871",
"Score": "0",
"body": "\"Is it because of the API calls or requests?\" - when in doubt, profile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T18:01:56.723",
"Id": "506932",
"Score": "0",
"body": "It can be I shall check the time for each call"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T23:58:11.720",
"Id": "507033",
"Score": "1",
"body": "The network requests are almost certainly orders of magnitude slower than your code. If you need to make many web requests, the solution lies in parallelism (making the several requests at once, with multiple threads and/or processes), not fine-tuning your own code to eek out some milliseconds."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T00:40:55.503",
"Id": "256705",
"Score": "0",
"Tags": [
"python",
"functional-programming",
"api",
"pandas"
],
"Title": "Optimize Yahoo Finance Code for Analysis"
}
|
256705
|
<p>So here's a simple command line parser. Is it safe? I can't use anything but C++14 and standard library.</p>
<pre><code>class cli {
public:
struct parameter {
struct help {};
struct single {};
template <typename T = void>
struct value {
using type = T;
};
parameter(const std::string& key)
: key_{key}
, description_{""}
, type_info_(typeid(void)) {
}
parameter(const std::string& key, help, const std::string& description = "")
: key_{key}
, description_{description}
, type_info_(typeid(help)) {
}
parameter(const std::string& key, single, const std::string& description = "")
: key_{key}
, description_{description}
, type_info_(typeid(single)) {
}
template <typename T>
parameter(const std::string& key, value<T>, const std::string& description, T argument)
: key_{key}
, description_{description}
, type_info_(typeid(T)) {
std::stringstream ss;
ss << argument;
argument_ = ss.str();
}
static std::string trim_dashs(const std::string& arg) {
if (arg.size() > 2 && arg[0] == '-' && arg[1] == '-')
return {arg.begin() + 2, arg.end()};
if (arg.size() > 1 && arg[0] == '-')
return {arg.begin() + 1, arg.end()};
return arg;
}
static bool is_valid_key(const std::string& in) {
return (in.size() == 2 && in[0] == '-' && in[2] >= 'A' && in[2] <= 'z') ||
(in.size() >= 3 && in[0] == '-' && in[1] == '-' && in[2] >= 'A' && in[2] <= 'z');
}
std::string key() const {
return key_;
}
std::string description() const {
return description_;
}
template <typename T>
T as() const {
assert((typeid(T).hash_code() == type_info_.get().hash_code()) ||
((typeid(T).hash_code() == typeid(bool).hash_code()) &&
(typeid(parameter::single).hash_code() == type_info_.get().hash_code())));
T arg;
std::stringstream ss(argument_);
ss >> arg;
return arg;
}
template <typename T = void>
bool is() const {
return typeid(T).hash_code() == type_info_.get().hash_code() ||
typeid(T).hash_code() == typeid(parameter::value<void>).hash_code();
}
void argument(const std::string& arg) {
assert(typeid(parameter::help).hash_code() != type_info_.get().hash_code() &&
typeid(parameter::single).hash_code() != type_info_.get().hash_code());
argument_ = arg;
}
void argument(bool value) {
argument_ = value ? "true" : "false";
}
bool operator <(const parameter& r) const {
return key() < r.key();
}
private:
std::string key_;
std::string description_;
std::string argument_;
std::reference_wrapper<const std::type_info> type_info_;
};
public:
cli(const std::set<parameter> parameters, int argc, char** argv)
: command_line_{parameters} {
std::vector<std::string> argvector;
for (int i = 1; i < argc; ++i) {
argvector.push_back(argv[i]);
}
auto is_defined = [this](const std::string& in) {
return command_line_.find({in, parameter::single()}) != command_line_.end();
};
for (auto it = argvector.begin(); it != argvector.end(); ++it) {
auto key = parameter::trim_dashs(*it);
if (!parameter::is_valid_key(*it) || !is_defined(key)) {
throw std::runtime_error(std::string("Unknown parameter '") + key + std::string("'\n") + help_message());
}
parameter p = *command_line_.find({key});
if (p.is<parameter::help>()) {
std::cerr << help_message() << std::endl;
exit(0);
}
auto next_it = std::next(it);
const bool is_valid_argument = next_it != argvector.end() && !parameter::is_valid_key(*next_it);
if (p.is<parameter::value<>>()) {
if (is_valid_argument) {
p.argument(*next_it);
std::advance(it, 1);
} else {
throw std::runtime_error(std::string("Missing argument for '") + key + std::string("'\n"));
}
} else {
p.argument("true");
}
std::pair<decltype(parameters_)::iterator, bool> inserted = parameters_.insert(p);
if (not inserted.second)
throw std::runtime_error(std::string("Double parameter: '") + key + std::string("'\n"));
}
}
const parameter& operator[] (const std::string& key) {
if (parameters_.count({key}))
return *parameters_.find({key});
auto p = command_line_.find({key});
return *p;
}
std::string help_message() const {
std::string message = "Usage: builder [options]\n"
"Allowed options:\n";
for (auto& argument : command_line_) {
message += std::string("\t--");
message += argument.key();
message += std::string(std::max(0, 10 - static_cast<int>(argument.key().size())), ' ');
message += std::string(":");
message += argument.description();
message += std::string("\n");
}
return message;
}
private:
std::set<parameter> command_line_;
std::set<parameter> parameters_;
};
</code></pre>
<p>And in the target code:</p>
<pre><code>const std::set<cli::parameter> parameters = {
{"help", cli::parameter::help(), "help message"},
{"config", cli::parameter::value<std::string>(), "default configuration", std::string("Debug")},
{"install", cli::parameter::single(), "build install target"},
{"pack", cli::parameter::single(), "build package target"},
{"timeout", cli::parameter::value<uint16_t>(), "timeout in seconds", uint16_t(10)}
};
cli c(parameters, argc, argv);
foo bar(cli["timeout"].as<uint16_t>());
</code></pre>
|
[] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Provide a way for users to catch errors</h2>\n<p>The <code>cli</code> constructor can <code>throw</code> an exception, which is not necessarily bad, but the lack of any other constructors make it hard to use. Consider this snippet as an attempt to use your library:</p>\n<pre><code>cli c;\ntry {\n c = cli{parameters, argc, argv};\n} catch (std::runtime_error &err) {\n std::cerr << err.what() << '\\n';\n return 1;\n} \nauto bar{c["timeout"].as<uint16_t>()};\nstd::cout << "timeout = " << bar << '\\n';\n</code></pre>\n<p>This fails because there is no default non-throwing constructor and no copy constructor. If we try to move the declaration inside the <code>try</code> block, it will fail again because now the use of <code>c</code> after the <code>catch</code> block attempts to use a variable no longer in scope. I would suggest adding these two lines:</p>\n<pre><code>cli() = default;\ncli(const cli& other) = default;\n</code></pre>\n<p>However, I haven't checked thoroughly to make sure that doesn't introduce other problems. You should.</p>\n<h2>Be consistent about <code>throw</code> vs <code>assert</code></h2>\n<p>If we attempt to call this as <code>builder --timeout 17 --install /usr/bin</code> the code aborts on a failed assert. I'd expect that a better approach would be to <code>throw</code> to allow the user a chance to handle the error gracefully.</p>\n<h2>Avoid <code>+=</code> for strings</h2>\n<p>The <code>help_message()</code> code, among other places uses <code>operator+=</code> to concatenate strings in many places. There are a few problems with this. The first is that each invocation of the operator may require memory reallocation for the resulting <code>std::string</code> which slows things down and may fragment memory. The second is that the string is built every time that function is called -- it could instead be built by the constructor since it does not change.</p>\n<h2>Consider alternatives to <code>std::set</code></h2>\n<p>I don't see a reason the code couldn't use <code>std::unordered_set</code> instead of <code>std::set</code>. Using <code>std::unordered_set</code> often confers a performance advantage over <code>std::set</code> if you don't need ordering.</p>\n<h2>Think of the user</h2>\n<p>Consider this line in the code listed above:</p>\n<pre><code>auto bar{c["timeout"].as<uint16_t>()};\n</code></pre>\n<p>As a user of the code, I might reasonably wonder why I can't just write this:</p>\n<pre><code>auto bar{c["timeout"]};\n</code></pre>\n<p>What this actually does is return the exact same <code>cli::parameter</code> that the user passed in to construct the <code>cli</code>, but isn't it more likely that what the user wants the associated <em>value</em> instead? This might be easier with something like the C++17 <a href=\"https://en.cppreference.com/w/cpp/types/type_identity\" rel=\"nofollow noreferrer\"><code>type_identity</code></a>.</p>\n<h2>Clearly separate the interface</h2>\n<p>The interface includes the required <code>#include</code>s. I believe the ones this needs are:</p>\n<pre><code>#include <cassert>\n#include <functional>\n#include <iostream>\n#include <set>\n#include <stdexcept>\n#include <string>\n#include <sstream>\n#include <typeinfo>\n#include <vector>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T14:59:01.763",
"Id": "256725",
"ParentId": "256710",
"Score": "2"
}
},
{
"body": "<p>Very cool. This is like a bespoke, simplified version of <a href=\"https://www.boost.org/doc/libs/release/doc/html/program_options.html\" rel=\"nofollow noreferrer\">Boost.ProgramOptions</a>. It could <em>definitely</em> be useful.</p>\n<p>Unfortunately, the restriction to C++14 (and disallowing any 3rd party libraries) would make it completely useless to me, and most people nowadays, but maybe some people out there are still stuck using C++14.</p>\n<p>Let’s dive in:</p>\n<pre><code>struct parameter\n</code></pre>\n<p><code>parameter</code> has an invariant, so by convention, <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c2-use-class-if-the-class-has-an-invariant-use-struct-if-the-data-members-can-vary-independently\" rel=\"nofollow noreferrer\">it should be a <code>class</code>, not a <code>struct</code></a>.</p>\n<pre><code>struct help {};\nstruct single {};\n\ntemplate <typename T = void>\nstruct value {\n using type = T;\n};\n</code></pre>\n<p>I see what you’re trying to do here, but the way you’re doing it is a bit problematic.</p>\n<p>To make this kind of design really work, ideally you’d want <a href=\"https://en.cppreference.com/w/cpp/utility/any\" rel=\"nofollow noreferrer\"><code>std::any</code></a>. Except that’s C++17… and you can’t even use <a href=\"https://www.boost.org/doc/libs/release/libs/any/\" rel=\"nofollow noreferrer\">Boost.Any</a>. So to <em>really</em> do this properly, you’re basically going to have to re-implement <code>std::any</code>. That sucks, but… well, you’re using C++14, so you’ll have to deal with it. At least it won’t be (entirely) wasted effort, because it will useful to you anyway (at least until you eventually move to C++17). So you might as well make it.</p>\n<p>Here’s why you need <code>std::any</code> (or rather, your own custom version of <code>std::any</code>): Your current design has as a flaw when dealing with typed arguments. If I do <code>builder --timeout xyz</code>, then parse the command line with <code>auto c = cli{parameters, argc, argv}</code>, it will pass without complaint. An error will be raised if I do <code>c["timeout"].as<std::uint16_t>()</code>… but that’s <em>MUCH</em> too late! By that point, I assume the arguments have all been properly parsed, so an error happening <em>here</em> would be jarring. Even worse, the error raised is actually an <em>assertion failure</em>. So rather than getting an error raised at the time the command line is parsed, instead the whole program just… dies… at some random time later.</p>\n<p>The reason why <code>std::any</code> fixes this problem is that you can hold an <code>any</code> in the <code>parameter</code> type—rather than a <code>string</code>—and do the checking early, like this:</p>\n<pre><code>class parameter\n{\n\n // ... [snip] ...\n\n template <typename T>\n parameter(std::string key, value<T>, std::string description, T argument)\n : key_{std::move(key)}\n , description_{std::move(description)}\n , argument_{std::move(argument)}\n , type_index_{typeid(T)}\n {}\n\n // ... [snip] ...\n\n template <typename T>\n auto as() const -> T\n {\n // will throw a bad_any_cast if the cast is bad\n return std::any_cast<T>(argument_);\n }\n\n // ... [snip] ...\n\n template <typename T>\n auto argument(std::string const& arg) -> void\n {\n if (std::type_index(typeid(T)) != type_index_)\n {\n // you really should make a custom exception for this kind of thing\n //\n // then you won't need this long-ass, ugly concatenation\n throw std::runtime_error{"wrong type assigned to option '" \n + key_\n + "': '"\n + std::string{std::type_index(typeid(T)).name()}\n + "' (expected: '"\n + std::string{type_index_.name()}\n + "')"};\n }\n\n // it would be nice to avoid the whole stringstream dance if we know\n // the type is easily converted to a string (or is actually a string)\n //\n // this would be trivial in C++17 with if constexpr, but... well,\n // you can figure out how to do it in C++14 on your own time\n\n auto iss = std::istringstream{arg};\n\n T value{};\n if (iss >> value)\n {\n argument_ = std::move(value);\n }\n else\n {\n // needs a custom exception\n throw std::runtime_error{"could not parse argument for option " + key_ + ": '" + arg + "'"};\n }\n }\n\n // ... [snip] ...\n\nprivate:\n std::string key_;\n std::string description_;\n std::any argument_;\n std::type_index type_index_;\n};\n</code></pre>\n<p>As you can see, the checking is done right when you try to assign the argument in <code>argument()</code>; the earliest possible point. Also, when a default value is given, that value is kept… it is not converted to a string (which may be lossy).</p>\n<pre><code>parameter(const std::string& key, help, const std::string& description = "")\n : key_{key}\n , description_{description}\n , type_info_(typeid(help)) {\n}\n</code></pre>\n<p>You take all the string arguments as <code>const&</code>… but they’re sink arguments, they’re actually going to keep a copy of the string. If you pass them as <code>const&</code>, that means they will make a copy every time… even when they don’t have to.</p>\n<p>When you do:</p>\n<pre><code>auto p = parameter{"foo", cli::parameter::help{}, "desc"};\n</code></pre>\n<p>… two strings are constructed—one for “foo” and one for “desc”—and then the constructor is actually called, and <em>both</em> strings are <em>copied</em>, so two <em>more</em> strings are constructed.</p>\n<p>If you take the arguments by value, like this:</p>\n<pre><code>parameter(std::string key, help, std::string description = {})\n : key_{std::move(key)}\n , description_{std::move(description)}\n // ...\n</code></pre>\n<p>… then in the code example above, two strings are constructed—“foo” and “desc”—and then the constructor is called… but this time, the two strings are <em>moved</em>. Which is potentially <em>much</em> cheaper than a copy, and less likely to trigger an error.</p>\n<p>Also, as a usability issue: is it really necessary to manually specify that you want a help message? Can we not assume that as a default, and then maybe offer a way to disable it or change the message for the rare cases that someone might want that?</p>\n<pre><code> static std::string trim_dashs(const std::string& arg) {\n if (arg.size() > 2 && arg[0] == '-' && arg[1] == '-')\n return {arg.begin() + 2, arg.end()};\n if (arg.size() > 1 && arg[0] == '-')\n return {arg.begin() + 1, arg.end()};\n return arg;\n }\n</code></pre>\n<p>Does this really need to be part of the public interface of <code>parameter</code>?</p>\n<p>Also, it looks like you could use a <code>starts_with()</code> function, to simplify:</p>\n<pre><code>auto trim_dashs(std::string const& arg)\n{\n if (arg.size() > 2 and starts_with(arg, "--"))\n return arg.substr(2);\n if (arg.size() > 1 and starts_with(arg, '-'))\n return arg.substr(1);\n return arg;\n}\n</code></pre>\n<p><code>starts_with()</code> will be generally useful elsewhere, too.</p>\n<pre><code> static bool is_valid_key(const std::string& in) {\n return (in.size() == 2 && in[0] == '-' && in[2] >= 'A' && in[2] <= 'z') ||\n (in.size() >= 3 && in[0] == '-' && in[1] == '-' && in[2] >= 'A' && in[2] <= 'z');\n }\n</code></pre>\n<p>There are a couple of issues here.</p>\n<p>The first is that you have a bug. I think you meant to use <code>in[1]</code>, not <code>in[2]</code> in the last part of the first line of that long expression.</p>\n<p>Another issue is the way you’re checking for <code>A <= ? <= z</code>… that really doesn’t make a lot of sense. If you’re using Unicode, then you’re saying that <code>-[</code> is a valid option… but <code>-1</code> isn’t. That’s a little weird.</p>\n<p>There doesn’t seem to be a reason why this function is part of <code>parameter</code>. It’s only used in <code>cli</code>, and only to check whether the next command line argument is (using regex) <code>-[^-]</code> or <code>--.+</code>.</p>\n<pre><code> std::string key() const {\n return key_;\n }\n\n std::string description() const {\n return description_;\n }\n</code></pre>\n<p>These functions can be made <em>much</em> more efficient <em>and</em> no-fail (<code>noexcept</code>) by returning <code>string const&</code> rather than <code>string</code>.</p>\n<pre><code> template <typename T>\n T as() const {\n assert((typeid(T).hash_code() == type_info_.get().hash_code()) ||\n ((typeid(T).hash_code() == typeid(bool).hash_code()) &&\n (typeid(parameter::single).hash_code() == type_info_.get().hash_code())));\n T arg;\n std::stringstream ss(argument_);\n ss >> arg;\n return arg;\n }\n</code></pre>\n<p>I already gave my thoughts on this function above, but I’ll just add that you don’t do any error checking on the conversion (<code>ss >> arg</code>).</p>\n<pre><code> template <typename T = void>\n bool is() const {\n return typeid(T).hash_code() == type_info_.get().hash_code() ||\n typeid(T).hash_code() == typeid(parameter::value<void>).hash_code();\n }\n</code></pre>\n<p>What exactly is this function supposed to be checking? If this parameter is supposed to be <code>int</code>, then <code>p.is<int>()</code> returns <code>true</code>… but <code>p.is<parameter::value<void>>()</code> also returns <code>true</code>. What does that mean?</p>\n<pre><code>std::reference_wrapper<const std::type_info> type_info_;\n</code></pre>\n<p>This is a bit clunky and silly; it makes more sense to just store a <code>std::type_index</code>.</p>\n<pre><code>cli(const std::set<parameter> parameters, int argc, char** argv)\n</code></pre>\n<p>Before I get into the guts of this constructor, I want to note that I’m not keen on the idea of storing the parameter list in a <code>set</code>. (Or an <code>unordered_set</code> for that matter.)</p>\n<p>The reason why is because very often the order of parameters is relevant. For example, if I have options for turning verbosity on and for “silent mode”, I might make the last one on the command line take precedence. Even if that’s not important, I may have ordered the options in some logical way so that when the help message is printed, they make more sense. Putting the parameters in a <code>set</code> (or <code>unordered_set</code>) throws away my ordering.</p>\n<p>Now, you may argue “but set lookup is fast!”… but is it? You should try profiling that. You may be surprised.</p>\n<p>In practice, your program is not going to have a million options. It probably won’t even have 100. The set of options is so small, that you probably won’t notice anything by leaving them “unordered” and searching through them sequentially.</p>\n<p>Now, this only applies to the option <em>description</em> set: the list you create when you do:</p>\n<pre><code>{\n {"config", cli::parameter::value<std::string>(), "default configuration", std::string("Debug")},\n {"install", cli::parameter::single(), "build install target"},\n {"pack", cli::parameter::single(), "build package target"},\n {"timeout", cli::parameter::value<uint16_t>(), "timeout in seconds", uint16_t(10)}\n}\n</code></pre>\n<p>The set you create after you actually read the options—what you call <code>parameters_</code> in this class—doesn’t need to be ordered. At least I can’t see any reason why it would. And <em>that</em> could use fast lookup, because you only <em>describe</em> the options (as above) once, and you only parse the command line once (presumably), but you may access the parsed options many times.</p>\n<p>So I would recommend creating a simple container class, maybe called <code>parameters</code>, that just holds a sequence of <code>parameter</code>s in the order given:</p>\n<pre><code>auto const params = parameters{\n {"config", cli::parameter::value<std::string>(), "default configuration", std::string("Debug")},\n {"install", cli::parameter::single(), "build install target"},\n {"pack", cli::parameter::single(), "build package target"},\n {"timeout", cli::parameter::value<uint16_t>(), "timeout in seconds", uint16_t(10)}\n};\n</code></pre>\n<p><code>parameters</code> could be a bespoke class, or it could be as simple as:</p>\n<pre><code>using parameters = std::vector<parameter>;\n</code></pre>\n<p>Now the biggest problem with this constructor is that it really shouldn’t be a constructor. You are not merely constructing a <code>cli</code> object (whatever that means; but we’ll get back to that). You are doing <em>multiple</em> tasks. At the very least, you are parsing the command line <em>and</em> constructing a <code>cli</code> object with the results of the parse.</p>\n<p>Shoehorning all that into a single constructor is bad form. It’s also inflexible. Let’s say I want to read program options from a configuration file instead of the command line. Or let’s say I want to read them from the command line <em>and</em> a configuration file. Now what? You’d have to completely redesign the entire class, over and over again, to handle every new use case. That’s a sign that you’ve messed up the abstraction.</p>\n<p>Without thinking at all about implementation, this is the kind of thing I think of when I want a command-line argument system:</p>\n<pre><code>// i want to be able to declare all my options, and their format:\nauto const cmd_line_params = cli::parameters{\n {"config", cli::value<std::string> + cli::with_default("Debug"), "default configuration"},\n {"install", "build install target"},\n {"pack", "build package target"},\n {"timeout", cli::with_default<uint16_t>(10), "timeout in seconds"} // cli::value<std::uint16_t> can be deduced\n\n // could also have other stuff, like:\n // {"required-option", cli::required, "this option is required"}\n // {"validated-option", cli::validate([](auto&& opt { return is_valid(opt); }), "this option is validated by a lambda"}\n};\n\n// i want to be able to declare *multiple* sets of options, and\n// and combine them in various ways:\nauto const secret_experimental_params = cli::parameters{\n // ...\n};\n\n// the above don’t need to be global args; they could be returned from\n// functions, or hidden in a translation unit, or whatever\n//\n// ideally, in C++20 and beyond, all of the above could be constinit\n\n// Lippincott function\nauto handle_error() -> int\n{\n try\n {\n throw;\n }\n catch (cli::option_error const& x)\n {\n std::cerr << x.what() << '\\n'\n // print usage/help message, possibly using the parameters above\n }\n // etc.\n\n return EXIT_FAILURE;\n}\n\nauto main(int argc, char* argv) -> int\n{\n try\n {\n auto const options = [argc, argv]\n {\n // first we try parsing some config files:\n auto opts = cli::parse(cmd_line_params, std::filesystem::path{"/etc/config"});\n\n // then we read options from the command line, which take precedence:\n opts.override_with(cli::parse(cmd_line_params, argc, argv));\n\n // or maybe with secret extra params, and codependent validation:\n // opts.override_with(cli::parse(\n // cmd_line_params + secret_experimental_params,\n // argc,\n // argv,\n // [] (auto&& opts) { check_options_1(opts); },\n // [] (auto&& opts) { check_options_2(opts); }));\n\n return opts;\n }();\n\n // if there were *any* problems parsing the command line arguments, an\n // error would have been thrown... so if we got here, we know the\n // command line arguments are all good.\n\n std::cout << "this should never be a problem (normally): "\n << options["timeout"].as<std::uint16_t>()\n << '\\n';\n }\n catch (...)\n {\n return handle_error();\n }\n}\n</code></pre>\n<p>Basically, I’m suggesting separating the parsing logic from the parsing rules <em>and</em> actual storage of the parsed results… rather than cramming all three into a single class, as you have. Separating everything will allow <em>much</em> more flexibility, at every level.</p>\n<pre><code> cli(const std::set<parameter> parameters, int argc, char** argv) \n : command_line_{parameters} {\n</code></pre>\n<p>I don’t see the sense in declaring <code>parameters</code> as <code>const</code>, and then immediately just putting it <code>command_line_</code>. Why not leave <code>parameters</code> as non-<code>const</code>, and move it into <code>command_line_</code>?</p>\n<pre><code> std::vector<std::string> argvector;\n for (int i = 1; i < argc; ++i) {\n argvector.push_back(argv[i]);\n }\n</code></pre>\n<p>Okay, first of all, if you’re going to pack all the arguments into a vector of strings, you might as well do it efficiently. At the very least you could do:</p>\n<pre><code> std::vector<std::string> argvector;\n argvector.reserve(argc - 1); // reserve the needed memory\n for (int i = 1; i < argc; ++i) {\n argvector.push_back(argv[i]);\n }\n</code></pre>\n<p>But it would be easier to just do:</p>\n<pre><code>auto argvector = std::vector<std::string>(argv + 1, argv + argc);\n</code></pre>\n<p>Doing it that way allows the vector to resize itself once, rather than having to adjust itself as more arguments are added.</p>\n<p>However… do you really <em>need</em> to copy the entire argument list into a vector, and convert each one to a string? Why can’t you just read them where they are. (Granted, this would be <em>much</em> easier with <code>std::string_view</code>, but, yeah, you’re stuck with C++14. You could always re-implement <code>std::string_view</code>, I suppose; it <em>is</em> super useful.)</p>\n<pre><code> auto is_defined = [this](const std::string& in) {\n return command_line_.find({in, parameter::single()}) != command_line_.end();\n };\n</code></pre>\n<p>Yikes, this is <em>wildly</em> inefficient. To find a particular option, you’re constructing an entire dummy <code>parameter</code> object… and those things ain’t cheap! (You have to construct <em>three</em> strings, plus do a <code>typeid()</code> lookup.) But all you’re <em>really</em> doing is searching for a matching <code>key</code>:</p>\n<pre><code>auto is_defined = [&command_line_](auto&& in)\n{\n return std::find_if(command_line_.begin(), command_line_.end(), [&in](auto&& p) { return p.key() == in; }) != command_line_.end();\n};\n</code></pre>\n<p>Even if <code>command_line_</code> is a <code>set</code> (and, remember, I don’t think it should be), this should <em>still</em> be significantly faster… even up to many, many hundreds of thousands of parameters.</p>\n<pre><code> auto key = parameter::trim_dashs(*it);\n if (!parameter::is_valid_key(*it) || !is_defined(key)) {\n throw std::runtime_error(std::string("Unknown parameter '") + key + std::string("'\\n") + help_message());\n }\n\n parameter p = *command_line_.find({key});\n</code></pre>\n<p>Okay, here’s the thing. First you construct the <code>key</code> as a string by trimming the dashes… and <em>then</em> you check whether it’s valid in the first place. But if it’s invalid, you’ve wasted the effort to construct it. And then, in <code>is_defined()</code>, you search through <code>command_line_</code> to find the key… and if you find it, you just… throw that information away… and then search through <code>command_line_</code> for the same key <em>AGAIN</em>.</p>\n<p>Let’s rethink what’s going on here. First, you could really use <code>std::string_view</code> (or rather, you’ll have to re-implement it yourself in C++14, but that’s not hard). Constructing strings willy-nilly is painfully slow. That’s why <code>std::string_view</code> was created in the first place.</p>\n<p>So to start, rather than creating a vector of strings, let’s just iterate through the command line arguments directly, creating string views for each one (which is cheap), and do all the checking one time rather than repeatedly:</p>\n<pre><code>for (auto p_arg = argv + 1; p_arg < argv + argc; ++p_arg)\n{\n // parse_key() helper function tries to remove leading dashes and return\n // a string view of the key, but if the argument is malformed, throws an\n // exception\n auto const key = parse_key(*p_arg);\n\n auto const& param = [&command_line_](auto&& key)\n {\n auto const p = std::find_if(command_line_.begin(), command_line_.end(),\n [&key](auto&& p) { return p.key() == key; });\n\n if (p == command_line_.end())\n throw ...;\n\n return *p;\n }(key);\n\n // ...\n}\n</code></pre>\n<p>Next, you check for a help option:</p>\n<pre><code> if (p.is<parameter::help>()) {\n std::cerr << help_message() << std::endl;\n exit(0);\n }\n</code></pre>\n<p>The first problem with this is that when someone asks for help, they won’t expect it to be an <em>error</em> message. If I ask for help, that’s the expected output; it should be printed to <code>std::cout</code> if anything. But even better would be if I could decide where to print it.</p>\n<p>But the <em>real</em> problem here is <code>std::exit()</code>. Never, ever, <em>EVER</em> use <code>exit()</code> in a C++ program. <code>exit()</code> is a C function; it doesn’t apply to C++. While <em>some</em> effort has been taken to make it sorta-kinda work with C++, the hard truth is that destructors for the vast majority of objects in most programs won’t be called… which could be catastrophic. Basically, you’re crashing the program, and who knows what state that will leave the environment in.</p>\n<p>So what should you do here? Well, frankly, you’ve kinda painted yourself into a corner. Because this is a constructor, there are only two options for leaving it early: either crash the program (as with <code>exit()</code>), or throw an exception. You <em>could</em> make a special class like <code>struct help_message_t {};</code> and throw that, and then catch it in <code>main()</code> to display a help message there, I suppose.</p>\n<p>On the other hand, if you were doing the parsing with a function and not a constructor—which just makes sense conceptually anyway, because parsing is not constructing—then you could return a flag or something to indicate that the help message was requested, and let the calling code decide whether, how, and where to display it.</p>\n<p>Next, you do this weird, back-assward check for an argument:</p>\n<pre><code> auto next_it = std::next(it);\n const bool is_valid_argument = next_it != argvector.end() && !parameter::is_valid_key(*next_it);\n if (p.is<parameter::value<>>()) {\n if (is_valid_argument) {\n p.argument(*next_it);\n std::advance(it, 1);\n } else {\n throw std::runtime_error(std::string("Missing argument for '") + key + std::string("'\\n"));\n }\n } else {\n p.argument("true");\n }\n</code></pre>\n<p>Rather than just forging ahead and parsing the next command line token and <em>then</em> checking to see if the option even <em>has</em> an argument, it makes more sense to check whether you even need an argument first:</p>\n<pre><code> if (param requires an argument) // you'll need this check, somehow; the is() function currently makes no sense\n {\n if (++p_arg == argv + argc)\n throw ...;\n\n auto const arg = std::string_view{p_arg};\n\n // there's some weirdness going on here that i'll get into later.\n //\n // for now, this is basically what has to happen:\n parameters_[key] = convert_to<T>(arg);\n // convert_to<T>() just uses an istringstream to try to parse the\n // string arg as a T, and throws an exception if that fails\n }\n else\n {\n parameters_[key] = true;\n }\n</code></pre>\n<p>Now, there’s some weirdness with <code>cli</code>. It has two data members: <code>command_line_</code> and <code>parameters_</code>. Normally I would <em>assume</em> that <code>command_line_</code> is just the set of parameters passed in to the constructor, and <code>parameters_</code> is what got parsed on the command line. But… so far as I can tell, that’s not what’s going on. Instead, <code>command_line_</code> is used <em>both</em> for the options description <em>and</em> for the parsed options values. And <code>parameters_</code> is used for nothing. But then, I see this:</p>\n<pre><code> const parameter& operator[] (const std::string& key) {\n if (parameters_.count({key}))\n return *parameters_.find({key});\n auto p = command_line_.find({key});\n return *p;\n }\n</code></pre>\n<p>What is going on there?</p>\n<pre><code> std::string help_message() const {\n std::string message = "Usage: builder [options]\\n"\n "Allowed options:\\n";\n for (auto& argument : command_line_) {\n message += std::string("\\t--");\n message += argument.key();\n message += std::string(std::max(0, 10 - static_cast<int>(argument.key().size())), ' ');\n message += std::string(":");\n message += argument.description();\n message += std::string("\\n");\n }\n\n return message;\n }\n</code></pre>\n<p>Returning the help message as a string isn’t <em>bad</em>… but more often than not, when you want the help message, it’s because you’re writing it to some stream. So why not make that possible:</p>\n<pre><code>auto write_usage_message(std::ostream& out) const\n{\n // it would be nice to be able to customize this\n out << "Usage: builder [options]\\n";\n}\n\nauto write_help_message(std::ostream& out) const\n{\n write_usage_message(out);\n\n out << "Allowed options:\\n";\n\n for (auto&& parameter : command_line_)\n {\n out << "\\t--" << parameter.key();\n\n for (indent as you please)\n out.put(' ');\n\n out << ':' << parameter.description() << '\\n';\n }\n}\n</code></pre>\n<p>If you want you could even still have your <code>help_message()</code> function:</p>\n<pre><code>auto help_message() const\n{\n auto oss = std::ostringstream{};\n write_help_message(oss);\n return oss.str();\n}\n</code></pre>\n<p>And it would incidentally probably be more efficient than your existing <code>help_message()</code> function.</p>\n<p>I think you need to rethink the overall design, because you have a single class that handles far too much—parsing, as well as storing the parsed data—not to mention that it does all of that in the constructor.</p>\n<p>Perhaps a better design would be basically 3 things:</p>\n<ol>\n<li>A class to describe options in a way that tells the parser how options should be parsed (basically <code>parameter</code>, but stripped down a bit—like, don’t actually store the parsed value).</li>\n<li>A class to hold parsed options (basically a map where the key is the option name, and the value is a <code>std::any</code> with the parsed value, if any… but of course, not actually <code>std::any</code>, but rather your own C++14 version of it).</li>\n<li>A parser function that basically takes (1) as argument, and returns (2).</li>\n</ol>\n<p>The tricky part is how to get an actual parse function for <code>T</code> from the <code>type_info</code> stored in the options description. That will be challenging… but not impossible. And it will be <em>much</em> better than just storing the value as a string and then parsing it on demand, both in terms of usability and efficiency.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T23:02:24.750",
"Id": "507032",
"Score": "0",
"body": "Thank you. Really liked your review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T05:26:54.440",
"Id": "256745",
"ParentId": "256710",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256745",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T08:46:23.033",
"Id": "256710",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Simple command line parser"
}
|
256710
|
<p>I am trying to make a program for matrix Calculator and have done this so far. I want to avoid iteration or replication of the statements in my code but I want to restrict using the pointers in this. Can you suggest improvement with the code I can do?</p>
<p>I know I can use structures as well but seems like I see some problem with that. Please help me in suggesting any kind of improvements in this also other feedbacks related to modulation are also acceptable.
Any kind of help will be appreciable. Thanks!</p>
<pre><code>#include <stdio.h>
void matrixReadValues(int rows, int columns, int readInput[rows][columns]);
void matrixPrint(int rows, int columns, int readOutput[rows][columns]);
void matrixAddition(int rows, int columns, int matrix1[rows][columns], int matrix2[rows][columns]);
void matrixSubtraction(int rows, int columns, int matrix1[rows][columns], int matrix2[rows][columns]);
void matrixMultiplication(int rowsA, int columnsA, int rowsB, int columnsB, int matrix1[rowsA][columnsA], int matrix2[rowsB][columnsB]);
void matrixTransposePrint(int rows, int columns, int matrixTranspose[rows][columns]);
int matrixDeterminant(int rows, int columns, int matrixDet[rows][columns], int matrixOrder);
void matrixRowEchleonForm(int rows, int columns, int matrix1[rows][columns]);
int main(void){
int operation; //used in swtich statements
char again = 'Y';
int rowsA, columnsA;
int rowsB, columnsB;
int matrixA[rowsA][columnsA];
int matrixB[rowsB][columnsB];
while (again == 'Y'){
//this is the operation menu just type A, B, C or D to calculate
printf("\n \t\t\tOperation Menu\n\n");
printf("\t1. to Add\n");
printf("\t2. to Subtract\n");
printf("\t3. to Multiply two matrices\n");
printf("\t4. to find the transpose of the matrix\n");
printf("\t5. to find the determinant of the matrix\n\n");
printf("\t6. to find the rowecheleon form of the matrix\n\n");
printf("\tEnter your choice: ");
scanf(" %d", &operation);
switch (operation){
//Case 1 is for addition of 2 matrices
case 1:
printf("\n\tEnter the #rows and #columns for matrix A: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\tEnter the #rows and #cols for matrix B: ");
scanf("%d%d", &rowsB, &columnsB);
while ((rowsA != rowsB) && (columnsA != columnsB)){
printf("\n\tMatrices must be of the same size\n");
printf("\n\tEnter the #rows and #columns for matrix A: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\n\tEnter the #rows and #cols for matrix B: ");
scanf("%d%d", &rowsB, &columnsB);
}
printf("\n\tNow Let us enter the elements of Matrix A %d x %d matrix.\n\n", rowsA, columnsA);
matrixReadValues(rowsA, columnsA, matrixA);
printf("\n\t\tMatrix A\n\n");
matrixPrint(rowsA, columnsA, matrixA);
printf("\n\tNow Let us enter the elements of Matrix B %d x %d matrix.\n\n", rowsB, columnsB);
matrixReadValues(rowsB, columnsB, matrixB);
printf("\n\t\tMatrix B\n\n");
matrixPrint(rowsB, columnsB, matrixB);
printf("\t\nAdding the 2 matrices now, we get Matrix A + B:\n\n");
matrixAddition(rowsA, columnsA, matrixA, matrixB);
break;
// Case 2 is for subtraction of the 2 matrices
case 2:
printf("\n\tEnter the #rows and #columns for matrix A: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\tEnter the #rows and #cols for matrix B: ");
scanf("%d%d", &rowsB, &columnsB);
while ((rowsA != rowsB) && (columnsA != columnsB)){
printf("\n\tMatrices must be of the same size\n");
printf("\n\tEnter the #rows and #columns for matrix A: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\n\tEnter the #rows and #cols for matrix B: ");
scanf("%d%d", &rowsB, &columnsB);
}
printf("\n\tNow Let us enter the elements of Matrix A %d x %d matrix.\n\n", rowsA, columnsA);
matrixReadValues(rowsA, columnsA, matrixA);
printf("\n\t\tMatrix A\n\n");
matrixPrint(rowsA, columnsA, matrixA);
printf("\n\tNow Let us enter the elements of Matrix B %d x %d matrix.\n\n", rowsB, columnsB);
matrixReadValues(rowsB, columnsB, matrixB);
printf("\n\t\tMatrix B\n\n");
matrixPrint(rowsB, columnsB, matrixB);
printf("\t\nSubtracting the 2 matrices now, we get Matrix A - Matrix B:\n\n");
matrixSubtraction(rowsA, columnsA, matrixA, matrixB);
break;
//Case 3 is for addition of 2 matrices
case 3:
printf("\n\tEnter the #rows and #columns for matrix A: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\tEnter the #rows and #cols for matrix B: ");
scanf("%d%d", &rowsB, &columnsB);
while ((rowsA != rowsB) && (columnsA != columnsB)){
printf("\n\tMatrices must be of the same size\n");
printf("\n\tEnter the #rows and #columns for matrix A: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\n\tEnter the #rows and #cols for matrix B: ");
scanf("%d%d", &rowsB, &columnsB);
}
printf("\n\tNow Let us enter the elements of Matrix A %d x %d matrix.\n\n", rowsA, columnsA);
matrixReadValues(rowsA, columnsA, matrixA);
printf("\n\t\tMatrix A\n\n");
matrixPrint(rowsA, columnsA, matrixA);
printf("\n\tNow Let us enter the elements of Matrix B %d x %d matrix.\n\n", rowsB, columnsB);
matrixReadValues(rowsB, columnsB, matrixB);
printf("\n\t\tMatrix B\n\n");
matrixPrint(rowsB, columnsB, matrixB);
printf("\t\n\tMultiplying the 2 matrices now:\n\n");
matrixMultiplication(rowsA, columnsA, rowsB, columnsB, matrixA, matrixB);
//Adding the default statemnt if no option matches
default:
printf("\nIncorrect option! Please choose a number between 1-4.");
break;
//Case 4 is for doing the transpose of the matrix
case 4:
printf("\n\tEnter the #rows and #columns for matrix A: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\n\tNow Let us enter the elements of Matrix %d x %d matrix.\n\n", rowsA, columnsA);
matrixReadValues(rowsA, columnsA, matrixA);
printf("\n\t\tMatrix\n\n");
matrixPrint(rowsA, columnsA, matrixA);
printf("\t\nDoing the transpose of the above matrix:\n\n");
matrixTransposePrint(rowsA, columnsA, matrixA);
break;
// Case 5 is for finding the determinant of a matrix
case 5:
printf("\n\tEnter the #rows and #columns for matrix A. Make sure you add the square matrix: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\n\tNow Let us enter the elements of Matrix %d x %d matrix.\n\n", rowsA, columnsA);
matrixReadValues(rowsA, columnsA, matrixA);
printf("\n\t\tMatrix\n\n");
matrixPrint(rowsA, columnsA, matrixA);
printf("\t\n Finding the determinant of the above matrix:\n\n");
int detRecievedFromFunction;
detRecievedFromFunction = matrixDeterminant(rowsA, columnsA, matrixA, rowsA);
printf("%d", detRecievedFromFunction);
break;
//Writing the Row Echeleon form
case 6:
printf("\n\tEnter the #rows and #columns for matrix A. Make sure you add the square matrix: ");
scanf("%d%d", &rowsA, &columnsA);
printf("\n\tNow Let us enter the elements of Matrix %d x %d matrix.\n\n", rowsA, columnsA);
matrixReadValues(rowsA, columnsA, matrixA);
printf("\n\t\tMatrix\n\n");
matrixPrint(rowsA, columnsA, matrixA);
printf("\t\n Finding the RowElcheleon form of the above matrix:\n\n");
matrixRowEchleonForm(rowsA, columnsA, matrixA);
matrixPrint(rowsA, columnsA, matrixA);
break;
}
}
}
//Function to read the value from the users
void matrixReadValues(int rows, int columns, int readInput[rows][columns]){
int i,j;
for(i=0; i < rows; i++ ){
for(j=0; j < columns; j++){
printf("\tEnter the elemnts [%d][%d]: ", i+1, j+1);
scanf("%d", &readInput[i][j]);
}
}
}
//Printing the matrix values
void matrixPrint(int rows, int columns, int readOutput[rows][columns]){
int i,j;
for(i=0; i < rows; i++ ){
for(j=0; j < columns; j++){
printf("\t%d\t", readOutput[i][j]);
}
printf("\n");
}
}
//Function to add the 2 matrices
void matrixAddition(int rows, int columns, int matrix1[rows][columns], int matrix2[rows][columns]){
int sum[rows][columns];
int i,j;
for(i=0; i < rows; i++ ){
for(j=0; j < columns; j++){
sum[i][j] = matrix1[i][j] + matrix2[i][j];
printf("\t%d\t", sum[i][j]);
}
printf("\n");
}
}
//Function to subtract the 2 matrices
void matrixSubtraction(int rows, int columns, int matrix1[rows][columns], int matrix2[rows][columns]){
int difference[rows][columns];
int i,j;
for(i=0; i < rows; i++ ){
for(j=0; j < columns; j++){
difference[i][j] = matrix1[i][j] - matrix2[i][j];
printf("\t%d\t", difference[i][j]);
}
printf("\n");
}
}
//Functrion to multiply the 2 matrices
void matrixMultiplication(int rowsA, int columnsA, int rowsB, int columnsB, int matrix1[rowsA][columnsA], int matrix2[rowsB][columnsB]){
int multiply[rowsA][columnsB];
int i, j, k;
//Initializing all the elemnts of multiply to 0
for (i = 0; i<rowsA; ++i)
for (j = 0; j<columnsB; ++j)
{
multiply[i][j] = 0;
}
// Checking whether the user wants to do "AB" or "BA" multiplication
int options;
printf("\t What type of operation do you want to perform from A x B or B x A? <Write either 1 for A x B or 2 for B x A>" );
scanf("%d", &options);
if(options == 1){
// Running the loop for the multiplication of the 2 matrices
for (i = 0; i<rowsA; i++){
for (j = 0; j<columnsB; j++){
for (k = 0; k<columnsA; k++){
multiply[i][j] += matrix1[i][k] * matrix2[k][j];
}
printf("\t%d\t", multiply[i][j]);
}
printf("\n");
}
}
else if( options == 2){
// Running the loop for the multiplication of the 2 matrices
for (i = 0; i<rowsB; i++){
for (j = 0; j<columnsA; j++){
for (k = 0; k<columnsB; k++){
multiply[i][j] += matrix2[i][k] * matrix1[k][j];
}
printf("\t%d\t", multiply[i][j]);
}
printf("\n");
}
}
else {
printf("Please add the appropiate values:");
printf("What type of operation do you want to perform from A x B or B x A? <Write either 1 for A x B or 2 for B x A>" );
scanf("%d", &options);
}
}
//Printing the transpose matrix values
void matrixTransposePrint(int rows, int columns, int matrixTranspose[rows][columns]){
int i,j;
for(i=0; i < rows; i++ ){
for(j=0; j < columns; j++){
printf("\t%d\t", matrixTranspose[j][i]);
}
printf("\n");
}
}
//Printing the Determinant of Matrix
int matrixDeterminant(int rows, int columns, int matrixDet[rows][columns], int matrixOrder){
int determinant=0, currentColumn, s = 1, i, j, m, n;
int subMatrixDet[rows][columns]; //This is the matrix which extracted from the enterred matrix (matrixDet[rows][columns]) as a sub matrix
if(matrixOrder == 1){
return(matrixDet[0][0]);
}
else{
// We would be applying the loop to perform the operation for every column
for(currentColumn = 0; currentColumn < matrixOrder - 1; currentColumn++){
m = 0, n = 0; //We initialized it because everytime loop will run we will extract new determinant
//Loop for writing/extracting the sub matrix from the original matrix in order to calculate the minor
for(i=0; i < matrixOrder; i++){
for(j=0; j < matrixOrder; j++){
subMatrixDet[i][j] = 0;
//Since we have to exclude the element which we multiply with the sub determinant matrix
if(i !=0 && j !=0 ){
subMatrixDet[m][n] = matrixDet[i][j];
//Incrementing the Value of n because first the different columns gets filled.
if(n < (matrixOrder - 2)){
n++;
}
else{
n=0;
m++;
}
}
}
}
}
determinant = determinant + s*(matrixDet[0][currentColumn] * matrixDeterminant(rows, columns, subMatrixDet, matrixOrder-1) );
s = -1 * s;
}
return determinant;
}
// Converting in the row echleon form
void matrixRowEchleonForm(int rows, int columns, int matrix1[rows][columns]){
int i,j, nextRow;
int firstElement;
int firstElementNextRow;
for(i = 0; i < rows; i++){
if(matrix1[i][i] != 1){
firstElement = matrix1[i][i];
//Checking if the furst element is the 0
if(firstElement == 0){
continue; //We are avoiding to divide the first element by 0
}
//Now dividing the specific row with different column number by the First element of the row
for(j=0; j < columns ; j++){
matrix1[i][j] = matrix1[i][j] / firstElement;
}
}
for(nextRow = i + 1; nextRow < rows; nextRow++){
//We are now subtracting the next row with the previous row in order to make the very first elements 0
firstElementNextRow = matrix1[nextRow][i];
for(j=0; j < columns; j++){
matrix1[nextRow][j] = matrix1[nextRow][j] - (matrix1[i][j] * firstElementNextRow);
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:23:10.203",
"Id": "506908",
"Score": "0",
"body": "This is not working; the addition only adds the second matrix to itself. There is quite a problem with the arrays: matrixA and matrixB are somehow the same zero-sized array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T16:49:06.870",
"Id": "506926",
"Score": "2",
"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. In particular, it's ok to have [variable length arrays](https://en.cppreference.com/w/c/language/array) since C99, but the array size must be initialized to *some actual value*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T17:37:36.967",
"Id": "506930",
"Score": "0",
"body": "Well, I just asked for the improvements only. That would be great if you can help in that. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:24:37.060",
"Id": "507074",
"Score": "0",
"body": "What compiler did you use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T11:48:32.777",
"Id": "507139",
"Score": "0",
"body": "(@user238196: `There is quite a problem with the arrays` I can see that. I don't see `addition only adds the second matrix to itself` or `matrixA and matrixB are somehow the same […] array`.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:21:51.927",
"Id": "507195",
"Score": "0",
"body": "Depending on what you are trying to achieve, you will be better off picking a different implementation environment. Or a different project altogether. C and arrays with more than one dimension not fixed at compile time is a misfit."
}
] |
[
{
"body": "<p>matrixA and B are the same, as illustrated by this printf:</p>\n<pre><code>int matrixA[rowsA][columnsA];\nint matrixB[rowsB][columnsB];\nprintf("%p %d %d %p\\n", matrixA, rowsA, columnsA, matrixB);\nreturn;\n</code></pre>\n<p>Both matrices have the same address:</p>\n<pre><code>0x7ffd8a489790 0 0 0x7ffd8a489790\n</code></pre>\n<p>as a consequence of declaring a <code>int matrixA[0][0]</code>.</p>\n<p>This leads to wrong results.</p>\n<hr />\n<pre><code> Enter the elemnts [1][1]: 5\n\n Matrix A\n\n 5\n\n Now Let us enter the elements of Matrix B 1 x 1 matrix.\n\n Enter the elemnts [1][1]: 30\n\n Matrix B\n\n 30\n\nAdding the 2 matrices now, we get Matrix A + B:\n\n 60\n</code></pre>\n<p><strong>Shouldn't this be 35 ?</strong></p>\n<hr />\n<p>The overwriting of A can also be seen by showing it agian after B was entered:</p>\n<pre><code> Now Let us enter the elements of Matrix A 2 x 2 matrix.\n\n Enter the elemnts [1][1]: 1\n Enter the elemnts [1][2]: 2\n Enter the elemnts [2][1]: 3\n Enter the elemnts [2][2]: 4\n\n Matrix A\n\n 1 2\n 3 4\n\n Now Let us enter the elements of Matrix B 2 x 2 matrix.\n\n Enter the elemnts [1][1]: 6\n Enter the elemnts [1][2]: 7\n Enter the elemnts [2][1]: 8\n Enter the elemnts [2][2]: 9\n\n Matrix B\n\n 6 7\n 8 9\n\n Matrix A\n\n 6 7 <------- now A has B's values\n 8 9\n\nAdding the 2 matrices now, we get Matrix A + B:\n\n 12 14 <-------- we get B + B\n 16 18 \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T13:30:03.627",
"Id": "506917",
"Score": "0",
"body": "but this is working for me. can you explain more please and also help me know how it can be improved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T13:31:34.720",
"Id": "506918",
"Score": "0",
"body": "Also, I made this code from this but this is just printing the address for me and I don't know why it is so http://pastie.org/p/5Qr5UA9qVYyYuJnVz7Eh8m"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T17:36:17.023",
"Id": "506929",
"Score": "0",
"body": "I see, so how can I correct it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T17:40:29.543",
"Id": "506931",
"Score": "0",
"body": "I just checked again and it is totally working correctly for me. I don't know why it is showing like this in your case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T14:52:34.623",
"Id": "507073",
"Score": "0",
"body": "@JaskiratSingh Probably a difference in compiler. It has been a while since I've written C, but it looks like your code is invoking undefined behaviour. Highly dangerous situation. In those cases, it will differ between compliers what the exact output is going to be."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T13:08:47.317",
"Id": "256719",
"ParentId": "256712",
"Score": "1"
}
},
{
"body": "<p><code>I want to restrict using the pointers in this [matrix calculator code]</code><br />\nThat should prove difficult with C and multidimensional arrays, more below.</p>\n<p>The code you present lacks lucid comments.<br />\nWhat comments I find seem to have been written before the (current) code: way to go!<br />\nBut gotten inconsistent after code changes - <code>this is the operation menu just type A, B, C or D to calculate</code> does not comment code that reacts to those characters - or mislead due to an archetypical copy&paste error - <code>//Case 3 is for addition of 2 matrices</code> <em>does</em> comment a <code>case 3</code> (a bit redundantly, at that) which does <em>not</em> add (like case 1…), but multiply.<br />\nTypos in comments more often than not are just irritating (<code>//used in swtich</code>, <code>default statemnt</code>, <code>//Functrion</code>), but please have a spelling checker help with the UI: <code>\\tEnter the elemnts</code>, <code>appropiate</code> - think of <em>internationalisation</em>.</p>\n<p><strong>• code replication</strong><br />\nYou are right, there is a conspicuous amount of that.<br />\nOne of the great powers is giving names, not just to tangible objects, but to abstractions, too.<br />\nSeeing</p>\n<pre><code>prompt("Now let us enter the elements of %d x %d matrix %s", rows, columns, "A");\nmatrixReadValues(rows, columns, matrix);\nmatrixPrint(rows, columns, matrix, "A");\n</code></pre>\n<p>(or B) for the third time suggests this is a <em>routine</em>/<em>method</em>/<em>function</em> that should be written once and only once.<br />\nIt needs a name and (in and/or out) parameters like <em>matrix-values, -name</em> and <em>-shape</em> to be called all over the place.<br />\n(It has been observed about 60 years ago that values describing one <em>object</em> tend to be used in groups - C does not <em>support</em> object orientation.)</p>\n<p>Trying to code such in C</p>\n<pre><code>int getMatrix[][](int m[][], int *rows, int *columns, const char *name) {\n if (null != name && *name)\n printf("\\n\\tEnter the #rows and #columns for matrix %s: ",\n name);\n scanf("%d%d", rows, columns);\n return m;\n}\n</code></pre>\n<p>gives the compiler an opportunity to remind that arrays in C are not like anything else.<br />\nWhile you can get used to one-dimensional arrays, "the problem" with multidimensional arrays is that every dimension but the first must be fixed at compile time. (My attempts to give further advice went down the road to madness and the umpteenth tutorial on how to work around in special cases and general.)</p>\n<p><strong>• code layout</strong><br />\n- alignment of compound statements&blocks is OK<br />\n- some <code>case</code>es are further to the right than others -<br />\n just like <code>default:</code>, veiling the omission of a <code>break</code> before<br />\n- there is a lot of blank lines separating - nothing, actually, and inconsistently at that.</p>\n<p>Whether or not it is a good idea to have considerable application logic in <code>int main(void)</code>: it seems too much for one function.<br />\nOptions include a separate function for each menu option (excepting, conceivably, exit).\nOr multiple case statements factoring out common code - how about a first one by <em>arity</em>: one or two input matrices, and a second one for dispatch.</p>\n<p>The shape logic in prompting for matrix multiplication input is wrong: I don't see the value of offering a choice between <em>AB</em> and <em>BA</em>, and without a loop, asking for another input if the first one was none of the offered ones is pointless.</p>\n<p><strong>• separation of concerns</strong><br />\n(Most of) Your "arithmetic functions" mix computation and output:<br />\nbetter separate both similar to the handling with <code>matrixRowEchleonForm()</code>(sic). (Imaging just a single place where "the" result is put out.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T18:59:09.903",
"Id": "256852",
"ParentId": "256712",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T09:21:41.933",
"Id": "256712",
"Score": "0",
"Tags": [
"c",
"matrix"
],
"Title": "Matrix Calculator program in C language. How to avoid redundancy"
}
|
256712
|
<p>I need to call some synchronization function and need they running in background and canbe canceled. So I write this:</p>
<pre><code>private static async Task WaitSyncFunction(Action syncFunction,
int timeoutMilliseconds,
CancellationToken token)
{
var syncFunctionTask = Task.Run(syncFunction);
var timeoutTask = Task.Delay(timeoutMilliseconds, token);
await Task.WhenAny(timeoutTask, syncFunctionTask).ContinueWith(task =>
{
if (timeoutTask.IsCanceled) throw new TaskCanceledException();
if (timeoutTask.IsCompletedSuccessfully) throw new TimeoutException();
if (syncFunctionTask.IsFaulted) throw syncFunctionTask.Exception.InnerException;
});
}
</code></pre>
<p>use it:</p>
<pre><code>//...async method of button click event handler in window
cancelSource = new CancellationTokenSource();
try
{
await WaitSyncFunction(() => MySyncFunction(), 5000, cancelSource.Token);
MessageBox.Show("Success!");
}
catch (TaskCanceledException) { MessageBox.Show("Canceled!"); }
catch (Exception ex) { MessageBox.Show("Error! "+ ex.Message); }
//...
</code></pre>
<p>What risks may exist in codes, and is it anti-pattern?</p>
<p>============Edit============<br />
Some improvements:</p>
<pre><code>//Custom exception for process task after timeout
public class TaskTimeoutException : TimeoutException
{
public Task task { get; }
public TaskTimeoutException(Task task)
=> this.task = task;
}
private static async Task WaitSyncFunction(Action syncFunction,
int timeoutMilliseconds,
CancellationToken token)
{
var syncFunctionTask = Task.Run(syncFunction);
var timeoutTask = Task.Delay(timeoutMilliseconds, token);
await Task.WhenAny(timeoutTask, syncFunctionTask);//.ContinueWith(task =>
//{ //Unnecessary ContinueWith
//if (timeoutTask.IsCanceled) throw new TaskCanceledException();
//return the function task so that it can do something else after it ending
if (timeoutTask.IsCanceled) throw new TaskCanceledException(syncFunctionTask);
//if (timeoutTask.IsCompletedSuccessfully) throw new TimeoutException();
//return the function task so that it can do something else after it ending
if (timeoutTask.IsCompletedSuccessfully) throw new TaskTimeoutException(syncFunctionTask);
if (syncFunctionTask.IsFaulted) throw syncFunctionTask.Exception.InnerException;
//});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:39:23.163",
"Id": "506909",
"Score": "3",
"body": "Have you read [this article](https://devblogs.microsoft.com/pfxteam/how-do-i-cancel-non-cancelable-async-operations/)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:51:27.073",
"Id": "506911",
"Score": "1",
"body": "Welcome to the Code Review Community. There really isn't enough code here to review. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) and [What types of questions should I avoid asking](https://codereview.stackexchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T02:13:43.040",
"Id": "506950",
"Score": "0",
"body": "@PeterCsala I've read it but I think it may not much fit for me, in my code it support 4 status: Canceled, Faulted, Timeout and Complated. but the code in article is only support 3 status: Canceled, Faulted and Complated. If i want to add timeout I need add a Task to achieve. I think it's not a good idea. (CancelAfter also not a good idea, it will be think as Canceled, not Timeout)"
}
] |
[
{
"body": "<p>Whenever we have an async method and we want to differentiate <code>Canceled</code> from <code>Timeout</code> then we usually do the following:</p>\n<ol>\n<li>We are anticipating <code>OperationCanceledException</code> (the base class of <code>TaskCanceledException</code>)</li>\n<li>We examine the <code>IsCancellationRequested</code> property of the <code>CancellationToken</code></li>\n</ol>\n<p>Let me show you a simple example:</p>\n<h3><code>Timeout</code></h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private static readonly TimeSpan OperationDuration = TimeSpan.FromSeconds(3);\n// timeoutSource will be triggered\nprivate static readonly TimeSpan Timeout = TimeSpan.FromSeconds(2); \nprivate static readonly TimeSpan CancelAfter = TimeSpan.FromSeconds(10);\n\nstatic async Task Main(string[] args)\n{\n var userCancellationSource = new CancellationTokenSource(CancelAfter);\n try\n {\n await TestAsync(userCancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Console.WriteLine(userCancellationSource.IsCancellationRequested ? "Canceled" : "Timed out");\n }\n}\n\npublic static async Task TestAsync(CancellationToken token = default)\n{\n var timeoutSource = new CancellationTokenSource(Timeout);\n var timeoutOrCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, token);\n await Task.Delay(OperationDuration, timeoutOrCancellationSource.Token);\n}\n</code></pre>\n<h3><code>Canceled</code></h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private static readonly TimeSpan OperationDuration = TimeSpan.FromSeconds(3);\nprivate static readonly TimeSpan Timeout = TimeSpan.FromSeconds(2); \n// userCancellationSource will be triggered \nprivate static readonly TimeSpan CancelAfter = TimeSpan.FromSeconds(1); \n\nstatic async Task Main(string[] args)\n{\n var userCancellationSource = new CancellationTokenSource(CancelAfter);\n try\n {\n await TestAsync(userCancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Console.WriteLine(userCancellationSource.IsCancellationRequested ? "Canceled" : "Timed out");\n }\n}\n\npublic static async Task TestAsync(CancellationToken token = default)\n{\n var timeoutSource = new CancellationTokenSource(Timeout);\n var timeoutOrCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, token);\n await Task.Delay(OperationDuration, timeoutOrCancellationSource.Token);\n}\n</code></pre>\n<p>I think the same pattern should be followed by your wrapper. To have the same behavior I have modified your <code>WaitSyncFunction</code> method in the following way</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static async Task WaitSyncFunction(Action syncFunction, int timeoutMilliseconds, CancellationToken token)\n{\n var syncFunctionTask = Task.Run(syncFunction);\n var timeoutTask = Task.Delay(timeoutMilliseconds, token);\n await Task.WhenAny(timeoutTask, syncFunctionTask);\n if (timeoutTask.IsCanceled) token.ThrowIfCancellationRequested(); //changed\n if (timeoutTask.IsCompletedSuccessfully) throw new OperationCanceledException(token); //changed\n if (syncFunctionTask.IsFaulted) throw syncFunctionTask.Exception.InnerException;\n}\n</code></pre>\n<h3><code>Timeout</code></h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private static readonly TimeSpan OperationDuration = TimeSpan.FromSeconds(3);\n// timeoutSource will be triggered\nprivate static readonly TimeSpan Timeout = TimeSpan.FromSeconds(2);\nprivate static readonly TimeSpan CancelAfter = TimeSpan.FromSeconds(10);\n\nstatic async Task Main(string[] args)\n{\n var userCancellationSource = new CancellationTokenSource(CancelAfter);\n try\n {\n await WaitSyncFunction(() => Thread.Sleep((int) OperationDuration.TotalMilliseconds),\n (int) Timeout.TotalMilliseconds, userCancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Console.WriteLine(userCancellationSource.IsCancellationRequested ? "Canceled" : "Timed out");\n }\n}\n\nprivate static async Task WaitSyncFunction(Action syncFunction, int timeoutMilliseconds,\n CancellationToken token)\n{\n var syncFunctionTask = Task.Run(syncFunction);\n var timeoutTask = Task.Delay(timeoutMilliseconds, token);\n await Task.WhenAny(timeoutTask, syncFunctionTask);\n if (timeoutTask.IsCanceled) token.ThrowIfCancellationRequested();\n if (timeoutTask.IsCompletedSuccessfully) throw new OperationCanceledException(token);\n if (syncFunctionTask.IsFaulted) throw syncFunctionTask.Exception.InnerException;\n}\n</code></pre>\n<h3><code>Canceled</code></h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private static readonly TimeSpan OperationDuration = TimeSpan.FromSeconds(3);\nprivate static readonly TimeSpan Timeout = TimeSpan.FromSeconds(2);\n// userCancellationSource will be triggered \nprivate static readonly TimeSpan CancelAfter = TimeSpan.FromSeconds(1);\n\nstatic async Task Main(string[] args)\n{\n var userCancellationSource = new CancellationTokenSource(CancelAfter);\n try\n {\n await WaitSyncFunction(() => Thread.Sleep((int) OperationDuration.TotalMilliseconds),\n (int) Timeout.TotalMilliseconds, userCancellationSource.Token);\n }\n catch (OperationCanceledException)\n {\n Console.WriteLine(userCancellationSource.IsCancellationRequested ? "Canceled" : "Timed out");\n }\n}\n\nprivate static async Task WaitSyncFunction(Action syncFunction, int timeoutMilliseconds,\n CancellationToken token)\n{\n var syncFunctionTask = Task.Run(syncFunction);\n var timeoutTask = Task.Delay(timeoutMilliseconds, token);\n await Task.WhenAny(timeoutTask, syncFunctionTask);\n if (timeoutTask.IsCanceled) token.ThrowIfCancellationRequested();\n if (timeoutTask.IsCompletedSuccessfully) throw new OperationCanceledException(token);\n if (syncFunctionTask.IsFaulted) throw syncFunctionTask.Exception.InnerException;\n}\n</code></pre>\n<hr />\n<p>Please bear in mind that with this implementation the <code>syncFunction</code> is not aborted in case of timeout. To support cooperative cancellation you have to pass the <code>CancellationToken</code> to the <code>syncFunction</code> and examine its <code>IsCancellationRequested</code> property periodically (at each checkpoint / milestone).</p>\n<p>Check out these for more details:</p>\n<ul>\n<li><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads\" rel=\"nofollow noreferrer\">Cancellation in Managed Threads</a></li>\n<li><a href=\"https://codereview.stackexchange.com/questions/256168/c-asynchronous-tasks-training-turn-based-simulation\">CodeReview topic: C# asynchronous tasks training (turn-based simulation)</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T01:28:42.570",
"Id": "507205",
"Score": "0",
"body": "If I want to do something process after the \"MySyncFunction\" end (complated or faulted), I should write a override`... WaitSyncFunction(Task syncFunctionTask, ...)` and create the task of sync function before calling? (Throw a exception with a task looks weird indeed)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T07:49:00.290",
"Id": "507218",
"Score": "0",
"body": "@Squirrel.Downy To be honest with you I'm not sure I've understood your question 100%, could you please rephrase it. If you want to execute something after completion then call it after your `await WaitSyncFunction( ...);` inside the `try` block. If you want to execute something in case of failure then call it inside the `catch` block."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T09:11:44.537",
"Id": "256754",
"ParentId": "256715",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256754",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:09:59.943",
"Id": "256715",
"Score": "-1",
"Tags": [
"c#",
"async-await"
],
"Title": "c# make synchronization function waitable and cancelable"
}
|
256715
|
<p>The full problem description can be found <a href="https://open.kattis.com/problems/driversdilemma" rel="nofollow noreferrer">here</a>, a slightly trimmed version below:</p>
<blockquote>
<p>A car driver is travelling on an isolated road (no gas stations, houses, or cell phone coverage). The driver glances at their fuel gauge: there is exactly half a tank left. They stop and see that the fuel tank is leaking.</p>
<p>The driver cannot repair the leak. Using a container of known volume and a wristwatch, they measure the rate of fuel loss at <code></code> gallons per hour. They empty the container back into the tank.</p>
<p>The driver checks the manual and sees the fuel tank capacity is <code></code> gallons. There's also a table resembling the one below, showing declining fuel efficiency in miles per gallon (MPG) as driving speed in miles per hour (MPH) increases. They must trade one against the other in an attempt to reach the nearest gas station <code></code> miles away before nightfall.</p>
<pre><code>Speed (MPH) Fuel Efficiency (MPG)
55 22.0
60 21.3
65 20.2
70 18.3
75 16.9
80 15.8
</code></pre>
<p>The driver assumes manuals authors are experts, and has an aversion to interpolation (and extrapolation), they decide to drive at exactly one of the 6 speeds listed. That way, the distance travelled before running out of gas will be 100% predictable.</p>
<p>Can the driver reach the gas station before running out of fuel? If so, what is the maximum speed they can drive?</p>
</blockquote>
<p>Examples:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Input</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>18 0.5 160<br>55 22.0<br>60 21.3<br>65 20.2<br>70 18.3<br>75 16.9<br>80 15.8</code></td>
<td><code>YES 60</code></td>
</tr>
<tr>
<td><code>16 0.07 160<br>55 20.49<br>60 18.40<br>65 17.78<br>70 17.10<br>75 16.38<br>80 15.60</code></td>
<td><code>NO</code></td>
</tr>
</tbody>
</table>
</div><hr />
<p><em>main.rs</em></p>
<pre class="lang-rust prettyprint-override"><code>use std::io::{self, BufRead};
#[derive(Debug)]
struct Car {
capacity: f32,
rate_of_loss: f32,
remaining: f32,
efficiancy: Vec<MPG>,
}
#[derive(Debug)]
struct MPG {
mph: f32,
mpg: f32,
}
impl Car {
fn in_range(&self, distance: f32) -> f32 {
let mut res: f32 = -1.0;
let volume = self.capacity * self.remaining;
for entry in &self.efficiancy {
let time = distance / entry.mph;
let total_loss = time * self.rate_of_loss;
let max_distance = (volume - total_loss) * entry.mpg;
if max_distance > distance {
res = res.max(entry.mph);
}
}
res
}
}
fn main() {
let remaining: f32 = 0.5;
let mut c: f32 = 0.0;
let mut x: f32 = 0.0;
let mut m: f32 = 0.0;
let mut efficiancies: Vec<MPG> = Vec::new();
let stdin = io::stdin();
for (i, line) in stdin.lock().lines().map(|x| x.unwrap()).enumerate() {
let nums: Vec<f32> = line
.split_whitespace()
.map(|n| n.parse().unwrap())
.collect();
if i == 0 {
c = nums[0];
x = nums[1];
m = nums[2];
} else {
efficiancies.push(MPG {
mph: nums[0],
mpg: nums[1],
});
}
}
let car = Car {
capacity: c,
rate_of_loss: x,
remaining: remaining,
efficiancy: efficiancies,
};
let y = car.in_range(m);
if y > 0.0 {
println!("YES {:.0}", y);
} else {
println!("NO");
}
}
</code></pre>
<p>I did initially write a smaller version that did everything in the main function, but I wanted to try using <code>struct</code> and <code>impl</code>. I primarily use python, so I'm mostly looking for pointers on style/idiomatic rust and intermediate/advanced topics that I could try out. Any advice is welcome :)</p>
|
[] |
[
{
"body": "<ul>\n<li>Just construct <code>let mut car = Car ...</code> at the beginning of <code>main</code>.</li>\n<li>Do not do unwrap, replace collects with <code>collect</code>ing to <code>Result<Vec<A>, E></code> and run <code>?</code> on the result. Return <code>Result<(), E></code> from <code>main</code>. You may use a crate such as <code>anyhow</code>. Look into error handling in parsing in this solution <a href=\"https://codereview.stackexchange.com/questions/254832/advent-of-code-2020-day-3-tobogganing-down-a-slope\">Advent of Code 2020 - Day 3: tobogganing down a slope</a></li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>impl<A, E, V> FromIterator<Result<A, E>> for Result<V, E>\nwhere\n V: FromIterator<A>,\n</code></pre>\n<ul>\n<li>Instead of implementing parsing on your own, look into crates such as <a href=\"https://crates.io/crates/parse-display\" rel=\"nofollow noreferrer\"><code>parse-display</code></a>, <a href=\"https://crates.io/crates/reformation\" rel=\"nofollow noreferrer\"><code>reformation</code></a> or <a href=\"https://crates.io/crates/recap\" rel=\"nofollow noreferrer\"><code>recap</code></a>.</li>\n<li>For <code>in_range</code>, I would do a <code>max</code> on an iterator, so that the code is functional rather than imperatively stateful with the <code>res</code> variable.</li>\n<li>a typo <code>efficiancy</code> -> <code>efficiency</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T13:19:08.217",
"Id": "256721",
"ParentId": "256716",
"Score": "1"
}
},
{
"body": "<h2>Design</h2>\n<p>I applaud the goal of using <code>struct</code> and <code>impl</code>, but this is a good example of where object-oriented style can go wrong: it is not clear exactly what functionality <code>Car</code> and <code>MPG</code> encapsulate. Rather, these are just structs that carry some relevant data for the <code>in_range</code> function, but they do not seem to lead to a meaningful "separation of concerns" or make the code easier to understand as written.</p>\n<p>For example, what is an <code>MPG</code> object? It carries a pair of a miles-per-hour and a miles-per-gallon, but why are these particular pieces of data grouped together and not with the other pieces of data? For <code>Car</code>, the primary problem is that it carries a lot of data but not enough functionality. If I were to reuse or extend your code, I would not be sure what to use a <code>Car</code> for, and whether and how I should extend <code>Car</code> with additional methods.</p>\n<p>To improve your code, I would start by getting rid of <code>MPG</code>. Then, I would settle on a simple abstraction of a car that seems generalizable. We could start with this: a car is something that drives, given a certain amount of fuel, a fuel leak rate, a certain speed, and a certain fuel efficiency. Note that we no longer have <code>efficiancy: Vec<MPG></code> as part of the car --- that muddles the meaning of a car, since it can then only drive at certain rates.\nWe might get something like the following design:</p>\n<pre><code>struct Car {\n fuel_remaining: f32, // Gallons\n fuel_leak_rate: f32, // Gallons/hour\n speed: f32, // Miles/hour\n efficiency: f32, // Miles/gallon\n}\nimpl Car {\n fn new(\n fuel_remaining: f32,\n fuel_leak_rate: f32,\n speed: f32,\n efficiency: f32,\n ) -> Self {\n assert!(fuel_remaining >= 0);\n assert!(fuel_leak_rate >= 0);\n assert!(speed > 0);\n assert!(efficiency > 0);\n Self { fuel_remaining, fuel_leak_rate, speed, efficiency }\n }\n fn can_drive(&self, distance: f32) -> bool {\n let time = distance / self.speed;\n let fuel_req = time * self.fuel_leak_rate + distance / self.efficiency;\n fuel_req < self.fuel_remaining\n }\n}\n</code></pre>\n<p>What I want to stress here is that the design is extensible:</p>\n<ul>\n<li><p>First, we've articulated the requirements on our struct in the <code>new</code> function: which arguments must be greater than or equal to zero, possibly equal to zero, and so on.</p>\n</li>\n<li><p>Second, we've simplified the functionality to <code>can_drive</code> which just checks whether we can drive a given distance, but we could now imagine adding other functions, like <code>fn drive(&mut self, distance: f32)</code> to actually do the drive, <code>fn out_of_gas(&self) -> bool</code> to check if we are out of gas, <code>fn fill_up(&mut self, new_gas: f32)</code>, and so on. These additional features would conceptually align with what the object is designed for.</p>\n</li>\n</ul>\n<h2>A Note On Units</h2>\n<p>Although overkill for this example, another improvement to your design would be to make use of Rust's type system to keep different units separate at compile time. Here's how you would do that: first we define <code>struct</code> wrappers for each different kind of unit we are interested in:</p>\n<pre><code>struct Miles(f32):\nstruct Gallons(f32):\nstruct Hours(f32);\nstruct MPH(f32);\nstruct MPG(f32);\n</code></pre>\n<p>Then we can define operations like multiplication for the particular types which "make sense" to multiply. E.g.:</p>\n<pre><code>use std::ops::{Add, Mul};\n\nimpl Add for Hours {\n type Output = Self;\n fn add(self, other: Self) -> Self {\n self.0 + other.0\n }\n}\nimpl Mul<Hours> for MPH {\n type Output = Miles;\n fn mul(self, time: Hours) -> Miles {\n self.0 * time.0\n }\n}\n</code></pre>\n<p>and so on.\nThe beauty of this approach is that we get a compiler error if we make any arithmetic mistakes, like adding <code>Miles</code> to <code>Hours</code>. And moreover, that comes for free: in the actual running code, <code>Miles</code> and <code>Hours</code> both compile to plain <code>f32</code> values.</p>\n<h2>Minutae</h2>\n<p>In addition to what the other answer said, run <code>cargo clippy</code>! It usually gives very helpful suggestions. Here you can replace <code>remaining: remaining</code> with <code>remaining</code>. It would also be great to see some unit tests.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T02:24:15.687",
"Id": "256789",
"ParentId": "256716",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256789",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:36:17.043",
"Id": "256716",
"Score": "2",
"Tags": [
"programming-challenge",
"rust"
],
"Title": "Kattis 'Driver's Dilemma'"
}
|
256716
|
<p>There are both a simple byte endian (little and big) order swapper and its testbench. A data stream inputs to the module and is converted to the other endianness by computational logic.</p>
<h2><code>byte_order_swap.v</code></h2>
<pre><code>`timescale 1ns / 1ps
module byte_order_swap #
(
parameter integer DATA_WIDTH = 32
)
(
input wire [DATA_WIDTH - 1 : 0] data_i,
input wire [DATA_WIDTH - 1 : 0] data_o
);
localparam integer DATA_BYTE_NUMBER = DATA_WIDTH / 8;
localparam integer DEC_DATA_WIDTH = DATA_WIDTH - 1;
generate
genvar i;
if (0 == (DATA_WIDTH % 4)) begin
for(i = 0; i < DATA_BYTE_NUMBER; i = i + 1) begin
assign data_o[(i * 8) +: 8] = data_i[(DEC_DATA_WIDTH - i * 8) -: 8];
end
end
else begin
assign data_o = {DATA_WIDTH{1'h0}};
end
endgenerate
endmodule
</code></pre>
<h2><code>byte_order_swap_tb.v</code></h2>
<pre><code>`timescale 1ns / 1ps
module byte_order_swap_tb;
localparam integer DATA_WIDTH = 32;
localparam integer CLOCK_PERIOD = 100;
localparam integer ITERATION_NUMBER = 1000;
localparam [DATA_WIDTH - 1 : 0] COUNTER_START_VALUE = 32'hAABB1122;
wire [DATA_WIDTH - 1 : 0] counter_swap_value;
reg clk;
reg [DATA_WIDTH - 1 : 0] counter_dir_value;
byte_order_swap #
(
.DATA_WIDTH (DATA_WIDTH)
)
byte_order_swap_dut
(
.data_i (counter_dir_value),
.data_o (counter_swap_value)
);
initial begin
clk = 1'h0;
forever begin
#( CLOCK_PERIOD / 2 ) clk = !clk;
end
end
initial begin
counter_dir_value <= COUNTER_START_VALUE;
repeat(ITERATION_NUMBER) begin
@(posedge clk);
counter_dir_value <= counter_dir_value + 1'h1;
end
end
task check_swap;
begin
repeat(ITERATION_NUMBER) begin
@(posedge clk);
$display("A direction value: %h -> the swap value: %h",counter_dir_value, counter_swap_value, $time);
end
end
endtask
initial begin
check_swap;
$stop();
end
endmodule
</code></pre>
|
[] |
[
{
"body": "<p>The code makes good use of parameters. However, I see a potential problem.</p>\n<pre><code> if (0 == (DATA_WIDTH % 4)) begin\n</code></pre>\n<p>That code seems to imply that any multiple of 4 is supported. But, if I try <code>DATA_WIDTH</code> = 20, then I see <code>z</code> values in the output. Perhaps you should restrict values to be a multiple of 8 instead:</p>\n<pre><code> if (0 == (DATA_WIDTH % 8)) begin\n</code></pre>\n<p>Conventionally, the word "check" means that you will compare an actual value to an expected value and report an error if the two do not match. The <code>check_swap</code> task simply displays the values. If that is all you are looking to do, then I suggest renaming the task as <code>display_swap</code> or <code>monitor_swap</code>.</p>\n<p>However, you could add code to the testbench to do a comparison. If your tool suite supports SystemVerilog features, then the following additions/modifications would provide automatic checking:</p>\n<pre><code>wire [DATA_WIDTH - 1 : 0] data_o;\ngenerate\n if (0 == (DATA_WIDTH % 8)) begin\n assign data_o = {<< 8{counter_dir_value}};\n end else begin\n assign data_o = '0;\n end\nendgenerate\n\ntask check_swap;\n repeat(ITERATION_NUMBER) begin\n @(posedge clk);\n $display("A direction value: %h -> the swap value: %h", counter_dir_value, counter_swap_value, $time);\n if (data_o !== counter_swap_value) begin\n $display("ERROR: data miscompare", $time);\n end\n end\nendtask\n</code></pre>\n<p>To create the expected data (<code>data_o</code>), I copied the <code>generate</code> code from the design and made some simplifications. The <code>{<< 8{counter_dir_value}}</code> syntax is another way to perform the byte swap. Refer to IEEE Std 1800-2017, section 11.4.14 <em>Streaming operators (pack/unpack)</em>. The <code>'0</code> syntax is a simplified way of assigning all bits to 0, equivalent to what you have already. If you plan to synthesize the design, and your tool chain supports this syntax, you could even use this code in your design module.</p>\n<p>A minor note: with that type of <code>task</code> body, the <code>begin/end</code> keywords are now optional.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T07:15:14.920",
"Id": "508267",
"Score": "1",
"body": "Thank you for the reply. Your criticism and rectification of my code are very important for me. Sorry for the late answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T14:12:38.807",
"Id": "508324",
"Score": "0",
"body": "@drakonof I'm glad to help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T22:18:06.880",
"Id": "256738",
"ParentId": "256717",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256738",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T12:50:19.057",
"Id": "256717",
"Score": "3",
"Tags": [
"reinventing-the-wheel",
"verilog"
],
"Title": "A byte endian swapper"
}
|
256717
|
<p>I've created a Node.js/Express application that accepts personal data in a form on the front end with React (name, address, etc). It's purpose is to take a user's name, address, and some other info and use it to display a formal letter (Dear Mr John Doe...) with the user's info automatically filled in.</p>
<p>The form data is submitted with front and backend validation utilizing a proxy and SmartyStreets API to check if the address is real.</p>
<p>Here is a typical success use case...</p>
<ol>
<li>User fills out form and clicks submit.</li>
<li>A modal window displays stating that the address in being verified.</li>
<li>Another modal displays with a list of possible addresses.</li>
<li>The user clicks their address from the list and submits.</li>
<li>The formal letter is displayed with the user's info filled in.</li>
</ol>
<p>I am a beginner and this is my first React app (written with hooks and function components), though it's been refactored many times.</p>
<p>I'm looking to improve this application according to SOLID principles (or have my assumptions corrected if this is really about functional programming) as it relates to the functions of the React front end. I also am looking for advice on how useReducer might compare to useState for improved readability, reliability, and debugging with specific code examples if possible. I realize this would be a lot of code to look over so I'll leave out the backend code and display the React components instead. I'll also provide the link to the github repo.</p>
<p><a href="https://github.com/kylewcode/react-html-letter-v2" rel="nofollow noreferrer">https://github.com/kylewcode/react-html-letter-v2</a></p>
<p>App.js</p>
<pre><code>import axios from "axios";
import React, { Fragment, useState } from "react";
import { stateList } from "./utils/stateList";
import Modal from "./Modal";
import Display from "./Display";
// Bootstrap
import Container from "react-bootstrap/Container";
import Row from "react-bootstrap/Row";
import Col from "react-bootstrap/Col";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import ModalContainer from "react-bootstrap/Modal";
import Spinner from "react-bootstrap/Spinner";
import Alert from "react-bootstrap/Alert";
// The purpose of this component is to maintain the global state and determine the rendering of all other components.
function App() {
const statesJSX = [];
for (const [index, value] of stateList.entries()) {
statesJSX.push(
<option key={index} value={value}>
{value}
</option>
);
}
const initState = {
firstName: "",
lastName: "",
street: "",
aptSuite: "",
city: "",
stateName: "",
zipcode: "",
date: "",
title: "",
status: "fillingOutForm",
};
const [state, setState] = useState(() => initState);
const [responseData, setResponseData] = useState(() => null);
const [showInvalidError, setShowInvalidError] = useState(false);
const [showSystemError, setShowSystemError] = useState(false);
function setStateByObject(object) {
setState({ ...state, ...object });
}
function setStateByKeyValue(key, value) {
setState({ ...state, [key]: value });
}
async function handleSubmit(e) {
// Purpose #1 Submit form data to API request
e.preventDefault();
setStateByKeyValue("status", "validatingData");
// Front end handles validation and all form inputs except apt/suite are required
const requestBody = {
street: state.street,
city: state.city,
state: state.stateName,
zipcode: state.zipcode,
};
if (state.aptSuite) requestBody.secondary = state.aptSuite;
const dataValidated = await requestData(requestBody);
// Purpose#2 Update the state to trigger Modal render with trimmed whitespace data otherwise the rendered letter will be formatted incorrectly. I don't currently know how I would keep onSubmit to a single purpose.
const inputs = e.target.elements;
const newState = trimTextInputs(inputs);
// Modal needs to be displayed after form is submitted.
if (dataValidated) newState.status = "formSubmitted";
setStateByObject(newState);
}
function trimTextInputs(inputs) {
let trimmed;
let name;
const result = {};
for (let i = 0; i < inputs.length; i++) {
if (inputs[i].nodeName === "INPUT" && inputs[i].type === "text") {
trimmed = inputs[i].value.trim();
name = inputs[i].name;
}
// Object is needed in order to update state properly because the key/name matches the state prop.
// Ex: name(firstName) state prop is firstName
result[name] = trimmed;
}
return result;
}
/* Address Validation */
async function requestData(body) {
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
// What backound route would I be posting to with Heroku?
const res = await axios.post("http://localhost:5000", body, config);
const isValidated = validateData(res.data);
// Because of how the data from the request is scoped here and invoked in handleSubmit, React state is the only option I can think of that can pass the data to the Modal component in the App render.
if (isValidated) {
setResponseData(res.data);
return true;
} else {
setResponseData(null);
return false;
}
} catch (err) {
console.log(err);
}
}
function validateData(data) {
if (Array.isArray(data) && data.length === 0) {
// If SmartyStreets gets an invalid address it sends back an empty array. This triggers an error to notify the user.
setShowInvalidError(true);
return false;
}
if (!Array.isArray(data)) {
// This error is just in case the API sends data that's completely wrong and notifies user.
setShowSystemError(true);
return false;
}
return true;
}
const formElement = (
<Fragment>
<Row className="justify-content-center">
<Col sm="auto">
<h1 className="text-center">Formal Letter Generator</h1>
<p className="text-center">All fields required except Apt/Suite #</p>
{showSystemError ? (
<Alert
variant="danger"
onClose={() => setShowSystemError(false)}
dismissible
>
<p>
There has been a system error. Please try again at a later time.
</p>
</Alert>
) : null}
</Col>
</Row>
<Row className="justify-content-center">
<Col sm="auto">
<Form onSubmit={(e) => handleSubmit(e)}>
<Form.Row>
<Col sm="auto">
<Form.Group>
<Form.Label htmlFor="user-first-name">First name</Form.Label>
<Form.Control
type="text"
name="firstName"
id="user-first-name"
value={state.firstName}
required
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
</Form.Group>
</Col>
<Col sm="auto">
<Form.Group>
<Form.Label htmlFor="user-last-name">Last name</Form.Label>
<Form.Control
type="text"
name="lastName"
id="user-last-name"
value={state.lastName}
required
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
</Form.Group>
</Col>
</Form.Row>
<Row className="p-3 border border-1 my-3 shadow-sm rounded">
<fieldset>
<legend>Mailing address</legend>
{showInvalidError ? (
<Alert
variant="danger"
onClose={() => setShowInvalidError(false)}
dismissible
>
<p>
You entered an invalid address. Please enter your address
and submit the form again.
</p>
</Alert>
) : null}
<Form.Row>
<Form.Group as={Col} sm="6">
<Form.Label htmlFor="user-street">Street</Form.Label>
<Form.Control
type="text"
name="street"
id="user-street"
value={state.street}
required
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
</Form.Group>
<Form.Group as={Col} sm="2">
<Form.Label htmlFor="user-apt-suite">Apt/Suite</Form.Label>
<Form.Control
type="text"
name="aptSuite"
id="user-apt-suite"
value={state.aptSuite}
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} sm="auto">
<Form.Label htmlFor="user-city">City</Form.Label>
<Form.Control
type="text"
name="city"
id="user-city"
value={state.city}
required
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
</Form.Group>
<Form.Group as={Col} sm="auto">
<Form.Label htmlFor="state-select">State</Form.Label>
<Form.Control
as="select"
name="stateName"
id="state-select"
value={state.stateName}
required
onChange={(e) => {
const key = e.currentTarget.name;
const value = e.currentTarget.value;
setStateByKeyValue(key, value);
}}
>
<option>Select state</option>
{statesJSX}
</Form.Control>
</Form.Group>
<Form.Group as={Col} sm="2">
<Form.Label htmlFor="user-zipcode">Zipcode</Form.Label>
<Form.Control
type="text"
name="zipcode"
id="user-zipcode"
value={state.zipcode}
required
pattern="\d{5}"
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
<Form.Text>Zipcodes must be 5 numbers.</Form.Text>
</Form.Group>
</Form.Row>
<Form.Row>
<Form.Group as={Col} sm="auto">
<Form.Label htmlFor="date-input">Date</Form.Label>
<Form.Control
type="date"
name="date"
id="date-input"
value={state.date}
required
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
</Form.Group>
</Form.Row>
</fieldset>
</Row>
<Form.Row>
<Form.Group as={Col} sm="auto">
<Form.Label htmlFor="user-title">What's your title?</Form.Label>
<Form.Control
htmlSize="1"
type="text"
name="title"
id="user-title"
value={state.title}
placeholder="Mr, Mrs, Ms, etc..."
required
onChange={(e) => {
const key = e.target.name;
const value = e.target.value;
setStateByKeyValue(key, value);
}}
/>
</Form.Group>
</Form.Row>
<Form.Row
as={Col}
sm="auto"
className="justify-content-center mb-3"
>
<Button variant="dark" type="submit" size="lg">
Submit
</Button>
</Form.Row>
</Form>
</Col>
</Row>
</Fragment>
);
return (
<Container className="my-md-3 border bg-light shadow rounded">
{state.status === "fillingOutForm" ? formElement : null}
{state.status === "validatingData" ? (
<Fragment>
<ModalContainer
backdrop="static"
centered
show={state.status === "validatingData"}
>
<ModalContainer.Header>
<ModalContainer.Title>Confirming address...</ModalContainer.Title>
</ModalContainer.Header>
<ModalContainer.Body>
<Spinner animation="border" role="status">
<span className="sr-only">Confirming address...</span>
</Spinner>
</ModalContainer.Body>
</ModalContainer>
{formElement}
</Fragment>
) : null}
{state.status === "formSubmitted" ? (
<Fragment>
<ModalContainer
backdrop="static"
centered
show={state.status === "formSubmitted"}
>
<ModalContainer.Body>
<Modal
addressData={responseData}
callParentState={(data) => setStateByObject(data)}
/>
</ModalContainer.Body>
</ModalContainer>
{formElement}
</Fragment>
) : null}
{state.status === "formConfirmed" ? (
<Display
formData={state}
callParentState={(key, value) => setStateByKeyValue(key, value)}
/>
) : null}
</Container>
);
}
export default App;
</code></pre>
<p>Modal.js</p>
<pre><code>import React, { Fragment } from "react";
import Form from "react-bootstrap/Form";
import Button from "react-bootstrap/Button";
import ListGroup from "react-bootstrap/ListGroup";
// @purpose To allow the user to validate the address based off a list of choices and send the correct address back to App.
// @data SmartyStreets list of addresses
function Modal({ addressData, callParentState }) {
const displayAddresses = (data) =>
data.map((address, index) => {
const fullAddress = `${address.deliveryLine1}, ${address.lastLine}`;
const { cityName, state, zipCode } = address.components;
return (
<ListGroup key={index}>
<ListGroup.Item>
<Form.Check
type="radio"
name="address-validate"
id={`validate-${index}`}
value={fullAddress}
label={fullAddress}
data-street={address.deliveryLine1}
data-city={cityName}
data-state={state}
data-zipcode={zipCode}
/>
</ListGroup.Item>
</ListGroup>
);
});
return (
<Fragment>
<p>
These are the addresses in our records that match what you have entered.
Note that apartment or suite numbers are disregarded. Please select one
of the following:
</p>
<Form
onSubmit={(e) => {
e.preventDefault();
const inputs = e.target;
for (let i = 0; i < inputs.length; i++) {
const element = inputs[i];
if (
element.checked &&
element.computedRole === "radio" &&
element.value !== "none"
) {
const { street, city, state, zipcode } = element.dataset;
const data = {
street: street,
city: city,
stateName: state,
zipcode: zipcode,
status: "formConfirmed",
};
callParentState(data);
}
if (
element.checked &&
element.computedRole === "radio" &&
element.value === "none"
) {
// User needs to return to the form if they don't see their address.
const data = {
status: "fillingOutForm",
};
window.alert("Returning to form. Please reenter your address.");
callParentState(data);
}
}
}}
>
{addressData === null ? null : displayAddresses(addressData)}
<ListGroup>
<ListGroup.Item>
<Form.Check
type="radio"
name="address-validate"
id="validate-none"
value="none"
label="I do not see my address here."
/>
</ListGroup.Item>
</ListGroup>
<div className="text-center">
<Button variant="primary" type="submit" className="mt-3">
Submit
</Button>
</div>
</Form>
</Fragment>
);
}
export default Modal;
</code></pre>
<p>Display.js</p>
<pre><code>import React, { Fragment } from "react";
import "./Display.css";
import Button from 'react-bootstrap/Button'
function Display({
callParentState,
formData: {
firstName,
lastName,
street,
aptSuite,
city,
stateName,
zipcode,
date,
title,
},
}) {
function handleClick() {
callParentState("status", "fillingOutForm");
}
return (
<Fragment>
<address className="sender-column">
<p>
<b>Dr. Eleanor Gaye</b> <br />
Awesome Science faculty <br />
University of Awesome <br />
Bobtown, CA 99999, <br />
USA <br />
<b>Tel</b>: 123-456-7890 <br />
<b>Email</b>: no_reply@example.com
</p>
</address>
<div className="sender-column">
<time dateTime="2016-01-20">{date}</time>
</div>
<address>
<p>
<b>
{title} {firstName} {lastName}
</b>
<br />
{street} {aptSuite ? `#${aptSuite}` : null}
<br />
{city}, {stateName} {zipcode}
<br />
USA
</p>
</address>
<h1>
Re: {title} {firstName} {lastName} university application
</h1>
<p>
Dear {firstName},
<br />
<br />
Thank you for your recent application to join us at the University of
Awesome's science faculty to study as part of your
<abbr title="A doctorate in any discipline except medicine, or sometimes theology.">
{" "}
PhD{" "}
</abbr>
next year. I will answer your questions one by one, in the following
sections.
</p>
<h2>Starting dates</h2>
<p>
We are happy to accommodate you starting your study with us at any time,
however it would suit us better if you could start at the beginning of a
semester; the start dates for each one are as follows:
</p>
<ul>
<li>
First semester: <time dateTime="2016-09-09">9 September 2016</time>
</li>
<li>
Second semester: <time dateTime="2016-01-15">15 January 2017</time>
</li>
<li>
Third semester: <time dateTime="2017-05-02">2 May 2017</time>
</li>
</ul>
<p>
Please let me know if this is ok, and if so which start date you would
prefer.
<br />
<br />
You can find more information about{" "}
<a href="http://example.com." target="_blank" rel="noreferrer">
important university dates
</a>
on our website.
</p>
<h2>Subjects of study</h2>
<p>
At the Awesome Science Faculty, we have a pretty open-minded research
facility — as long as the subjects fall somewhere in the realm of
science and technology. You seem like an intelligent, dedicated
researcher, and <strong>just </strong>
the kind of person we'd like to have on our team. Saying that, of the
ideas you submitted we were most intrigued by are as follows, in order
of priority:
</p>
<ul>
<li>
Turning H<sub>2</sub>0 into wine, and the health benefits of
Resveratrol (C<sub>14</sub>H<sub>12</sub>O<sub>3</sub>.)
</li>
<li>
Measuring the effect on performance of funk bassplayers at
temperatures exceeding 30°C (86°F), when the audience size
exponentially increases (effect of 3 × 10<sup>3</sup>
increasing to 3 × 10<sup>4</sup>.)
</li>
<li>
<abbr title="HyperText Markup Language">HTML</abbr> and{" "}
<abbr title="Cascading Style Sheets">CSS </abbr>
constructs for representing musical scores.
</li>
</ul>
<p>
So please can you provide more information on each of these subjects,
including how long you'd expect the research to take, required staff and
other resources, and anything else you think we'd need to know? Thanks.
</p>
<h2>Exotic dance moves</h2>
<p>
Yes, you are right! As part of my post-doctorate work, I <em>did</em>{" "}
study exotic tribal dances. To answer your question, my favourite dances
are as follows, with definitions:
</p>
<dl>
<dt>Polynesian chicken dance</dt>
<dd>
A little known but very influential dance dating back as far as 300
<abbr title="Before Christ">BC</abbr>, a whole village would dance
around in a circle like chickens, to encourage their livestock to be
"fruitful".
</dd>
<dt>Icelandic brownian shuffle</dt>
<dd>
Before the Icelanders developed fire as a means of getting warm, they
used to practice this dance, which involved huddling close together in
a circle on the floor, and shuffling their bodies around in
imperceptibly tiny, very rapid movements. One of my fellow students
used to say that he thought this dance inspired modern styles such as
Twerking.
</dd>
<dt>Arctic robot dance</dt>
<dd>
An interesting example of historic misinformation, English explorers
in the 1960s believed to have discovered a new dance style
characterized by "robotic", stilted movements, being practiced by
inhabitants of Northern Alaska and Canada. Later on however it was
discovered that they were just moving like this because they were
really cold.
</dd>
</dl>
<p>
For more of my research, see my{" "}
<a href="http://example.com." target="_blank" rel="noreferrer">
exotic dance research page
</a>
.
<br />
<br />
Yours sincerely,
<br />
<br />
Dr Eleanor Gaye
<br />
<br />
University of Awesome motto: <q>Be awesome to each other.</q> --
<cite>
The memoirs of Bill S Preston,
<abbr title="An abbreviation for esquire."> Esq</abbr>
</cite>
</p>
<div className="return-button">
<h3>Made a mistake?</h3>
<Button onClick={handleClick}>Click to return to form</Button>
</div>
</Fragment>
);
}
export default Display;
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T16:01:16.857",
"Id": "256727",
"Score": "3",
"Tags": [
"beginner",
"functional-programming",
"react.js"
],
"Title": "Dynamic text rendering from form data, Express proxy server API requests, and validation in React"
}
|
256727
|
<p>I've found some resources about PHP performance optimization here and there but I don't know how to start. I send 130k CSV rows in approximatively 7min. My script read CSV file and send <code>$batch_size</code> row per query, while doing some string operations such as changing date to the correct format or replacing <code>,</code> with <code>.</code> for the floats.</p>
<pre><code>$db = new PDO("mysql:host=$db_host;port=$db_port;charset=utf8","$db_username", "$db_password");
$csv_path = "path/to/myfile.csv";
$table = "TableName";
//Start of the query
$query="USE ".$db_name.";";
$FilePath = $csv_path;
$is_not_title_row=FALSE;//Usefull not to take the first row
$row_batch_count=0;//Counter for batches
//1 data = 1 part of the row
$number_of_data=0;
$data='';
// Open file in read-only mode
$handle = fopen($FilePath, "r");
while (($data = fgetcsv($handle, 2000, ";" , chr(8))) !== FALSE) {
$number_of_data = count($data)-1;
// Generate MySQL query
if($is_not_title_row)
{
$query .= "INSERT INTO ".$table." VALUES (";
//We read all the data of one row
for ($c=0; $c <= $number_of_data; $c++) {
$data[$c]=utf8_decode($data[$c]);
$data[$c]=str_replace('/', '-', $data[$c]);
$data[$c]=str_replace(',', '.', $data[$c]);
//If it's a date, we convert it to the right date format
if (DateTime::createFromFormat('d-m-Y', $data[$c]) !== FALSE) {
$data[$c] = date("Y-m-d", strtotime($data[$c]));
$query .= "'" . mres($data[$c]) ."',";
//If there is nothing, we send NULL value
else if(mres($data[$c])==NULL){
$query .= "NULL,";
}
else{
$query .= "'" . mres($data[$c]) ."',";
}
//If this is the end of the INSERT INTO we remove the comma
if($c==$number_of_data)
{
$query=substr_replace($query ,"", -1);
}
}
$query .= ");";
$row_batch_count++;
//If we are at the end of the batch, we send the query then start the creation of another
if($row_batch_count==$batch_size)
{
echo "There is ".$row_batch_count." row sent<br/>";
echo "<br/><br/>";
$query_to_execute = $db->prepare($query);
$query_to_execute->execute();
$query="USE ".$db_name.";";
$row_batch_count=0;
}
}
//Usefull to remove the first row
if(!$is_not_title_row){
$is_not_title_row=TRUE;
}
}
//Without more batches, we execute the query(=we are at the end of the file)
$query_to_execute = $db->prepare($query);
$query_to_execute->execute();
$query_to_execute = NULL;
</code></pre>
<p><strong>Solution</strong></p>
<p>Instead of doing one <code>INSERT INTO</code> for each row, I've simply inserted multiple row in a single INSERT INTO.
The output query looks like that :</p>
<pre><code>INSERT INTO Table VALUES (x,x,x),(x,x,x),(x,x,x),(...
</code></pre>
<p>The csv insertion is now 30 times faster </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T16:50:17.773",
"Id": "506927",
"Score": "1",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/256728/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T18:09:41.040",
"Id": "506933",
"Score": "1",
"body": "Please provide more complete code - e.g. complete function/method/class. It would be useful to know more about variables like `$handle`, `$table`, etc. [\"_there are significant pieces of the core functionality missing, and we need you to fill in the details. Excerpts of large projects are fine, but if you have omitted too much, then reviewers are left imagining how your program works._\"](https://codereview.meta.stackexchange.com/a/3652/120114)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T18:43:11.087",
"Id": "506934",
"Score": "1",
"body": "I'm also missing a bit of input data. We are asked to understand and improve code for which we don't have the most important bits: input & output. I can certainly give some pointers to improve this code, but it would be nice to also provide a bit of code that actually works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:05:32.263",
"Id": "506968",
"Score": "0",
"body": "I've added the input, which is the path to the CSV file. It seemed to me that the query execution was enough for the output, or should I add something to make it clearer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:32:17.450",
"Id": "506970",
"Score": "0",
"body": "By \"input\" I meant some real data. Without real data there's, for instance, no way for us to understand why you choose `chr(8)` in `fgetcsv()`. That looks weird to me. It's also difficult to understand why you process the rows, the way you do, without any idea of what the data looks like, and what it has to become."
}
] |
[
{
"body": "<p>What I found to greatly improves the speed of insert queries, is inserting multiple rows using a single query. You seems to have found the same solution, but it is implemented in a very roundabout way.</p>\n<p>Your code could also benefit a lot from using functions. So, let's start with the most important one: How to insert multiple rows. It could look something like this:</p>\n<pre><code>function insertRows($db, $table, $rows)\n{\n $values = '(' . implode(',', array_fill(0, count($rows[0]), '?')) . ')';\n $query = 'INSERT INTO '.$table . ' VALUES ' .\n implode(',', array_fill(0, count($rows), $values));\n $statement = $db->prepare($query);\n $index = 1;\n foreach($rows as $row) {\n foreach($row as $value) {\n $statement->bindValue($index++, $value);\n } \n }\n $statement->execute();\n}\n</code></pre>\n<p>This bit of code has only one function: Insert a certain number of rows into the database as quickly as possible. This function doesn't read data, change it in any way, but it does use parameter binding for extra security. That's probably not needed in this case, but it also doesn't hurt. No more problems with quotes.</p>\n<p>You can insert quite a few rows using this function, somewhere around 50 to 150 rows, depending on what your input looks like. Above a certain number the speed simply won't increase anymore, so there's no point in going to extremely large number of rows.</p>\n<p>I would create another function for changing the row data from the format you received to the format you want to insert:</p>\n<pre><code>function reformatRow($row)\n{\n // <...put your code here...>\n return $row;\n}\n</code></pre>\n<p>We can now also implement a function that does the above for multiple rows:</p>\n<pre><code>function reformatRows($rows)\n{\n foreach ($rows as $key => $row) {\n $rows[$key] = reformatRow($row);\n }\n return $rows;\n}\n</code></pre>\n<p>Functions don't have to be complex to be useful. I actually will not use this function, but I thought it was nice to show it.</p>\n<p>All that's now left to do is to read the input, so let's do that. I will use parts of your code:</p>\n<pre><code>const MAX_ROWS = 100;\n\nfgetcsv($handle, 2000, ";", chr(8)); // read header and dump it\n\n$rows = [];\nwhile (($row = fgetcsv($handle, 2000, ";", chr(8))) !== FALSE) {\n $rows[] = reformatRow($row);\n if (count($rows) >= MAX_ROWS) {\n insertRows($db, $table[$i], $rows);\n $rows = [];\n }\n}\n\nif (count($rows) > 0) {\n insertRows($db, $table[$i], $rows);\n}\n</code></pre>\n<p><strong>I haven't fully tested all this code.</strong></p>\n<p>I also don't think this code will be any quicker than yours. There's also no way for me to test any optimization, since I don't have your data, so I'm afraid I can't help you there. Reading data into a database just takes time. It is possible that <code>fgetcsv()</code> is not the optimal way to read a big CSV file, but I haven't tested that.</p>\n<p>What I have tried to make clear is that by splitting your code into functional parts it become easier to understand, and more reusable. The <code>insertRows()</code> is, for instance, is, partly, reused from my own code. Once you've written a function like that, and it works, you can reuse it everywhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T19:54:47.083",
"Id": "506937",
"Score": "0",
"body": "Unless you specifically don't want to explain it, you could suggest using the row index instead of starting with `$index = 1` so the foreach would be `foreach($rows as $index => $row) {` and then instead of incrementing it after using it, use `$index + 1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:30:18.820",
"Id": "506969",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I edited my question. I didn't quite get what you were trying to say, but I hope this is an improvement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T19:27:05.323",
"Id": "256733",
"ParentId": "256728",
"Score": "2"
}
},
{
"body": "<h3>Initial thoughts</h3>\n<p>I agree with the ideas in the answer by KIKOSoftware (which is deleted - hopefully only termporarily). Creating functions can not only clean up the code but also allow for better testing. Using bound parameters is always a great idea. And using arrays to hold the strings and imploding them will eliminate the need to remove trailing commas.</p>\n<h3>Standards for readability</h3>\n<p>Consider adhering to <a href=\"https://www.php-fig.org/psr/\" rel=\"nofollow noreferrer\">PHP Standards Recommendations</a> - especially <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>. The biggest concern I have for readability with this code is whitespace - e.g. around operators like <code>=</code>:</p>\n<blockquote>\n<h3><a href=\"https://www.php-fig.org/psr/psr-12/#62-binary-operators\" rel=\"nofollow noreferrer\">6.2. Binary operators</a></h3>\n<p>All binary arithmetic, comparison, assignment, bitwise, logical,\nstring, and type operators MUST be preceded and followed by at least\none space:</p>\n<pre><code>if ($a === $b) {\n $foo = $bar ?? $a ?? $b; } elseif ($a > $b) {\n $foo = $a + $b * $c; }\n</code></pre>\n<p><sup><a href=\"https://www.php-fig.org/psr/psr-12/#62-binary-operators\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<h3>replacing characters</h3>\n<p>Instead of calling <code>str_replace()</code> multiple times - e.g.</p>\n<blockquote>\n<pre><code>$data[$c]=str_replace('/', '-', $data[$c]);\n$data[$c]=str_replace(',', '.', $data[$c]);\n</code></pre>\n</blockquote>\n<p>Consider passing arrays for the <code>search</code> and <code>replace</code> arguments:</p>\n<pre><code>$data[$c]=str_replace(['/', ','], ['-', '.'], $data[$c]);\n</code></pre>\n<p>You might also explore using <a href=\"https://php.net/strtr\" rel=\"nofollow noreferrer\"><code>strtr()</code></a> instead of <code>str_replace()</code> to see if it performs better - in some cases it does, others it doesn't.<sup><a href=\"https://www.reddit.com/r/PHP/comments/3qk44w/performance_of_strtr_vs_str_replace/\" rel=\"nofollow noreferrer\">2</a></sup>.</p>\n<h3>Comparison operators</h3>\n<p>There are two comparisons that use loose equality comparisons:</p>\n<blockquote>\n<pre><code> else if(mres($data[$c])==NULL){\n</code></pre>\n</blockquote>\n<p>and</p>\n<blockquote>\n<pre><code>//If this is the end of the INSERT INTO we remove the comma\nif($c==$number_of_data)\n</code></pre>\n</blockquote>\n<p>There are other places where <a href=\"https://www.php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">strict equality comparisons</a> are used - i.e. <code>===</code> and <code>!==</code> and it is advisable to always use those unless you are sure you want to allow types to be coerced <sup><a href=\"https://softwareengineering.stackexchange.com/questions/126585/what-are-some-examples-of-wartiness-making-a-programming-language-more-useful\">3</a></sup>.</p>\n<h3>bonus - an external webpage</h3>\n<p>I happened to search the web for "CSV to SQL" and found <a href=\"https://www.convertcsv.com/csv-to-sql.htm\" rel=\"nofollow noreferrer\">this tool</a> that could replace the script...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T19:45:13.610",
"Id": "256735",
"ParentId": "256728",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256733",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T16:05:35.923",
"Id": "256728",
"Score": "4",
"Tags": [
"performance",
"php",
"csv"
],
"Title": "Read a csv file and insert into DB table"
}
|
256728
|
<p>I am new to Julia and have only written in python before which is most likely also reflected by my coding style.
Unfortunately, my applications require very high numerical precision which is why I am resorting to <code>BigFloat</code> and <code>BigInt</code> in Julia. For some reason, this leads to a major increase in allocations besides the obvious increase in computational time.
I am wondering where my code can be improved.</p>
<p>I have attached the current version of my code below with example parameters that allow for execution under 1s.</p>
<pre><code>using Combinatorics
function gamma_mpnq(m::Int, p::Int, n::Int, q::Int)::BigFloat
return sqrt(factorial(big(m)) * factorial(big(n))) / (big(2)^(p + q) * factorial(big(m - 2 * p)) * factorial(big(n - 2 * q)) * factorial(big(q)) * factorial(big(p)))
end
function general_binomial(alpha::Float64, k::Int)
"""
Implementation of the generalized binomial.
"""
_prod = BigFloat(1.0)
for kk in 1:k
_prod *= (alpha - kk + 1.)
end
return _prod / factorial(big(k))
end
function construct_M(nmax::Int, mmax::Int)::Array
"""
Construct the matrix M containing all moments <C^n * C*^m> up to nmax and mmax.
"""
_M = zeros(BigFloat, nmax, mmax)
for mm in 1:nmax
for nn in 1:mmax
if nn == 1
_M[nn, mm] = 1. / doublefactorial(BigInt(2*mm - 1))
elseif mm == 1
_M[nn, mm] = 1. / doublefactorial(BigInt(2*nn - 1))
else
_M[nn, mm] = (((nn-1) * _M[nn-1, mm] + (mm-1) * _M[nn, mm-1]) / (2. * (nn-mm)^2 + (nn-1) + (mm-1)))
end
end
end
return _M
end
function maclaurin_exp(n::Int, m::Int, p::Int, q::Int, M::Array, cutoff::Int)::BigFloat
"""
Calculate the expectation value of ((1+C)/(1+C*))^((n-m)/2) * C^p * C*^q
using the Maclaurin expansion and the matrix containing all moments M.
"""
inner::BigFloat = 0.0
@views for nn in 1:cutoff
for mm in 1:cutoff
inner += (general_binomial((n-m)/2., mm-1) * general_binomial((m-n)/2., nn-1) * M[q+nn, p+mm])
end
end
return inner
end
function Hmn(m::Int, n::Int, M::Array, cutoff::Int)::Float64
"""
Calculates a single entry of the Hmn matrix.
"""
ppmax = div(m, 2)
qqmax = div(n, 2)
outer = 0.0
for pp in 0:ppmax
for qq in 0:qqmax
outer += (gamma_mpnq(m, pp, n, qq) * maclaurin_exp(n, m, pp, qq, M, cutoff))
# println(pp, " ", qq, " ", outer)
end
end
return outer
end
dim = 128
cutoff = 64
M = construct_M(dim+cutoff, dim+cutoff)
@btime Hmn(12, 2, M, cutoff)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The following is a workaround for your speed and memory issue rather than a general review of your code.</p>\n<p>Profiling is useful for investigating the source of performance issues, and Julia's standard library includes a profiling module (<a href=\"https://docs.julialang.org/en/v1/manual/profile/\" rel=\"nofollow noreferrer\">guide</a>, <a href=\"https://docs.julialang.org/en/v1/stdlib/Profile/\" rel=\"nofollow noreferrer\">doc</a>).</p>\n<p>Here's a basic use of it: (I'm using <a href=\"https://docs.julialang.org/en/v1/base/base/#Base.@eval\" rel=\"nofollow noreferrer\"><code>@eval</code></a> just to interpolate in the construction of <code>M</code>)</p>\n<pre><code>using Profile\n@eval @profile Hmn(12, 2, $(construct_M(192, 192)), 64)\n</code></pre>\n<pre><code>julia> Profile.print()\nOverhead ╎ [+additional indent] Count File:Line; Function\n=========================================================\n ╎963 @Base/task.jl:356; (::IJulia.var"#15#18")()\n...\n ╎ ╎ 963 In[1]:61; Hmn(::Int64, ::Int64, ::Arr...\n ╎ ╎ 1 In[1]:4; gamma_mpnq(::Int64, ::Int6...\n...\n 18╎ ╎ 962 In[1]:46; maclaurin_exp(::Int64, ::I...\n 1╎ ╎ 1 In[1]:0; general_binomial(::Float6...\n ╎ ╎ 14 In[1]:11; general_binomial(::Float6...\n...\n ╎ ╎ 786 In[1]:13; general_binomial(::Float6...\n...\n ╎ ╎ 97 In[1]:15; general_binomial(::Float6...\n...\n</code></pre>\n<p>I've removed all the lines that point to code in external files. Of the 963 samples collected in <code>Hmn</code>, more than 800 were spent within calculations of <code>general_binomial</code>.</p>\n<p>Looking at how <code>general_binomial(alpha, k)</code> is used, I noticed that it is called repeated with only a small number of different <code>alpha</code> and <code>k</code> values. Since it is a <a href=\"https://en.wikipedia.org/wiki/Pure_function\" rel=\"nofollow noreferrer\">pure function</a> (i.e., it does not interact with external state), basic <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoization</a> can be applied to speed it up.</p>\n<p>We can use a <code>Dict</code> to cache the results (make sure it is defined with concrete key and value types). To allow for easy benchmarking, we'll define it as a global constant; for performance, it is important that global variables are constant (or otherwise type-constrained in code using it) so that type inference works (also, the compiled code can avoid an extra lookup).</p>\n<p>Here's a simple way to do this. Rename <code>general_binomial</code> to <code>_general_binomial</code>, then create the <code>Dict</code> and redefine <code>general_binomial</code> to cache the results. Like so:</p>\n<pre><code>@isdefined(general_binomial) && Base.delete_method.(methods(general_binomial))\n\nconst GENERAL_BINOMIAL_CACHE = Dict{Tuple{Float64, Int}, BigFloat}()\n\nfunction general_binomial(alpha, k)\n return get!(GENERAL_BINOMIAL_CACHE, (alpha, k)) do\n _general_binomial(alpha, k)\n end\nend\n</code></pre>\n<p>Benchmarking shows a substantial improvement in speed and memory use using the parameters you provided.</p>\n<p>Before:</p>\n<pre><code>julia> @benchmark Hmn(12, 2, $(construct_M(192, 192)), 64)\nBenchmarkTools.Trial: \n memory estimate: 435.29 MiB\n allocs estimate: 8543119\n --------------\n minimum time: 787.497 ms (5.88% GC)\n median time: 791.734 ms (5.83% GC)\n mean time: 792.690 ms (5.76% GC)\n maximum time: 802.070 ms (5.17% GC)\n --------------\n samples: 7\n evals/sample: 1\n</code></pre>\n<p>After: (the cache is cleared before each sample by <code>empty!(GENERAL_BINOMIAL_CACHE)</code>)</p>\n<pre><code>julia> @benchmark Hmn(12, 2, $(construct_M(192, 192)), 64) evals=1 setup=empty!(GENERAL_BINOMIAL_CACHE)\nBenchmarkTools.Trial: \n memory estimate: 12.74 MiB\n allocs estimate: 239309\n --------------\n minimum time: 10.684 ms (0.00% GC)\n median time: 12.844 ms (0.00% GC)\n mean time: 14.181 ms (7.58% GC)\n maximum time: 32.631 ms (14.03% GC)\n --------------\n samples: 353\n evals/sample: 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T05:13:33.617",
"Id": "257429",
"ParentId": "256729",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257429",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T16:21:51.867",
"Id": "256729",
"Score": "2",
"Tags": [
"performance",
"julia"
],
"Title": "Reducing allocations in arbitrary precision calculations with Julia"
}
|
256729
|
<h2>Context</h2>
<p>I may have accidentally gotten a little sidetracked during homeschooling, and wrote a JSON4 parser in Typescript during the down-time. This project started as an idea that I got while discussing something actually school-related and over the past few days grew into this.</p>
<p>I have no formal education on how compilers/parser/lexers work, except for the few hours I wasted on the internet reading up on the topic. This makes me especially curious if this implementation is somewhat correct - in the grand scheme of things.</p>
<p>I have dedicated myself to make it as spec-compliant as I deemed reasonable. I used <a href="https://www.json.org/json-en.html" rel="nofollow noreferrer">this</a> specification as a reference.</p>
<p>In the GIT repository I pulled in a "JSON test suite", which I used to run tests against the code. This helped me fix several bugs, but I think there are still lots of edge-cases that are not handled.</p>
<p>To help anyone kind enough to review my code, I've <a href="https://github.com/PatrickHollweck/Creative/tree/master/projects/myjson" rel="nofollow noreferrer">published this thing in my "pet project" github</a> repo, with everything already set up, so you just have to clone that and install using yarn.</p>
<h2>Questions</h2>
<p>I am mainly interested in the technical implementation of the code. I tried to focus on readability, how did that work out?</p>
<ul>
<li>How readable/understandable is the code?</li>
<li>How is the design/architecture of the code?</li>
<li>Are there any best-practices or techniques I could implement?</li>
</ul>
<p>I know this is a lot of code, but there is <strong>no</strong> need to review all of it!</p>
<p>This thing works as is, the only thing that is still a little wanky is the string escaping.</p>
<h2>Code</h2>
<p><code>src/Json.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { JsonValue } from './lib/types';
import { parse } from './lib/parser';
import { tokenize } from "./lib/lexer";
import { convertNodeToJsValue } from './lib/generator';
export class Json {
static parse(source: string): JsonValue {
const tokens = tokenize(source);
const ast = parse(tokens);
const jsValue = convertNodeToJsValue(ast);
return jsValue;
}
}
</code></pre>
<p><code>src/lib/util/JsonError.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { Token } from "../Token";
function serializeTokens(tokens: Token[]) {
return tokens.map((token) => {
if (token.isString) {
return `"${token.value}"`;
}
return token.value;
}).join("");
}
function formatMessage(message: string, tokens: Token[]): string {
const source = serializeTokens(tokens);
return `${message}\n\nSource at the point of the Error:\n${source}\n^`;
}
export class JsonError extends Error {
constructor(message: string, tokens: Token[]) {
super(formatMessage(message, tokens));
}
}
</code></pre>
<p><code>src/lib/types.ts</code></p>
<pre class="lang-js prettyprint-override"><code>export type JsonScalar = boolean | number | string | null;
export type JsonObject = { [key: string]: JsonValue };
export type JsonArray = JsonValue[];
export type JsonValue = JsonObject | JsonArray | JsonScalar;
</code></pre>
<p><code>src/lib/Token.ts</code></p>
<pre class="lang-js prettyprint-override"><code>type TokenType = "punctuation" | "boolean" | "string" | "number" | "null";
export class Token {
public readonly type: TokenType;
public readonly value: string;
public constructor(type: TokenType, value: string) {
this.type = type;
this.value = value;
}
public get isString(): boolean {
return this.type === "string";
}
public get isNumber(): boolean {
return this.type === "number";
}
public get isBoolean(): boolean {
return this.type === "boolean";
}
public get isNull(): boolean {
return this.type === "null";
}
public get isScalar(): boolean {
return this.isNull || this.isString || this.isNumber || this.isBoolean;
}
public get isPunctuation(): boolean {
return this.type === "punctuation";
}
public get isArrayOpen(): boolean {
return isPredefinedPunctuation("arrayOpen", this);
}
public get isArrayClose(): boolean {
return isPredefinedPunctuation("arrayClose", this);
}
public get isObjectOpen(): boolean {
return isPredefinedPunctuation("objectOpen", this);
}
public get isObjectClose(): boolean {
return isPredefinedPunctuation("objectClose", this);
}
public get isComma(): boolean {
return isPredefinedPunctuation("comma", this);
}
public get isColon(): boolean {
return isPredefinedPunctuation("colon", this);
}
}
export const PUNCTUATION_TOKENS = {
comma: new Token("punctuation", ","),
colon: new Token("punctuation", ":"),
arrayOpen: new Token("punctuation", "["),
arrayClose: new Token("punctuation", "]"),
objectOpen: new Token("punctuation", "{"),
objectClose: new Token("punctuation", "}"),
};
function isPredefinedPunctuation(
key: keyof typeof PUNCTUATION_TOKENS,
token: Token,
): boolean {
return token.isPunctuation && PUNCTUATION_TOKENS[key].value === token.value;
}
</code></pre>
<p><code>src/lib/lexer.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { PUNCTUATION_TOKENS, Token } from "./Token";
type TokenizerResult =
| { matched: false; cursor?: number }
| { matched: true; token: Token; cursor: number };
type Tokenizer = (source: string, cursor: number) => TokenizerResult;
export function tokenize(source: string): Token[] {
let cursor = 0;
const tokens: Token[] = [];
const tokenizers: Tokenizer[] = [
tokenizeWhitespace,
tokenizePunctuation,
tokenizeNull,
tokenizeNumber,
tokenizeString,
tokenizeBoolean,
];
while (cursor < source.length) {
let didMatch = false;
for (const tokenizer of tokenizers) {
const result = tokenizer(source, cursor);
if (result.matched) {
didMatch = true;
cursor = result.cursor;
tokens.push(result.token);
break;
}
// Even if a tokenizer did not match, it is free to move the cursor
// this is usefull for example when parsing white-space, which does not result in a token
if (!result.matched && typeof result.cursor === "number") {
didMatch = true;
cursor = result.cursor;
break;
}
}
if (!didMatch) {
throw new Error(`Could not lex token: "${source.substr(cursor)}"`);
}
}
return tokens;
}
function tokenizeWhitespace(source: string, cursor: number): TokenizerResult {
const result = matchRegex(source, cursor, /^(?!\f)\s/);
if (result.matched) {
return {
matched: false,
cursor: result.cursor,
};
}
return {
matched: false,
};
}
function tokenizeNull(source: string, cursor: number): TokenizerResult {
return matchStaticToken(source, cursor, new Token("null", "null"));
}
function tokenizeBoolean(source: string, cursor: number): TokenizerResult {
const booleanTokens = [new Token("boolean", "true"), new Token("boolean", "false")];
for (const token of booleanTokens) {
const result = matchStaticToken(source, cursor, token);
if (result.matched) {
return result;
}
}
return {
matched: false,
};
}
function tokenizeNumber(source: string, cursor: number): TokenizerResult {
const result = matchRegex(
source,
cursor,
/^(?:(?!0\d)(?!-0\d)-?(?:0(?:\.\d+)|\d+(?:\d+)?(?:\.\d+)?)(?:(?:e|E)(?:-?|\+?)\d+)?)/,
);
if (result.matched) {
return {
matched: true,
cursor: result.cursor,
token: new Token("number", result.value),
};
}
return {
matched: false,
};
}
function tokenizeString(source: string, cursor: number): TokenizerResult {
const result = matchRegex(source, cursor, /^"(?:[^\n"\\]|\\.)*"/);
if (result.matched) {
let value = result.value;
if (
// Check if we even have a value, dont run the following check if we dont
value != null &&
value.length > 0 &&
// Check if the first or last character is a quotation mark, in which case we would need to remove them
(value[0] === '"' || value[value.length - 1] === '"') &&
// Ensure we do not remove quotation marks on a string with no content ("")
!(value.length === 2 && value[0] === '"' && value[value.length - 1] === '"')
) {
value = value.replace(/^"/, "").replace(/"$/, "");
}
return {
matched: true,
cursor: result.cursor,
token: new Token("string", value),
};
}
return {
matched: false,
};
}
function tokenizePunctuation(source: string, cursor: number): TokenizerResult {
for (const token of Object.values(PUNCTUATION_TOKENS)) {
const matchResult = matchLiteral(source, cursor, token.value);
if (matchResult.matched) {
return {
matched: true,
token,
cursor: matchResult.cursor,
};
}
}
return {
matched: false,
};
}
/*
* Helper Functions
*/
function matchRegex(
source: string,
cursor: number,
regex: RegExp,
): { matched: false } | { matched: true; value: string; cursor: number } {
const currentSource = source.substr(cursor);
const match = currentSource.match(regex);
if (!match || match.length === 0) {
return {
matched: false,
};
}
if (match.length === 1) {
const value = match[0];
return {
value,
matched: true,
cursor: cursor + value.toString().length,
};
}
// We should not get here, regex passed in here should be designed
// as such that there is only one Group match. (Use non-capture) groups.
// Therefore it is most likely a programmer's error if we get here.
throw new Error("Invalid regex matches");
}
function matchLiteral(
source: string,
cursor: number,
token: string,
): { matched: false } | { matched: true; cursor: number } {
if (source.substr(cursor, token.length) === token) {
return {
matched: true,
cursor: cursor + token.length,
};
}
return {
matched: false,
};
}
function matchStaticToken(source: string, cursor: number, token: Token): TokenizerResult {
const lookahead = matchLiteral(source, cursor, token.value);
if (lookahead.matched) {
return {
matched: true,
cursor: lookahead.cursor,
token,
};
}
return {
matched: false,
};
}
</code></pre>
<p><code>src/lib/parser.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { Token } from "./Token";
import { Node, ScalarNode, ObjectNode, ArrayNode } from "./nodes";
import { JsonError } from "./util/JsonError";
export function parse(tokens: Token[]): Node {
const rootNode = parseSingle(tokens);
if (tokens.length > 0) {
throw new JsonError("Unexpected tokens at the end of source", tokens);
}
return rootNode;
}
export function parseSingle(tokens: Token[]): Node {
if (tokens.length === 0) {
throw new JsonError("Unexpected end of source!", tokens);
}
const initialToken = tokens[0];
if (initialToken.isScalar) {
return parseScalar(tokens);
}
if (initialToken.isObjectOpen) {
return parseObject(tokens);
}
if (initialToken.isArrayOpen) {
return parseArray(tokens);
}
throw new JsonError(
`Could not parse token of type '${initialToken.type}' at this location`,
tokens,
);
}
function parseScalar(tokens: Token[]): ScalarNode {
const { type, value } = tokens[0];
if (type === "string") {
validateString(value, tokens);
}
const scalar = new ScalarNode(type, value);
tokens.shift();
return scalar;
}
function parseArray(tokens: Token[]): ArrayNode {
const arrayNode = new ArrayNode();
// Removes the opening "[" token.
tokens.shift();
const firstToken = tokens[0];
// Empty Array, exit early.
if (firstToken && firstToken.isArrayClose) {
tokens.shift();
return arrayNode;
}
while (tokens.length > 0) {
arrayNode.addChild(parseSingle(tokens));
// The next token is either a comma or it is the closing bracket.
// In both cases the token needs to be removed. We just need to keep it around
// to check if it is a comma.
const nextToken = tokens.shift();
// If the next token "after" the value is not a comma, we do not expect
// any more values. Technically we dont even need the comma, but we are stick
// to the standard strictly.
if (nextToken && nextToken.isComma) {
continue;
}
if (nextToken && nextToken.isArrayClose) {
return arrayNode;
}
throw new JsonError("Additional comma at end of array entries", tokens);
}
throw new JsonError(
"Unexpected token at the end of an array entry, most likely a missing comma",
tokens,
);
}
function parseObject(tokens: Token[]) {
const objectNode = new ObjectNode();
tokens.shift();
const firstToken = tokens[0];
// Empty Object, exit early
if (firstToken && firstToken.isObjectClose) {
tokens.shift();
return objectNode;
}
while (tokens.length > 0) {
objectNode.addEntry(parseObjectEntry(tokens));
const nextToken = tokens.shift();
// If there is a comma, the json specifies that there *must*
// be another entry on the object
if (nextToken && nextToken.isComma) {
continue;
}
// If the next token is not a comma, there are no more entries
// which means that the next token *must* be a "}
if (nextToken && nextToken.isObjectClose) {
return objectNode;
}
throw new JsonError(
"Unexpected token at the end of an object entry, most likely a missing comma",
tokens,
);
}
throw new JsonError("Unexpected end of source, while parsing object", tokens);
}
function parseObjectEntry(tokens: Token[]) {
const [keyToken, seperatorToken] = tokens;
if (!keyToken || !keyToken.isString) {
throw new JsonError(
`Unexpected token of type "${keyToken.type}" ("${keyToken.value}") on object key`,
tokens,
);
}
if (!seperatorToken || !seperatorToken.isColon) {
throw new JsonError(
`Unexpected token of type "${seperatorToken.type}" ("${seperatorToken.value}") as object key-value seperator`,
tokens,
);
}
tokens.splice(0, 2);
return {
key: keyToken.value,
value: parseSingle(tokens),
};
}
function validateString(value: string, tokens: Token[]) {
const chars = value.split("");
for (let index = 0; index < chars.length; index++) {
const element = chars[index];
if (
element === "\t" ||
element === "\n" ||
element === "\b" ||
element === "\f" ||
element === "\r"
) {
throw new JsonError(
"Invalid characters in string. Control characters must be escaped!",
tokens,
);
}
if (element !== "\\") {
continue;
}
if (chars.length <= index + 1) {
throw new JsonError("Unexpected end of escape-sequence", tokens);
}
const escapeCharacter = chars[index + 1];
if (escapeCharacter === "\\" || escapeCharacter === "/") {
index++;
continue;
}
if (["b", "f", "n", "r", "t", '"'].includes(escapeCharacter)) {
continue;
}
if (escapeCharacter === "u") {
if (chars.length >= index + 6) {
const unicodeEscapeSequence = chars.slice(index + 2, index + 6).join("");
if (/^[0-9A-Fa-f]{4}$/.test(unicodeEscapeSequence)) {
index += 5;
continue;
} else {
throw new JsonError("Invalid unicode escape sequence", tokens);
}
} else {
throw new JsonError("Unexpected end of escape-sequence", tokens);
}
}
throw new JsonError("Unrecognized escape sequence", tokens);
}
}
</code></pre>
<p><code>src/lib/generator.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { JsonArray, JsonObject, JsonValue } from "./types";
import { Node, ObjectNode, ArrayNode, ScalarNode } from "./nodes";
export function convertNodeToJsValue(root: Node): JsonValue {
if (root instanceof ScalarNode) {
return scalarToJsValue(root);
}
if (root instanceof ObjectNode) {
const result: JsonObject = {};
for (const [key, value] of root.entries) {
result[key] = convertNodeToJsValue(value);
}
return result;
}
if (root instanceof ArrayNode) {
const result: JsonArray = [];
for (const value of root.children) {
result.push(convertNodeToJsValue(value));
}
return result;
}
throw new Error(
`Unknown node type "${root.constructor.name}" found while deserializing tree`,
);
}
function scalarToJsValue(node: ScalarNode) {
const { type, value } = node;
switch (type) {
case "boolean":
if (value === "true") {
return true;
}
if (value === "false") {
return false;
}
throw new Error(`Invalid boolean value "${value}" found.`);
case "null":
return null;
case "number":
return Number(value as string);
case "string":
return value;
default:
throw new Error(`Unknown node of type "${type}" cannot be converted to a js value`);
}
}
</code></pre>
<p><code>src/lib/nodes/index.ts</code></p>
<pre class="lang-js prettyprint-override"><code>export * from './Node';
export * from './ArrayNode';
export * from './ScalarNode';
export * from './ObjectNode';
</code></pre>
<p><code>src/lib/nodes/Node.ts</code></p>
<pre class="lang-js prettyprint-override"><code>/**
* Simple node base class.
*
* This class mainly exists to make typing a little easier.
*/
export class Node {}
</code></pre>
<p><code>src/lib/nodes/ScalarNode.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { Node } from './Node';
export class ScalarNode extends Node {
public readonly type: string;
public readonly value: string;
public constructor(type: string, value: string) {
super();
this.type = type;
this.value = value;
}
}
</code></pre>
<p><code>src/lib/nodes/ObjectNode.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { Node } from './Node';
export class ObjectNode extends Node {
public readonly entries: Map<string, Node>;
public constructor() {
super();
this.entries = new Map();
}
public addEntry(entry: { key: string, value: Node }): void {
this.entries.set(entry.key, entry.value);
}
}
</code></pre>
<p><code>src/lib/nodes/ArrayNode.ts</code></p>
<pre class="lang-js prettyprint-override"><code>import { Node } from './Node';
export class ArrayNode extends Node {
public readonly children: Node[];
public constructor() {
super();
this.children = [];
}
public addChild(value: Node): void {
this.children.push(value);
}
}
</code></pre>
<p>Thanks in advance </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-19T02:07:59.983",
"Id": "519656",
"Score": "0",
"body": "Pardon my naivety but is JSON4 a subset/derivative of JSON? My cursory search of the web didn’t yield anything…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-19T06:01:19.750",
"Id": "519663",
"Score": "2",
"body": "The json standard is pretty loosly defined. There are two main versions of the specification. The stricter v4 and the more lenient v5. The new version was created to ease the many pains of v4. See more at https://json5.org/ @Sam"
}
] |
[
{
"body": "<p>All in all, this is some well-written, well-structured and well-typed code. I like it! I do have a few nitpicks, though:</p>\n<p>The type of <code>ScalarNode.type</code> might be a bit too broad. If it were me, I'd probably restrict it to <code>'string' | 'number' | 'boolean' | 'null'</code>.</p>\n<p>The type of <code>ScalarNode.value</code> feels wrong - a <code>ScalarNode</code> with <code>type = 'number'</code> feels like it should have a <code>value</code> which is a number, rather than a string. <code>parseScalar</code> already knows the <code>type</code>, it should be able to ensure the <code>value</code> conforms to that as well.</p>\n<p>On a related note, you <em>validate</em> the various escape sequences of strings there, but wouldn't that be a good place to actually <em>parse</em> them? Instead of <code>validateString(value); scalar = new ScalarNode(type, value)</code>, why not <code>parsedValue = parseString(value); scalar = new ScalarNode(type, parsedValue)</code>? If we take the <code>value</code> of a string <code>ScalarNode</code> to be the <em>already-parsed</em> value, it means we can, by <em>definition</em>, never have an invalid string <code>ScalarNode</code>.</p>\n<p>Personally, I might even be tempted to do that kind of thing while tokenizing. It doesn't make sense to me to have <code>{type: 'number', value: 'just kidding!'}</code> be considered a valid <code>Token</code> - as far as I'm concerned, that's wrong by definition, and "wrong by definition" is exactly the kind of wrong the typechecker should be detecting for me.</p>\n<p>It feels a bit odd to allow a <code>Tokenizer</code> that fails to match to still move the cursor. Yes, it's useful for getting past whitespace, but I would argue that <code>tokenizeWhitespace</code> <em>does</em> match the input there, even though it doesn't produce a token. It feels natural to me to have whitespace be a token, the parser can just skip it. Or if not that, it does feel a bit more natural to me to instead of letting a <code>TokenizerResult</code> with <code>matched = false</code> move the cursor, allowing one with <code>matched = true</code> to not contain a token.</p>\n<p>Your JSON objects appear to allow the same key to appear multiple times (or at least <code>parseObjectEntry</code>, <code>parseObject</code> and <code>convertNodeToJsValue</code> don't seem to check for that as far as I can tell). When that happens, it seems like you keep the last value. I don't know whether that's the correct behaviour, or even if an object with repeated keys is valid JSON, so I figured I'd point it out.</p>\n<p>The <code>instanceof</code> checks in <code>convertNodeToJsValue</code> are a bit awkward. It might be nicer to define the <code>Node</code> interface such that it includes a <code>toJsonValue : () => JsonValue</code> and let each node type deal with its own conversion?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-21T12:27:11.923",
"Id": "519803",
"Score": "0",
"body": "Very nice review. Agree with all points. [duplicate-keys](https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object) seems to be a controversial topic. I found that almost every JSON parser handles them a little differently. It's a shame that the spec for JSON (which is so widely used) is so loosely defined - especially for things like this. JSON is meant to be interchangeable, leaving stuff like this for implementors to decide is worrying imo. Some just fail, some take the first value, some take the last. I found taking the last to be the most sensible :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-19T23:57:19.940",
"Id": "263228",
"ParentId": "256731",
"Score": "4"
}
},
{
"body": "<p>I don't often look at code for compilers/parsers. I did take a course on compilers as a university student and in order to complete the course had to implement a compiler though since then have not really done anything like that.</p>\n<blockquote>\n<h2>How readable/understandable is the code?</h2>\n</blockquote>\n<p>The code is simple to read and understand. Whitespace follows common conventions accepted by many popular style guides. Indentation is consistent and names are appropriate - for variables, functions, etc.</p>\n<p>It might help others with understanding the code if docblocks were added. <a href=\"https://softwareengineering.stackexchange.com/q/51307/244085\">Some argue that good code is self-documenting</a> though others point out that <a href=\"https://softwareengineering.stackexchange.com/a/51380/244085\">"<em>You shouldn't document what the code is doing, but you should document why it's doing it.</em>"</a>.</p>\n<blockquote>\n<h2>Are there any best-practices or techniques I could implement?</h2>\n</blockquote>\n<p>There are a couple of techniques that could be used to simplify the code in a couple spots.</p>\n<h3><code>return</code> early more often, avoid <code>else</code></h3>\n<p>Much of the code returns/throws early, but there is a block towards the end of <code>validateString()</code> in src/lib/parser.ts:</p>\n<blockquote>\n<pre><code>if (escapeCharacter === "u") {\n if (chars.length >= index + 6) {\n const unicodeEscapeSequence = chars.slice(index + 2, index + 6).join("");\n\n if (/^[0-9A-Fa-f]{4}$/.test(unicodeEscapeSequence)) {\n index += 5;\n\n continue;\n } else {\n throw new JsonError("Invalid unicode escape sequence", tokens);\n }\n } else {\n throw new JsonError("Unexpected end of escape-sequence", tokens);\n }\n}\n\nthrow new JsonError("Unrecognized escape sequence", tokens);\n</code></pre>\n</blockquote>\n<p>By placing the <code>throw</code> statements earlier (which required flipping the logic on the conditions), the indentation levels of subsequent lines can be decreased, and there is no need for the <code>continue</code> statement:</p>\n<pre><code>if (escapeCharacter !== "u") {\n throw new JsonError("Unrecognized escape sequence", tokens);\n}\nif (chars.length < index + 6) {\n throw new JsonError("Unexpected end of escape-sequence", tokens);\n}\nconst unicodeEscapeSequence = chars.slice(index + 2, index + 6).join("");\n\nif (!/^[0-9A-Fa-f]{4}$/.test(unicodeEscapeSequence)) {\n throw new JsonError("Invalid unicode escape sequence", tokens);\n}\nindex += 5;\n</code></pre>\n<p>With such changes the decision tree of the logic could go from looking something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/znsHk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/znsHk.jpg\" alt=\"screenshot of wider decision tree\" /></a>\n<sub>screenshot captured from source: <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ&t=917\" rel=\"nofollow noreferrer\"><em>Your code sucks, let's fix it - By Rafael Dohms</em> at 15:17</a></sub></p>\n<p>To this:</p>\n<p><a href=\"https://i.stack.imgur.com/1GFJN.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1GFJN.jpg\" alt=\"enter image description here\" /></a>\n<sub>screenshot captured from source: <a href=\"https://youtu.be/GtB5DAfOWMQ?t=928\" rel=\"nofollow noreferrer\"><em>Your code sucks, let's fix it - By Rafael Dohms</em> at 15:28</a></sub></p>\n<h3>use <code>map</code> method instead of <code>push</code> in loop</h3>\n<p>In <code>convertNodeToJsValue()</code> of src/lib/generator.ts:</p>\n<blockquote>\n<pre><code>if (root instanceof ArrayNode) {\n const result: JsonArray = [];\n\n for (const value of root.children) {\n result.push(convertNodeToJsValue(value));\n }\n\n return result;\n</code></pre>\n</blockquote>\n<p>Whenever a loop iterates over one array and pushes into another array, the array method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>map</code></a> can be used, so the block above can be simplified to the following:</p>\n<pre><code>if (root instanceof ArrayNode) {\n return root.children.map(convertNodeToJsValue);\n}\n</code></pre>\n<p>Not only does this require fewer lines of code but also the loop iteration function remains <a href=\"https://softwareengineering.stackexchange.com/tags/pure-function/info\">pure</a>.</p>\n<p><em>For the next suggestion: performance might likely be impacted so if that is a priority then skip this advice.</em></p>\n<p>The block before that is similar, except keys are set on an object instead of pushing into an array:</p>\n<blockquote>\n<pre><code>if (root instanceof ObjectNode) {\n const result: JsonObject = {};\n\n for (const [key, value] of root.entries) {\n result[key] = convertNodeToJsValue(value);\n }\n\n return result;\n }\n</code></pre>\n</blockquote>\n<p>this can be simplified by converting the entries (iterator values) to an array and using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\">the array method <code>reduce</code></a>:</p>\n<pre><code>if (root instanceof ObjectNode) {\n return Array.from(root.entries).reduce((result: JsonObject, [key, value]) => {\n result[key] = convertNodeToJsValue(value);\n return result;\n }, {});\n}\n</code></pre>\n<p>To learn more about methods like <code>map</code>, <code>reduce</code>, etc. check out <a href=\"http://reactivex.io/learnrx/\" rel=\"nofollow noreferrer\">these functional programming exercises</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-20T03:09:52.087",
"Id": "263237",
"ParentId": "256731",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "263228",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T18:17:48.110",
"Id": "256731",
"Score": "8",
"Tags": [
"parsing",
"node.js",
"json",
"typescript"
],
"Title": "JSON4 parser in Typescript"
}
|
256731
|
<p>I have a worker class that catches uncaught exceptions and logs them for tracking purposes. However, I do NOT want to swallow those exceptions, nor do I want to abstract them (<em>i.e. losing the stack trace</em>). I believe the best practice in the industry is to throw a new exception and set the inner exception to the caught exception.</p>
<p>With that in mind, I would like a peer review of my implementation in a stripped down form that can be reproduced in a console application:</p>
<pre><code>private static void ExecuteAction(Action action) {
Exception uncaughtException = null;
try {
action();
} catch (Exception e) {
Console.WriteLine(e.Message); // In reality this logs to a database.
uncaughtException = e;
}
// Some fake extra work for sample purposes.
for (int i = 0; i < 1000; i += 3)
i -= 2;
if (uncaughtException != null)
throw new Exception("An uncaught exception was detected by the worker. Check the inner exception for details.", uncaughtException);
}
</code></pre>
<p>To test it out, in your main method of a console application:</p>
<pre><code>try {
int maxValue = int.MaxValue;
ExecuteAction(() => {
Console.WriteLine("This is a test.");
Console.WriteLine(checked(maxValue + 1));
});
}
catch (Exception e) {
Console.WriteLine(e.Message);
if (e.InnerException != null)
Console.WriteLine($"Inner Exception: {e.InnerException.Message}");
}
</code></pre>
<p>The expected output is:</p>
<blockquote>
<p>This is a test.</p>
<p>Arithmetic operation resulted in an overflow.</p>
<p>An uncaught exception was detected by the worker. Check the inner exception for details.</p>
<p>Inner Exception: Arithmetic operation resulted in an overflow.</p>
</blockquote>
<p>Are there some scenarios that may not be covered by this? Are there any gotchas to this implementation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T00:07:32.287",
"Id": "506945",
"Score": "1",
"body": "Rethrow it `throw uncaughtException;` instead of `new`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T01:30:54.633",
"Id": "506947",
"Score": "2",
"body": "Why not just use a finally block for code you want executed if throws or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:46:00.997",
"Id": "506966",
"Score": "0",
"body": "What if your original exception has an inner exception? Your current code doesn't seem to log those inner messages. You'll need to loop through those to get them all, e.g. https://github.com/BJMdotNET/code-samples/blob/master/ExceptionMessageRetriever.cs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T13:53:33.477",
"Id": "506986",
"Score": "0",
"body": "@aepot you lose stack trace information that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T13:56:20.370",
"Id": "506987",
"Score": "0",
"body": "@CharlesNRice because the code after the `try-catch-finally` needs to execute regardless. The point of the worker is to track unhandled errors (among other things). The `finally` will only execute if the exception is handled somewhere up the call stack. In my case, the worker lives in a DLL that is referenced by many applications on the same system, so it needs to record the exception, regardless of if someone catches it up stream :)"
}
] |
[
{
"body": "<p>I think that is where <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.runtime.exceptionservices.exceptiondispatchinfo\" rel=\"nofollow noreferrer\">ExceptionDispatchInfo</a> comes into play.</p>\n<ul>\n<li>It resides inside the <code>System.Runtime.ExceptionServices</code> namespace.</li>\n</ul>\n<p>It preserve the original exception and won't truncate/alter the <code>StackTrace</code>.</p>\n<ul>\n<li>It appends the <code>StackTrace</code> with one more <code>StackFrame</code> from where the exception is re-thrown.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>class Program\n{\n static void Main(string[] args)\n {\n ExceptionDispatchInfo edi = null;\n\n try\n {\n // Do your stuff\n throw new Exception("A");\n }\n catch (Exception ex)\n {\n edi = ExceptionDispatchInfo.Capture(ex);\n }\n\n //Do whatever is needed, like logging\n edi?.Throw();\n }\n}\n</code></pre>\n<p>The output:</p>\n<pre><code>Unhandled exception. System.Exception: A\n at EDI_Demo.Program.Main(String[] args) in C:\\Users\\...\\Program.cs:line 15\n--- End of stack trace from previous location where exception was thrown ---\n at EDI_Demo.Program.Main(String[] args) in C:\\Users\\...\\Program.cs:line 23\n</code></pre>\n<ul>\n<li>Line 15: <code>throw new Exception("A");</code></li>\n<li>Line 23: <code>edi?.Throw();</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T13:57:06.270",
"Id": "506988",
"Score": "2",
"body": "Ohhhhhh I love that! It's, it's beautiful! Thank you! :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T09:19:37.420",
"Id": "256755",
"ParentId": "256732",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256755",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T18:18:14.710",
"Id": "256732",
"Score": "-1",
"Tags": [
"c#",
"error-handling"
],
"Title": "Rethrowing unhandled exceptions later in the catching method"
}
|
256732
|
<p>I'm a newbie in C, and currently following Stanford CS107 - Programming Paradigms. For assignment 6, I find it'd be better to isolate the threads management from the service logic.</p>
<p>The following code is a producer-consumer pattern using semaphore to limit the maximum number of threads. <code>recycle_threads()</code> itself is a thread, which automatically waits for previous threads to exit and free the resources. Users can call <code>create_thread()</code> function whenever they want to run a function in a new thread.</p>
<p>Feel free to leave any comment, about the coding style, design, or utility. Especially, I want to know for what purpose, a real-life thread pool is designed, and what's the feature it must realize.</p>
<p><code>threads_pool.h</code></p>
<pre class="lang-c prettyprint-override"><code>#ifndef _THREADS_POOL_
#define _THREADS_POOL_
#define THREAD_POOL_INIT_OK 0
#define THREAD_POOL_INIT_ERR 1
typedef void *(*thread_fn)(void *arg);
/**
* Create a new thread pool
*/
int threads_pool_init(unsigned size);
/**
* Apply a new thread in threads pool.
*/
void create_thread(thread_fn thd_fn, void *arg);
/**
* Notice no more threads to be created.
* Threads pool can start to recycle and destroy resources.
*/
void threads_pool_close(void);
#endif // _THREADS_POOL_
</code></pre>
<p><code>threads_pool.c</code></p>
<pre class="lang-c prettyprint-override"><code>#include "threads_pool.h"
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
/* threads pool */
static pthread_t *pool;
static unsigned pool_size;
static unsigned create_p;
static unsigned recycle_p;
/* semaphore */
static sem_t *create_sem;
static sem_t *recycle_sem;
static const char *kThreadPoolCreateSem = "/create_sem";
static const char *kThreadPoolRecycleSem = "/recycle_sem";
/* recycle thread id */
static pthread_t recycle_tid;
/* signal recycle thread to exit */
static volatile sig_atomic_t recycle_sig;
#define RECYCLE_RUN 0
#define RECYCLE_TO_EXIT 1
/**
* Producer of producer-consumer pattern.
*/
void create_thread(thread_fn thd_fn, void *arg) {
sem_wait(create_sem);
pthread_create(pool + create_p++ % pool_size, NULL, thd_fn, arg);
sem_post(recycle_sem);
}
/**
* Consumer of producer-consumer pattern.
* Automatically recycle exited threads.
*/
static void *recycle_threads(void *arg) {
while (RECYCLE_RUN == recycle_sig) {
sem_wait(recycle_sem);
pthread_join(*(pool + recycle_p++ % pool_size), NULL);
sem_post(create_sem);
}
while (recycle_p < create_p) {
sem_wait(recycle_sem);
pthread_join(*(pool + recycle_p++ % pool_size), NULL);
sem_post(create_sem);
}
pthread_exit(NULL);
}
/**
* Create the threads pool, and run recycle_thread() thread.
*/
int threads_pool_init(unsigned size) {
pool = malloc(size * sizeof *pool);
pool_size = size;
create_p = 0;
recycle_p = 0;
create_sem = sem_open(kThreadPoolCreateSem, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, size);
recycle_sem = sem_open(kThreadPoolRecycleSem, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 0);
recycle_sig = RECYCLE_RUN;
int code = pthread_create(&recycle_tid, NULL, recycle_threads, NULL);
if (0 == code) return THREAD_POOL_INIT_OK;
return THREAD_POOL_INIT_ERR;
}
/**
* Dispose resources
*/
static void threads_pool_destroy(void) {
free(pool);
sem_unlink(kThreadPoolCreateSem);
sem_unlink(kThreadPoolRecycleSem);
}
/**
* Signal recycle_threads() to exit, and wait it to finish it's job.
*/
void threads_pool_close(void) {
recycle_sig = RECYCLE_TO_EXIT;
pthread_join(recycle_tid,NULL);
threads_pool_destroy();
}
</code></pre>
<p>A simple use-case, simulating tickets selling: <code>agents_tickets.c</code></p>
<pre class="lang-c prettyprint-override"><code>/**
* Using semaphore to limit maximum thread number.
* https://stackoverflow.com/questions/66404929/always-unlink-the-posix-named-semaphore-in-shared-memory?noredirect=1
*/
#include "threads_pool.h"
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
typedef struct {
unsigned agent_id; // simulate an agent
unsigned tickets_tosell; // agent's personal goal of the day
unsigned *tickets_pool; // shared tickets pool
pthread_mutex_t *pool_lock; // mutex lock for visiting the shared tickets pool
} agent;
/**
* Constructor
*/
static void new_agent(agent *a, unsigned agentid, unsigned tickets_num, unsigned *pool, pthread_mutex_t *lock) {
a->agent_id = agentid;
a->tickets_tosell = tickets_num;
a->tickets_pool = pool;
a->pool_lock = lock;
}
/**
* Implement void *(*start_rtn)(void *);
* -------------------------------------
* Each thread execute this function.
*/
static void *sell_tickets(void *agent_addr) {
agent *a = (agent *)agent_addr;
while (a->tickets_tosell > 0) {
pthread_mutex_lock(a->pool_lock); // begin of race condition
(*a->tickets_pool)--;
fprintf(stdout, "agent@%d sells a ticket, %d tickets left in pool.\n", a->agent_id, *a->tickets_pool);
fflush(stdout);
pthread_mutex_unlock(a->pool_lock); // end of race condition
a->tickets_tosell--;
fprintf(stdout, "agent@%d has %d tickets to sell.\n", a->agent_id, a->tickets_tosell);
fflush(stdout);
}
pthread_exit((void *)&a->agent_id);
}
typedef struct {
unsigned num_agents;
unsigned num_tickets;
} project;
void run(project *p) {
unsigned tickets_pool;
pthread_mutex_t lock;
agent agents[p->num_agents];
unsigned id;
tickets_pool = p->num_tickets; // shared resource
pthread_mutex_init(&lock, NULL);
threads_pool_init(10);
for (int i = 0; i < p->num_agents; i++) {
id = i + 1;
new_agent(&agents[i], id, p->num_tickets / p->num_agents, &tickets_pool, &lock);
create_thread(sell_tickets, &agents[i]);
}
threads_pool_close();
pthread_mutex_destroy(&lock);
}
int main(void) {
project p;
p.num_agents = 30;
p.num_tickets = 300;
run(&p);
}
</code></pre>
|
[] |
[
{
"body": "<h1>Keep threads alive</h1>\n<p>What you implemented is not really a thread pool, but just an elaborate way of limiting how many concurrent threads there can be. You still spawn a separate thread for each task and destroy it afterwards. But it is exactly this overhead of creating and destroying threads that you typically want to reduce by using a thread pool.</p>\n<p>The normal solution is to keep threads in the pool alive indefinitely, and have an atomic queue of work that threads can pick work from. This can be implemented using mutexes and condition variables, see for example <a href=\"https://stackoverflow.com/questions/6954489/how-to-utilize-a-thread-pool-with-pthreads\">this StackOverflow question</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:12:38.623",
"Id": "256889",
"ParentId": "256736",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256889",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T20:21:22.443",
"Id": "256736",
"Score": "4",
"Tags": [
"beginner",
"c",
"multithreading",
"concurrency",
"pthreads"
],
"Title": "A tiny threads pool in C"
}
|
256736
|
<p>I'm working on a personal project (Flask CRUD app) and I am currently building the user service. I am trying to use as less as libraries as possible (that's why I do not use WTF-forms for example, just for learning purposes). I am really not sure about a couple of things.</p>
<p>I am aware that form validation should be handled in both front and back-end (or at the very least on the back-end). In order to validate a new user, I am (currently) checking 3 things:</p>
<p><code>1)</code> email does not already exist on the db (can only be verified on the back-end)</p>
<p><code>2)</code> password is strong enough (can be done in both front and back end)</p>
<p><code>3)</code> password and password_confirm matches (can be done in both front and back end)</p>
<p>My goal is to display a small error message on the registration page if either at least one those errors appears. Currently, I am checking option <code>1</code>, <code>2</code> and <code>3</code> and the back-end but only return <code>True</code> if the registration is valid otherwise, <code>False</code>.</p>
<p>Since case <code>1</code> and <code>2</code> can directly be handle also on the front-end, can I display the error message using JavaScript and not from the back-end? I am still confused on what would be the best return for <code>validate_registration</code> (currently a <code>Boolean</code>).</p>
<p>Also, I am not quite sure my code is over-engineered, I made a <code>RegistrationForm</code> class just to validate a registration form. I did that because I am able to pick validations methods from my <code>validators.py</code> which may be used in other Classes as well.</p>
<p>So this is what I did so for for the registration form:</p>
<p><strong>user/blueprints/routes.py</strong></p>
<pre><code>@user.route('/new-user',methods = ['POST'])
def register_user():
form_email = request.form.get('email')
form_password = request.form.get('psw')
form_password_repeat = request.form.get('psw-repeat')
registration_form = RegistrationForm(form_email, form_password, form_password_repeat).validate_registration()
if registration_form:
new_user = UserService().register_user(form_email, form_password)
user_repository = UserRepository(conn, 'users')
user_repository.add_user(new_user)
user_repository.save()
return "ok" #will probably change return statements later on
return "not ok" #will probably change return statements later on
</code></pre>
<p><strong>user/blueprints/forms.py</strong></p>
<pre><code>from prepsmarter.blueprints.user.validators import email_already_in_use, password_matching
class RegistrationForm():
def __init__(self, email, pwd_1, pwd_2):
self.email = email
self.pwd_1 = pwd_1
self.pwd_2 = pwd_2
def validate_registration(self):
is_valid = email_already_in_use(self.email) and is_strong_password(self.pwd_1) and password_matching(self.pwd_1, self.pwd_2)
return is_valid
class LoginForm():
# to do
</code></pre>
<p><strong>user/blueprints/validators.py</strong></p>
<pre><code>import re
from email_validator import validate_email, EmailNotValidError
from prepsmarter.extensions import conn
def is_strong_password(password):
length_error = len(password) < 8
digit_error = re.search(r"\d", password) is None
uppercase_error = re.search(r"[A-Z]", password) is None
return length_error and digit_error and uppercase_error
def is_email_formated_correctly(email):
is_correct = True
try:
validate_email(email)
except EmailNotValidError:
is_correct = False
return is_correct
def password_matching(pwd_1, pwd_2):
return pwd_1 == pwd_2
def email_already_in_use(email):
sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM users WHERE email = (%s)) THEN 1 ELSE 0 END;"
cursor = conn.cursor()
cursor.execute(sql, (email))
res = cursor.fetchall()
return res == 1
</code></pre>
|
[] |
[
{
"body": "<p>I have not thought carefully about all of your code and questions, but here's\none suggested technique for how to handle validation code more simply. In most\ncontexts, people find it easier to understand affirmative boolean logic rather\nthan negated logic. My guess is that the bug in <code>is_strong_password()</code> stems\nfrom that phenomenon (the function tells me <code>hi</code> is strong, for example).\nYou've created 3 variables to be true when something is wrong but then combined\nthem under the opposite assumption. Here are two alternatives to consider:</p>\n<pre><code># This alternative uses affirmative variables: True means OK. Also notice\n# how the variable names are a bit more intuitive because of the\n# affirmative framing. When possible, try to name boolean variables to\n# convey their nature: is_X, has_X, contains_X, etc. Your current code has\n# variables names implying that they each hold an "error" of some kind --\n# but they do not. Finally, the usage of bool() here is not strictly\n# necessary, but it does convey intent explicitly.\n\ndef is_strong_password(password):\n is_long = len(password) >= 8\n has_digit = bool(re.search(r"\\d", password))\n has_upper = bool(re.search(r"[A-Z]", password))\n return is_long and has_digit and has_upper\n \n# This alternative illustrates a handy code-layout technique\n# that often works well when doing validation. This version\n# is shorter (sometimes nice) but less explicit. In this\n# case, I would tend to favor the short version, because the\n# checks are so simple. If the complexity were higher, I would\n# prefer the approach that names every check to increase clarity\n\ndef is_strong_password(password):\n return (\n len(password) >= 8 and\n re.search(r"\\d", password) and \n re.search(r"[A-Z]", password)\n )\n</code></pre>\n<p>The <code>is_email_formated_correctly()</code> can be simplified by doing things more\ndirectly. In addition, if <code>validate_email()</code> returns True/False you could\nsimplify further by just returning its return value.</p>\n<pre><code>def is_email_formated_correctly(email):\n try:\n validate_email(email)\n return True\n except EmailNotValidError:\n return False\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:31:42.387",
"Id": "507078",
"Score": "0",
"body": "Thank you again for your feedback, very constructive. Today I am working on the email confirmation during registration, I may submit again today"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T23:54:19.140",
"Id": "256785",
"ParentId": "256737",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>Since case 1 and 2 can directly be handle also on the front-end, can I\ndisplay the error message using JavaScript and not from the back-end?</p>\n</blockquote>\n<p>Sure, you can do some front-end validation using Javascript, when the user submits the form. But you should still perform the same validation on the backend because there is no guarantee that Javascript is enabled on the client. Remember the client cannot be trusted.</p>\n<p>I don't know if this is already part of your code, but the goal also should be to present a clear message outlining the errors detected while processing the form eg:</p>\n<ul>\n<li>password must contain at least 8 characters including digits and uppercase letters</li>\n<li>password and password confirmation do not match</li>\n</ul>\n<p>Personally I would use a list like this if I want to test multiple conditions:</p>\n<pre><code>errors = []\nif not password_matching(pwd_1, pwd_2):\n errors.append('Password and password confirmation do not match')\n...\n</code></pre>\n<p>And then <code>if len(errors) > 0</code>, you know that errors were found and you can display them back to the client. You can pass the list of errors as a parameter using render_template for example. In fact you will probably be passing the form object back to render_template to populate the form as it was submitted.</p>\n<p>If you will be using a CSS/JS framework like Bootstrap, there is already some client-side validation baked in that you can use: <a href=\"https://getbootstrap.com/docs/5.0/forms/validation/\" rel=\"nofollow noreferrer\">https://getbootstrap.com/docs/5.0/forms/validation/</a></p>\n<p>Instead of:</p>\n<pre><code>sql = "SELECT CASE WHEN EXISTS ( SELECT * FROM users WHERE email = (%s)) THEN 1 ELSE 0 END;"\n</code></pre>\n<p>You could simply have:</p>\n<pre><code>sql = "SELECT COUNT(*) FROM users WHERE email = (%s)"\n</code></pre>\n<p>That should either return 0 or 1 but make sure email has a unique constraint in your DB.</p>\n<p>And although you say you want to use as few libraries as possible you have actually implemented some WTF-forms functionality in the form of <a href=\"https://wtforms.readthedocs.io/en/2.3.x/validators/\" rel=\"nofollow noreferrer\">validators</a>. This is good for learning purposes but I think there is no real advantage here.</p>\n<p>I also have the impression that you implemented your own ORM in lieu of SQL Alchemy. I am not sure it is worth reinventing the wheel unless there is a clear gain in simplicity of flexibility that is not easily achieved with the existing tools.</p>\n<p>Note that there are Flask implementations for <a href=\"https://flask-wtf.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">WTF</a> and <a href=\"https://flask-sqlalchemy.palletsprojects.com/en/2.x/\" rel=\"nofollow noreferrer\">Sql Alchemy</a> respectively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:21:57.307",
"Id": "256858",
"ParentId": "256737",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256785",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T20:53:06.663",
"Id": "256737",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"design-patterns",
"form"
],
"Title": "Python Back-end registration validation"
}
|
256737
|
<p>I am trying to write a system where the focus is trapped inside the elements of a container, so that pressing tab or shift + tab just cycles through instead of going outside it. The following is my code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var trapElems = [];
var trapActive = false; // Set to true after the initial tabbing
var trapIndex; // Current index
// Function for handling tabbing forward
function trapTab() {
if (trapElems.length === 0) {
return;
}
if (!trapActive) {
trapActive = true;
trapIndex = 0;
trapElems[trapIndex].focus();
return;
}
trapIndex = trapIndex + 1;
if (trapIndex === trapElems.length) {
trapIndex = 0;
}
trapElems[trapIndex].focus();
}
// Function for handling tabbing backward
function trapShiftTab() {
if (trapElems.length === 0) {
return;
}
if (!trapActive) {
trapActive = true;
trapIndex = trapElems.length - 1;
trapElems[trapIndex].focus();
return;
}
trapIndex = trapIndex - 1;
if (trapIndex < 0) {
trapIndex = trapElems.length - 1;
}
trapElems[trapIndex].focus();
}
document.addEventListener("DOMContentLoaded", function() {
// Get the focus trap elements inside the box
var focusableElems = document.getElementById("box").querySelectorAll("button, [href], input, select, textarea, summary, [tabindex]");
trapElems = [];
for (var i = 0, j = 0; i < focusableElems.length; i++) {
if ((focusableElems[i].tabIndex !== -1) && (!focusableElems[i].disabled)) {
focusableElems[i].setAttribute("data-focus-trap", j.toString());
trapElems.push(focusableElems[i]);
j = j + 1;
}
}
// Handle the [tab] and [shift] key down events
document.addEventListener(
"keydown",
function(event) {
// [shift] + [tab]
if (event.shiftKey && event.code === "Tab") {
event.preventDefault();
trapShiftTab();
}
// [tab] only
else if (event.code === "Tab") {
event.preventDefault();
trapTab();
}
},
false
);
// Handle the focus in event
// If one of the trapped elements is focused in other ways, the index is set to its place
document.addEventListener(
"focusin",
function(event) {
if (event.target.hasAttribute("data-focus-trap")) {
trapActive = true;
trapIndex = parseInt(event.target.getAttribute("data-focus-trap"));
}
},
false
);
}, false);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
body {
margin: 20px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}
#box {
border: 1px solid blue;
padding: 20px 10px;
margin: 20px 0;
}
a {
padding: 5px;
border: 1px dotted gray;
display: inline-block;
}
a:focus {
outline: 2px solid blue;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
<div id="box">
<a href="#" id="box-link-1" tabindex="-1" style="pointer-events: none;">Box link 1 (not tabbable)</a>
<a href="#" id="box-link-2">Box link 2</a>
<a href="#" id="box-link-3">Box link 3</a>
<br /><br />
<span tabindex="0">Tabbable span</span>
<button type="button">Button 1</button>
<button type="button" disabled="disabled">Button 2</button>
<br /><br />
<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>
</div>
<a href="#">Link 4</a>
<a href="#">Link 5</a>
<a href="#">Link 6</a>
</div></code></pre>
</div>
</div>
</p>
<p>Please view the above snippet in full view and use the tab (or shift + tab) keys to see the intended effect. Would really appreciate reviews of the JS code. Thank you.</p>
<p><strong>Edited</strong> again to handle focusing on the elements in other ways, eg, using a mouse to click.</p>
<p><strong>Edited</strong> to work with <code>tabindex="-1"</code> and <code>disabled</code> elements.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T23:08:46.263",
"Id": "256739",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Trapping focus inside container using pure JavaScript"
}
|
256739
|
<p>I have a question: Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.</p>
<p>Given some queries in the form [a,b,k]:</p>
<pre><code>[[1,5,3],[4,8,7],[6,9,1]]
</code></pre>
<p>Add the values of k between the indices a and b inclusive:</p>
<pre><code>[0,0,0, 0, 0,0,0,0,0, 0]
[3,3,3, 3, 3,0,0,0,0, 0]
[3,3,3,10,10,7,7,7,0, 0]
[3,3,3,10,10,8,8,8,1, 0]
</code></pre>
<p>And then return the max value which is 10</p>
<p>My attempt is:</p>
<pre><code>from itertools import accumulate
def Operations(size, Array):
values = [0] * (size+2)
for a,b,k in Array:
values[a] += k
values[b+1] -= k
values = list(accumulate(values))
Result = max(values)
return Result
def main():
nm = input().split()
n = int(nm[0])
m = int(nm[1])
queries = []
for _ in range(m):
queries.append(list(map(int, input().rstrip().split())))
result = Operations(n, queries)
if __name__ == "__main__":
main()
</code></pre>
<p>This code works, however, hits runtime errors when the arrays get too large. I have no idea how to lower the runtime further.</p>
<p>Example input is as follows:</p>
<pre><code>5 3
1 2 100
2 5 100
3 4 100
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T02:06:02.743",
"Id": "506949",
"Score": "0",
"body": "How big is the input? Is it a runtime error or a time limit exceeded error? If it is a coding challenge please post the link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:57:11.040",
"Id": "506967",
"Score": "0",
"body": "Here is the question: https://www.hackerrank.com/challenges/crush/problem?filter=python3&filter_on=language&h_l=interview&h_r=next-challenge&h_v=zen&limit=100&page=6&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays"
}
] |
[
{
"body": "<p>The solution looks good, my suggestions:</p>\n<ul>\n<li><strong>Generators</strong>: the function <a href=\"https://docs.python.org/3/library/itertools.html#itertools.accumulate\" rel=\"nofollow noreferrer\">itertools.accumulate</a> returns a generator which doesn't create the whole list in memory, but calling <code>list</code> on it does create the actual list in memory. This is probably why you get the runtime error. Changing <code>Operations</code> from:\n<pre><code>def Operations(size, Array):\n\n values = [0] * (size+2)\n for a,b,k in Array:\n values[a] += k\n values[b+1] -= k\n\n values = list(accumulate(values))\n\n Result = max(values)\n return Result\n</code></pre>\nTo:\n<pre><code>def Operations(size, Array):\n values = [0] * (size + 2)\n for a, b, k in Array:\n values[a] += k\n values[b + 1] -= k\n return max(accumulate(values))\n</code></pre>\nsolves the problem and all tests pass.</li>\n<li><strong>PEP 8</strong>: function names should be lowercase, with words separated by underscores as necessary to improve readability. Variable names follow the same convention as function names. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">More info</a>. The function name is probably given by HackerRank, but the variable names <code>Array</code> and <code>Result</code> should be lowercase.</li>\n</ul>\n<p>FYI, <a href=\"https://codereview.stackexchange.com/a/251001/227157\">this</a> is my old review on the same problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:23:12.937",
"Id": "256750",
"ParentId": "256740",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256750",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T01:06:32.183",
"Id": "256740",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Optimising Prefix Sum"
}
|
256740
|
<p>I have a dataframe:</p>
<pre><code>>>> import pandas as pd
>>> import plotly.express as px
>>> df = pd.DataFrame({
... 'P': ['P1', 'P2', 'P3'],
... 'Q1': [1, 2, 3],
... 'Q2': [3, 1, 2],
... })
>>> df
P Q1 Q2
0 P1 1 3
1 P2 2 1
2 P3 3 2
>>>
</code></pre>
<p>For each row, I should sort Qx columns in descending order, and than do plots but each Qx column should have the same color. Something like this:</p>
<pre><code>qcols = [col for col in df.columns if col.startswith('Q')]
# I have to define colors in advance
color_dict = {col: color for col, color in zip(
qcols,
px.colors.qualitative.Plotly[:len(df)]
)}
for p in df.P.unique():
# Transformation needed for sorting columns descending
dfp = df.query("P == @p").set_index('P').T.sort_values(p, ascending=False).T.reset_index().melt(id_vars='P', var_name='Q', value_name='val')
fig = px.bar(data_frame=dfp, x='Q', y='val', color='Q', color_discrete_map=color_dict, width=300, height=300)
fig.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/kYVw6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kYVw6.png" alt="enter image description here" /></a></p>
<p>It looks quite complicated to me.
Can it be done in a simpler way?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T05:51:01.713",
"Id": "256746",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"data-visualization"
],
"Title": "Bar chart - can we simplify?"
}
|
256746
|
<p>How does the following C program look to compare to strings and return a case-insensitive sort? The following is what I have so far:</p>
<pre><code>int main(void)
{
char* strings[4] = {"Onus", "deacon", "Alex", "zebra"};
for (int i=0; i<4; i++) printf("%d. %s\n", i+1, strings[i]);
qsort(strings, 4, 8, scmp);
}
int scmp(const void *p1, const void *p2)
{
// being a string (pointer-to-char)
const char* s1 = *(char**) p1;
const char* s2 = *(char**) p2
size_t len_s1 = strlen(s1);
size_t len_s2 = strlen(s2);
// lower-case first string buffer
char s1_lower[len_s1+1]; // cannot initialize with {[len_s1]=0} in VLA ?
s1_lower[len_s1] = 0;
for (int i=0; s1[i] != 0; i++)
s1_lower[i] = tolower(s1[i]);
// lower-case second string buffer
char s2_lower[len_s2+1];
s2_lower[len_s2] = 0;
for (int i=0; s2[i] != 0; i++)
s2_lower[i] = tolower(s2[i]);
// built-in string compare (strcmp) will return the sort value
return strcmp(s1_lower, s2_lower);
/* printf("%s -- %s\n", s1_lower, s2_lower); */
}
</code></pre>
<p>Another version extracting out the <code>str_lower</code> function would be:</p>
<pre><code>void lower_string(char buffer[], const char* str, size_t len)
{
char str_lower[len+1];
str_lower[len] = 0;
for (int i=0; str[i] != 0; i++)
str_lower[i] = tolower(str[i]);
}
int scmp(const void *p1, const void *p2)
{
const char* s1 = *(char**) p1;
const char* s2 = *(char**) p2;
char s1_lower[strlen(s1)+1];
lower_string(s1_lower, s1, strlen(s1));
char s2_lower[strlen(s2)+1];
lower_string(s2_lower, s2, strlen(s2));
return strcmp(s1_lower, s2_lower);
}
</code></pre>
|
[] |
[
{
"body": "<p>Firstly, thank you for providing a test program. We could make the test even better, if we make it self-checking:</p>\n<pre><code>char const *expected[] = {"Alex", "deacon", "Onus", "zebra"};\nfor (int i = 0; i < 4; ++i) {\n if (strcmp(expected[i], strings[i])) {\n return EXIT_FAILURE;\n }\n}\n</code></pre>\n<p>We might consider including some non-alphabetic characters, too ("should <code>"A-team"</code> sort before or after <code>"abacus"</code>?). And we'll want some tests of equal and almost-equal strings; not just ones that differ in the first character.</p>\n<hr />\n<p>There were a few errors and warnings to fix up (I compiled with <code>gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion</code> to catch all of these):</p>\n<ul>\n<li><p>We missed a few necessary includes for the comparison function:</p>\n<pre><code>#include <ctype.h>\n#include <stdint.h>\n#include <string.h>\n</code></pre>\n<p>And for the test program:</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n</code></pre>\n</li>\n<li><p>We're assigning <code>char*</code> pointers using string literals. Whilst C allows this for historical reasons, it's dangerous, and should be avoided (because assignment through such pointers is UB, and the compiler can't spot that for you). It's easy to fix that:</p>\n<pre><code>const char* strings[4] = {"Onus", "deacon", "Alex", "zebra"};\n</code></pre>\n</li>\n</ul>\n<p>And one that GCC can't spot:</p>\n<blockquote>\n<pre><code>qsort(strings, 4, 8, scmp);\n// ^^^\n</code></pre>\n</blockquote>\n<p>We can't assume that a <code>const char*</code> is a particular size on the target platform. Whilst this value may be correct where you are, it's not true everywhere. Luckily, C provides the <code>sizeof</code> operator to help:</p>\n<pre><code>qsort(strings, 4, sizeof strings[0], scmp);\n</code></pre>\n<hr />\n<p>Looking in detail at the comparison function, it does a lot of extra work to make a copy of each input string (we have to traverse each string up to three times - once to find its length, once to copy and convert case, and once to compare).</p>\n<p>Instead of preparing the ground for <code>strcmp()</code>, we could (and should) write a case-insensitive version of <code>strcmp()</code>, so we traverse each string once, and downcase only those characters we actually need for the comparison, as we reach them:</p>\n<pre><code>#include <ctype.h>\n\n/* N.B. name not beginning with "str". */\nint ci_strcmp(const char *s1, const char *s2)\n{\n while (*s1) {\n if (!*s2) {\n /* s1 is longer */\n return 1;\n }\n int c1 = tolower(*s1);\n int c2 = tolower(*s2);\n if (c1 < c2) {\n return -1;\n }\n if (c2 < c1) {\n return 1;\n }\n ++s1;\n ++s2;\n }\n if (*s2) {\n /* s2 is longer */\n return -1;\n }\n /* compare equal */\n return 0;\n}\n\n/* Adapter for qsort */\nint scmp(const void *p1, const void *p2)\n{\n const char *const *sp1 = p1;\n const char *const *sp2 = p2;\n return ci_strcmp(*sp1, *sp2);\n}\n</code></pre>\n<p>We can make the body of the comparer more compact (but functionally identical) with a little cleverness:</p>\n<pre><code>int ci_strcmp(const char *s1, const char *s2)\n{\n for (;;) {\n int c1 = tolower(*s1++);\n int c2 = tolower(*s2++);\n int result = (c1 > c2) - (c1 < c2);\n if (result || !c1) return result;\n }\n}\n</code></pre>\n<p>As mentioned in another answer, we need to use <code>unsigned char</code> with <code>tolower()</code>:</p>\n<pre><code>int ci_strcmp(const unsigned char *s1, const unsigned char *s2)\n{\n for (;;) {\n int c1 = tolower(*s1++);\n int c2 = tolower(*s2++);\n int result = (c1 > c2) - (c1 < c2);\n if (result || !c1) return result;\n }\n}\n\n/* Adapter for qsort */\nint scmp(const void *p1, const void *p2)\n{\n const unsigned char *const *sp1 = p1;\n const unsigned char *const *sp2 = p2;\n return ci_strcmp(*sp1, *sp2);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T17:57:26.023",
"Id": "507007",
"Score": "1",
"body": "An annoying attribute about standard _string_ functions is that their functional interface is `char *`, but the internal workings are as if `unsigned char *`. Unfortunately calling `my_strfoo1(unsigned char *)` with a `char *` can give a warning, hence often a `my_strfoo2(char *)` obliges a pointer conversion within. As much string processing is ASCII only - this issue is not common and left unaddressed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:16:52.167",
"Id": "256749",
"ParentId": "256747",
"Score": "4"
}
},
{
"body": "<blockquote>\n<p>How does the following C program look to compare to strings and return a case-insensitive sort?</p>\n</blockquote>\n<p>In addition to <a href=\"https://codereview.stackexchange.com/a/256749/29485\">@Toby Speight</a> fine answer:</p>\n<p><strong>Order consideration</strong></p>\n<p>Folding values to lower case gives a different sort than folding to uppercase.</p>\n<p>Consider <code>"a", "A", "_"</code>. What order is expected? Is <code>'_'</code> before or after letters?</p>\n<p>Function description should specify its intent.</p>\n<p><strong>Non-ASCII values</strong></p>\n<p>Values outside the 0-127 are tricky as they may be negative. <code>tolower()</code> is not defied well for most negative values.</p>\n<pre><code>const char* s1 = *(char**) p1;\n...\ns1_lower[i] = tolower(s1[i]); // Potential UB\n</code></pre>\n<p>Instead handle as <code>unsigned char *</code>.</p>\n<pre><code>const unsigned char* s1 = *(const unsigned char**) p1;\nunsigned char s1_lower[len_s1+1];\n...\ns1_lower[i] = tolower(s1[i]); \n</code></pre>\n<p><strong>Non-ASCII values (more)</strong></p>\n<p>Various non-ASCII letters can form a non-1-to-1 mapping between lower and upper case.</p>\n<p>How should <code>"E", "e", "è", "é", "ê", "ë", "É"</code> sort?</p>\n<p>Code could round trip</p>\n<pre><code>s1_lower[i] = tolower(toupper(s1[i]));\n</code></pre>\n<p>Going forward, this non-ASCII issue concern tends to be a Unicode one.</p>\n<p><strong>Candidate caseless compare</strong></p>\n<pre><code>int scmpi(const void *p1, const void *p2) {\n const unsigned char* s1 = *(unsigned char**) p1;\n const unsigned char* s2 = *(unsigned char**) p2;\n\n // Keep loop simple\n while ((tolower(*s1) == tolower(*s2)) && *s2) {\n s1++;\n s2++;\n }\n int ch1 = tolower(*s1);\n int ch2 = tolower(*s2);\n return (ch1 > ch2) - (ch1 < ch2);\n}\n</code></pre>\n<p><strong>Speedier??</strong></p>\n<p>I found <a href=\"https://codereview.stackexchange.com/a/180524/29485\"><code>my_strcmp_caseless()</code></a> about twice as fast, back-in-the-day; useful in a string heavy application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T18:10:55.593",
"Id": "507009",
"Score": "0",
"body": "@David542 You might like [Additional pitfalls to watch out for when doing case insensitive compares](https://stackoverflow.com/a/51992138/2410359)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T03:02:15.013",
"Id": "507035",
"Score": "0",
"body": "thanks for this great answer. What would be an example of how a string could have an `unsigned char` in it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T03:33:59.280",
"Id": "507038",
"Score": "1",
"body": "@David542 `unsigned char example[] = { 255, 0 };`. In C: \"A string is a contiguous sequence of characters terminated by and including the first null character.\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T14:15:56.280",
"Id": "256764",
"ParentId": "256747",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256749",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T06:40:49.410",
"Id": "256747",
"Score": "3",
"Tags": [
"c"
],
"Title": "Doing a qsort function to compare strings, case insensitive"
}
|
256747
|
<p>I made a little drawing program in OOP.</p>
<p>The game consists of a canvas which is basically a 2d array where the user can draw various shapes on it. There can be multiple shapes overlapped on top of each other at the same spot. The shape that was drawn the last would appear on the top of the canvas and that is what gets printed out when we print the canvas - only those shapes at the top would be printed out.</p>
<p>Here I have two classes <code>Rectangle</code> and <code>Canvas</code></p>
<pre class="lang-js prettyprint-override"><code>
class Rectangle {
constructor(positions) {
this.positions = positions
this.character = Symbol()
}
move(dx, dy) {
for (const position of this.positions) {
const nx = position[0] + dx
const ny = position[1] + dy
position[0] = nx
position[1] = ny
}
}
}
class Canvas {
constructor(size) {
this.canvas = Array.from({ length: size }, () =>
Array.from({ length: size }, () => null)
)
}
draw(rectangle) {
const { positions, character } = rectangle
for (const [row, col] of positions) {
if (this.canvas[row][col] === null) this.canvas[row][col] = [character]
else this.canvas[row][col].push(character)
}
}
remove(rectangle) {
const { positions, character } = rectangle
if (positions.length === 0) return
for (const position of positions) {
const list = this.canvas[position[0]][position[1]]
list.splice(list.indexOf(character), 1)
}
}
print(palette) {
let rows = ''
for (let i = 0; i < this.canvas.length; i++) {
for (let j = 0; j < this.canvas[i].length; j++) {
if (this.canvas[i][j] === null || this.canvas[i][j].length === 0) {
rows += '*' // empty
} else {
rows += palette[this.canvas[i][j][this.canvas[i][j].length - 1]]
}
}
rows += '\n'
}
console.log(rows)
}
moveToTop(rectangle) {
this.remove(rectangle)
this.draw(rectangle)
}
drag(startPosition, endPosition, map) {
const list = this.canvas[startPosition[0]][startPosition[1]]
if (list?.length === 0) return
const character = list[list.length - 1]
const rectangle = map[character]
const dx = endPosition[0] - startPosition[0]
const dy = endPosition[1] - startPosition[1]
this.remove(rectangle)
rectangle.move(dx, dy)
this.draw(rectangle)
}
}
</code></pre>
<p>And I have a map that maps the <code>Rectangle</code>'s <code>character</code> to that Rectangle instance. and another object called <code>palette</code> which tells the canvas how that shape or pixel would look like when being printed (initially <code>palette</code> is part of <code>canvas</code> but I feel like I should decouple them so <code>canvas</code> only holds the state of the current canvas and is not opinionated on how the shapes should look like when they are printed out).</p>
<pre class="lang-js prettyprint-override"><code>const rectangle1 = new Rectangle(
[
[0, 1],
[1, 2],
[0, 2],
]
)
const rectangle2 = new Rectangle(
[
[0, 0],
[0, 1],
[1, 0],
]
)
const rectangle3 = new Rectangle([[0, 0]])
const palette = {
[rectangle1.character]: 'A',
[rectangle2.character]: 'B',
[rectangle3.character]: 'C',
}
const map = {
[rectangle1.character]: rectangle1,
[rectangle2.character]: rectangle2,
[rectangle3.character]: rectangle3,
}
</code></pre>
<p><a href="https://codesandbox.io/s/game-xqrep?file=/src/index.js" rel="nofollow noreferrer">here is the link to a live demo</a></p>
<p>Please feel free to give me any feedback. Specifically, I would love to know:</p>
<ol>
<li>if there is a better to approach the OO design here? Did I do a good job at separating the concerns here? Does every class have the methods here?</li>
<li>I think I need some help to refactor the <code>map</code> and <code>palette</code>. Specifically <code>map</code>, it is manually constructed right now. I am not sure if I need to create two classes for them.</li>
<li>Is there any alternatives to approach implementing such a canvas? What are some of the pros and cons?</li>
</ol>
|
[] |
[
{
"body": "<h1>Question responses</h1>\n<blockquote>\n<p><em>if there is a better to approach the OO design here?</em></p>\n</blockquote>\n<p>It seems okay. As was pointed out in answers to your other recent questions there currently is no use of OO features like inheritance.</p>\n<blockquote>\n<p><em>Did I do a good job at separating the concerns here?</em></p>\n</blockquote>\n<p>The separation seems okay.</p>\n<h1>Suggestions</h1>\n<h3>Simplify <code>move</code> method</h3>\n<p>The <code>Rectangle</code> method <code>move</code> is currently implemented as this:</p>\n<blockquote>\n<pre><code>move(dx, dy) {\n for (const position of this.positions) {\n const nx = position[0] + dx\n const ny = position[1] + dy\n position[0] = nx\n position[1] = ny\n }\n }\n</code></pre>\n</blockquote>\n<p>Variables <code>nx</code> and <code>ny</code> are only used once. The method could greatly be simplified:</p>\n<pre><code>position[0] += dx;\nposition[1] += dy;\n</code></pre>\n<h3>functional approach to print</h3>\n<p>In the <code>Canvas</code> method <code>print</code> two <code>for</code> loops are used. A functional approach, similar to how the canvas is created in the constructor, would allow fewer lines and the variable <code>rows</code> could be assigned in one statement, which would allow <code>const</code> to be used, though this would not be wise to change if <a href=\"https://hackernoon.com/javascript-performance-test-for-vs-for-each-vs-map-reduce-filter-find-32c1113f19d7\" rel=\"nofollow noreferrer\">performance is a major concern</a>.</p>\n<pre><code>print(palette) {\n const rows = this.canvas.map(column => column.map(cell => {\n if (cell === null || !cell.length) {\n return '*';\n }\n return palette[cell[cell.length - 1]];\n }).join('') + "\\n" ).join('');\n</code></pre>\n<h3>check parameter types</h3>\n<p>Since JavaScript is loosely typed, there isn’t much support for ensuring a method is called with parameters of certain types. However, if a method expects to be called with certain types of arguments (e.g. <code>Canvas::draw()</code> and <code>::remove()</code> expect a <code>Rectangle</code> instance) then the type of those arguments can be checked - e.g. using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof\" rel=\"nofollow noreferrer\"><code>typeof</code></a> keyword. If an argument doesn’t match an expected type then perhaps an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error\" rel=\"nofollow noreferrer\"><code>Error</code></a> should be <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw\" rel=\"nofollow noreferrer\"><code>throw</code></a>n.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T15:16:38.553",
"Id": "257101",
"ParentId": "256748",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:44:45.080",
"Id": "256748",
"Score": "5",
"Tags": [
"javascript",
"object-oriented",
"array",
"ecmascript-6",
"iteration"
],
"Title": "JavaScript: A drawing program in OOP"
}
|
256748
|
<p>I would appreciate a code review - specifically of the javascript - for a tic tac toe game that I have built. I am looking for feedback on where improvements can be made in the overall structure, syntax, and style of code.</p>
<p>View the whole app on codepen here, with html/css included: <a href="https://codepen.io/OKiguess/pen/poNZZQa" rel="nofollow noreferrer">https://codepen.io/OKiguess/pen/poNZZQa</a></p>
<p>Thanks in advance.</p>
<pre class="lang-javascript prettyprint-override"><code>//Module to produce the underlying game board array
const GameBoard = (() => {
let arr = [];
function buildArr() {
arr = new Array(3);
for (let i = 0; i < arr.length; i++) {
arr[i] = new Array(3);
for (let j = 0; j < arr[i].length; j++) {
arr[i][j] = `${i}${j}`;
};
};
return this.arr = arr;
};
function resetArr() {
this.arr = [];
this.arr = buildArr();
return this.arr = arr;
};
return {
arr,
buildArr,
resetArr
};
})();
//uses the GameBoard module to create the DOM structure for the game
const GameDOM = (() => {
let _boardArr, _gameBoardDiv;
const populate = () => {
if (GameBoard.arr.length === 0) { //checks to see whether game board array already exists
_boardArr = GameBoard.buildArr(); //makes it if it doesnt
_gameBoardDiv = document.querySelector('.board')
populateLoop("cell-hidden");
}
else { //if it does already exist
_gameBoardDiv.innerHTML = ""; //reset the GameBoard DOM element
_boardArr = GameBoard.resetArr(); //recreate the gameboard array
populateLoop("cell-shown");
}
}
const populateLoop = (gameState) => {
for (let i = 0; i < _boardArr.length; i++) {
for (let j = 0; j < _boardArr[i].length; j++) {
let _cell = document.createElement("div");
_cell.setAttribute('class', `${gameState}`);
_cell.setAttribute('id', `${_boardArr[i][j]}`);
_gameBoardDiv.appendChild(_cell);
}
}
}
return {
populate,
}
})();
//Player object used for storing and retreiving player's name, piece, score, and type (for player 2 - AI)
const Player = (playerName) => {
let score = 0;
const getName = () => playerName;
const getScore = () => score;
function getPiece() {
return this.piece;
}
function setPiece(piece) {
this.piece = piece;
return this.piece;
}
function setName(playerName) {
this.name = playerName;
return this.name;
}
function addPoint() {
score++
return score;
}
return {
setName,
setPiece,
getName,
getPiece,
getScore,
addPoint,
};
}
//controls the state of the game, including: whose turn, total turns so far, how turns are displayed, the display of the board, checking end state (wins and draw), and the player 2 AI
const gameState = (() => {
//game state variables
let turn;
let turnTally = 0
let p1name, p2name, p1piece, p2piece, p2type
let winner = "";
//DOM identifierd
const p1nameDisplay = document.querySelector(".player1-name");
const p2nameDisplay = document.querySelector(".player2-name");
const board = document.querySelector(".board");
const startDiv = document.querySelector(".new-game-form-shown");
const startButton = document.querySelector(".start");
const scoreBoard = document.querySelectorAll(".player-hidden")
//starts the game and takes player name values & type
startButton.onclick = function () {
let p1text = document.querySelector(`[name="player1-name"]`).value;
let p2text = document.querySelector(`[name="player2-name"]`).value;
p2type = document.querySelector('input[name="type2"]:checked').value;
if (p1text != "") {
player1 = Player(p1text)
} else if (p1text == "") {
player1 = Player("Player 1")
};
if (p2text != "") {
player2 = Player(p2text)
} else if (p2text == "") {
player2 = Player("Player 2")
};
p1name = player1.getName();
p2name = player2.getName();
player1.num = "player1";
player2.num = "player2";
p1nameDisplay.innerHTML = `<h2>${player1.getName()}</h2>`
p2nameDisplay.innerHTML = `<h2>${player2.getName()}</h2>`
hideStartScreen();
showScoreBoard();
randomPiece();
setTimeout(whoStarts, 500);
activeTurn();
return;
}
//displays scoreboard
function showScoreBoard() {
for (let i = 0; i < scoreBoard.length; i++) {
scoreBoard[i].classList.add("player-shown")
scoreBoard[i].classList.remove("player-hidden")
}
}
//reveals game grid
function showBoard() {
let grid = board.querySelectorAll(".cell-hidden");
for (i = 0; i < grid.length; i++) {
grid[i].classList.add("cell-shown");
grid[i].classList.remove("cell-hidden");
}
}
//hides the initial start screen
function hideStartScreen() {
startDiv.classList.add("new-game-form-hidden")
startDiv.classList.remove("new-game-form-shown")
const startDivHidden = document.querySelector(".new-game-form-hidden");
removeStart(startDivHidden);
}
//conrols animation transitions and removin start DIV from DOM
const promiseTransition = (div, property, value) =>
new Promise(resolve => {
div.style[property] = value;
const transitionEnded = e => {
if (e.propertyName !== property) return;
div.removeEventListener('transitionend', transitionEnded);
resolve();
}
div.addEventListener('transitionend', transitionEnded);
});
async function removeStart(startDivHidden) {
await promiseTransition(startDivHidden, "opacity", "0");
startDivHidden.remove();
GameDOM.populate();
setTimeout(showBoard, 1);
}
//controls display of each players piece
const displayPlayerPiece = (p1, p2) => {
const p1pieceDiv = document.querySelector(".player1-piece")
const p2pieceDiv = document.querySelector(".player2-piece")
p1pieceDiv.innerHTML = `<button class="${p1}" role="radio" type="button">${p1}</button>`
p2pieceDiv.innerHTML = `<button class="${p2}" role="radio" type="button">${p2}</button>`
}
//randomises players pieces
const randomPiece = () => {
let coinFlip = Math.round(Math.random());
if (coinFlip === 0) {
p1piece = player1.setPiece("X");
p2piece = player2.setPiece("O");
displayPlayerPiece(p1piece, p2piece);
return;
} else {
p1piece = player1.setPiece("O");
p2piece = player2.setPiece("X");
displayPlayerPiece(p1piece, p2piece);
return;
}
}
//randomise who starts each round
const whoStarts = () => {
let coinFlip = Math.round(Math.random());
if (coinFlip === 0) {
turn = p1name;
activeTurn();
return turn;
} else if (p2type == "AI") {
turn = p2name
activeTurn();
AImove();
} else return turn = p2name;
};
//function for switching turns between players
const nextTurn = () => {
if (turn == p1name) {
turn = p2name
if (p2type == "AI") AImove();
}
else if (turn == p2name) {
turn = p1name
}
activeTurn();
return turn;
}
//click listener for placing pieces
board.onclick = function (e) {
if ((winner == "") && ((e.target.className == "cell-shown cell-hover-X") || (e.target.className == "cell-shown cell-hover-O"))) {
if (!e.target.innerHTML) {
if (turn == p1name) {
placePiece(e, p1piece);
}
else placePiece(e, p2piece)
}
}
else return;
}
//place piece functionality
function placePiece(e, piece) {
gameArrayIndex = e.target.attributes.id.value;
splitIndexValue = gameArrayIndex.split("");
splitValueX = gameArrayIndex[0];
splitValueY = gameArrayIndex[1];
GameBoard.arr[splitValueX][splitValueY] = piece;
e.target.innerHTML = piece;
turnTally++
if (turnTally > 4) {
if (winCondition()) {
whoStarts();
return;
};
};
nextTurn();
}
//highlights whose turn is active
const activeTurn = () => {
const p1board = document.querySelector(".player1-info")
const p2board = document.querySelector(".player2-info")
if (turn == p1name) {
p1board.classList.remove("inactive")
p2board.classList.add("inactive")
} else {
p2board.classList.remove("inactive")
p1board.classList.add("inactive")
}
}
//randomise AI starting move to best squares
function AIstartingMove() {
startingMove = ["00", "02", "11", "20", "22"]
let randomStartIndex = Math.floor(Math.random() * startingMove.length);
return startingMove[randomStartIndex]
}
//overall AI move control function
const AImove = () => {
if (turnTally > 8) return;
if (turnTally == 0) {
let startingMove = AIstartingMove()
AIplaceDOM(startingMove)
}
if (turnTally > 0) {
let bestMove = minimax(GameBoard.arr, p2piece);
AIplaceDOM(bestMove.index)
}
turnTally++
if (turnTally > 4) {
if (winCondition()) {
whoStarts();
return;
};
};
nextTurn();
}
//responsible for showin the move in the DOM
function AIplaceDOM(move) {
AImoveCoOrds = move.toString().split("");
let xMove = AImoveCoOrds[0]
let yMove = AImoveCoOrds[1]
GameBoard.arr[xMove][yMove] = p2piece
let placeDOM = document.getElementById(`${xMove}${yMove}`)
placeDOM.innerHTML = p2piece
return;
}
//announces winner in centre square
function announceWinner(player) {
let announceCell = document.getElementById("11")
announceCell.innerHTML = `${player} wins!`
winner = player
announceCell.onclick = function () {
winner = "";
GameDOM.populate();
turnTally = 0;
whoStarts()
}
}
//announces draw in centre square
function announceDraw() {
let announceCell = document.getElementById("11")
announceCell.innerHTML = `Tie! Nobody wins.`
winner = "none"
announceCell.onclick = function () {
winner = "";
GameDOM.populate();
turnTally = 0;
whoStarts();
}
}
//Point control function
function winnerFound(player) {
player.addPoint()
updateScore(player.num, player.getScore());
announceWinner(turn);
}
//updates scoreboard display
const updateScore = (player, score) => {
const scoreDiv = document.querySelector(`.${player}-score`)
scoreDiv.innerText = score;
return;
}
//Game end state control function
function winCondition() {
if (checkWinner(GameBoard.arr, p1piece)) {
winnerFound(player1)
return;
}
else if (checkWinner(GameBoard.arr, p2piece)) {
winnerFound(player2)
return;
};
if (turnTally > 8) { //evaluates draw
announceDraw();
return;
}
};
//evaluates whether win has occurred, also used by AI for working out their best move.
function checkWinner(board, player, theory) {
const diagDownEqual = (board, player) => {
if ((board[0][0] === player) && (board[0][0] === board[1][1]) && (board[0][0] === board[2][2])) {
if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
for (let i = 0; i < 3; i++) {
let cell = document.getElementById(`${i}${i}`)
cell.classList.add(`cell-win-${player}`)
}
return true;
}
return true;
}
}
const diagUpEqual = (board, player) => {
if ((board[0][2] === player) && (board[0][2] === board[1][1]) && (board[0][2] === board[2][0])) {
if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
let cells = [];
cells.push(document.getElementById(`02`))
cells.push(document.getElementById(`11`))
cells.push(document.getElementById(`20`))
for (let i = 0; i < 3; i++) {
cells[i].classList.add(`cell-win-${player}`)
}
return true;
}
return true;
}
}
const rowEqual = function (board, player) {
const xCheck = (board, player) => board.every(val => val === player);
for (i = 0; i < board.length; i++) {
if (xCheck(board[i], player)) {
if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
for (j = 0; j < board[i].length; j++) {
let cell = document.getElementById(`${i}${j}`)
cell.classList.add(`cell-win-${player}`)
}
return true;
}
return true;
}
}
return false;
}
const columnEqual = function (board, player) {
for (let i = 0; i < board[0].length; i++) {
if ((board[0][i] === player) && (board[0][i] === board[1][i]) && (board[0][i] === board[2][i])) {
if (theory !== "yes") { //if theory = "yes", AI is calculating best move and therefore winning highlight should not be applied.
for (let j = 0; j < board[0].length; j++) {
let cell = document.getElementById(`${j}${i}`)
cell.classList.add(`cell-win-${player}`)
}
return true;
}
return true;
}
}
return false;
}
if ((diagUpEqual(board, player)) || (diagDownEqual(board, player)) || (rowEqual(board, player)) || (columnEqual(board, player))) {
return true
}
else return false;
}
//creates 2D array of available spaces to play
function emptySpace(arr) {
const freeSpaceArray = [];
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
if ((arr[i][j] != "X") && (arr[i][j] != "O")) {
freeSpaceArray.push(arr[i][j]);
}
}
}
return freeSpaceArray;
}
//minimax AI function
function minimax(newBoard, player, depth = 0) {
let availSpots = emptySpace(GameBoard.arr);
if (checkWinner(newBoard, p1piece, "yes")) {
return { score: depth - 100 };
} else if (checkWinner(newBoard, p2piece, "yes")) {
return { score: 100 - depth };
} else if (availSpots.length == 0) {
return { score: 0 };
}
let moves = [];
for (let i = 0; i < availSpots.length; i++) {
let move = {};
splitCoOrds = availSpots[i].toString().split("");
let xCoOrd = splitCoOrds[0]
let yCoOrd = splitCoOrds[1]
move.index = newBoard[xCoOrd][yCoOrd]
newBoard[xCoOrd][yCoOrd] = player
//recursive function call
if (player == p2piece) {
result = minimax(newBoard, p1piece, depth + 1);
move.score = result.score;
} else {
result = minimax(newBoard, p2piece, depth + 1);
move.score = result.score;
};
//test to reset the board position to empty depending on coordinates
let splitCoOrds2 = availSpots[i].toString().split("");
let xCoOrd2 = splitCoOrds2[0];
let yCoOrd2 = splitCoOrds2[1];
newBoard[xCoOrd2][yCoOrd2] = move.index
moves.push(move);
}
let bestMove;
if (player === p2piece) {
let bestScore = -10000;
for (let i = 0; i < moves.length; i++) {
if (moves[i].score > bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
} else {
let bestScore = 10000;
for (let i = 0; i < moves.length; i++) {
if (moves[i].score < bestScore) {
bestScore = moves[i].score;
bestMove = i;
}
}
}
return moves[bestMove];
}
//highlight cell function
board.onmouseover = function (e) {
if (e.target.className == "cell-shown") {
if (turn == p1name) {
if (player1.getPiece() == "X") {
e.target.classList.add('cell-hover-X')
} else e.target.classList.add('cell-hover-O')
}
else if ((turn == p2name) && (p2type == "human")) {
if (player2.getPiece() == "X") {
e.target.classList.add('cell-hover-X')
} else e.target.classList.add('cell-hover-O')
}
}
else return;
}
//unhighlight cell function
board.onmouseout = function (e) {
e.target.classList.remove('cell-hover-X');
e.target.classList.remove('cell-hover-O')
return;
};
})();
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T08:42:11.120",
"Id": "256751",
"Score": "0",
"Tags": [
"javascript",
"html",
"css",
"tic-tac-toe"
],
"Title": "Vanilla JS Tic Tac Toe"
}
|
256751
|
<p>My current position implies a lot of programming but I lack formal knowledge concerning how to properly code, and this is the object of my question. I believe the form of my code could be improved. As a result, here is a much simplified version of the program I am writting, that shares the same structure but is much simpler to read. I think I could realy use the opinion of people who knows python better than me.</p>
<p>Here, I define a class « geometric_shape », which can be used to calculate proporties of shapes, for exemple the area square or rectangles.</p>
<ul>
<li>The main class has two arguments, "dimensions" and "model", that is used to define the shape.</li>
<li>The different shapes are defined in the dictionnary "self.list_of_models".
<ul>
<li>The key is the name of the different possible shapes.</li>
<li>Each value is a empty subclass instance, in which we define all the parameters of a given shape, here the number of parameters that describes the shape and the function used to calculate the area.</li>
</ul>
</li>
<li>Finally, there is one method "area" that returns the area for the defined shape.</li>
</ul>
<p>The advantage is, I can easily get the properties of a given shape by calling them using the string "self.model". For example, here, I can call the number of parameters required to completely describe a shape using self.list_of_models[ self.model ].noparameters</p>
<p>The problem is that I do not feel like it is an elegant way of doing things. For exemple, if I call the object instance, I see the variable is defined in a weird way.</p>
<pre><code>self.list_of_models['square']
Out[2]: <__main__.geometric_shape.__init__.<locals>.model at 0x1dc810ea988>
</code></pre>
<p>So my question is : Would someone know a more elegant way to input a list of « shapes » than a dictionnary of object instances, or is this formulation fine the way it is ?</p>
<pre><code># -*- coding: utf-8 -*-
class geometric_shape:
''' Fonction utilitaires de spindiff, importé en tant que super classe dans spindiff'''
# ==============================================================================================
@staticmethod
def __squared__(a):
return a[0]**2
@staticmethod
def __product__(a):
return a[0]*a[1]
# ==============================================================================================
def __init__(self):
''' Create list of available models'''
self.dimensions = [1, 2 ]
self.model = 'square' # rectangle
class model :
''' Définit une classe de modèle de système dans lequel la diffusion de spin est simulée.'''
def __init__(self):
self.noparameters = 1
self.area_function = None
self.list_of_models = {
'square' : model() ,
'rectangle' : model() ,
}
# model square
self.list_of_models['square'].noparameters = 1
self.list_of_models['square'].area_function = self.__squared__
# model rectangle
self.list_of_models['rectangle'].noparameters = 2
self.list_of_models['rectangle'].area_function = self.__product__
# ==============================================================================================
def area(self):
''' Return the area of the figure '''
if len(self.dimensions) != self.list_of_models[ self.model ].noparameters:
raise ValueError('Nombre of parameters not compatible with this shape')
return self.list_of_models[ self.model ].area_function( self.dimensions )
# ==============================================================================================
if __name__ == '__main__':
square = geometric_shape()
self = square
square.dimensions = [ 3. ]
square.model = 'square'
print( square.area() )
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T09:00:26.710",
"Id": "256753",
"Score": "0",
"Tags": [
"python-3.x"
],
"Title": "How to write a dictionnary of object instances describing geometrical shapes"
}
|
256753
|
<p>Problem : Read three integers and sort them in ascending order. After, print these values in ascending order, a blank line and then the values in the sequence as they were inputted.</p>
<pre><code>input: 7 21 -14
output: -14
7
21
7
21
-14
</code></pre>
<p>I have solved this problem in this way:</p>
<pre><code>#include <stdio.h>
int main()
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
if (a < b && a < c)
{
//first smallest number identified
printf("%d\n",a);
if (b < c)
{
//second and third smallest number identified
printf("%d\n",b);
printf("%d\n",c);
printf("\n");
printf("%d\n%d\n%d\n",a,b,c);
}
else if (c < b)
{
//second and third smallest number identified
printf("%d\n",c);
printf("%d\n",b);
printf("\n");
printf("%d\n%d\n%d\n",a,b,c);
}
}
else if (b < a && b < c)
{
//first smallest number identified
printf("%d\n",b);
if (a < c)
{
//second and third smallest number identified
printf("%d\n",a);
printf("%d\n",c);
printf("\n");
printf("%d\n%d\n%d\n",a,b,c);
}
else if (c < a)
{
//second and third smallest number identified
printf("%d\n",c);
printf("%d\n",a);
printf("\n");
printf("%d\n%d\n%d\n",a,b,c);
}
}
else if (c < a && c < b)
{
//first smallest number identified
printf ("%d\n",c);
if(a < b){
//second and third smallest number identified
printf("%d\n",a);
printf("%d\n",b);
printf("\n");
printf("%d\n%d\n%d\n",a,b,c);
}
else if (b < a)
{
//second and third smallest number identified
printf("%d\n",b);
printf("%d\n",a);
printf("\n");
printf("%d\n%d\n%d\n",a,b,c);
}
}
return 0;
}
</code></pre>
<p>What I am looking for: How can I simplify my solution? Will I face any problems with some conditions? If yes, then how can I handle this?</p>
|
[] |
[
{
"body": "<p>In terms of simplifying the code it would be better to add all of the elements into an array and sort it rather than using if else statements to capture every case. I would look into the qsort library, which handles sorting for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T11:26:55.377",
"Id": "256761",
"ParentId": "256757",
"Score": "1"
}
},
{
"body": "<p>This block can be put in a function:</p>\n<pre><code> //second and third smallest number identified\n printf("%d\\n",a);\n printf("%d\\n",b);\n printf("\\n");\n printf("%d\\n%d\\n%d\\n",a,b,c);\n</code></pre>\n<p>The last line is even constant. It can be placed at the end.</p>\n<p><code>other_two()</code> works by the way which two arguments are passed.</p>\n<pre><code>#include <stdio.h>\n\nvoid other_two(int x, int y) {\n if (x < y)\n printf("2) %d\\n3) %d\\n", x, y);\n else\n printf("2) %d\\n3) %d\\n", y, x);\n}\n\nvoid main() {\n int a,b,c;\n scanf("%d %d %d",&a,&b,&c);\n\n if (a <= b && a <= c) {\n printf("1) %d\\n", a);\n other_two(b, c);\n } else if (b <= a && b <= c) {\n printf("1) %d\\n", b);\n other_two(a, c);\n } else if (c <= b && c <= a) {\n printf("1) %d\\n", c);\n other_two(a, b);\n }\n\n printf("%d\\n%d\\n%d", a, b, c);\n return;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T12:54:50.583",
"Id": "256762",
"ParentId": "256757",
"Score": "1"
}
},
{
"body": "<p><strong>Bug</strong></p>\n<p>If all 3 values are the same, nothing is printed.</p>\n<p>When 2 values are the same, some problems can occur too.</p>\n<p>Code is using <code><</code> when <code><=</code> is called for, in which case the last <code>else if (c <= a && c <= b)</code> can be simply <code>else</code>.</p>\n<p>The 3x use of code like <code>if (b < c) ... else if (c < b)</code> deserves to be <code>if (b < c) ... else</code></p>\n<hr />\n<p><strong>Redundant code</strong></p>\n<p>Below code used 6 times. Once, toward the end, is enough.</p>\n<pre><code> printf("\\n");\n printf("%d\\n%d\\n%d\\n",a,b,c);\n</code></pre>\n<hr />\n<p><strong><code>qsort()</code></strong></p>\n<p>Consider <code>qsort()</code></p>\n<pre><code>#define N 3\nint a[N];\nint b[N];\nfor (int i=0; i<N; i++) {\n if (scanf("%d", &a[i]) != 1) TBD_Code_Handle_Error();\n b[i] = a[i];\n}\nqsort(b, sizeof b[0], N, my_int_cmp);\nfor (int i=0; i<N; i++) {\n printf("%d\\n", b[i]);\n}\nfor (int i=0; i<N; i++) {\n printf("%d\\n", a[i]);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T18:22:09.013",
"Id": "256772",
"ParentId": "256757",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256772",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T10:29:52.170",
"Id": "256757",
"Score": "1",
"Tags": [
"c"
],
"Title": "Simple sort in c"
}
|
256757
|
<p>The provided code controls a 3-phase heater by generating a PWM signal (in software) which controls 3 triacs that are connected to the heater. Between the MCU (running Zephyr RTOS) and the triacs is a PCF8574 IO extender. The idea is to simply tell the heater module which percentage of power is desired.</p>
<p>Furthermore, phase-shifting is implemented to reduce big transitions in current-draw. Also the triacs should be as evenly loaded as possible such that they degrade similarly over time. This is handled in <code>PWM_Start()</code>.</p>
<p>In the code I have added <code>// CODE REVIEW COMMENT:</code> to give some context where perhaps relevant, like for Zephyr-specific things.</p>
<p>While writing this code I already had some doubts:</p>
<ol>
<li>Should I use on/off and start/stop functions, or have parameters for this?</li>
<li>Am I using the <code>ASSERTS</code> correctly or should I just check it in-code?</li>
<li>Should I prevent the timers from running in the boundary cases of 0% and 100% duty cycle? I feel like maybe it makes the code less generic for only a small benefit?</li>
<li>I should probably split the Phase-shifted PWM code to a dedicated file, but I'm afraid this will require callback functions to be called at the PWM edges. I'm struggling with the trade-off, as the PWM code is only used here at the moment.</li>
</ol>
<h2>Notes</h2>
<ol>
<li><p><code>__ASSERT</code> is <a href="https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/zephyr/reference/kernel/other/fatal.html" rel="nofollow noreferrer">provided by Zephyr</a>.</p>
</li>
<li><p><code>k_work_init()</code> <a href="https://github.com/zephyrproject-rtos/zephyr/blob/fe7c2efca800a0cf1bccf23aefe08b3c4beb88bf/include/kernel.h#L2554" rel="nofollow noreferrer">is</a>:</p>
<blockquote>
<pre><code>static inline void k_work_init(struct k_work *work, k_work_handler_t handler)
{
*work = (struct k_work)Z_WORK_INITIALIZER(handler);
}
</code></pre>
</blockquote>
</li>
<li><p><code>k_work_handler_t</code> <a href="https://github.com/zephyrproject-rtos/zephyr/blob/fe7c2efca800a0cf1bccf23aefe08b3c4beb88bf/include/kernel.h#L2479" rel="nofollow noreferrer">is</a>:</p>
<blockquote>
<pre><code>typedef void (*k_work_handler_t)(struct k_work *work);
</code></pre>
</blockquote>
</li>
</ol>
<h1>The code</h1>
<h2>Implementation .c file</h2>
<pre><code>/*********************************************************************
* INCLUDES
*/
#include <zephyr.h>
#include "heater.h"
#include "pcf8574.h"
#include <logging/log.h>
LOG_MODULE_REGISTER(Heater, LOG_LEVEL_DBG);
/*********************************************************************
* DEFINES
*/
// Time (in seconds) between phase activations
#define TIME_BETWEEN_PHASES 3
#define PWM_PERIOD (TRIAC_COUNT * TIME_BETWEEN_PHASES)
/*********************************************************************
* MACROS
*/
/*********************************************************************
* TYPEDEFS
*/
typedef struct
{
struct k_timer timer;
bool active;
}
S_TriacInfo;
typedef enum
{
TRIAC_R = 0,
TRIAC_S,
TRIAC_T,
TRIAC_COUNT,
}
E_Triacs;
typedef struct
{
struct k_work work;
E_Triacs triac;
}
S_PWMWork;
/*********************************************************************
* CONSTANTS
*/
static const E_PCF8574Ports triacToPortMapping[TRIAC_COUNT] = { PCF8574_P4, PCF8574_P5, PCF8574_P6 };
/*********************************************************************
* PUBLIC VARIABLES
*/
/*********************************************************************
* LOCAL VARIABLES
*/
static S_TriacInfo triacs[TRIAC_COUNT];
static uint8_t dutyCycle;
static S_PWMWork flipPWM;
/*********************************************************************
* LOCAL FUNCTION PROTOTYPES
*/
static void TriacTimerFxn (struct k_timer *timer);
static void FlipPWM (struct k_work *item);
static bool PWM_Start (void);
static bool PWM_StartHighCycle (E_Triacs triac);
static bool PWM_StartLowCycle (E_Triacs triac);
static bool TurnOnTriac (E_Triacs triac);
static bool TurnOffTriac (E_Triacs triac);
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void TriacTimerFxn (struct k_timer *timer)
{
for (E_Triacs triac = TRIAC_R; triac < ARRAY_SIZE(triacs); triac++)
{
if (timer == &triacs[triac].timer)
{
flipPWM.triac = triac;
k_work_submit(&flipPWM.work);
break;
}
}
}
static void FlipPWM (struct k_work *item) // CODE REVIEW COMMENT: This function follows a library typedef, it's always a void
{
S_PWMWork *pPWMWork = CONTAINER_OF(item, S_PWMWork, work);
E_Triacs triac = pPWMWork->triac;
if (triacs[triac].active)
PWM_StartLowCycle(triac);
else
PWM_StartHighCycle(triac);
}
static bool PWM_Start (void)
{
static E_Triacs currentFirstTriac = TRIAC_R;
// Start PWM cycle for the first triac
if (!PWM_StartHighCycle(currentFirstTriac))
{
LOG_ERR("Failed to start PWM");
return false;
}
// Start timers to support phase-shifting for the other triacs
for (uint8_t i = 1; i < ARRAY_SIZE(triacs); i++)
{
E_Triacs triac = (currentFirstTriac + i) % ARRAY_SIZE(triacs);
if (!TurnOffTriac(triac))
{
LOG_ERR("Failed to start PWM");
return false;
}
uint16_t timer_ms = 1000 * (triac * TIME_BETWEEN_PHASES);
k_timer_start(&triacs[triac].timer, K_MSEC(timer_ms), K_SECONDS(0));
}
currentFirstTriac = (currentFirstTriac + 1) % ARRAY_SIZE(triacs);
LOG_DBG("PWM started");
return true;
}
static bool PWM_StartHighCycle (E_Triacs triac)
{
__ASSERT(triac >= TRIAC_R &&
triac < ARRAY_SIZE(triacs),
"Invalid triac");
if (!TurnOnTriac(triac))
{
LOG_ERR("Failed to start high cycle for triac %u", triac);
return false;
}
uint16_t timer_ms = 1000 * PWM_PERIOD * dutyCycle / 100;
k_timer_start(&triacs[triac].timer, K_MSEC(timer_ms), K_SECONDS(0));
LOG_DBG("Started high cycle for triac %u (%u ms)", triac, timer_ms);
return true;
}
static bool PWM_StartLowCycle (E_Triacs triac)
{
__ASSERT(triac >= TRIAC_R &&
triac < ARRAY_SIZE(triacs),
"Invalid triac");
if (!TurnOffTriac(triac))
{
LOG_ERR("Failed to start low cycle for triac %u", triac);
return false;
}
uint16_t timer_ms = 1000 * PWM_PERIOD * (100 - dutyCycle) / 100;
k_timer_start(&triacs[triac].timer, K_MSEC(timer_ms), K_SECONDS(0));
LOG_DBG("Started low cycle for triac %u (%u ms)", triac, timer_ms);
return true;
}
static bool TurnOnTriac (E_Triacs triac)
{
__ASSERT(triac >= TRIAC_R &&
triac < ARRAY_SIZE(triacs),
"Invalid triac");
E_PCF8574Ports port = triacToPortMapping[triac];
if (!PCF8574_ConfigurePin(port, PCF8574_OUTPUT_LOW))
{
LOG_ERR("Failed to turn on triac %u", triac);
return false;
}
LOG_DBG("Turned on triac: %u", triac);
triacs[triac].active = true;
return true;
}
static bool TurnOffTriac (E_Triacs triac)
{
__ASSERT(triac >= TRIAC_R &&
triac < ARRAY_SIZE(triacs),
"Invalid triac");
E_PCF8574Ports port = triacToPortMapping[triac];
if (!PCF8574_ConfigurePin(port, PCF8574_OUTPUT_HIGH))
{
LOG_ERR("Failed to turn off triac %u", triac);
return false;
}
LOG_DBG("Turned off triac: %u", triac);
triacs[triac].active = false;
return true;
}
/*********************************************************************
* PUBLIC FUNCTIONS
*/
bool Heater_Init (void) // CODE REVIEW COMMENT: This is a bool so it follows the style of all other modules, currently there are no fault conditions
{
LOG_DBG("Initializing heater");
for (E_Triacs triac = TRIAC_R; triac < ARRAY_SIZE(triacs); triac++)
{
k_timer_init(&triacs[triac].timer, TriacTimerFxn, NULL);
triacs[triac].active = false;
}
k_work_init(&flipPWM.work, FlipPWM);
return true;
}
bool Heater_SetPower (uint8_t powerPercentage)
{
__ASSERT(powerPercentage <= 100, "Invalid power percentage");
LOG_DBG("Setting heater power: %u%%", powerPercentage);
dutyCycle = powerPercentage;
return PWM_Start();
}
</code></pre>
<h2>Header .h file</h2>
<pre><code>#ifndef HEATER_H
#define HEATER_H
/*********************************************************************
* INCLUDES
*/
#include <stdint.h>
/*********************************************************************
* DEFINES
*/
/*********************************************************************
* MACROS
*/
/*********************************************************************
* TYPEDEFS
*/
/*********************************************************************
* CONSTANTS
*/
/*********************************************************************
* PUBLIC VARIABLES
*/
/*********************************************************************
* PUBLIC FUNCTIONS
*/
bool Heater_Init (void);
bool Heater_SetPower (uint8_t powerPercentage);
#endif // HEATER_H
</code></pre>
|
[] |
[
{
"body": "<h1>Consider using Doxygen</h1>\n<p>I see you have some structured way of documenting your code using comments. However, I recommend you use <a href=\"https://www.doxygen.nl/index.html\" rel=\"nofollow noreferrer\">Doxygen</a>'s format to document your code. This ensures you still have human-readable comments documenting your code, but it also comes with tools that can generate manuals from the comments in your source code, as well as verify that you didn't forget to document all functions, parameters and variables.</p>\n<h1>Avoid macros for constants</h1>\n<p>Instead of using <code>#define</code> for constants, declare <code>static const</code> variables. The advantage is that they will have a proper type, and you avoid potential issues if you have epxressions but forgot to add parentheses (you did it correctly in your code though). So for example:</p>\n<pre><code>static const uint16_t TIME_BETWEEN_PHASES = 3;\nstatic const uint16_t PWM_PERIOD = TRIAC_COUNT * TIME_BETWEEN_PHASES;\n</code></pre>\n<h1>Don't overuse <code>enum</code>s</h1>\n<p>While <code>enum</code>s are usually good to use, there are some cases where they can be problematic. For example in this line:</p>\n<pre><code>for (E_Triacs triac = TRIAC_R; triac < ARRAY_SIZE(triacs); triac++)\n</code></pre>\n<p>Are you sure that <code>TRIAC_R</code> is the first triac? What if someone reorders the declaration of <code>E_Triacs</code>? Since you just want to iterate over all the elements of <code>triacs</code>, I would not use an <code>enum</code> for the loop iterator here, but rather a regular integer, and start at <code>0</code> explicitly:</p>\n<pre><code>for (uint16_t triac = 0; triac < ARRAY_SIZE(triacs); triac++)\n</code></pre>\n<p>Looking at the rest of the code, <code>TRIAC_S</code> and <code>TRIAC_T</code> are never used, and even <code>TRIAC_COUNT</code> is not used a lot. This tells me you are not really interested in giving each triac a symbolic name, they are just three triacs. So I would just use a regular integer:</p>\n<pre><code>enum {\n TRIAC_COUNT = 3, // So we can still use it to declare arrays\n};\n\ntypedef struct\n{\n struct k_work work;\n uint16_t triac;\n}\nS_PWMWork;\n</code></pre>\n<p>It also simplifies some of the asserts if you keep the triac number in an unsigned int, for example:</p>\n<pre><code>__ASSERT(triac >= TRIAC_R && triac < ARRAY_SIZE(triacs), "Invalid triac");\n</code></pre>\n<p>Becomes:</p>\n<pre><code>__ASSERT(triac < ARRAY_SIZE(triacs), "Invalid triac");\n</code></pre>\n<p>That assert was a bit weird anyway, since you already assumed that the triacs were numbered starting with <code>0</code> in statements like these:</p>\n<pre><code>E_Triacs triac = (currentFirstTriac + i) % ARRAY_SIZE(triacs);\n</code></pre>\n<h1>About error checking</h1>\n<p>There is a lot of error checking happening in your code. Let's look at:</p>\n<pre><code>if (!PCF8574_ConfigurePin(port, PCF8574_OUTPUT_LOW))\n</code></pre>\n<p>I am surprised by this; would setting a port low or high ever be able to fail on your MCU? And the return value of <code>PWM_StartLowCycle()</code> and <code>PWM_StartHighCycle()</code> are ignored in <code>FlipPWM()</code> anyway. What is the point of error checking if you don't do anything with the error?</p>\n<p>Either it can never fail while running (although perhaps you could do a simple one-shot test at the start of your program to ensure the pins and ports are configured correctly), in which case I would not perform these error checks, or it can fail, in which case I would add some code to address the situation. Think about what can go wrong if a triac gets stuck in the on or off position. Could it overheat? If it stops heating, could something freeze? Is there a way to get an alarm signal out to notify a human to intervene? Is there a safe mode you could go into while the problem persists?</p>\n<h1>Consider merging start/stop functions into one</h1>\n<p>Indeed, you were thinking about whether you should have separate start and stop functions versus one function that takes a parameter. Consider that a lot of the code in <code>PWM_StartHighCycle()</code> and <code>PWM_StartLowCycle()</code> is the same, so there is a lot of duplication that can be removed. The same goes for <code>TurnOnTriac()</code> and <code>TurnOffTriac()</code>. So I would indeed try to merge these functions so they look like:</p>\n<pre><code>static void PWM_StartCycle(uint16_t triac, bool high) {\n ...\n SetTriac(triac, high);\n ...\n}\n\nstatic void SetTriac(uint16_t triac, bool on) {\n ...\n}\n</code></pre>\n<p>This would also simplify <code>FlipPWN()</code>:</p>\n<pre><code>static void FlipPWM (struct k_work *item) {\n S_PWMWork *pPWMWork = CONTAINER_OF(item, S_PWMWork, work);\n E_Triacs triac = pPWMWork->triac;\n PWM_StartCycle(triac, !trias[triac].active);\n}\n</code></pre>\n<h1>Handling boundary cases</h1>\n<p>If 0% and 100% duty cycle are valid operating points, then I would ensure these are handled correctly. If you don't special case them, what would happen is that you still flip between on/off, but for example at 0% you will then still have a very small time where it is on. Could this be an issue? Would that wear out the triac or heater? It would be relatively simple to check for this situation and avoid the additional stress on the system.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T11:41:27.417",
"Id": "507136",
"Score": "1",
"body": "When changing macros to constants, it's a good idea to change the names, so that only macros are `ALL_CAPS`. That helps us maintain awareness of which identifiers don't obey the usual rules of scope."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:57:36.060",
"Id": "507427",
"Score": "0",
"body": "Strongly disagree that Doxygen can generate manuals. It can summarize all your in-source comments, but if those are verbose enough to make up the contents of a manual, you are doing something very wrong. Similarly, brief stuff like `/* this does x and then y */` are helpful inside the source but not elsewhere. Doxygen in general is abused a lot when people are too lazy to write proper documentation. I've yet to see any sufficient documentation coming out of any Doxygen project. Also, Doxygen is most definitely not a replacement for code templates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T08:02:11.323",
"Id": "507429",
"Score": "0",
"body": "\"Avoid macros for constants\" This is an embedded system. Turning macros into constants may create all kinds of problems on Harvard architectures. Also, when you have more complex equations inside constants, those need to be in the form of integer constant expressions. You cannot do `const int x=1; const int y=x+1;` in C, since in order for constants to make sense on an embedded system, they must always have static storage duration and get allocated in `.rodata`, never on the stack. This `static const uint16_t PWM_PERIOD = TRIAC_COUNT * TIME_BETWEEN_PHASES;` won't compile and is misguided."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:15:24.943",
"Id": "507482",
"Score": "0",
"body": "@Lundin About Doxygen, I'm merely pointing out that using a widely used standard to format your comments in has potential advantages. I agree you can't just document functions and call that a manual, but it does automatically generate the reference part of the manual for you. Also, you can use Doxygen formatting in your code templates, for example using `\\section` commands in each header comment, although Doxygen will already be able to split typedefs, functions, macros etc. by itself without needing that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:17:47.840",
"Id": "507483",
"Score": "0",
"body": "@Lundin As for constants: it doesn't matter if it's an embedded system or not. If you declare a `static const` (note the `static`), then compilers do not have to allocate anything in `.rodata`, and in fact they don't, see for example: https://godbolt.org/z/jKEGej. You're right about the expression not compiling though, I was probably thinking about C++'s `constexpr` constants."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T08:43:11.833",
"Id": "507562",
"Score": "0",
"body": "That would be because your example has optimization enabled, but also because AVR is some Harvard oddball architecture, where I think you need to perform various rituals to get the data into flash. Something called PROGMEM I think? I don't use AVR. On von Neumann parts it is usually sufficient to do `const` and static storage duration."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T10:48:05.597",
"Id": "256799",
"ParentId": "256758",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256799",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T10:39:08.207",
"Id": "256758",
"Score": "4",
"Tags": [
"c",
"embedded"
],
"Title": "Software-implemented Phase-shifted PWM for Heater"
}
|
256758
|
<p>I made this function to test if the content has 301 redirections.. Please can you help me optimize it better because it's too slow</p>
<pre><code>function contains_http_301_link($content, $current_site){
$pattern = '~<a(.*?)href="([^"]+)"(.*?)>~';
$links = array();
// Check if there is a url in the content
if(preg_match_all($pattern, $content, $urls)) {
foreach($urls[0] as $url){
// get external links
if ( !strpos( $url, $current_site )) { // Is an external link
$vowels = array('"' ,"<a", " ", "href", "=", ">");
$links[] = str_replace($vowels, "", $url);
}
}
}
foreach ($links as $link) {
$_headers = @get_headers($link,1);
if($_headers && strpos( $_headers[0], '301')) {
return true;
}
}
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T12:10:03.447",
"Id": "506976",
"Score": "1",
"body": "How did you isolate the performance issue to this function? What do you consider `too slow`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T13:51:43.410",
"Id": "506985",
"Score": "0",
"body": "@pacmaninbw it works in the local but it gets crashed on production website due to timeout"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T13:59:27.673",
"Id": "506989",
"Score": "2",
"body": "This title does not describe what your code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T16:15:02.783",
"Id": "506998",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/256759/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] |
[
{
"body": "<p>I have never attempted such a task, but I will assume that you entertained the cURL techniques (including <code>CURLOPT_NO_BODY</code> and <code>CURLINFO_HTTP_CODE</code>) as suggest at <a href=\"https://stackoverflow.com/q/2964834/2943403\">1</a> and <a href=\"https://stackoverflow.com/q/427203/2943403\">2</a>.</p>\n<p>As for parsing an html document, using regex may outperform a legitimate parser, but you might enjoy more accurate scaping if you use a DOM parser.</p>\n<p>Since your focus is on performance, I'll [cringe] suggest regex to parse your html.</p>\n<p>Your pattern <code>~<a(.*?)href="([^"]+)"(.*?)>~</code> uses lazy quantifiers and this can slow things down a little. Also, your <code><a(.*?)href</code> will allow the matching of <code><a data-href</code> and <code><abbr href</code> -- which is not what you intend.</p>\n<p>Your intention is to capture ONLY the url inside of the <code>href</code> attribute, so don't bother matching more than you need. You can probably get away with a wordboundary after <code>a</code> and a space before <code>href</code>, then reset the fullstring match with <code>\\K</code> to only retain the href's value. If this isn't strong enough validation, then you could add a lookahead to confirm that the opening tag is completed properly.</p>\n<ul>\n<li><code>~<a\\b.*? href="\\K[^"]+~</code> or</li>\n<li><code>~<a\\b.*? href="\\K[^"]+(?=".*?>)~</code></li>\n</ul>\n<p>Either way, your code can skip the sanitizing step. Thank goodness because <code>$vowels</code> contains data that are not all vowels.</p>\n<p><code>strpos()</code> can return <code>false</code> or <code>0</code> as the offset. This means that you must not rely on the type juggled condition using merely <code>!</code>. You must explicitly check for <code>false</code> or if you are on a php version that enjoys <code>str_contains()</code> -- that'll work.</p>\n<p>I personally condemn the use of the "stfu operator" (<code>@</code>), but because I am not familiar with this task, I'll avoid calling it an abomination.</p>\n<pre><code>function contains_http_301_link(string $content, string $current_site): bool\n{\n preg_match_all('~<a\\b.*? href="\\K[^"]+~', $content, $matches);\n foreach ($matches[0] as $url) {\n if (strpos($url, $current_site) !== false) {\n continue;\n }\n $headers = @get_headers($url, 1);\n if($headers && strpos($headers[0], '301') !== false) {\n return true;\n } \n }\n return false;\n}\n</code></pre>\n<p>I could possibly include the <code>$current_site</code> filtration into the regex but it may do more harm than good.</p>\n<hr />\n<p>If you were going to entertain (and benchmark) a DOM parser script, then perhaps use this:</p>\n<pre><code>function contains_http_301_link(string $content, string $current_site): bool\n{\n $dom = new DOMDocument; \n $dom->loadHTML($content);\n $xpath = new DOMXPath($dom);\n foreach ($xpath->query("//a[not(contains(@href, '$current_site'))]/@href") as $href) {\n $headers = @get_headers($href->nodeValue, 1);\n if($headers && strpos($headers[0], '301') !== false) {\n return true;\n } \n }\n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T13:17:04.780",
"Id": "256835",
"ParentId": "256759",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T11:06:54.360",
"Id": "256759",
"Score": "0",
"Tags": [
"performance",
"php",
"regex"
],
"Title": "function to check if anchor tags contain href attributes with 301"
}
|
256759
|
<p>I want to extract combinations of numpy arrays in that way:</p>
<pre><code>from itertools import combinations
import numpy as np
X = np.array(np.random.randn(4, 6))
combination = np.array([X[:, [i, j]] for i, j in combinations(range(X.shape[1]), 2)])
</code></pre>
<p>Is there a way to speed? My array has a shape of 200x50000.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T09:08:41.863",
"Id": "507048",
"Score": "1",
"body": "Asymptotically the answer is no. If you generate all $k$-combinations of an $n$-element universe, then any algorithm will require at least $n \\choose k$ steps because there's exactly as many elements in the output. If you want speed, your best bet might be to first consider whether you can avoid enumerating everything (i.e., is there a smarter algorithm for what you are actually doing), but if not, maybe you get small speedups that are faster than `combinations`."
}
] |
[
{
"body": "<p>I decided to use an example of shape 20x5000. For which I could reduce the time from ~58 sec to ~3 sec i.e. almost a factor of 20.</p>\n<pre><code>def combinations(arr):\n n = arr.shape[0]\n a = np.broadcast_to(arr, (n, n))\n b = np.broadcast_to(arr.reshape(-1,1), (n, n))\n upper = np.tri(n, n, -1, dtype='bool').T\n return b[upper].reshape(-1), a[upper].reshape(-1)\n\nX = np.array(np.random.randn(20,5000))\n%timeit X[:, [*combinations(np.arange(X.shape[1]))]]\n%timeit np.array([X[:, [i, j]] for i, j in itertools.combinations(range(X.shape[1]), 2)])\n</code></pre>\n<p>is giving me</p>\n<pre><code>3.2 s ± 29.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n57.8 s ± 2.35 s per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n<p>And</p>\n<pre><code>combination = np.array([X[:, [i, j]] for i, j in itertools.combinations(range(X.shape[1]), 2)])\nnp.allclose(combination, np.moveaxis(X[:, [*combinations(np.arange(X.shape[1]))]], -1, 0))\n</code></pre>\n<p>confirms I am calculating the right thing. Just the axes are ordered differently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T22:26:00.507",
"Id": "521878",
"Score": "0",
"body": "Can you explain why your code is better than the original code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T22:45:48.830",
"Id": "521880",
"Score": "0",
"body": "@pacmaninbw Sure. It's the standard `numpy` approach. You work with whole arrays at once rather than looping over individual entries. So rather than having a slow python interpreter doing the work you can hand it all to highly optimized/pre-compiled `c` or `fortran` code written by the `numpy` community."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T17:39:44.203",
"Id": "264249",
"ParentId": "256763",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T13:01:06.770",
"Id": "256763",
"Score": "0",
"Tags": [
"python",
"performance",
"numpy",
"combinatorics"
],
"Title": "Fast bruth force numpy array combination"
}
|
256763
|
<p>I am a beginner coder and SonarLint tells me code is too complex. I tried recursion, iterators, slicing but had not luck making this code any simpler.</p>
<p>The code will parse the input string to detect the following categories:</p>
<ul>
<li>bold</li>
<li>italic</li>
<li>normal</li>
</ul>
<p>depending on whether the characters are enclosed in 0-2 asterisks.</p>
<p>Sorry for the short description luckily, Iterniam inferred correctly. And side note nested <code>**Bold *and* italic**</code> are not supported by the code. I will read more on Iterniam's answer thank you for that!</p>
<p>Maybe a philosophical question at last, even though cyclomatic complexity in my code is higher the regex answer, the proposed solution is still much harder to understand (if it were not for the comments), debug and has worse performance. So is it the better code or should I just ignore cyclomatic complexity hints in the future?</p>
<pre><code>txt = "A **A** is *italic* **bold** but some are *a* *b* **B**"
def fun(text=None):
if text:
bold_splits = text.split('**')
for i, s in enumerate(bold_splits):
if i % 2:
print('BOLD:', s )
else:
italic_splits = s.split('*')
for m, n in enumerate(italic_splits):
if m % 2:
print('ITALIC:', n )
else:
if n != '':
print('NORMAL:', n )
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T15:42:41.633",
"Id": "506996",
"Score": "4",
"body": "We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T18:07:24.707",
"Id": "507008",
"Score": "2",
"body": "By \"too complex\", they're likely referring to \"cyclomatic complexity\". If that's the case, it means essentially that your code is too deeply nested, which is leading to too many independent paths of execution within the function. Some code (like the inner loop) can be factored out into its own function for starters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T18:23:37.347",
"Id": "507010",
"Score": "1",
"body": "Is nesting supposed to be supported? `\"For example: **Bold text with *Italics* embedded inside**.\"`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T12:44:32.663",
"Id": "507234",
"Score": "0",
"body": "The code complexity can be reduced by breaking the solution into functions. Check out the [Single Responsibility Principle](https://en.wikipedia.org/wiki/Single_responsibility_principle)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:21:03.210",
"Id": "507287",
"Score": "0",
"body": "[`the proposed solution is still much harder to understand, debug…`](https://codereview.stackexchange.com/a/256770/93149) this entirely depends on internalisation of *regular expression implementations* - once mastered, [Iterniam](https://codereview.stackexchange.com/users/238507/iterniam)'s proposition is obvious, if excellently crafted."
}
] |
[
{
"body": "<p>It looks like you're trying to extract information from a string. This is most often done through regexes as they are often faster than your own code while being less complex.</p>\n<p>Because as of writing, you have no clear description of your goal, I'm inferring these assumptions from your code:</p>\n<ul>\n<li>You want to split every sequence of characters in your string in one of the categories bold, italic and normal, determined by the characters being enclosed in 2, 1 or 0 asterisks.</li>\n<li>You want to preserve the order of the original string.</li>\n</ul>\n<p>If we disallow asterisks in the normal text, a regex for this is rather simple. I recommend exploring what it does on <a href=\"https://regex101.com/r/Wb8Hd0/3\" rel=\"nofollow noreferrer\">regex101</a>.</p>\n<pre><code>\\*\\*(?P<bold>.+?)\\*\\*|\\*(?P<italic>.+?)\\*|(?P<normal>[^*]+)\n</code></pre>\n<p>Notably, the <code>|</code> character matches on the first match it finds, from left to right, meaning that a match will always try to match bold, then italic, then normal.</p>\n<p>In Python, we can iterate over all the matches using <code>re.finditer</code>. For every <code>match</code>, <code>lastgroup</code> will return the name of the captured group, so we can use that in our print statement and also use it to get the actual match that we're interested in.</p>\n<pre><code>def fun(text=None):\n if text:\n for match in re.finditer(r'\\*\\*(?P<bold>.+?)\\*\\*|' # match bold lazily\n r'\\*(?P<italic>.+?)\\*|' # match italics lazily\n r'(?P<normal>[^*]+)', # match normal greedily\n text):\n print(f'{match.lastgroup.upper()}: {match.group(match.lastgroup)}')\n</code></pre>\n<p>It should be noted that if the function is called plenty of times and performance is of concern, you should compile the regex once before using it in <code>fun</code>.</p>\n<p>The regex used in this example is very primitive because you haven't specified your constraints or even what the function is meant to do. By specifying your question better and explaining how edge cases like <code>** a **</code> <code>***</code> and <code>**ab*cd**</code> should behave, a more complete answer can be given.</p>\n<p>Everything below this is in response to your 'philosophical question':</p>\n<blockquote>\n<p>The regex answer [...] has worse performance.</p>\n</blockquote>\n<p>I did some testing using <code>timeit</code> on the original string (multiplied in size anywhere between 0-3000 times) on differing number of runs and found that the regex approach is consistently 1.5 times faster than the original solution as long as the print statements are included.<br />\nBecause printing it is unlikely to be your actual use-case, I modified both functions to return a tuple of all bold, italic and normal matches. I was surprised to find that your code is generally twice as fast.</p>\n<blockquote>\n<p>The proposed solution is still much harder to understand (if it were not for the comments).</p>\n</blockquote>\n<p>The comments are exactly what make the regex a relatively readable solution compared to yours. By commenting what the individual parts do, someone that needs to use the code can quickly see what the code achieves. The cost is that it may require more time to figure out how the code works.</p>\n<p>Note that this extra cost also diminishes as you get more experience. For some, figuring out how your code achieves its goal is more difficult than understanding the regex. Regexes are very powerful, quite popular, and are used in many languages. This means that when one encounters a regex construct they know what to look for and how to read it. Your solution, meanwhile, is based on a few implicit assumptions like "every other string from the split is the thing we want to match". Someone that reads your code has to discover these assumptions because they're not explicitly written down.</p>\n<blockquote>\n<p>The proposed solution is still much harder to [...] debug.</p>\n</blockquote>\n<p>If nothing else, it's easy to pinpoint where the issue if there is one: in the regex. Given the input, it shouldn't be hard to figure out why the regex is failing if you inspect it using a tool like regex101. It may be difficult to correct the regex, but at least you won't have a scavenger hunt for where your bug is.</p>\n<blockquote>\n<p>Should I just ignore cyclomatic complexity hints in the future?</p>\n</blockquote>\n<p>Avoiding a high cyclomatic complexity mostly comes down to avoiding nesting a little more. This ensures that you have a more linear (and therefore more comprehensible) flow to your code.</p>\n<p>The algorithm you used requires quite a bit of nesting which is not readily avoidable. You can, however, make some improvements by using the <code>if</code> as a guard. Using list comprehension, you can also eliminate the final <code>for-if-else</code> loop.</p>\n<pre><code>def fun_unnested_order(text=None):\n if not text:\n return None\n\n res = []\n bold_splits = text.split('**') # Odd entries are bold, even entries are italicized or normal.\n for i, s in enumerate(bold_splits):\n if i % 2 == 1: # Store bold\n res.append((s, 'bold'))\n else:\n italic_splits = s.split('*') # Odd entries are italicized, rest normal.\n # Replace the for-if-else loop with list comprehension\n res += [(e, 'italic') if i % 2 == 1 else (e, 'normal')\n for i, e in enumerate(italic_splits)]\n return res\n</code></pre>\n<p>This example is 30% slower than your original code using the same <code>timeit</code> setup.</p>\n<blockquote>\n<p>So is it the better code?</p>\n</blockquote>\n<p>It depends on your viewpoint. If performance is of concern, you should go for greybeard's <a href=\"https://codereview.stackexchange.com/a/256882\">answer</a> as it is around 30% faster than your original code.<br />\nIf readability is of concern, I would take the regex version any day of the week. While many may consider regexes black magic, it is widely applicable to many problems in most if not all popular languages. Most crucially perhaps, <strong>the regex solution doesn't require a complex algorithm</strong>, which means it's easier to develop and less error-prone.<br />\nAgain, in terms of readability, it's about the familiarity of the programmer. If you are unfamiliar with regexes, list comprehensions and/or list slicing, your original version is the option to go for.</p>\n<p>In the end, there is no one implementation that wins across all categories. You should familiarize yourself with the different ways to approach the problem and then tackle it in a way you deem the best solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T17:07:45.760",
"Id": "507003",
"Score": "0",
"body": "FWIW to support `**ab*cd**` you can change bold's `[^*]+` to `.+?`. We can do the same for italic, but currently nothing would change. IMO non-greedy searches are normally more helpful here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T17:55:57.397",
"Id": "507006",
"Score": "0",
"body": "@Peilonrayz I've edited the post to include your suggestion as it is indeed cleaner, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T21:57:44.250",
"Id": "507030",
"Score": "0",
"body": "From the [documentation](https://docs.python.org/3.8/library/re.html#regular-expression-syntax) \"REs separated by '|' are tried from left to right. When one pattern completely matches, that branch is accepted. This means that once A matches, B will not be tested further, even if it would produce a longer overall match. In other words, the '|' operator is never greedy.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T19:30:04.490",
"Id": "507091",
"Score": "0",
"body": "@RootTwo I corrected it in the post. I originally tested matching `aba|aabaa` against `aabaa`, which matches the latter, which led me to conclude that the longest match was used. Instead, it appears to be because `aabaa` occurs earlier in the string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T11:39:13.583",
"Id": "507319",
"Score": "1",
"body": "@Iterniam Thank you for taking the time, you really helped me a lot. I guess readability comes down to what you are used to and I agree with you about debugging my code has more implicit assumptions. My only nitpick is the last solution would be the help I was looking for, if it would preserve the order. I tried playing with enumerate but could not find anything \"more\" elegant than the original."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T21:10:11.923",
"Id": "507398",
"Score": "0",
"body": "@new_here6432 Happy to help! I redid the final algorithm and the text after that to provide an 'unnesting' of your code that preserves order. The list comprehension is not as clean as I hoped for, and I'm not sure if I would use that myself, but it's something to consider."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T21:13:40.680",
"Id": "507519",
"Score": "0",
"body": "Beautiful, thank you for another solution to study. It is funny how seemingly simple problems require so much effort to solve elegantly."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T16:54:51.430",
"Id": "256770",
"ParentId": "256765",
"Score": "4"
}
},
{
"body": "<p>A tool telling how complex code is.<br />\n<em>Cyclomatic complexity</em>, at that.</p>\n<p>Take a somewhat deep breath - or sigh.<br />\nOmission of <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstring</a>s, renaming and comments in the following is intentional:</p>\n<pre><code>def fun(text=None):\n if not text:\n return\n splits = text.split('*')\n bold = text[0] == '*'\n italics = True\n for s in splits:\n italics = not italics\n if s:\n category = 'BOLD:' if bold \\\n else 'ITALIC:' if italics \\\n else 'NORMAL:'\n print(category+s+'#')\n else:\n bold = not bold\n</code></pre>\n<p>What is your assessment of relative complexity, what is the tool's?<br />\n(Well, there <em>is</em> something to take away:<br />\n returning from a method early does not only reduce statement nesting&indentation level:<br />\n I find it simpler to think about the resultant code.<br />\n Same for leaving the current loop iteration early via <code>continue</code> or <code>break</code>.)<br />\n(p.s. Do you <em>believe</em> the above works? (Do I?))</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T11:49:07.120",
"Id": "507320",
"Score": "1",
"body": "I am not sure if this is the point you wanted to make, but I think this code is awesome! I definitely play with this solution. More to your point, SonarLint has an easier time telling a lot of indentations mean high code complexity, whereas this seems far more complex. Good point!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T17:24:56.093",
"Id": "256882",
"ParentId": "256765",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256770",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T14:54:46.560",
"Id": "256765",
"Score": "3",
"Tags": [
"python",
"strings",
"parsing"
],
"Title": "Parse sequence of characters detecting formatting categories"
}
|
256765
|
<p>I'm new to data science. I wrote this script for plotting all different kinds of iris data set scatter plot. trying not to plot something with itself . how can I optimize my code ?</p>
<pre class="lang-py prettyprint-override"><code>
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
iris=load_iris()
list1=[]
fig, ax =plt.subplots(nrows=3,ncols=2,figsize=(10,10))
for ii in range(4):
for jj in range(1,4):
if ii==jj:
break
if ii*jj not in list1[1::2]:
list1.extend((ii+jj,ii*jj))
elif ii+jj in list1[::2]:
break
a=ii
b=jj
x_index=ii
y_index=jj
colors=['blue','red','green']
if ii==0:
b=b-1
elif jj==1:
a=a-2
b,a=a,b
elif ii==3:
a=a-1
b=b-1
a,b=b,a
for label , color in zip(range(len(iris.target_names)),colors):
ax[b,a].scatter(iris.data[iris.target==label,x_index]
, iris.data[iris.target==label,y_index]
, label=iris.target_names[label]
, color=color)
ax[b,a].set_xlabel(iris.feature_names[x_index])
ax[b,a].set_ylabel(iris.feature_names[y_index])
ax[b,a].legend(loc="upper right")
fig.tight_layout()
fig.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/cqfkJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cqfkJ.png" alt="enter image description here" /></a>
this is the output</p>
<p>how would you write it if it was you?</p>
<p>I appreciate any help.</p>
|
[] |
[
{
"body": "<p>Two remarks on your code:</p>\n<ul>\n<li><p>There seems to be an indentation error in your code, everything before your first for loop has too much indentation.</p>\n</li>\n<li><p>In general, it is a good idea to use telling names for variables. For example, <code>column</code> and <code>row</code> instead of <code>a</code> and <code>b</code>.</p>\n</li>\n</ul>\n<p>Following is my version of the code. It is not an exact reproduction of your plot, but the way I would approach an analysis like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from sklearn.datasets import load_iris\nimport pandas as pd\nimport seaborn as sns\n\niris = load_iris()\n\n# convert dataset to pandas DataFrame\niris_df = pd.DataFrame(iris['data'])\niris_df.columns = iris['feature_names']\niris_df['species'] = iris['target']\niris_df['species'] = iris_df['species'].replace([0, 1, 2], iris['target_names'])\n\n# alternative: load dataset from seaborn library (they use slightly different column names)\n# iris_df = sns.load_dataset('iris')\n\nsns.pairplot(data=iris_df, corner=True, hue='species')\n</code></pre>\n<p>This produces the following plot:\n<a href=\"https://i.stack.imgur.com/ItDxs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ItDxs.png\" alt=\"enter image description here\" /></a></p>\n<p>As you can see, the code has become much shorter and the resulting figure still contains all the plots you wanted (plus a few extra ones). Great thing about using pandas and other related libraries (e.g., seaborn) is that you can often write very compact code (e.g., by getting rid of many for loops).</p>\n<p>First, I converted the iris dataset to a pandas <code>DataFrame</code> (<a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html\" rel=\"nofollow noreferrer\">documentation</a>). A <code>DataFrame</code> is the main data type in pandas and makes analysis and processing of your data much easier. As shown in the code, there is an alternative way of loading the iris dataset into python using the seaborn library (<code>sns.load_dataset('iris')</code>) This will give you the dataset directly as a <code>DataFrame</code>, no more need to convert it.</p>\n<p>Then, I call <code>pairplot</code> from the seaborn library. seaborn is a plotting library based on matplotlib that works with <code>DataFrame</code> objects. It has a high-level interface, meaning you can produce complex plots such as the one you see with often a few lines of code.</p>\n<hr />\n<p>I just found out that pandas already has a very similar plot function, check out <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.plotting.scatter_matrix.html\" rel=\"nofollow noreferrer\">scatter_matrix</a>. So you don't necessarily need to use seaborn (even though it's a great library and I recommend it).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T23:30:38.053",
"Id": "256945",
"ParentId": "256766",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256945",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T14:57:14.527",
"Id": "256766",
"Score": "0",
"Tags": [
"python",
"performance",
"matplotlib"
],
"Title": "scatter subplot for iris dataset"
}
|
256766
|
<p>I have this class representing a period of time:</p>
<pre><code> public class Period
{
public Period(DateTime dateFrom)
{
DateFrom = dateFrom;
}
public Period(DateTime dateFrom, DateTime? dateTo)
{
DateFrom = dateFrom;
DateTo = dateTo;
}
public DateTime DateFrom { get; set; }
public DateTime? DateTo { get; set; }
public bool IsOverlapping(Period other)
{
if (!DateTo.HasValue)
{
return DateFrom <= other.DateTo.Value;
}
if (!other.DateTo.HasValue)
{
return other.DateFrom <= DateTo.Value;
}
return DateFrom <= other.DateTo.Value && other.DateFrom <= DateTo.Value;
}
public bool IsFinite => DateTo.HasValue;
public bool IsInfinite => !IsFinite;
protected bool Equals(Period other)
{
return DateFrom.Equals(other.DateFrom) && Nullable.Equals(DateTo, other.DateTo);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Period) obj);
}
public override int GetHashCode()
{
return HashCode.Combine(DateFrom, DateTo);
}
}
</code></pre>
<p>Now a have a list of periods and for each of them I have to perform an network call so to minimize them I decide to merge all overlapping periods.</p>
<p>So a list like that :</p>
<ul>
<li>2020-01-01 -> 2020-01-10</li>
<li>2020-02-05 -> 2020-02-10</li>
<li>2020-02-07 -> 2020-02-15</li>
<li>2020-02-13 -> 2020-02-20</li>
<li>2020-03-01 -> 2020-03-10</li>
<li>2020-03-25 -> 2020-03-31</li>
<li>2020-03-30 -></li>
</ul>
<p>Should become :</p>
<ul>
<li>2020-01-01 -> 2020-01-10</li>
<li>2020-02-05 -> 2020-02-20</li>
<li>2020-03-01 -> 2020-03-10</li>
<li>2020-03-25 -></li>
</ul>
<p>I tried this code</p>
<pre><code> public static IEnumerable<Period> Implementation(IEnumerable<Period> periods)
{
return periods.OrderBy(p => p.DateFrom)
.Aggregate(new List<Period>(), (ps, p) =>
{
if (!ps.Any())
{
ps.Add(p);
return ps;
}
var last = ps.Last();
if (last.IsOverlapping(p))
{
if (last.IsInfinite || p.IsInfinite)
{
ps[ps.Count() - 1] = new Period(DateTimeHelpers.Min(last.DateFrom, p.DateFrom), null);
}
else
{
ps[ps.Count() - 1] = new Period(DateTimeHelpers.Min(last.DateFrom, p.DateFrom),
DateTimeHelpers.Max(last.DateTo.Value, p.DateTo.Value));
}
return ps;
}
ps.Add(p);
return ps;
});
}
</code></pre>
<p>Here is the DateTimeHelpers I'm using :</p>
<pre><code>public class DateTimeHelpers
{
public static DateTime Max(DateTime first, DateTime second)
{
return first <= second
? second
: first;
}
public static DateTime Min(DateTime first, DateTime second)
{
return first >= second
? second
: first;
}
}
</code></pre>
<p>It's working properly but I'm not satisfied with it so I wonder if there is a more performant/elegant/readable way to do it ?</p>
<p>I'm not talking about just refactoring to extract some methods but a fundamentally different solution, it's possible I missed a useful LINQ operator.</p>
<p>Here is my test if you want to reproduce it (MsTest + FluentAssertions). The period are not in the right order to ensure it will be take care of by the method itself:</p>
<pre><code> // Arrange
var periods = new List<Period>()
{
new Period(new DateTime(2020, 2, 13), new DateTime(2020, 2, 20)),
new Period(new DateTime(2020, 3, 1), new DateTime(2020, 3, 10)),
new Period(new DateTime(2020, 3, 25), new DateTime(2020, 3, 31)),
new Period(new DateTime(2020, 3, 30)),
new Period(new DateTime(2020, 1, 1), new DateTime(2020, 1, 10)),
new Period(new DateTime(2020, 2, 5), new DateTime(2020, 2, 10)),
new Period(new DateTime(2020, 2, 7), new DateTime(2020, 2, 15))
};
// Act
var mergedPeriods = Implementation(periods);
// Assert
mergedPeriods.Should().HaveCount(4);
mergedPeriods[0].Should().Be(new Period(new DateTime(2020, 1, 1), new DateTime(2020, 1, 10)));
mergedPeriods[1].Should().Be(new Period(new DateTime(2020, 2, 5), new DateTime(2020, 2, 20)));
mergedPeriods[2].Should().Be(new Period(new DateTime(2020, 3, 1), new DateTime(2020, 3, 10)));
mergedPeriods[3].Should().Be(new Period(new DateTime(2020, 3, 25)));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T18:24:28.263",
"Id": "507011",
"Score": "0",
"body": "I voted to close as the `Period` class, as presented, doesn't compile and therefore can't be reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T18:28:30.113",
"Id": "507012",
"Score": "1",
"body": "Well... For this example I made the DateFrom not nullable and I forgot to remove the \".Value\" in the code. It's maybe a bit excessive to say the code can't be reviewed...\nI will update it to also provide the Equals/GetHashCode I guess..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T18:33:29.257",
"Id": "507013",
"Score": "1",
"body": "I will remove my close vote now that it has been updated to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T12:19:37.593",
"Id": "507324",
"Score": "0",
"body": "Your `Aggreate` still does not compile: `DateFrom` does not have `Value`. Please also indicate which `DateTimeHelpers` nuget package are you using."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T17:28:37.710",
"Id": "507372",
"Score": "1",
"body": "I remove the .Value (...) and add my helpers implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T07:44:10.557",
"Id": "525490",
"Score": "0",
"body": "Is there really a reason to want better performance? We all want that, but if performance is good enough there's not need to make it better, which often means that readability is \nsacrificed for all kinds of ugly premature optimizations."
}
] |
[
{
"body": "<p>Here are my observations:</p>\n<h3><code>Period</code></h3>\n<ul>\n<li><code>public Period(DateTime dateFrom)</code>: Do not repeat yourself. Just call the other ctor:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public Period(DateTime dateFrom) \n : this(dateFrom, null)\n{ }\n</code></pre>\n<ul>\n<li><code>public DateTime DateFrom { get; set; }</code>: Because you have a ctor, where you specify its value that's why you don't need public setter:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public DateTime DateFrom { get; }\npublic DateTime? DateTo { get; }\n</code></pre>\n<ul>\n<li><code>return DateFrom <= other.DateTo.Value;</code>: <code>other.DateTo</code> can be null, so this could result an <code>InvalidOperationException</code>. Include null check as well:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>if (!DateTo.HasValue)\n{\n return other.DateTo != null && DateFrom <= other.DateTo.Value;\n}\n</code></pre>\n<ul>\n<li><code>IsFinite</code>: It is used only by the <code>IsInfinite</code>, so you could merge them:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public bool IsInfinite => !DateTo.HasValue;\n</code></pre>\n<ul>\n<li><code>Equals</code> and <code>GetHashCode</code>: The default ones are good, you don't need to override them.</li>\n</ul>\n<p>So, the <code>Period</code> class after refactor:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Period\n{\n public Period(DateTime dateFrom)\n : this(dateFrom, null)\n { }\n\n public Period(DateTime dateFrom, DateTime? dateTo)\n {\n DateFrom = dateFrom;\n DateTo = dateTo;\n }\n\n public DateTime DateFrom { get; }\n public DateTime? DateTo { get; }\n\n public bool IsOverlapping(Period other)\n {\n if (!DateTo.HasValue)\n {\n return other.DateTo != null && DateFrom <= other.DateTo.Value;\n }\n\n if (!other.DateTo.HasValue)\n {\n return other.DateFrom <= DateTo.Value;\n }\n\n return DateFrom <= other.DateTo.Value && other.DateFrom <= DateTo.Value;\n }\n\n public bool IsInfinite => !DateTo.HasValue;\n}\n</code></pre>\n<hr />\n<h3><code>DateTimeHelpers</code></h3>\n<ul>\n<li><code>Min</code>: I think the <code>GetEarlier</code> name would be more expressive. Also you can easily modify it to become an extension method:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public static DateTime GetEarlier(this DateTime first, DateTime second)\n => first >= second ? second : first;\n</code></pre>\n<ul>\n<li><code>Max</code> It is used against <code>DateTo</code> properties. So, I would suggest to rename it to <code>GetLater</code> and use <code>DateTime?</code> instead of <code>DateTime</code>:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public static DateTime? GetLater(this DateTime? first, DateTime? second)\n => first <= second ? second : first;\n</code></pre>\n<ul>\n<li><code>Implementation</code>: This name is way too generic. I would suggest to change it to be an extension method and name it like <code>Merge</code> or <code>Consolidate</code> or whatver:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public static IReadOnlyCollection<Period> Merge(this IEnumerable<Period> periods)\n{\n\n}\n</code></pre>\n<ul>\n<li>When they are not overlapping: I would suggest to handle that case right after the empty collection case. With this approach you have to early exits inside the Aggregator</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>periods\n .OrderBy(period => period.DateFrom)\n .Aggregate(new List<Period>(),\n (mergedPeriods, period) =>\n {\n if (!mergedPeriods.Any())\n {\n mergedPeriods.Add(period);\n return mergedPeriods;\n }\n\n var latest = mergedPeriods.Last();\n if (!latest.IsOverlapping(period))\n {\n mergedPeriods.Add(period);\n return mergedPeriods;\n }\n \n //When overlapping\n });\n</code></pre>\n<ul>\n<li>When they are overlapping: Here you have several repeated commands The repetition can be refactored like this:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime from = latest.DateFrom.GetEarlier(period.DateFrom);\nDateTime? to = null;\nif (!latest.IsInfinite && !period.IsInfinite)\n{\n to = latest.DateTo.GetLater(period.DateTo);\n}\n\nmergedPeriods[^1] = new Period(from, to);\nreturn mergedPeriods;\n</code></pre>\n<ul>\n<li>Instead of calculating the <code>from</code> in both cases here we calculate only once</li>\n<li>Instead of accessing the last element in both cases here we access it only once\n<ul>\n<li>We use here <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges#systemindex\" rel=\"nofollow noreferrer\">C# 8's new syntax</a>: <code>[^1]</code></li>\n</ul>\n</li>\n<li>Instead of calling the ctor in both cases here we call it only once</li>\n<li>Instead of having two branches now can handle the special case with a single branch</li>\n</ul>\n<p>So, the <code>Helper</code> class after refactor:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class Helpers\n{\n public static DateTime GetEarlier(this DateTime first, DateTime second)\n => first >= second ? second : first;\n\n public static DateTime? GetLater(this DateTime? first, DateTime? second)\n => first <= second ? second : first;\n\n public static IReadOnlyCollection<Period> Merge(this IEnumerable<Period> periods)\n => periods\n .OrderBy(period => period.DateFrom)\n .Aggregate(new List<Period>(),\n (mergedPeriods, period) =>\n {\n if (!mergedPeriods.Any())\n {\n mergedPeriods.Add(period);\n return mergedPeriods;\n }\n\n var latest = mergedPeriods.Last();\n if (!latest.IsOverlapping(period))\n {\n mergedPeriods.Add(period);\n return mergedPeriods;\n }\n\n DateTime from = latest.DateFrom.GetEarlier(period.DateFrom);\n DateTime? to = null;\n if (!latest.IsInfinite && !period.IsInfinite)\n {\n to = latest.DateTo.GetLater(period.DateTo);\n }\n\n mergedPeriods[^1] = new Period(from, to);\n return mergedPeriods;\n });\n}\n</code></pre>\n<hr />\n<h3>Usage is this simple</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var period in periods.Merge())\n{\n Console.WriteLine($"{period.DateFrom:M} => {period.DateTo:M}");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T09:01:56.310",
"Id": "256959",
"ParentId": "256771",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T16:59:21.707",
"Id": "256771",
"Score": "0",
"Tags": [
"c#",
"linq"
],
"Title": "Linq query to merge overlapping elements"
}
|
256771
|
<p>I really need a more accurate way to size inf_string. This code works but gets exponentially more inefficient the bigger max(queries) is, and therefore just can't hold up to the gargantuan numbers that CSES throws into it.</p>
<p>Problem:
Consider an infinite string that consists of all positive integers in increasing order:
12345678910111213141516171819202122232425...
Your task is to process q queries of the form: what is the digit at position k in the string?
The first input line has an integer q: the number of queries.
After this, there are q lines that describe the queries. Each line has an integer k: a 1-indexed position in the string. For each query, print the corresponding digit.</p>
<pre><code>queries = []
for i in range(int(input())):
queries.append(int(input()))
# TODO FIND A BETTER WAY TO LIMIT inf_string LENGTH
inf_string = [str(x) for x in range(1, max(queries)+1)]
inf_string = "".join(inf_string)
for k in queries:
print(inf_string[k-1])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T19:35:29.250",
"Id": "507017",
"Score": "2",
"body": "What are the bounds for \\$q\\$ and \\$k\\$?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T20:19:48.947",
"Id": "507022",
"Score": "0",
"body": "1≤q≤1000\n1≤k≤10^18 @Peilonrayz"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T03:57:02.973",
"Id": "507039",
"Score": "1",
"body": "Why don't you give us the link?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T01:59:35.227",
"Id": "507102",
"Score": "1",
"body": "this is http://oeis.org/A033307"
}
] |
[
{
"body": "<p>You need to identify a pattern.\nWe should be able to build a fairly simple pattern by grouping numbers in specific ways.</p>\n<pre><code>123456789 # One dimensional\n 10111213141516171819 # Two dimensional\n 20212223242526272829\n 30313233343536373839\n ...\n 90919293949596979899\n 100101102103104105106107108109 200201202203204205206207208209 # Three dimensional\n 110111112113114115116117118119\n 120121122123124125126127128129\n ...\n 190191192193194195196197198199\n 1000100110021003100410051006100710081009 # Four dimensional\n</code></pre>\n<ol>\n<li><p>We know if <span class=\"math-container\">\\$k\\$</span> is less than 10 the value is <span class=\"math-container\">\\$k\\$</span>.\nTo see the pattern look at the one dimensional group and see the index where each number belongs.\nWe can see each digit has only one possible position.</p>\n<ul>\n<li><span class=\"math-container\">\\$k \\in \\{1\\} \\therefore 1\\$</span><br />\n(if <span class=\"math-container\">\\$k = 1\\$</span> then the digit is 1)</li>\n<li><span class=\"math-container\">\\$k \\in \\{2\\} \\therefore 2\\$</span><br />\n(if <span class=\"math-container\">\\$k = 2\\$</span> then the digit is 2)</li>\n</ul>\n<p><span class=\"math-container\">$$\nf_1(k) = k\n$$</span></p>\n</li>\n<li><p>To make the pattern easier to see <span class=\"math-container\">\\$k_2 = k - 10\\$</span>.<br />\nNow <span class=\"math-container\">\\$f_2(0) = 1\\$</span>, <span class=\"math-container\">\\$f_2(1) = 0\\$</span>, <span class=\"math-container\">\\$f_2(2) = 1\\$</span>, <span class=\"math-container\">\\$f_2(3) = 1\\$</span>.</p>\n<p>If we focus on how to build each section of the number we can see similar patterns.\nFor example the end digit is 0 in the 2nd column in the entire two dimensional block.\nSince we know the width of the two dimensional block is 20 we know every <span class=\"math-container\">\\$20n + 1\\$</span> number results in 0.</p>\n<ul>\n<li><p>End digits (Odd numbers, <span class=\"math-container\">\\$k_2\\ \\%\\ 2 = 1\\$</span>)</p>\n<p>Just like we did for 0 we can look at every second column and see the value repeats all the way down.</p>\n<ul>\n<li><span class=\"math-container\">\\$k_2 \\in \\{1, 21, 41, ..., 161\\} \\therefore 0\\$</span><br />\n(if <span class=\"math-container\">\\$k_2 = 1\\$</span> or <span class=\"math-container\">\\$k_2 = 21\\$</span> or etc, the digit is 0)</li>\n<li><span class=\"math-container\">\\$k_2 \\in \\{3, 23, 43, ..., 163\\} \\therefore 1\\$</span></li>\n<li><span class=\"math-container\">\\$k_2 \\in \\{5, 25, 45, ..., 165\\} \\therefore 2\\$</span></li>\n</ul>\n<p>We can then calculate the digit from the input number.\nFirst we can modulo the number, <span class=\"math-container\">\\$k_2 % 20\\$</span>, to truncate each of the sets to the same number.\nFor example <span class=\"math-container\">\\$21 \\% 20 = 1\\$</span>, <span class=\"math-container\">\\$41 \\% 20 = 1\\$</span>, etc.\nNow the sets are much simpler.</p>\n<ul>\n<li><span class=\"math-container\">\\$k_2\\ \\%\\ 20 \\in \\{1\\} \\therefore 0\\$</span><br />\n(if <span class=\"math-container\">\\$k_2\\ \\%\\ 20 = 1\\$</span> the digit is 0)</li>\n<li><span class=\"math-container\">\\$k_2\\ \\%\\ 20 \\in \\{3\\} \\therefore 1\\$</span></li>\n<li><span class=\"math-container\">\\$k_2\\ \\%\\ 20 \\in \\{5\\} \\therefore 2\\$</span></li>\n</ul>\n<p>Now getting the same digit for each input is <em>really</em> easy.\nWe can just floor divide by 2.\nSince <span class=\"math-container\">\\$\\lfloor\\frac{1}{2}\\rfloor = 0\\$</span>, <span class=\"math-container\">\\$\\lfloor\\frac{3}{2}\\rfloor = 1\\$</span>, etc.</p>\n<p>So we know if the number is odd we can get the digit by using the following formula:</p>\n<p><span class=\"math-container\">$$\\lfloor\\frac{k_2\\ \\%\\ 20}{2}\\rfloor$$</span></p>\n</li>\n<li><p>Head digits (Even numbers, <span class=\"math-container\">\\$k_2\\ \\%\\ 2 = 0\\$</span>)</p>\n<p>Just like we did for the columns we can see a pattern in the rows.\nEvery two columns the first number is the same.\nWe can build the sets for where each number is.</p>\n<ul>\n<li><span class=\"math-container\">\\$k_2 \\in \\{ 0, 2, 4, ..., 18\\} \\therefore 1\\$</span></li>\n<li><span class=\"math-container\">\\$k_2 \\in \\{20, 22, 24, ..., 38\\} \\therefore 2\\$</span></li>\n<li><span class=\"math-container\">\\$k_2 \\in \\{40, 42, 44, ..., 58\\} \\therefore 3\\$</span></li>\n</ul>\n<p>We can see any less than 20 are 1, then any less than 40 are 2.\nWe can floor divide by 20 and add 1.\nAnd so the formula is:</p>\n<p><span class=\"math-container\">$$\\lfloor\\frac{k_2}{20}\\rfloor + 1$$</span></p>\n</li>\n</ul>\n<p>We can merge both the previous functions into one function.</p>\n<p><span class=\"math-container\">$$\nf_2(k_2) =\n\\begin{cases}\n\\lfloor\\frac{k_2}{20}\\rfloor + 1, & \\text{if $k_2 \\% 2 = 0$ (head)} \\\\\n\\lfloor\\frac{k_2\\ \\%\\ 20}{2}\\rfloor, & \\text{if $k_2 \\% 2 = 1$ (end)}\n\\end{cases}\n$$</span></p>\n</li>\n<li><p>To make the pattern easier to see <span class=\"math-container\">\\$k_3 = k_2 - 180\\$</span>.</p>\n<p>Again we'll focus on building each digit.</p>\n<ul>\n<li><p>End digits <span class=\"math-container\">\\$k_3\\ \\%\\ 3 = 2\\$</span></p>\n<p>Ok the end digits are following the same pattern again.\nEvery <span class=\"math-container\">\\$30n + 2 = 0\\$</span>, <span class=\"math-container\">\\$30n + 5 = 1\\$</span>.</p>\n<ul>\n<li><span class=\"math-container\">\\$k_3 \\in \\{2, 32, 62, ..., 2672\\} \\therefore 0\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\in \\{5, 35, 65, ..., 2675\\} \\therefore 1\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\in \\{8, 38, 68, ..., 2678\\} \\therefore 2\\$</span></li>\n</ul>\n<p>Again we can use a similar algorithm as before to truncate the sets to just one number each.\nAfterwards we can figure out how to convert each of the numbers to the digit.</p>\n<p>We can modulo <span class=\"math-container\">\\$k_3\\$</span> by 30 to truncate each set to one number each, leaving 2, 5, 8, ....\nThe final numbers can be converted to the correct output by just floor dividing by 3.</p>\n<p><span class=\"math-container\">$$\\lfloor\\frac{k_3\\ \\%\\ 30}{3}\\rfloor$$</span></p>\n</li>\n<li><p>Mid digits <span class=\"math-container\">\\$k_3\\ \\%\\ 3 = 1\\$</span></p>\n<p>The mid digits have an interesting pattern.\nBecause the numbers are repeating in the 3rd dimension each time starting from around 100, 200, 300, etc.\nAs such I have used nested sets to show the split patterns.\nThe nested sets are just to show the start, end and step of the repeating patterns.</p>\n<ul>\n<li><span class=\"math-container\">\\$k_3 \\in \\{\\{1, 4, 7, ..., 28\\}, \\{301, 304, ... 328\\}, ..., \\{2401, 2404, ..., 2428\\}\\} \\therefore 0\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\in \\{\\{31, 34, 37, ..., 58\\}, \\{331, 334, ... 358\\}, ..., \\{2431, 2434, ..., 2458\\}\\} \\therefore 1\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\in \\{\\{61, 64, 67, ..., 88\\}, \\{361, 364, ... 388\\}, ..., \\{2461, 2464, ..., 2488\\}\\} \\therefore 2\\$</span></li>\n</ul>\n<p>Just like in both the previous end digits we can use modulo to reduce the size of the set.\nWe can see the outer sets repeat every 300 digits so using modulo 300 we can reduce the sets to something more manageable.</p>\n<ul>\n<li><span class=\"math-container\">\\$k_3 \\% 300 \\in \\{1, 4, 7, ..., 28\\} \\therefore 0\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\% 300 \\in \\{31, 34, 37, ..., 58\\} \\therefore 1\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\% 300 \\in \\{61, 64, 67, ..., 88\\} \\therefore 2\\$</span></li>\n</ul>\n<p>Now the sets look like sets we got in the head digit.\nNow we can just floor divide by 30 to get the digit.</p>\n<p><span class=\"math-container\">$$\\lfloor\\frac{k_3\\ \\%\\ 300}{30}\\rfloor$$</span></p>\n</li>\n<li><p>Head digits <span class=\"math-container\">\\$k_3\\ \\%\\ 3 = 0\\$</span></p>\n<ul>\n<li><span class=\"math-container\">\\$k_3 \\in \\{ 0, 3, 6, ..., 297\\} \\therefore 1\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\in \\{300, 303, 306, ..., 597\\} \\therefore 2\\$</span></li>\n<li><span class=\"math-container\">\\$k_3 \\in \\{600, 603, 606, ..., 797\\} \\therefore 3\\$</span></li>\n</ul>\n<p>Again the head digit pattern is the same, just with a different number.\nWe can just floor divide by 300 and add one to get the digit.</p>\n<p><span class=\"math-container\">$$\\lfloor\\frac{k_3}{300}\\rfloor + 1$$</span></p>\n</li>\n</ul>\n<p>Again we can merge the patterns into a single function:</p>\n<p><span class=\"math-container\">$$\nf_3(k_3) =\n\\begin{cases}\n\\lfloor\\frac{k_3}{300}\\rfloor + 1, & \\text{if $k_3\\ \\%\\ 3 = 0$ (head)} \\\\\n\\lfloor\\frac{k_3\\ \\%\\ 300}{30}\\rfloor, & \\text{if $k_3\\ \\%\\ 3 = 1$ (mid)} \\\\\n\\lfloor\\frac{k_3\\ \\%\\ 30}{3}\\rfloor, & \\text{if $k_3\\ \\%\\ 3 = 2$ (end)}\n\\end{cases}\n$$</span></p>\n</li>\n</ol>\n<p>We can see a pattern emerging. Lets have <span class=\"math-container\">\\$k_1 = k - 1\\$</span>.</p>\n<ul>\n<li><p>We can see similar values 2, 20, 3, 30 and 300.\nSo we can move the dimension, <span class=\"math-container\">\\$n\\$</span>, out of the numbers and get <span class=\"math-container\">\\$1n\\$</span>, <span class=\"math-container\">\\$10n\\$</span>, <span class=\"math-container\">\\$1n\\$</span>, <span class=\"math-container\">\\$10n\\$</span> and <span class=\"math-container\">\\$100n\\$</span> respectively.</p>\n</li>\n<li><p>Looking at the previous numbers we can see a pattern again 1, 10 and 100.\nThe pattern between the numbers is <span class=\"math-container\">\\$10^?\\$</span> where we currently don't know what <span class=\"math-container\">\\$?\\$</span> is.</p>\n</li>\n<li><p>We can see the numerator's modulo is always <span class=\"math-container\">\\$? + 1\\$</span> the denominator's <span class=\"math-container\">\\$?\\$</span>.</p>\n</li>\n</ul>\n<p>As such we can change the above functions to a very similar pattern.</p>\n<p><span class=\"math-container\">$$\nf_3(k_3) =\n\\begin{cases}\n\\lfloor\\frac{k_3\\ \\%\\ (3 * 10^{3 - 0})}{3 * 10^{3 - 1}}\\rfloor + 1, & \\text{if $k_3\\ \\%\\ 3 = 0$} \\\\\n\\lfloor\\frac{k_3\\ \\%\\ (3 * 10^{3 - 1})}{3 * 10^{3 - 2}}\\rfloor, & \\text{if $k_3\\ \\%\\ 3 = 1$} \\\\\n\\lfloor\\frac{k_3\\ \\%\\ (3 * 10^{3 - 2})}{3 * 10^{3 - 3}}\\rfloor, & \\text{if $k_3\\ \\%\\ 3 = 2$}\n\\end{cases}\\\\\nf_2(k_2) =\n\\begin{cases}\n\\lfloor\\frac{k_2\\ \\%\\ (2 * 10^{2 - 0})}{2 * 10^{2 - 1}}\\rfloor + 1, & \\text{if $k_2 \\% 2 = 0$} \\\\\n\\lfloor\\frac{k_2\\ \\%\\ (2 * 10^{2 - 1})}{2 * 10^{2 - 2}}\\rfloor, & \\text{if $k_2 \\% 2 = 1$}\n\\end{cases}\\\\\nf_1(k_1) =\n\\begin{cases}\n\\lfloor\\frac{k_1\\ \\%\\ (1 * 10^{1 - 0})}{1 * 10^{1 - 1}}\\rfloor + 1, & \\text{if $k_1 \\% 1 = 0$}\n\\end{cases}\n$$</span></p>\n<p>Here we have found what <span class=\"math-container\">\\$?\\$</span> is.\nLooking at the "if" we can see <span class=\"math-container\">\\$?\\$</span> is based on the modulo of <span class=\"math-container\">\\$k\\$</span>.\nAs such we can improve the function further to:</p>\n<p><span class=\"math-container\">$$\nf_n(k_n) =\n\\lfloor\\frac{k_n\\ \\%\\ (n10^{n - (k_n\\ \\%\\ n)})}{n10^{n - (k_n\\ \\%\\ n) - 1}}\\rfloor + \\begin{cases}\n1, & \\text{if $k_n \\% n = 0$}\\\\\n0, & \\text{otherwise}\n\\end{cases}\n$$</span></p>\n<p>I'll leave getting <span class=\"math-container\">\\$n\\$</span> and <span class=\"math-container\">\\$k_n\\$</span> from <span class=\"math-container\">\\$k\\$</span> as a challenge for the OP.</p>\n<p>We can check the equation works with the following code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fn(k, n):\n mod = k % n\n return (\n (\n (k % (n * 10 ** (n - mod)))\n // (n * 10 ** (n - mod - 1))\n )\n + (0 if mod else 1)\n )\n\nfor row in range(0, 180, 20):\n digits = [\n fn(index, 3)\n for index in range(row, row + 20)\n ]\n print("".join(str(d) for d in digits))\n</code></pre>\n<pre><code>10111213141516171819\n20212223242526272829\n30313233343536373839\n40414243444546474849\n50515253545556575859\n60616263646566676869\n70717273747576777879\n80818283848586878889\n90919293949596979899\n</code></pre>\n<p><strong>Note</strong>: The function doesn't work correctly on the 'last chunk' of numbers, <code>fn(180, 2) == 10</code> but when the function loops back around we get the correct numbers <code>fn(200, 2) == 1</code>.\nBecause we don't need to generate <span class=\"math-container\">\\$00\\ \\to\\ 09\\$</span> I defiled the function.\nTo get the 'pure' function remove <code>+ (0 if mod else 1)</code> and adjust the input accordingly.\nI.e start at 20 not 0.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T02:05:20.243",
"Id": "507103",
"Score": "0",
"body": "I think your solution is correct but your explanation makes the problem seem way more complicated than it really is by even thinking about end digits or head digits or whatever. Kelly Bundy's solution is much simpler to understand of grouping numbers by length."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T02:32:57.863",
"Id": "507104",
"Score": "0",
"body": "@qwr I think you've misunderstood the point of the answer. It was to teach how to solve other pattern based problems in the future. By showing how to break big problems down into smaller and more manageable parts. Then solving all the small problems to solve the big one. A lot of programming challenges rely on pattern recognition skills, where using strings are not an option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T02:51:54.020",
"Id": "507108",
"Score": "0",
"body": "I know about pattern recognition. I still think you are overcomplicating the problem. Maybe I will write my own answer of how I think about the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T07:50:55.170",
"Id": "507120",
"Score": "0",
"body": "It would be nice if you provided a working solution for f(k). As it stands, the function still needs n as input!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T09:28:23.497",
"Id": "507127",
"Score": "0",
"body": "@qwr \"It would be nice if you provided a working solution for f(k).\" I set figuring out an exponential function as homework to the asker. So the user can build pattern recognition skills. Maybe you know the saying; give a man a fish feed him for a day, teach a man to fish feed him for a lifetime."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T21:30:35.080",
"Id": "256780",
"ParentId": "256773",
"Score": "4"
}
},
{
"body": "<p>As <a href=\"https://codereview.stackexchange.com/a/256780/100620\">Peilonrayz</a> pointed out, there is a mathematical approach to the problem.</p>\n<p>Let's assume there wasn't.</p>\n<pre class=\"lang-py prettyprint-override\"><code># TODO FIND A BETTER WAY TO LIMIT inf_string LENGTH\ninf_string = [str(x) for x in range(1, max(queries)+1)]\ninf_string = "".join(inf_string)\n</code></pre>\n<p>With <span class=\"math-container\">\\$k \\le 10^{18}\\$</span>, your string can have up to <span class=\"math-container\">\\$10^{18}\\$</span> digits. That's a lot of memory for a program to use for one string.</p>\n<p>There is no reason to make the string that large. One can simply generate the string, one value at a time, and return the digits of those strings, yielding the infinite digit string while taking almost no memory.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Iterable\n\ndef infinite_digits() -> Iterable[str]:\n """\n An infinite series of digits from the infinite sequence of positive\n integers. Ie:\n\n "1" "2" "3" "4" "5" "6" "7" "8" "9" "1" "0" "1" "1" "1" "2" "1" "3" ...\n """\n\n x = 1\n while True:\n yield from str(x)\n x += 1\n</code></pre>\n<p>To find the <span class=\"math-container\">\\$n^{th}\\$</span> digit, simply generate the sequence, discarding all of the digits until you reach the desired one. There is even a recipe for that in <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\">the <code>itertools</code> docs</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from more_itertools import nth\n\ndef digit(k: int) -> str:\n return nth(infinite_digits(), k - 1)\n</code></pre>\n<p>With the above two functions, your code can be simplified to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(int(input())):\n k = int(input())\n print(digit(k))\n</code></pre>\n<p>The code will still take a very, very long time, but at least it won't consume much memory.</p>\n<p>You can make things more efficient by sorting your queries, pass over the <code>infinite_digit()</code> stream once, and remember the positions of interest. Finally, pass over the original query set again, and output the memorized digit for that query value.</p>\n<p>It could be up to 1000 times faster, since you have up to 1000 queries, but it can still take a very long time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T00:16:18.603",
"Id": "507034",
"Score": "3",
"body": "You just made me realize for a performant and simple solution we could use something like `def fn(i, n): return str(range(10**(n - 1), 10**n)[i // n])[i % n]` (very similar to your code but with how my `fn` works). Ugh, why'd I spend like an hour looking at math when I could have just used something so simple! ♀️"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T06:15:39.283",
"Id": "507043",
"Score": "0",
"body": "@Peilonrayz Huh. I would have used the math approach myself, but you had already gone that route, so I went the brute-force-and-ignorance method, but without the memory impact, to show that the problem could be solved in smaller pieces than just building the complete huge string. Nice performant upgrade."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T06:26:01.273",
"Id": "507045",
"Score": "0",
"body": "I completely disagree with the checkmark being awarded to this answer. At 1 nanosecond per digit, a \\$10^{18}\\$ query would take over **31 years** to solve. The math solution deserves the checkmark."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T01:59:04.207",
"Id": "507101",
"Score": "0",
"body": "this is not the correct solution for the problem asked, which is a competition programming problem, and so will still result in TLE (time limit exceeded)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T02:38:22.013",
"Id": "507105",
"Score": "2",
"body": "@qwr Code Review is about teaching skills the asker needs not just giving solutions to problems. Effective memory utilization is a skill needed in many other parts of programming, even in programming challenges."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T02:47:51.463",
"Id": "507107",
"Score": "1",
"body": "@qwr I know it is not the *optimal* solution. I said as much in the comment immediately above yours. The 31 year run time to solve the last test case is excessive, but won't drag the computer to its knees allocating and swapping memory while trying to build a quintillion digit string. It does however solve the OP's issue of \"_FIND A BETTER WAY TO LIMIT inf_string LENGTH_\": the length issue is avoided."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T07:46:08.900",
"Id": "507119",
"Score": "0",
"body": "@Peilonrayz the infinite string iterable is not the right approach to the problem at all. generating the entire string itself is a red herring. what is the point of effective memory utilization if it cannot produce the answer?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T00:01:28.100",
"Id": "256786",
"ParentId": "256773",
"Score": "5"
}
},
{
"body": "<p>Building or iterating the whole string takes far too long. Instead group the numbers by length:</p>\n<pre><code>length 1 digit: 1 to 9 -> 9 numbers => 9 digits total\nlength 2 digits: 10 to 99 -> 90 numbers => 180 digits total\nlength 3 digits: 100 to 999 -> 900 numbers => 2700 digits total\nlength 4 digits: 1000 to 9999 -> 9000 numbers => 36000 digits total\netc\n</code></pre>\n<p>The number of digits per group (9, 180, 2700, 36000, etc) are easy to compute. Skip these groups of equal-length numbers until you reach the right group (the remaining <code>k</code> falls into it). Then just compute the right number inside the group and get the right digit from it.</p>\n<pre><code>for _ in range(int(input())):\n k = int(input())\n\n length = 1\n while k > 9 * 10**(length-1) * length:\n k -= 9 * 10**(length-1) * length\n length += 1\n q, r = divmod(k-1, length)\n print(str(10**(length-1) + q)[r])\n</code></pre>\n<p>Takes about 0.03 seconds of the allowed 1 second.</p>\n<p>Or keeping <code>10**(length-1)</code> in a variable for less duplication:</p>\n<pre><code>for _ in range(int(input())):\n k = int(input())\n\n length = first = 1\n while k > 9 * first * length:\n k -= 9 * first * length\n length += 1\n first *= 10\n q, r = divmod(k-1, length)\n print(str(first + q)[r])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T02:55:34.917",
"Id": "507109",
"Score": "0",
"body": "this is a good answer. in fact the string does not need to be generated at all, although the final string generation is very small."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T17:03:38.303",
"Id": "508346",
"Score": "0",
"body": "Could you elaborate more on why we take `divmod` of `k-1` ?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T04:25:18.593",
"Id": "256792",
"ParentId": "256773",
"Score": "7"
}
},
{
"body": "<p>This is a competition programming problem so it's worth thinking about the algorithmic complexity of our approaches. Let n=10^18 be the original length of the string. Generating the entire string one digit at a time will take O(n) time, even if we don't store the whole string, so that approach won't work. Instead, the goal is to compute precisely which number of all the concatenated numbers our index lands in and how far into the number it is. (By the way, this sequence is <a href=\"http://oeis.org/A033307\" rel=\"nofollow noreferrer\">http://oeis.org/A033307</a>)</p>\n<p>A simple approach is to group all numbers by how many digits is in each number, like in Kelly Bundy's answer.</p>\n<ul>\n<li>For numbers 1 to 9, there are 9 numbers and each number is 1-digit, so there are 9*1=9 digits in the group.</li>\n<li>For numbers 10 to 90, there are 90 numbers and each number is 2-digit, so there are 90*2 = 180 total digits.</li>\n<li>etc.</li>\n<li>In general, for d-digit numbers, there are g = 9*(10^(d-1)) * d total digits. This is <a href=\"http://oeis.org/A212704\" rel=\"nofollow noreferrer\">http://oeis.org/A212704</a>.</li>\n</ul>\n<p>So we can find out what d is for our given k by incrementing d and subtracting from k until we cannot subtract any more. Each time we subtract on the order of 10^d, so we only need O(log10(n)) steps to reach our group (check index of <a href=\"http://oeis.org/A033713\" rel=\"nofollow noreferrer\">http://oeis.org/A033713</a> to see just how many steps we need), so for q=1000 queries, this is very fast.</p>\n<p>Then we can compute the digit inside the number we are currently in by using m = 10^(d-1) + q, where q is floor division of k-1 by d (convince yourself why this is true). Within each number, we need to extract the exact digit, which can be done with mod and floor division powers of 10 operations in constant time instead of using strings. There is little performance difference but I like to avoid using strings for numeric problems if I can as a matter of elegance: although this problem is presented as one of an infinite string, it is computed mathematically without any strings at all, showing that this is not really a string manipulation problem but one of careful counting and nothing more.</p>\n<p>Here is the modified version of Kelly Bundy's code, using the new python walrus operator to make the code a little cleaner and without using strings, thus very fast and suitable for implementation in C/assembly/any language without nice string functions.</p>\n<pre><code>def f(k):\n d = 1\n while k > (g := 9 * 10**(d-1) * d):\n k -= g\n d += 1\n q, r = divmod(k-1, d) # convert 1-indexing\n m = 10**(d-1) + q\n return (m // (10**(d-1-r))) % 10\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T16:30:10.500",
"Id": "507165",
"Score": "0",
"body": "Hmm, I didn't downvote, but... 1) You make a big deal of getting the code accepted being important, and then you modify my code so that it doesn't get accepted anymore. It gets `SyntaxError: invalid syntax` for the `:=`. I had already tried that and that's why I didn't use it. 2) If you consider your final digit extraction constant time, you must also consider the string-way constant time. 3) You say \"as a matter of elegance\", but `(m // (10**(d-1-r))) % 10` really doesn't look more elegant than `str(m)[r]` to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T16:38:08.330",
"Id": "507166",
"Score": "0",
"body": "4) It looks [almost twice as *slow*](https://tio.run/##PY5LDsIwDET3OcVsUJKqiJbyR5wEIYREClnkI9csOH1ICMIL23pjjya@@Rn8sIuU0kjBga0zlmFdDMQgE82NhZgMvyJOkPfc@u0RrszlsFpvtrt999uOoIz3UogxEK6wHnTzD6MGfRDIVfDEjosiJybl9JkusoVUDosFVN81jbrP@zlprTFD38n6WYqzubNe1VCqGLX4JtP6fxTJelZFyHLFFemUPg), and the conversion to `str` that `print` will do makes it [even slower](https://tio.run/##PU0xCgMxDNvzCnNLYrjtOCgtfUu5Idd6SGIcdejr06SBajBCkiX94FXydlFr7bSSCJKigCRpMZBFjQecqxFvpTsttR@/@xtJJ/vi3FmMHiSZ7MjPGDa@OuoYckXCcHyFhcp@nUzYz8wAek2SHOZQGC8r/daY/yE1yQjD6PaUp8StfQE). Not saying it matters, just saying I wouldn't ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T16:40:24.170",
"Id": "507167",
"Score": "0",
"body": "... advertise that as a speed improvement when it appears to be *slower*. Though if my benchmarks are somehow bad and I'm mistaken about that, feel free to demonstrate that :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:11:54.770",
"Id": "507193",
"Score": "0",
"body": "1. What version of python are you using? I tested it on python 3.8.5 on ubuntu 20.04. 2. I know this and I said there is little performance benefit, although maybe my wording made it sound like the string time took not effectively constant time. 3. personal preference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:20:41.523",
"Id": "507194",
"Score": "0",
"body": "4. I do not advertise any speed improvement, rather I say the code is very fast, which given the time limit it is. It is useless to micro-optimize python for competition programming anyway because python is not a good language for competition programming. Anyhow the python code is just psuedocode for a C or assembly implementation where I believe string functions are slow and cumbersome. Idk if this applies to C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:23:35.957",
"Id": "507196",
"Score": "0",
"body": "I added a little note about strings in my post"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:26:42.663",
"Id": "507197",
"Score": "0",
"body": "I'm presumably using the same version that you are using when you're submitting the code at the site, which appears to be Python 3.6.9. About speed: Ok, I see you indeed didn't explicitly call it faster, that's just the impression I got from the way it's phrased. Python can be very good for competition programming. Depends on the competition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T21:34:24.890",
"Id": "507199",
"Score": "0",
"body": "Btw when I say \"working solution\" I mean one that fully answers the problem or provides a solution that is trivially converted to a full program. I didn't signup for CSES and I just assumed they had python 3.8, my bad. My opinion on python is that it is just too slow for some competitions, even with pypy jit compilation which I use a lot in my Project Euler solutions (those are untimed, so I can get away with using python)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T07:44:26.567",
"Id": "256831",
"ParentId": "256773",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256792",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T19:18:30.277",
"Id": "256773",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"time-limit-exceeded"
],
"Title": "\"Digit Queries\" CSES Solution giving TLE"
}
|
256773
|
<p>This is my first ever Python program and I wanted to get everyone's opinions on it. The goal of the program is to separate an email address into its username and domain name.</p>
<pre><code>import sys
import getopt
argv = sys.argv[1:]
# -------Error Handling-Start----------
try:
opts, args = getopt.getopt(argv, "l:s:h", ["list ", "single ", "help "])
except getopt.GetoptError as err:
print(f"{err}\n""\n"
"Usage: <Options> <Input> \n"
"-l, --list Specify a list of emails to be sliced \n"
"-s, --single Specify a single email to be sliced \n"
"-h, --help Show options")
opts = []
# -------Error Handling-End------------
for opt, file_arg in opts:
if opt in ['-h', '--help']:
sys.exit("Usage: <Options> <Input> \n"
"-l, --list Specify a list of emails to be sliced \n"
"-s, --single Specify a single email to be sliced \n"
"-h, --help Show options")
# If option -h is present, display MAN page
for opt, email_arg in opts:
if opt in ['-s', '--single']:
email = email_arg
username = email[:email.index('@')]
domain = email[email.index('@') + 1:]
print(f"Your username: {username}")
print(f"Your domain name: {domain}\n")
# If option -s is present, split input email into username and domain then print the output
for opt, file_arg in opts:
if opt in ['-l', '--list']:
file = file_arg
email_file = open(file, "r")
for string in email_file:
username = string[:string.index('@')]
domain = string[string.index('@') + 1:]
print(f"Your username: {username}")
print(f"Your domain name: {domain}")
# If option -l is present read file specified then loop through each line while splitting each into username and domain
if len(sys.argv) == 1:
sys.exit("Usage: <Options> <Input> \n"
"-l, --list Specify a list of emails to be sliced \n"
"-s, --single Specify a single email to be sliced \n"
"-h, --help Show options")
# If only one argument is supplied, print MAN page.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T19:53:26.927",
"Id": "507018",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/256774/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] |
[
{
"body": "<p>The general style looks good. The biggest opportunity for improvement is your use of <code>getopt</code>. You should use the newer and easier <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> instead. Most of your code is used to parse and use the command line arguments. All of that can be done in three lines with <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import argparse\n\narg_parser = argparse.ArgumentParser()\narg_parser.add_argument("-f", "--file", dest="file", default=False, action="store_true")\narg_parser.add_argument("input", type=str)\nargs = arg_parser.parse_args()\n</code></pre>\n<p>Instead of using <code>--single</code> or <code>--list</code>, I added a single flag <code>--file</code> (or <code>-f</code>), as the former choice is not only ambiguous (what happens if you specify neither or both?) as well as potentially misleading in their name.\nA help option with "-h" is introduced automatically.</p>\n<p><code>"-f", "--file"</code> are the flags you can use to specify this argument. <code>dest=file</code> means that the created object <code>args</code> wil have an attribute <code>args.file</code> that stores the resulting value. <code>action="store_true"</code> means that the flag has to be specified without a value (i.e. <code>-f</code> instead of <code>-f True</code>) to set it.</p>\n<p>After that, you can access your inputs as a strings (because <code>type=str</code>) by <code>args.input</code> (because the first argument to <code>add_argument</code> was <code>"input"</code>).</p>\n<p><code>open</code> of a file should always be paired with a <code>close</code> when you are done using it, as is also true for other I/O objects such as network connections. Instead of manually calling <code>close</code>, one should prefer to use Python's context managers with the <code>with</code> keyword, which automatically perform any cleanup.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if args.file:\n with open(args.input, "r") as file:\n emails = file.readlines()\nelse:\n emails = [args.input]\n</code></pre>\n<p>Your code to split the email into username and domain can be done with <code>str.split</code>, assuming that there is exactly one "@". If there are not "@" or more than one, you should probably notify the user that there is an error anyway. If you want to have actual "serious" code that goes into production in a live system, see Toby Speight's comment on pointers how to properly do that.</p>\n<pre class=\"lang-py prettyprint-override\"><code> if email.count("@") != 1:\n ... # Notify the user\n username, domain = email.split("@")\n print(f"Your username: {username}")\n print(f"Your domain name: {domain}")\n</code></pre>\n<p>Finally, your use of <code>sys.exit</code> is incorrect. You should only use <code>sys.exit(n)</code> with an integer <code>n</code>. <code>sys.exit(0)</code> means "successful", anything else means "failed". Unless you have specific needs, <code>sys.exit(1)</code> is the default choice for failure.</p>\n<p>To give user friendly error messages, the easiest way is to use <code>print</code>. You can show the messages as an error by specifying <code>file=sys.stderr</code> (as opposed to the default <code>file=sys.stdout</code>).</p>\n<pre class=\"lang-py prettyprint-override\"><code> print(f"{email} is not a valid email.", file=sys.stderr)\n sys.exit(1)\n</code></pre>\n<p>In total, this is what I'd propose your program could look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import sys\nimport argparse\n\narg_parser = argparse.ArgumentParser()\narg_parser.add_argument("-f", "--file", dest="file", default=False, action="store_true")\narg_parser.add_argument("input", type=str)\nargs = arg_parser.parse_args()\n\nif args.file:\n with open(args.input, "r") as file:\n emails = file.readlines()\nelse:\n emails = [args.input]\n\nfor email in emails:\n if email.count("@") != 1:\n print(f"{email} is not a valid email.", file=sys.stderr)\n sys.exit(1)\n username, domain = email.split("@")\n print(f"Your username: {username}")\n print(f"Your domain name: {domain}")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T20:31:10.750",
"Id": "507023",
"Score": "1",
"body": "I'd have to look up the relevant RFC (5322, these days?) to see if `@` is allowed in the local part. If so, we'll want to find the _last_ `@` to identify the domain. There's far to much broken email-handling code around (I frequently encounter systems that think they are allowed to change the case of the local part!) that I wouldn't want to encourage more implementation by those who can't or won't read the RFC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T20:33:04.287",
"Id": "507024",
"Score": "1",
"body": "I think you misread the code - `--single` seems to be accepting arguments, and `--list` means _read from file_. I think they could helpfully be renamed, as your interpretation shows!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T20:53:45.953",
"Id": "507026",
"Score": "1",
"body": "@TobySpeight You're completely right regarding the arguments. I'll update my answer to show the correct behavior. Regarding RFC5322, you are right as well. Although I think this should be more of a note \"If you actually want a serious and safe system, don't try to implement an email parser yourself\". Going into detail I feel would exceed the scope of a review on this level."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T19:47:18.160",
"Id": "256775",
"ParentId": "256774",
"Score": "2"
}
},
{
"body": "<p>This works for toto@domain.com and also with toto@tutu@domain.com which is an RFC compliant email address.</p>\n<pre><code>def splitMail(mail: str):\n parts = mail.rsplit('@', 1)\n user = parts[0]\n domain = parts[1]\n \n return user, domain\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T14:39:50.097",
"Id": "526694",
"Score": "0",
"body": "This would be a stronger answer if it showed that the original code did not support @ symbols in the user ID part and provided a citation for the claim that they were RFC-compliant. It would be even stronger if there was a citation that showed that any email addresses actually use more than one @ symbol. You also might consider explaining the other choices that you made. E.g. why you assigned the two parts to variables rather than just returning them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T13:51:09.767",
"Id": "266592",
"ParentId": "256774",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T19:28:21.413",
"Id": "256774",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"strings",
"parsing"
],
"Title": "Separate an email address into its username and domain name"
}
|
256774
|
<p>I'm trying to understand how to use <a href="https://pydantic-docs.helpmanual.io/" rel="nofollow noreferrer">pydantic</a> for data parsing & validation.</p>
<p>The idea I had in mind was following:</p>
<ul>
<li>I have a list of DOI names for which I need to collect metadata</li>
<li>I could use <code>pydantic</code> to test if the DOI name is valid
<ul>
<li>if it's valid, I proceed with making a request to <em>scite</em> api</li>
<li>if not, the code raises an exception instead of calling api</li>
</ul>
</li>
</ul>
<p>Very basic idea as you see.</p>
<hr />
<p>The code:</p>
<p><em>scite_utils.py</em></p>
<pre class="lang-py prettyprint-override"><code>import requests
from ratelimit import limits, sleep_and_retry
from pydantic import BaseModel, ValidationError, constr
class DOI(BaseModel):
name: constr(regex=r"^10\.\d{4,9}/[-._;()/:a-zA-Z0-9]+$")
@sleep_and_retry
@limits(calls=40, period=60) # api ratelimits
def remote_call(endpoint: str):
r = requests.get(f"https://api.scite.ai/{endpoint}")
r.encoding = "UTF-8"
return r.json()
def get_paper(doi: DOI):
if not isinstance(doi, DOI):
try:
doi = DOI(name=doi).name
except ValidationError:
return
return remote_call(endpoint=f"papers/{doi}")
</code></pre>
<hr />
<p><em>test.py</em></p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
from typing import List
from scite_utils import DOI, get_paper
# a sample of 5 but realisticlly - thousands?
DOIs = [
"10.12724/ajss.47.0",
"10.31124/advance.12630065.v1",
"obv_error",
"10.1122ajss.123.9",
"10.1080/09662830500528294"
]
def create_table(names: List[DOI]):
data = [get_paper(name) for name in names]
return pd.DataFrame(
publication
for publication in data
if publication is not None
)
if __name__=="__main__":
result = create_table(DOIs)
print(result)
</code></pre>
<hr />
<p>Questions:</p>
<ol>
<li>Is this a valid use case for <code>pydantic</code>?</li>
<li>Should I validate DOI name inside of the function that makes a request
(or is there a better place for it, like a separate function)?</li>
<li>Doesn't it look awkward generally? I feel like I'm missing the point,
because I could've written a custom function with <code>re</code> to validate DOI name.</li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T20:17:44.783",
"Id": "256778",
"Score": "1",
"Tags": [
"python",
"pydantic"
],
"Title": "DOI name validation with pydantic"
}
|
256778
|
<p><a href="https://leetcode.com/problems/range-sum-query-mutable/" rel="nofollow noreferrer">https://leetcode.com/problems/range-sum-query-mutable/</a></p>
<p>I am trying to solve this question using dynamic programming.</p>
<p>I guess the guys in leetcode want to limit us to use segment tree or one of the other solutions.</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace DynamicProgrammingQuestions
{
/// <summary>
///https://leetcode.com/problems/range-sum-query-mutable/
/// ["NumArray", "sumRange","sumRange","sumRange","update","update","update","sumRange","update","sumRange","update"]
///[[[0,9,5,7,3]],[4,4], [2,4], [3,3] ,[4,5], [1,7] ,[0,8] ,[1,2],[1,9],[4,4],[3,4]]
/// [ null, 3, 15, 7, null ,null ,null ,12,null,5,null]
/// </summary>
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
int[] nums = {0, 9, 5, 7, 3};
NumArray numArray = new NumArray(nums);
Assert.AreEqual(3, numArray.SumRange(4, 4));
Assert.AreEqual(15, numArray.SumRange(2, 4));
Assert.AreEqual(7, numArray.SumRange(3, 3));
numArray.Update(4,5);
numArray.Update(1,7);
numArray.Update(0,8);
// 8,7,5,7,5
Assert.AreEqual(12, numArray.SumRange(1, 2));
}
}
public class NumArray
{
int[] _dp;
int[] _nums;
public NumArray(int[] nums)
{
_dp = new int[nums.Length + 1];
//0,1,2,3
// 1,4,9
for (int i = 0; i < nums.Length; i++)
{
_dp[i + 1] = _dp[i] + nums[i];
}
_nums = nums;
}
public void Update(int index, int val)
{
int old = _nums[index];
_nums[index] = val;
for (int i = index; i < _dp.Length - 1; i++)
{
_dp[i + 1] = _dp[i + 1] - old + val;
}
}
public int SumRange(int left, int right)
{
return _dp[right + 1] - _dp[left];
}
}
}
</code></pre>
<p>here is my code. i'm trying to understand if I can optimize it?
can you please suggest runtime performance optimizations?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T22:08:33.490",
"Id": "256781",
"Score": "1",
"Tags": [
"c#",
"performance",
"programming-challenge",
"dynamic-programming"
],
"Title": "LeetCode: range sum query mutable c#"
}
|
256781
|
<p>Rubberduck VBA permits creation of virtual project hierarchy within the IDE, but the project is imported/exported as a single folder with all files. Sometimes, direct access to the project folder is useful, in which case having materialized project structure on hard drive is helpful. For example, when a set of modules implementing certain common functionality is transferred between projects.</p>
<p>The class module <code>ProjectUtils</code> below implements such a functionality, also permitting export/import of library references.</p>
<pre class="lang-vb prettyprint-override"><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "ProjectUtils"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
'@Folder "Common.Project Utils"
'@PredeclaredId
'@IgnoreModule ProcedureNotUsed, IndexedDefaultMemberAccess
Option Explicit
Private Const PROJECT_FOLDER As String = "Project"
Private Const COMMON_FOLDER As String = "Common"
Private Const REFERENCES_FILE As String = "References.xsv"
Private Type TProjectUtils
Project As VBIDE.VBProject
ProjectPath As String
Paths As Scripting.Dictionary
Files As Scripting.Dictionary
fso As Scripting.FileSystemObject
wsh As IWshRuntimeLibrary.WshShell
EnvVarNames As Variant
End Type
Private this As TProjectUtils
Private Sub Class_Initialize()
With this
Select Case Application.Name
Case "Microsoft Excel"
Set .Project = Application.ActiveWorkbook.VBProject
Case "Microsoft Access", "Microsoft Word"
Set .Project = Application.VBE.ActiveVBProject
Case "Microsoft PowerPoint"
'@Ignore IndexedDefaultMemberAccess
Set .Project = Application.VBE.VBProjects(1)
End Select
Set .Paths = New Scripting.Dictionary
.Paths.CompareMode = TextCompare
Set .Files = New Scripting.Dictionary
.Files.CompareMode = TextCompare
Set .fso = New Scripting.FileSystemObject
Set .wsh = New IWshRuntimeLibrary.WshShell
.ProjectPath = .fso.GetParentFolderName(.Project.FileName) & Application.PathSeparator & PROJECT_FOLDER
If Dir$(.ProjectPath, vbDirectory) = vbNullString Then MkDir .ProjectPath
.EnvVarNames = Array("CommonProgramFiles(x86)", "CommonProgramFiles", "ProgramFiles (x86)", "ProgramFiles", "SystemRoot")
End With
End Sub
Private Sub Class_Terminate()
With this
Set .Project = Nothing
Set .Paths = Nothing
Set .Files = Nothing
Set .fso = Nothing
Set .wsh = Nothing
End With
End Sub
'@Description "Creates path, including any non-existing subdirectories."
Private Sub MkPath(ByVal FullPath As String)
Attribute MkPath.VB_Description = "Creates path, including any non-existing subdirectories."
Dim Folders As Variant
Folders = Split(FullPath, Application.PathSeparator)
Dim Path As String
Path = Folders(0)
If Dir$(Path, vbDirectory) = vbNullString Then Err.Raise 76, "ProjectUtils", "Path not found"
Dim FolderIndex As Long
For FolderIndex = 1 To UBound(Folders, 1)
Path = Path & Application.PathSeparator & Folders(FolderIndex)
If Dir$(Path, vbDirectory) = vbNullString Then MkDir Path
Next FolderIndex
End Sub
'@Description "Save references info for the Project of the ActiveWorkbook into tsv/csv file."
Public Sub ReferencesSaveToFile()
Attribute ReferencesSaveToFile.VB_Description = "Save references info for the Project of the ActiveWorkbook into tsv/csv file."
Dim References As VBIDE.References
Set References = this.Project.References
Dim ReferenceString As String
Dim ReferencesArray() As Variant
ReDim ReferencesArray(0 To References.Count)
Dim Reference As VBIDE.Reference
Dim ReferenceIndex As Long: ReferenceIndex = 0
ReferenceString = "Name" & _
vbTab & "GUID" & _
vbTab & "Major" & _
vbTab & "Minor" & _
vbTab & "FullPath"
ReferencesArray(ReferenceIndex) = ReferenceString
ReferenceIndex = ReferenceIndex + 1
Dim EnvVarIndex As Long
Dim FullPath As String
Dim FullPathLen As Long
Dim EnvVarCount As Long: EnvVarCount = UBound(this.EnvVarNames, 1) + 1
For Each Reference In References
'''' Replace path prefix with corresponding common environment variable if exists
FullPath = Reference.FullPath
FullPathLen = Len(FullPath)
EnvVarIndex = 0
Do While (Len(FullPath) = FullPathLen) And (EnvVarIndex < EnvVarCount)
FullPath = Replace(FullPath, Environ(this.EnvVarNames(EnvVarIndex)), "%" & this.EnvVarNames(EnvVarIndex) & "%", 1, 1, vbTextCompare)
EnvVarIndex = EnvVarIndex + 1
Loop
If Len(FullPath) = FullPathLen Then
FullPath = Replace(FullPath, "C:\ProgramFiles", "%ProgramFiles%", 1, 1, vbTextCompare)
End If
ReferenceString = Reference.Name & _
vbTab & Reference.GUID & _
vbTab & CStr(Reference.Major) & _
vbTab & CStr(Reference.Minor) & _
vbTab & FullPath
ReferencesArray(ReferenceIndex) = ReferenceString
ReferenceIndex = ReferenceIndex + 1
Next Reference
'''' Save references to a tab separated file in the project folder
Dim PathName As String
PathName = this.ProjectPath & Application.PathSeparator & REFERENCES_FILE
Dim FileHandle As Long: FileHandle = FreeFile
Open PathName For Output As #FileHandle
Print #FileHandle, Join(ReferencesArray, vbNewLine)
Close #FileHandle
End Sub
'''' Errors during reference addition are ignored (expect the major source due to already
'''' activated references). Alternatively, read activated refernces first and skip addition
'''' of activated references.
'@Description "Add references from the tsv/csv file to the Project of the ActiveWorkbook ."
Public Sub ReferencesAddFromFile(Optional ByVal PathName As String = vbNullString, Optional ByVal UseGUID As Boolean = True)
Attribute ReferencesAddFromFile.VB_Description = "Add references from the tsv/csv file to the Project of the ActiveWorkbook ."
If PathName = vbNullString Then PathName = this.ProjectPath & Application.PathSeparator & REFERENCES_FILE
Dim ReadBuffer As String
Dim FileHandle As Long: FileHandle = FreeFile
Open PathName For Input As #FileHandle
ReadBuffer = Input$(LOF(FileHandle), #FileHandle)
Close #FileHandle
Dim refj As Long
If Len(ReadBuffer) > 0 Then
'''' Split buffer into record lines
Dim ReadLines() As String
ReadLines = Split(ReadBuffer, vbNewLine)
Dim ReferencesArray() As Variant
ReDim ReferencesArray(0 To UBound(ReadLines, 1) - 2)
For refj = 0 To UBound(ReadLines, 1) - 2
'''' Split records into fields
ReferencesArray(refj) = Split(ReadLines(refj + 1), vbTab)
ReferencesArray(refj)(4) = this.wsh.ExpandEnvironmentStrings(ReferencesArray(refj)(4))
Next refj
End If
'''' Add all references ignoring errors
Debug.Print "Adding references from " & PathName & vbNewLine & _
"For refernces that are already activated, a warning" & vbNewLine & _
UCase("Name conflicts with existing module, project, or object library") & vbNewLine & _
"will be reported. Please ignore it." & vbNewLine
On Error Resume Next
If UseGUID Then
For refj = 0 To UBound(ReferencesArray, 1)
this.Project.References.AddFromGuid ReferencesArray(refj)(1), CLng(ReferencesArray(refj)(2)), CLng(ReferencesArray(refj)(3))
If VBA.Information.Err.Number > 0 Then Debug.Print VBA.Information.Err.Description
Next refj
Else
For refj = 0 To UBound(ReferencesArray, 1)
this.Project.References.AddFromFile ReferencesArray(refj)(4)
If VBA.Information.Err.Number > 0 Then Debug.Print VBA.Information.Err.Description
Next refj
End If
On Error GoTo 0
End Sub
'@Description "Iterates over VBComponents, extracts @Folder annotation and collects File/Folder hierarchy information."
Public Sub ProjectStructureParse()
Attribute ProjectStructureParse.VB_Description = "Iterates over VBComponents, extracts @Folder annotation and collects File/Folder hierarchy information."
this.Paths.RemoveAll
this.Files.RemoveAll
Dim Component As VBComponent
Dim AnnotateStart As Long
Dim AnnotateStop As Long
Dim Path As String
Dim Ext As String
Dim ComponentType As String
Dim ComponentDeclareLines As String
For Each Component In this.Project.VBComponents
Select Case Component.Type
Case vbext_ComponentType.vbext_ct_StdModule
ComponentType = "Module"
Ext = ".bas"
Case vbext_ComponentType.vbext_ct_ClassModule
ComponentType = "Class"
Ext = ".cls"
Case vbext_ComponentType.vbext_ct_MSForm
ComponentType = "Form"
Ext = ".frm"
Case vbext_ComponentType.vbext_ct_Document
ComponentType = "Document"
Ext = ".doccls"
End Select
ComponentDeclareLines = Component.CodeModule.Lines(1, Component.CodeModule.CountOfDeclarationLines)
AnnotateStart = InStr(1, ComponentDeclareLines, "'@Folder", vbTextCompare)
If AnnotateStart > 0 Then
AnnotateStart = InStr(AnnotateStart, ComponentDeclareLines, """")
AnnotateStop = InStr(AnnotateStart + 1, ComponentDeclareLines, """")
Path = Mid$(ComponentDeclareLines, AnnotateStart + 1, AnnotateStop - AnnotateStart - 1)
Else
Path = COMMON_FOLDER & "." & ComponentType
Component.CodeModule.InsertLines 1, "'@Folder """ & Path & """"
End If
Path = Replace$(Path, ".", Application.PathSeparator)
this.Paths(Path) = vbNullString
this.Files(Component.Name) = Array(Ext, ComponentType, Path)
Next Component
End Sub
'If provided, prefix must use system path separator
'@Description "Recreates project folder structure in the Project folder (for the entire project or just a path matching provided prefix)."
Public Sub ProjectStructureExport(Optional ByVal Prefix As String = vbNullString)
Attribute ProjectStructureExport.VB_Description = "Recreates project folder structure in the Project folder (for the entire project or just a path matching provided prefix)."
ProjectStructureParse
Dim Path As Variant
Dim PrefixMatch As String
For Each Path In this.Paths
Select Case Len(Path) - Len(Prefix)
Case Is > 0
PrefixMatch = Prefix & Application.PathSeparator
Case 0
PrefixMatch = Prefix
Case Is < 0
PrefixMatch = vbNullString
End Select
If (Len(PrefixMatch) > 0) And (Left$(Path, Len(PrefixMatch)) = PrefixMatch) Or (Len(Prefix) = 0) Then
MkPath this.ProjectPath & Application.PathSeparator & Path
End If
Next Path
End Sub
'If provided, prefix must use system path separator
'@Description "Exports code modules (entire project or prefix matching path) to Project folder."
Public Sub ProjectFilesExport(Optional ByVal Prefix As String = vbNullString)
Attribute ProjectFilesExport.VB_Description = "Exports code modules (entire project or prefix matching path) to Project folder."
ProjectStructureExport Prefix
Dim File As Variant
Dim Path As String
Dim PrefixMatch As String
For Each File In this.Files.Keys
Path = this.Files(File)(2)
Select Case Len(Path) - Len(Prefix)
Case Is > 0
PrefixMatch = Prefix & Application.PathSeparator
Case 0
PrefixMatch = Prefix
Case Is < 0
PrefixMatch = vbNullString
End Select
If (Len(PrefixMatch) > 0) And (Left$(Path, Len(PrefixMatch)) = PrefixMatch) Or (Len(Prefix) = 0) Then
this.Project.VBComponents(File).Export this.ProjectPath & Application.PathSeparator & Path & Application.PathSeparator & File & this.Files(File)(0)
End If
Next File
End Sub
Private Sub WalkTreeCore(ByVal Folder As Folder)
Dim SubFolder As Folder
this.Paths(Folder.Path) = vbNullString
For Each SubFolder In Folder.SubFolders
WalkTreeCore SubFolder
Next SubFolder
End Sub
Public Sub WalkTree(Optional ByVal Prefix As String = vbNullString, Optional ByVal SkipRoot As Variant = Empty)
this.Paths.RemoveAll
Dim RootPrefix As String
RootPrefix = IIf(Prefix = vbNullString, this.ProjectPath, this.ProjectPath & Application.PathSeparator & Prefix)
Dim Root As Folder
Set Root = this.fso.GetFolder(RootPrefix)
WalkTreeCore Root
Dim SkipRootDir As Boolean
SkipRootDir = IIf(IsEmpty(SkipRoot), (Prefix = vbNullString), SkipRoot)
If SkipRootDir Then this.Paths.Remove RootPrefix
End Sub
Public Sub CollectFiles(Optional ByVal Prefix As String = vbNullString, Optional ByVal SkipRoot As Variant = Empty)
WalkTree Prefix, SkipRoot
this.Files.RemoveAll
Dim File As IWshRuntimeLibrary.File
Dim Path As Variant
For Each Path In this.Paths
For Each File In this.fso.GetFolder(Path).Files
this.Files(this.fso.GetBaseName(File.Name)) = Array(this.fso.GetExtensionName(File.Name), Path)
Next File
Next Path
End Sub
Public Sub ImportFiles(Optional ByVal Prefix As String = vbNullString, Optional ByVal SkipRoot As Variant = Empty)
Dim DestructiveWarning As Boolean
Dim Message As String
Message = "Warning, you are about to overwrite existing project modules in project " & UCase(this.Project.Name) & "! Continue?"
DestructiveWarning = MsgBox(Message, vbYesNo + vbExclamation + vbDefaultButton2)
If Not DestructiveWarning Then Exit Sub
CollectFiles Prefix, SkipRoot
Dim Path As String
Dim FileName As Variant
Dim Ext As String
Dim PathName As String
Dim Module As VBIDE.VBComponent
Dim DummyModule As VBIDE.VBComponent
On Error Resume Next
For Each FileName In this.Files.Keys
Set Module = this.Project.VBComponents(FileName)
Path = this.Files(FileName)(1)
Ext = this.Files(FileName)(0)
If Ext = "frx" Then
Ext = "frm"
this.Files(FileName)(0) = Ext
End If
PathName = Path & Application.PathSeparator & FileName & "." & Ext
If Not Module Is Nothing Then this.Project.VBComponents.Remove Module
Select Case Ext
Case "cls", "bas", "frm"
this.Project.VBComponents.Import PathName
Case "doccls"
Set DummyModule = this.Project.VBComponents.Import(PathName)
Module.CodeModule.DeleteLines 1, Module.CodeModule.CountOfLines
Module.CodeModule.InsertLines 1, DummyModule.CodeModule.Lines(1, DummyModule.CodeModule.CountOfLines)
this.Project.VBComponents.Remove DummyModule
End Select
Next FileName
On Error GoTo 0
'''' If "References.xsv" exists in the prefix root, add the references.
PathName = this.ProjectPath _
& IIf(Prefix <> vbNullString, Application.PathSeparator & Prefix, vbNullString) _
& Application.PathSeparator & REFERENCES_FILE
If Dir$(PathName) <> vbNullString Then ReferencesAddFromFile PathName
End Sub
</code></pre>
<p>And a regular module, with demo snippets:</p>
<pre class="lang-vb prettyprint-override"><code>Attribute VB_Name = "ProjectUtilsSnippets"
'@Folder "Common.Project Utils"
'@IgnoreModule ProcedureNotUsed, EmptyStringLiteral
Option Explicit
Private Sub ReferencesSaveToFile()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Project.ReferencesSaveToFile
End Sub
Private Sub ReferencesAddFromFile()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Project.ReferencesAddFromFile
End Sub
Private Sub ProjectStructureParse()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Project.ProjectStructureParse
End Sub
Private Sub ProjectStructureExport()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Dim ExportFolder As String
ExportFolder = "" '"Storage\Record"
Project.ProjectStructureExport ExportFolder
End Sub
Private Sub ProjectFilesExport()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Dim ExportFolder As String
ExportFolder = "" '"Storage\Record"
Project.ProjectFilesExport ExportFolder
End Sub
Private Sub WalkTree()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Dim ImportFolder As String
ImportFolder = "" '"Storage\Record"
Project.WalkTree ImportFolder
End Sub
Private Sub CollectFiles()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Dim ImportFolder As String
ImportFolder = "" '"Storage\Record"
Project.CollectFiles ImportFolder
End Sub
Private Sub ImportFiles()
Dim Project As ProjectUtils
Set Project = New ProjectUtils
Dim ImportFolder As String
ImportFolder = "" '"Storage\Record"
Project.ImportFiles ImportFolder
End Sub
</code></pre>
<p>The Project uses "Windows Script Host Object Model" and "Microsoft Scripting Runtime" library references.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T22:47:23.957",
"Id": "507031",
"Score": "1",
"body": "This appears to be relative to https://github.com/rubberduck-vba/Rubberduck/issues/4646"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T09:09:35.823",
"Id": "507049",
"Score": "0",
"body": "Thank you for pointing this out"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T22:26:08.727",
"Id": "256782",
"Score": "4",
"Tags": [
"vba",
"rubberduck"
],
"Title": "Export/Import Rubberduck VBA Virtual Folder Structure with Library References to/from Project Folder on Hard Drive"
}
|
256782
|
<p>I am trying to implement <a href="https://play2048.co/" rel="nofollow noreferrer">the game 2048</a> in Excel VBA.</p>
<p><img src="https://user-images.githubusercontent.com/5549662/110186224-82636400-7e4f-11eb-8f75-fca0d1945638.png" alt="Figure1" /></p>
<p>The each TRUE / FALSE Boolean value in row 2, 4, 6 and 8 are used for determining the data of each cell in row 1, 3, 5 and 7 is 0 or not.</p>
<p><strong>The experimental implementation</strong></p>
<pre><code>Sub MergeUp()
Dim loop_num
Dim loop_num2
For loop_num2 = 1 To 3
For loop_num = 1 To 4
If Cells(6, loop_num) = True Then
Cells(5, loop_num) = Cells(7, loop_num)
Cells(7, loop_num) = 0
End If
If Cells(4, loop_num) = True Then
Cells(3, loop_num) = Cells(5, loop_num)
Cells(5, loop_num) = 0
End If
If Cells(2, loop_num) = True Then
Cells(1, loop_num) = Cells(3, loop_num)
Cells(3, loop_num) = 0
End If
Next
Next
For loop_num = 1 To 4
If Cells(1, loop_num) = Cells(3, loop_num) Then
Cells(1, loop_num) = Cells(1, loop_num) + Cells(3, loop_num)
Cells(9, "C") = Cells(9, "C") + Cells(3, loop_num)
Cells(3, loop_num) = 0
End If
If Cells(3, loop_num) = Cells(5, loop_num) Then
Cells(3, loop_num) = Cells(3, loop_num) + Cells(5, loop_num)
Cells(9, "C") = Cells(9, "C") + Cells(5, loop_num)
Cells(5, loop_num) = 0
End If
If Cells(5, loop_num) = Cells(7, loop_num) Then
Cells(5, loop_num) = Cells(5, loop_num) + Cells(7, loop_num)
Cells(9, "C") = Cells(9, "C") + Cells(7, loop_num)
Cells(7, loop_num) = 0
End If
Next
For loop_num2 = 1 To 3
For loop_num = 1 To 4
If Cells(6, loop_num) = True Then
Cells(5, loop_num) = Cells(7, loop_num)
Cells(7, loop_num) = 0
End If
If Cells(4, loop_num) = True Then
Cells(3, loop_num) = Cells(5, loop_num)
Cells(5, loop_num) = 0
End If
If Cells(2, loop_num) = True Then
Cells(1, loop_num) = Cells(3, loop_num)
Cells(3, loop_num) = 0
End If
Next
Next
Call rand_num
End Sub
</code></pre>
<pre><code>Sub MergeDown()
Dim loop_num
Dim loop_num2
For loop_num2 = 1 To 3
For loop_num = 1 To 4
If Cells(4, loop_num) = True Then
Cells(3, loop_num) = Cells(1, loop_num)
Cells(1, loop_num) = 0
End If
If Cells(6, loop_num) = True Then
Cells(5, loop_num) = Cells(3, loop_num)
Cells(3, loop_num) = 0
End If
If Cells(8, loop_num) = True Then
Cells(7, loop_num) = Cells(5, loop_num)
Cells(5, loop_num) = 0
End If
Next
Next
For loop_num = 1 To 4
If Cells(7, loop_num) = Cells(5, loop_num) Then
Cells(7, loop_num) = Cells(7, loop_num) + Cells(5, loop_num)
Cells(9, "C") = Cells(9, "C") + Cells(5, loop_num)
Cells(5, loop_num) = 0
End If
If Cells(5, loop_num) = Cells(3, loop_num) Then
Cells(5, loop_num) = Cells(5, loop_num) + Cells(3, loop_num)
Cells(9, "C") = Cells(9, "C") + Cells(3, loop_num)
Cells(3, loop_num) = 0
End If
If Cells(3, loop_num) = Cells(1, loop_num) Then
Cells(3, loop_num) = Cells(3, loop_num) + Cells(1, loop_num)
Cells(9, "C") = Cells(9, "C") + Cells(1, loop_num)
Cells(1, loop_num) = 0
End If
Next
For loop_num2 = 1 To 3
For loop_num = 1 To 4
If Cells(4, loop_num) = True Then
Cells(3, loop_num) = Cells(1, loop_num)
Cells(1, loop_num) = 0
End If
If Cells(6, loop_num) = True Then
Cells(5, loop_num) = Cells(3, loop_num)
Cells(3, loop_num) = 0
End If
If Cells(8, loop_num) = True Then
Cells(7, loop_num) = Cells(5, loop_num)
Cells(5, loop_num) = 0
End If
Next
Next
Call rand_num
End Sub
</code></pre>
<pre><code>Sub MergeLeft()
For loop_num2 = 1 To 3
For loop_num = 1 To 7 Step 2
If Cells(loop_num + 1, "C") = True Then
Cells(loop_num, "C") = Cells(loop_num, "D")
Cells(loop_num, "D") = 0
End If
If Cells(loop_num + 1, "B") = True Then
Cells(loop_num, "B") = Cells(loop_num, "C")
Cells(loop_num, "C") = 0
End If
If Cells(loop_num + 1, "A") = True Then
Cells(loop_num, "A") = Cells(loop_num, "B")
Cells(loop_num, "B") = 0
End If
Next
Next
For loop_num = 1 To 7 Step 2
If Cells(loop_num, "A") = Cells(loop_num, "B") Then
Cells(loop_num, "A") = Cells(loop_num, "A") + Cells(loop_num, "B")
Cells(9, "C") = Cells(9, "C") + Cells(loop_num, "B")
Cells(loop_num, "B") = 0
End If
If Cells(loop_num, "B") = Cells(loop_num, "C") Then
Cells(loop_num, "B") = Cells(loop_num, "B") + Cells(loop_num, "C")
Cells(9, "C") = Cells(9, "C") + Cells(loop_num, "C")
Cells(loop_num, "C") = 0
End If
If Cells(loop_num, "C") = Cells(loop_num, "D") Then
Cells(loop_num, "C") = Cells(loop_num, "C") + Cells(loop_num, "D")
Cells(9, "C") = Cells(9, "C") + Cells(loop_num, "D")
Cells(loop_num, "D") = 0
End If
Next
For loop_num2 = 1 To 3
For loop_num = 1 To 7 Step 2
If Cells(loop_num + 1, "C") = True Then
Cells(loop_num, "C") = Cells(loop_num, "D")
Cells(loop_num, "D") = 0
End If
If Cells(loop_num + 1, "B") = True Then
Cells(loop_num, "B") = Cells(loop_num, "C")
Cells(loop_num, "C") = 0
End If
If Cells(loop_num + 1, "A") = True Then
Cells(loop_num, "A") = Cells(loop_num, "B")
Cells(loop_num, "B") = 0
End If
Next
Next
Call rand_num
End Sub
</code></pre>
<pre><code>Sub MergeRight()
For loop_num2 = 1 To 3
For loop_num = 1 To 7 Step 2
If Cells(loop_num + 1, "B") = True Then
Cells(loop_num, "B") = Cells(loop_num, "A")
Cells(loop_num, "A") = 0
End If
If Cells(loop_num + 1, "C") = True Then
Cells(loop_num, "C") = Cells(loop_num, "B")
Cells(loop_num, "B") = 0
End If
If Cells(loop_num + 1, "D") = True Then
Cells(loop_num, "D") = Cells(loop_num, "C")
Cells(loop_num, "C") = 0
End If
Next
Next
For loop_num = 1 To 7 Step 2
If Cells(loop_num, "C") = Cells(loop_num, "D") Then
Cells(loop_num, "D") = Cells(loop_num, "D") + Cells(loop_num, "C")
Cells(9, "C") = Cells(9, "C") + Cells(loop_num, "C")
Cells(loop_num, "C") = 0
End If
If Cells(loop_num, "B") = Cells(loop_num, "C") Then
Cells(loop_num, "C") = Cells(loop_num, "C") + Cells(loop_num, "B")
Cells(9, "C") = Cells(9, "C") + Cells(loop_num, "B")
Cells(loop_num, "B") = 0
End If
If Cells(loop_num, "A") = Cells(loop_num, "B") Then
Cells(loop_num, "B") = Cells(loop_num, "B") + Cells(loop_num, "A")
Cells(9, "C") = Cells(9, "C") + Cells(loop_num, "A")
Cells(loop_num, "A") = 0
End If
Next
For loop_num2 = 1 To 3
For loop_num = 1 To 7 Step 2
If Cells(loop_num + 1, "B") = True Then
Cells(loop_num, "B") = Cells(loop_num, "A")
Cells(loop_num, "A") = 0
End If
If Cells(loop_num + 1, "C") = True Then
Cells(loop_num, "C") = Cells(loop_num, "B")
Cells(loop_num, "B") = 0
End If
If Cells(loop_num + 1, "D") = True Then
Cells(loop_num, "D") = Cells(loop_num, "C")
Cells(loop_num, "C") = 0
End If
Next
Next
Call rand_num
End Sub
</code></pre>
<pre><code>Public Sub rand_num()
Dim cell_row(4)
cell_row(1) = 1
cell_row(2) = 3
cell_row(3) = 5
cell_row(4) = 7
Dim rand_number(2)
rand_number(1) = cell_row(Int((4 - 1 + 1) * Rnd + 1))
rand_number(2) = Int((4 - 1 + 1) * Rnd + 1)
While (Cells(rand_number(1) + 1, rand_number(2)) = False)
rand_number(1) = cell_row(Int((4 - 1 + 1) * Rnd + 1))
rand_number(2) = Int((4 - 1 + 1) * Rnd + 1)
Wend
Cells(rand_number(1), rand_number(2)) = Int((2 - 1 + 1) * Rnd + 1)
Randomize [Timer]
End Sub
</code></pre>
<pre><code>Sub Clear()
For loop_num = 1 To 4
Cells(1, loop_num) = 0
Cells(3, loop_num) = 0
Cells(5, loop_num) = 0
Cells(7, loop_num) = 0
Next
Cells(9, "C") = 0
Call rand_num
Call rand_num
End Sub
</code></pre>
<p>All suggestions are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:51:05.373",
"Id": "507080",
"Score": "0",
"body": "micro review:); `=IF(A1=0,TRUE,FALSE)` is equivalent to `=A1=0` (or `=(A1=0)` if you're an anxious sort)"
}
] |
[
{
"body": "<p>Some quick feedback because I think you can make some small changes to really improve the readability of your code. If you decide to make some of them you can then post a new question with updated code to get some more targeted reviews...</p>\n<h3>Variables</h3>\n<blockquote>\n<pre><code>Dim loop_num\nDim loop_num2\nDim rand_number(2) 'etc.\n</code></pre>\n</blockquote>\n<p>Although not explicitly required, variables in VBA can have types, just like in strongly typed languages such as <code>c++</code>. Including types in code has 2 benefits:</p>\n<ul>\n<li>Improves performance, as typed variables work faster and take up less memory</li>\n<li>Perhaps more importantly, helps to document the code; if we know <code>loop_num</code> is an integer or <code>rand_num</code> is floating point, then we can assume some stuff about what they might be used for. This makes reading, maintaining and improving the code much easier.</li>\n</ul>\n<p>So prefer:</p>\n<pre><code>Dim loop_num As Long\nDim loop_num2 As Long\nDim rand_number(2) As Single\n</code></pre>\n<hr />\n<p>While we're at it, those variable names aren't very descriptive are they? Sure <code>loop_num</code> tells me it's probably the incremented variable in a for-loop, but I can already see that just by looking! It's better to use descriptive names that make the code self-documenting and easy to follow. I don't really know what all those variables are for, as I'm focussing on the general problems for now, but maybe something like:</p>\n<pre><code>Dim worksheetRow As Long\nDim iterationPassNumber As Long\n</code></pre>\n<p>...would be better.</p>\n<p>Also in a couple of places you don't declare variables; aside from meaning you can't declare a type, failing to enforce variable declarations can allow typos to slip through, <code>loop_counter</code> vs <code>loop_cuonter</code>. Add <code>Option Explicit</code> at the top of your module(s) to enforce variable declaration and help you pick up on typos.</p>\n<hr />\n<h3>Magic Numbers</h3>\n<p>Your code contains a lot of magic numbers - literal values that don't mean anything in isolation but which have some special meaning in your code.</p>\n<pre><code>Dim cell_row(4)\ncell_row(1) = 1 'ok I guess, thanks to a fairly descriptive variable name\ncell_row(2) = 3\ncell_row(3) = 5\ncell_row(4) = 7\nDim rand_number(2) 'um sure, 2 of them why not\nrand_number(1) = cell_row(Int((4 - 1 + 1) * Rnd + 1)) 'I'm at a loss... What do these numbers mean?!\nrand_number(2) = Int((4 - 1 + 1) * Rnd + 1)\nWhile (Cells(rand_number(1) + 1, rand_number(2)) = False)\nrand_number(1) = cell_row(Int((4 - 1 + 1) * Rnd + 1))\nrand_number(2) = Int((4 - 1 + 1) * Rnd + 1)\nWend\nCells(rand_number(1), rand_number(2)) = Int((2 - 1 + 1) * Rnd + 1)\n</code></pre>\n<p>Imagine reading this code for the first time (as I am right now) - would you have any idea what that function was doing. I see random numbers being put in cells, some loop that looks like it might never stop, I have no idea what the logic of this code is supposed to be. I mean</p>\n<blockquote>\n<pre><code>Int((4 - 1 + 1) ' * [...]\n</code></pre>\n</blockquote>\n<p>Why??</p>\n<p>Adding comments to explain why your code is doing what it's doing, or better yet, renaming those numbers as constants:</p>\n<pre><code>Const randomNumberScalingFactor As Long = 4 'or 4 + SomeMagicNumber - AnotherMagicNumber\n</code></pre>\n<p>... then (for example)</p>\n<pre><code>randomColumnIndexInSheet = Int(ColumnCount * Rnd + ColumnOffset))\n</code></pre>\n<hr />\n<h3>DRY</h3>\n<p>Don't Repeat Yourself; <code>MergeUp/Down</code> and<code>MergeLeft/Right</code> contain a lot of repetition, but with slightly different combinations of <code>A,B,C,D</code>. It would be better to take these as arguments to a single Sub, so you can reuse the code to do multiple things.</p>\n<p>For example:</p>\n<blockquote>\n<pre><code>For loop_num2 = 1 To 3\n For loop_num = 1 To 7 Step 2\n If Cells(loop_num + 1, "B") = True Then\n Cells(loop_num, "B") = Cells(loop_num, "A")\n Cells(loop_num, "A") = 0\n End If\n If Cells(loop_num + 1, "C") = True Then\n Cells(loop_num, "C") = Cells(loop_num, "B")\n Cells(loop_num, "B") = 0\n End If\n If Cells(loop_num + 1, "D") = True Then\n Cells(loop_num, "D") = Cells(loop_num, "C")\n Cells(loop_num, "C") = 0\n End If\n Next\n\nFor loop_num2 = 1 To 3\n For loop_num = 1 To 7 Step 2\n If Cells(loop_num + 1, "C") = True Then\n Cells(loop_num, "C") = Cells(loop_num, "D")\n Cells(loop_num, "D") = 0\n End If\n If Cells(loop_num + 1, "B") = True Then\n Cells(loop_num, "B") = Cells(loop_num, "C")\n Cells(loop_num, "C") = 0\n End If\n If Cells(loop_num + 1, "A") = True Then\n Cells(loop_num, "A") = Cells(loop_num, "B")\n Cells(loop_num, "B") = 0\n End If\n Next\nNext\n</code></pre>\n</blockquote>\n<p>could become something like:</p>\n<pre><code>Sub MoveSidewaysWithMapping(ByVal first As String, ByVal second As String, ByVal third As String, ByVal fourth As String)\n '[...]\n For loop_num2 = 1 To 3\n For loop_num = 1 To 7 Step 2\n If Cells(loop_num + 1, third) = True Then\n Cells(loop_num, third) = Cells(loop_num, fourth)\n Cells(loop_num, fourth) = 0\n End If\n If Cells(loop_num + 1, second) = True Then\n Cells(loop_num, second) = Cells(loop_num, third)\n Cells(loop_num, third) = 0\n End If\n If Cells(loop_num + 1, first) = True Then\n Cells(loop_num, first) = Cells(loop_num, second)\n Cells(loop_num, second) = 0\n End If\n Next\n Next\n 'etc...\n</code></pre>\n<p>called like</p>\n<pre><code>'move left:\n MoveSidewaysWithMapping "A","B","C","D"\n\n'move right\n MoveSidewaysWithMapping "D","C","B","A"\n</code></pre>\n<p>you get the idea (p.s. the <code>Call</code> keyword as in <code>Call rand_num</code> is obsolete, you don't need it anymore, and it's good to remove IMO because it's excess clutter for your brain to process)</p>\n<p>Re-using code is valuable as it means if you change the logic, you only change it in one place making it less bug prone. Also less code to process probably makes the code easier to interpret for reviewers and maintainers (you in 6 months), as long as shortening doesn't reduce legibility (which in this case I don't think it would)</p>\n<hr />\n<p>Anyway, that's an initial first pass, if you want more feedback about your technique and algorithm perhaps, then I'd recommend tidying your code up as much as possible with some of the above techniques, and posting a follow up question.</p>\n<p>Hope that helps, let me know if you need clarification (PS, I'm not sure how much of that will be new to you as I see you've asked a lot of questions on CR already, and this is pretty general/basic advice, but I understand if you're just dabbling with a newish language, you can spend most of your time trying to get it work and forget some of the important stylistic fundamentals!)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T03:45:32.417",
"Id": "507281",
"Score": "0",
"body": "Capitalize constants and all those implicit Activesheet references are a bug fest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:03:40.160",
"Id": "507307",
"Score": "0",
"body": "@QHarr oh yeah, haven't mentioned a number of things here, I was waiting for a follow up post that fixes these even more low-hanging points I mention, to make life easier for reviewers. What do you mean about \"Capitalize constants\"? You think I should write them YELLCASE or are you saying that the \"A\",\"B\",\"C\",\"D\" arguments are fraught with risk? I've never really been convinced either way on yellcase since I tend to prefer descriptive names and YELLCASEWITHOUTUNDERSCORES is hard to read, with underscores feels like a clash with IInterface_ImplementationMethods"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:06:22.950",
"Id": "507308",
"Score": "0",
"body": "e.g. `randomColumnIndexInSheet` vs `RANDOMCOLUMNINDEXINSHEET`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T11:16:32.083",
"Id": "507317",
"Score": "1",
"body": "lol! I get what you mean and I think yelling with underscores is the common middle ground."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T12:45:22.717",
"Id": "507680",
"Score": "2",
"body": "@QHarr yeah, but that's what I'm saying, YELL_WITH_UNDERSCORES looks great I agree, but in VBA `_` has special meaning for names (indicates interface implementation) which it doesn't in other languages. E.g. the python [convention for naming constants](https://www.python.org/dev/peps/pep-0008/#id48) is as you describe, but they also use `snake_case` for function names which is generally frowned upon in VBA - because an _ in a function means that function can't be implemented (IIRC). So generally I avoid underscores, and therefore prefer `PascalCase` for public and camelCase for private consts"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:46:28.127",
"Id": "256815",
"ParentId": "256784",
"Score": "5"
}
},
{
"body": "<h2>Helper Variables and Cells</h2>\n<p>Helper variables and cells should be used to better describe simplify our code. The cell formulas are complicating the process. They are forcing you to process Merge Up and Merge Down differently from Merge Left and Merge Right. Use a simple 4 x 4 matrix instead.</p>\n<p>Using a 4 x 4 matrix would allow you to load the data into an array, process it in memory, and overwrite the original data. Not only is this more efficient but it separates the data model from the data view. You will be able to apply the same logic whether the game board starts in cell A1 or Z100.</p>\n<h2>Use Fully Qualified References</h2>\n<p>It is a best practice to qualify your cell references to a worksheet. This makes it easier to debug and reuse your code.</p>\n<p>Here is how I would setup the borad to use a 4 x 4 matrix:</p>\n<pre><code>Private Const GameSheetName As String = "2048"\nPrivate Const TopLeftCellAddress As String = "A1"\nPrivate Const ColumnCount As Long = 4\nPrivate Const RowCount As Long = 4\n\nFunction GameSheet() As Worksheet\n Set GameBoard = ThisWorkbook.Worksheets(GameSheetName)\nEnd Function\n\nFunction GameBoard() As Range\n Set GameBoard = GameSheet.Range(TopLeftCellAddress).Resize(RowCount, ColumnCount)\nEnd Function\n\nFunction Scrore() As Range\n Set GameBoard = GameBoard.Offset(RowCount, ColumnCount).Offset(2, 3)\nEnd Function\n</code></pre>\n<h2>Merge Numbers</h2>\n<p>I might be missing something but shouldn't the loop decrement 1 so that the next value can be moved and possibly merged?</p>\n<h2>Don't Repeat Yourself Principle (DRY)</h2>\n<p>As Greedo correctly states, you should try and avoid repeat code. I recommend passing an enumerated value into a main subroutine and having it process the data.</p>\n<p>In this main procedure I would have two nested loops. The enum would be used to determine the start, end and step values of the loops.</p>\n<pre><code>Private Enum MergeDirection\n Left\n Right\n Up\n Down\nEnd Enum\n\nSub MergeTiles(Direction As MergeDirection)\n Dim Data As Variant\n Data = GameBoard.Value\n Dim a As Long, b As Long\n \n Rem Loop Logic\n \n GameBoard.Value = Data\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-27T19:03:30.867",
"Id": "258776",
"ParentId": "256784",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256815",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T23:51:01.477",
"Id": "256784",
"Score": "4",
"Tags": [
"beginner",
"vba",
"excel",
"2048"
],
"Title": "2048 Game Implementation with Excel VBA"
}
|
256784
|
<p>I am creating an application that interacts with spotify. A part of my app is a <code>FlatList</code> screen displaying a list of songs and song controls.
<a href="https://i.stack.imgur.com/SHEPT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SHEPT.png" alt="enter image description here" /></a></p>
<p>I am under the impression that my <code>FlatList</code> is very poorly optimized, leading to slow load times as you scroll down.</p>
<p>The main issue I want to resolve is this performance issue.</p>
<p>First, the authentication wrapper</p>
<pre><code>import {
setAccessToken,
setRefreshToken,
} from '_redux/features/authenticationSlice'
import authHandler from '_utils/authenticationHandler'
async function updateReduxWithValidAccessToken({
accessToken,
accessExpiration,
refreshToken,
}) {
if (accessToken === null || new Date() > new Date(accessExpiration)) {
console.log('Access Token is Invalid, Refreshing...')
console.log('refreshToken=', refreshToken)
const response = await authHandler.refreshLogin(refreshToken)
accessToken = response.accessToken
setAccessToken({
accessToken,
accessExpiration: response.accessTokenExpirationDate,
})
setRefreshToken({
refreshToken: response.refreshToken,
})
}
return accessToken
}
</code></pre>
<p>Next, the song fetching code. This lives within the component</p>
<pre><code> const [songs, setSongs] = useState([])
const [songsToFetch, setSongsToFetch] = useState(100)
const [page, setPage] = useState(0)
const getSongsOfPlaylist = async (aToken, aPlaylist, aPage, aLimit) => {
const response = await authHandler.get(
`/playlists/${aPlaylist}/tracks`,
aToken,
{
offset: 100 * aPage,
limit: aLimit,
fields:
'total,items(track(preview_url, id, name, duration_ms, artists, album(!available_markets)))',
},
)
if (response) {
const remainingSongs =
response.data.total - songs.length - response.data.items.length
setSongsToFetch(Math.min(100, remainingSongs))
setSongs([...songs, ...response.data.items])
}
}
</code></pre>
<p>Then all the functions related to rendering the list:</p>
<pre><code> useEffect(() => {
console.log('Loading page #', page)
setLoading(true)
updateReduxWithValidAccessToken(authentication)
.then((token) => getSongsOfPlaylist(token, playlistID, page))
.then(() => {
setLoading(false)
})
}, [page])
async function loadMore() {
if (!loading && songsToFetch > 1) {
setPage(page + 1)
}
}
function renderFooter() {
if (!loading) {
return null
}
return <ActivityIndicator animating />
}
function renderSeparator() {
return <SeparatorLine />
}
</code></pre>
<p>Finally, the flatlist code:</p>
<pre><code> <MySongList
data={songs}
renderItem={renderListItem}
keyExtractor={(_, index) => index.toString()}
ItemSeparatorComponent={renderSeparator}
ListFooterComponent={renderFooter}
onEndReached={loadMore}
onEndReachedThreshold={0.1} />
</code></pre>
<p>All this code (except for the authentication wrapper) lives inside a wrapper component, <code>PlaylistDetailScreen</code>.</p>
<pre><code>function PlaylistDetailScreen({ route, navigation, authentication, ...props }) {
// All code above
return loading && page === 0 ? (
<MyText> Loading... </MyText>
) : (
<ContainerView>
<MySongList />
<ContainerView />
)
</code></pre>
<p>From my efforts, it appears that the list is rerendering multiple times. Why would this be?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T00:05:48.410",
"Id": "256787",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"react-native"
],
"Title": "React Native FlatList with Scroll-To-load data"
}
|
256787
|
<p>I noticed that I have a lot of duplication in my codes, but I really don't know how to solve duplication that's why I decided to seek for advice and help from Stack Overflow. I also notice that I have been using more than 1 loop in more cases so I wonder can you all check on my following code snippet and tell me how do I reduce the amount of loop usage and remove the duplication.</p>
<p>My code is a bit long so I decide to <a href="https://onlinegdb.com/BJVPOLlmu" rel="nofollow noreferrer">put it in an online compiler</a> so that you guys can see it clearly, I'm also a bit sorry for asking this ridiculous question, but I really wanted to know how can I reduce the number of lines and memory usage in my program, I'm pretty bad at this..</p>
<p>The following code snippet is basically a program that captures the record about sanitizing a venue; the data will be written in a binary file.</p>
<h3>Infection Level Check</h3>
<p>This function is mainly for prompting the user and collecting the response from user. It is for tracking their level of infection based on their response. I only allow the user to answer yes or no which is a method of validation I believe.</p>
<h3>Table Header / Footer</h3>
<p>This is just for printing the table header and footer which will be used in most of the functions. I decided to make it a function to reduce duplication.</p>
<h3>Sanitize Menu</h3>
<p>This is basically the main menu of this program.</p>
<p>It allows user to navigate to any other feature that he or she wishes to use.</p>
<p>I use a nested <code>do</code>…<code>while</code> for doing validation. I feel like this is not the best way of doing it, but I really don't know how can I improve it.</p>
<h3>Add Record</h3>
<p>It is mainly for adding a new sanitization record. It prompts and asks the user a few things and all the data will be written in a binary file call <code>Sanitization Record.dat</code>. I did some validation for date and time, but I feel like it is a little bit too long. I wonder if I can reduce the amount of lines for the validation?</p>
<h3>Search Record</h3>
<p>This is just a menu for searching a record based on their ID, the company name and etc. Yes, I did use a nested <code>while</code> loop in here for doing validation, which I feel is definitely not the right way of doing it. Maybe you guys can give me any suggestions on it?</p>
<h3>The Rest of the Search Function</h3>
<p>All of these are the same, just that the searching method is different. If it's a string, I will be using <code>strcmp</code>, else I will just compare it with a normal <code>if</code> condition. Once the record is found in the binary file, it will print out the record for the user to see.</p>
<h3>Modify Function</h3>
<p>It allows the user to modify everything inside the binary file except the venue ID. It will prompt and ask the user to enter the venue id he wish to modify, and it will print out the relevant detail to that venue ID and ask for confirmation. If the user answers "Y", it will allow the user to modify those records. Once modified, all the records will be rewritten into the binary file.</p>
<h3>Delete Function</h3>
<p>It allows the user to delete any record inside the binary file. It will first read the binary file and capture all the data into an array structure, then it will ask the user to enter the venue ID for deleting the record. If a record is found, it will prompt and ask whether the user wants to delete; if the user answers "Y" the record will be deleted through array shifting method. Then everything will be rewritten into the binary file.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#pragma warning (disable:4996)
#define MAX 20
typedef struct {
char companyName[41], personInCharge[41], gender, contactNum[13];
float temperature;
int infectionLevel;
}Company;
typedef struct {
int hours, minute;
}Time;
typedef struct {
int day, month, year;
}Date;
struct SanitizeData {
char venueID[10];
Company Details;
Time Start;
Time End;
Date sanitizeDate;
};
// Function Prototype Declaration
int infectionLevelCheck();
void tableHeader();
void tableFooter(int, int);
void sanitizeMenu();
void addRecord();
void searchRecord();
void searchVenueID();
void searchDate();
void searchCompany();
void searchName();
void searchContactNumber();
void searchGender();
void searchTemperature();
void modifyRecord();
void displayRecord();
void deleteRecord();
int infectionLevelCheck() {
char userResponse;
int infectionLevel;
int invalidCounter;
do {
invalidCounter = 0;
infectionLevel = 0;
printf("\n\nRisk Of Infection Check: \n");
printf("-----------------------\n");
printf("Are you having the 2 or more of the following symptoms listed?\n");
printf("- Fever\n");
printf("- Sore Throat\n");
printf("- Runny Nose\n");
printf("- Diarrhea\n");
printf("- Headache\n");
printf("- Body Ache\n");
printf("(Y = Yes, N = No): ");
scanf("%c", &userResponse);
rewind(stdin);
if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
invalidCounter++;
}
else if (toupper(userResponse) == 'Y') {
infectionLevel++;
}
printf("\n\nBesides the Symptoms listed above, are you having the following symptoms: \n");
printf("- Cough\n");
printf("- Difficulty breathing\n");
printf("- Loss of smell\n");
printf("- Loss of taste\n");
printf("(Y = Yes, N = No): ");
scanf("%c", &userResponse);
rewind(stdin);
if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
invalidCounter++;
}
else if (toupper(userResponse) == 'Y') {
infectionLevel += 4;
}
printf("\n\nHave you travelled to any country outside Malaysia\nwithin the past 14 days?\n");
printf("(Y = Yes, N = No): ");
scanf("%c", &userResponse);
rewind(stdin);
if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
invalidCounter++;
}
else if (toupper(userResponse) == 'Y') {
infectionLevel += 2;
}
printf("\n\nHave you had closed contact with anyone who \nconfirmed or suspected case of COVID 19 within the 14 days?");
printf("(Y = Yes, N = No): ");
scanf("%c", &userResponse);
rewind(stdin);
if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {
invalidCounter++;
}
else if (toupper(userResponse) == 'Y') {
infectionLevel += 4;
}
if (invalidCounter > 0) {
printf("\n- Error Found: Invalid Response Entered - \n\n");
}
} while (invalidCounter != 0);
return infectionLevel;
}
void tableHeader() {
printf("------------------------------------------------------------------------------------------------------------------------\n");
printf("| Venue | Sanitization | Ending | Company | Person | Gender | Contact | Temperature | Infection |\n");
printf("| ID | Time | Time | In-Charge | In-Charge | | | | Risk |\n");
printf("|-------|------------------|----------|---------------|-------------|--------|--------------|-------------|------------|\n");
}
void tableFooter(int i, int emptyRecord) {
printf("------------------------------------------------------------------------------------------------------------------------\n");
if (emptyRecord == MAX) {
printf("No Such Record Found\n");
}
else {
printf("%d Record Found\n", i);
}
}
void addRecord() {
struct SanitizeData newData;
FILE* addPtr;
char userResponse;
int validate, invalidCounter, counter = 0, infectionlevel = 0;
addPtr = fopen("Sanitization Record.dat", "ab");
if (addPtr == NULL) {
printf("Unable to open Sanitization Record.dat\n");
exit(-1);
}
else {
do {
system("cls");
do {
invalidCounter = 0;
printf("Add Sanitization Record\n");
printf("-----------------------\n");
printf("Enter Venue ID: ");
scanf("%s", &newData.venueID);
rewind(stdin);
printf("Enter Sanitized Date in [DD/MM/YYYY Format Eg: 19/02/2021] : ");
validate = scanf("%d/%d/%d", &newData.sanitizeDate.day, &newData.sanitizeDate.month, &newData.sanitizeDate.year);
rewind(stdin);
printf("Enter Sanitized Time in [HH:MM Format Eg: 12:51] - \n");
printf("Starting: ");
validate = scanf("%d:%d", &newData.Start.hours, &newData.Start.minute);
rewind(stdin);
printf("Ending: ");
validate = scanf("%d:%d", &newData.End.hours, &newData.End.minute);
rewind(stdin);
printf("Enter Santizie Handling Company Details: \n");
printf("Company Name: ");
scanf("%[^\n]", &newData.Details.companyName);
rewind(stdin);
printf("Person In-Charge Name: ");
scanf("%[^\n]", &newData.Details.personInCharge);
rewind(stdin);
printf("Person In-Charge Gender: ");
scanf("%c", &newData.Details.gender);
rewind(stdin);
printf("Person In-Charge Contact Numer: ");
scanf("%s", &newData.Details.contactNum);
rewind(stdin);
printf("Person In-Charge Temperature: ");
validate = scanf("%f", &newData.Details.temperature);
rewind(stdin);
newData.Details.infectionLevel = infectionLevelCheck();
if (newData.Details.temperature > 37.8) newData.Details.infectionLevel++;
if (validate == 0
|| newData.sanitizeDate.day < 1 || newData.sanitizeDate.day > 31
|| newData.sanitizeDate.month > 12 || newData.sanitizeDate.month < 1
|| newData.Start.hours > 24 || newData.Start.hours < 1
|| newData.Start.minute > 60 || newData.Start.minute < 1
|| newData.End.hours > 24 || newData.End.hours < 1
|| newData.End.minute > 60 || newData.End.minute < 1
|| toupper(newData.Details.gender) != 'M' && toupper(newData.Details.gender) != 'F')
{
if (newData.sanitizeDate.day < 1 || newData.sanitizeDate.day > 31 || newData.sanitizeDate.month > 12 || newData.sanitizeDate.month < 1) {
printf("- Error Found: Invalid Month or Days Entered. -\n");
}
if (newData.Start.hours > 24 || newData.Start.hours < 1 || newData.Start.minute > 60 || newData.Start.minute < 1) {
printf("- Error Found: Invalid Starting Hours or Minutes Entered. - \n");
}
if (newData.End.hours > 24 || newData.End.hours < 1 || newData.End.minute > 60 || newData.End.minute < 1) {
printf("- Error Found: Invalid Ending Hours or Minutes Entered. - \n");
}
if (toupper(newData.Details.gender) != 'M' || toupper(newData.Details.gender) != 'F') {
printf("- Error Found: Invalid Gender Entered. -\n");
}
if (validate == 0) {
printf("- Error Found: Kindly Enter Valid Input Only. - \n");
}
invalidCounter++;
system("pause");
system("cls");
}
else {
fwrite(&newData, sizeof(newData), 1, addPtr);
counter++;
}
} while (invalidCounter != 0);
printf("Add Another Record? (N = No): ");
scanf("%c", &userResponse);
rewind(stdin);
} while (toupper(userResponse) != 'N');
printf("%d Record Added.....\n", counter);
fclose(addPtr);
}
}
void searchVenueID() {
struct SanitizeData data[20];
FILE* searchPtr;
int i = 0, emptyRecord = 0;
int counter = 0;
char venueID[10];
searchPtr = fopen("Sanitization Record.dat", "rb");
if (searchPtr == NULL) {
printf("Unable to open Santization Record.dat\n");
exit(-1);
}
while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) {
i++;
}
printf("Enter Venue ID to Search: ");
scanf("%s", &venueID);
tableHeader();
for (int i = 0; i < 20; i++) {
if (strcmp(venueID, data[i].venueID) == 0) {
counter++;
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data[i].venueID, data[i].sanitizeDate.day, data[i].sanitizeDate.month, data[i].sanitizeDate.year,
data[i].Start.hours, data[i].Start.minute, data[i].End.hours, data[i].End.minute, data[i].Details.companyName,
data[i].Details.personInCharge);
switch (toupper(data[i].Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data[i].Details.contactNum, data[i].Details.temperature);
if (data[i].Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data[i].Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data[i].Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
}
else {
emptyRecord++;
}
}
tableFooter(counter, emptyRecord);
fclose(searchPtr);
}
void searchDate() {
struct SanitizeData data[20];
FILE* searchPtr;
int i = 0, emptyRecord = 0;
int counter = 0;
int day, month, year;
searchPtr = fopen("Sanitization Record.dat", "rb");
if (searchPtr == NULL) {
printf("Unable to open Santization Record.dat\n");
exit(-1);
}
while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) {
i++;
}
printf("Enter Date to Search [Format: 19/02/2021] : ");
scanf("%d/%d/%d", &day, &month, &year);
tableHeader();
for (i = 0; i < 20; i++) {
if (day == data[i].sanitizeDate.day && month == data[i].sanitizeDate.month && year == data[i].sanitizeDate.year) {
counter++;
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data[i].venueID, data[i].sanitizeDate.day, data[i].sanitizeDate.month, data[i].sanitizeDate.year,
data[i].Start.hours, data[i].Start.minute, data[i].End.hours, data[i].End.minute, data[i].Details.companyName,
data[i].Details.personInCharge);
switch (toupper(data[i].Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data[i].Details.contactNum, data[i].Details.temperature);
if (data[i].Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data[i].Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data[i].Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
}
else {
emptyRecord++;
}
}
tableFooter(counter, emptyRecord);
fclose(searchPtr);
}
void searchCompany() {
struct SanitizeData data[20];
FILE* searchPtr;
int i = 0, emptyRecord = 0;
char companyName[41];
int counter = 0;
searchPtr = fopen("Sanitization Record.dat", "rb");
if (searchPtr == NULL) {
printf("Unable to open Santization Record.dat\n");
exit(-1);
}
while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) {
i++;
}
printf("Enter Company Name to Search: ");
scanf("%[^\n]", &companyName);
tableHeader();
for (i = 0; i < 20; i++) {
if (strcmp(companyName, data[i].Details.companyName) == 0) {
counter++;
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data[i].venueID, data[i].sanitizeDate.day, data[i].sanitizeDate.month, data[i].sanitizeDate.year,
data[i].Start.hours, data[i].Start.minute, data[i].End.hours, data[i].End.minute, data[i].Details.companyName,
data[i].Details.personInCharge);
switch (toupper(data[i].Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data[i].Details.contactNum, data[i].Details.temperature);
if (data[i].Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data[i].Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data[i].Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
}
else {
emptyRecord++;
}
}
tableFooter(counter, emptyRecord);
fclose(searchPtr);
}
void searchName() {
struct SanitizeData data[20];
FILE* searchPtr;
int i = 0, emptyRecord = 0;
char personInCharge[41];
int counter = 0;
searchPtr = fopen("Sanitization Record.dat", "rb");
if (searchPtr == NULL) {
printf("Unable to open Santization Record.dat\n");
exit(-1);
}
while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) {
i++;
}
printf("Enter Person In-Charge Name to Search: ");
scanf("%[^\n]", &personInCharge);
tableHeader();
for (i = 0; i < 20; i++) {
if (strcmp(personInCharge, data[i].Details.personInCharge) == 0) {
counter++;
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data[i].venueID, data[i].sanitizeDate.day, data[i].sanitizeDate.month, data[i].sanitizeDate.year,
data[i].Start.hours, data[i].Start.minute, data[i].End.hours, data[i].End.minute, data[i].Details.companyName,
data[i].Details.personInCharge);
switch (toupper(data[i].Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data[i].Details.contactNum, data[i].Details.temperature);
if (data[i].Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data[i].Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data[i].Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
}
else {
emptyRecord++;
}
}
tableFooter(counter, emptyRecord);
fclose(searchPtr);
}
void searchContactNumber() {
struct SanitizeData data[20];
FILE* searchPtr;
int i = 0, emptyRecord = 0;
char contactNum[13];
int counter = 0;
searchPtr = fopen("Sanitization Record.dat", "rb");
if (searchPtr == NULL) {
printf("Unable to open Santization Record.dat\n");
exit(-1);
}
while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) {
i++;
}
printf("Enter Contact Number to Search [Format: 010-2012687]: ");
scanf("%s", &contactNum);
tableHeader();
for (i = 0; i < 20; i++) {
if (strcmp(contactNum, data[i].Details.contactNum) == 0) {
counter++;
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data[i].venueID, data[i].sanitizeDate.day, data[i].sanitizeDate.month, data[i].sanitizeDate.year,
data[i].Start.hours, data[i].Start.minute, data[i].End.hours, data[i].End.minute, data[i].Details.companyName,
data[i].Details.personInCharge);
switch (toupper(data[i].Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data[i].Details.contactNum, data[i].Details.temperature);
if (data[i].Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data[i].Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data[i].Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
}
else {
emptyRecord++;
}
}
tableFooter(counter, emptyRecord);
fclose(searchPtr);
}
void searchGender() {
struct SanitizeData data[20];
FILE* searchPtr;
int i = 0, emptyRecord = 0;
char gender;
int counter = 0;
searchPtr = fopen("Sanitization Record.dat", "rb");
if (searchPtr == NULL) {
printf("Unable to open Santization Record.dat\n");
exit(-1);
}
while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) {
i++;
}
printf("Enter Person In-Charge Gender to Search [F = Female, M = Male]: ");
scanf("%c", &gender);
tableHeader();
for (i = 0; i < 20; i++) {
if (gender == data[i].Details.gender) {
counter++;
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data[i].venueID, data[i].sanitizeDate.day, data[i].sanitizeDate.month, data[i].sanitizeDate.year,
data[i].Start.hours, data[i].Start.minute, data[i].End.hours, data[i].End.minute, data[i].Details.companyName,
data[i].Details.personInCharge);
switch (toupper(data[i].Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data[i].Details.contactNum, data[i].Details.temperature);
if (data[i].Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data[i].Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data[i].Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
}
else {
emptyRecord++;
}
}
tableFooter(counter, emptyRecord);
fclose(searchPtr);
}
void searchTemperature() {
struct SanitizeData data[20];
FILE* searchPtr;
int i = 0, emptyRecord = 0;
float temperature;
int counter = 0;
searchPtr = fopen("Sanitization Record.dat", "rb");
if (searchPtr == NULL) {
printf("Unable to open Santization Record.dat\n");
exit(-1);
}
while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) {
i++;
}
printf("Enter Temperature To Search [Eg: 36.6]: ");
scanf("%f", &temperature);
tableHeader();
for (i = 0; i < 20; i++) {
if (temperature == data[i].Details.temperature) {
counter++;
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data[i].venueID, data[i].sanitizeDate.day, data[i].sanitizeDate.month, data[i].sanitizeDate.year,
data[i].Start.hours, data[i].Start.minute, data[i].End.hours, data[i].End.minute, data[i].Details.companyName,
data[i].Details.personInCharge);
switch (toupper(data[i].Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data[i].Details.contactNum, data[i].Details.temperature);
if (data[i].Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data[i].Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data[i].Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
}
else {
emptyRecord++;
}
}
tableFooter(counter, emptyRecord);
fclose(searchPtr);
}
void searchRecord() {
int selection, invalidCounter;
char userResponse;
do {
system("cls");
do {
invalidCounter = 0;
printf("Search Record Based On Following Criteria: \n");
printf("1. Venue ID\n");
printf("2. Sanitization Date\n");
printf("3. Company Name\n");
printf("4. Person In-Charge\n");
printf("5. Contact Number\n");
printf("6. Gender\n");
printf("7. Temperature\n");
printf("8. Back to Sanitize Menu\n");
printf("Enter Your Choice > ");
scanf("%d", &selection);
if (selection < 1 || selection > 8) {
invalidCounter++;
printf("- Error Found: Enter 1 - 8 ONLY - \n");
system("pause");
system("cls");
}
} while (invalidCounter != 0);
switch (selection) {
case 1:
searchVenueID();
break;
case 2:
searchDate();
break;
case 3:
searchCompany();
break;
case 4:
searchName();
break;
case 5:
searchContactNumber();
break;
case 6:
searchGender();
break;
case 7:
searchTemperature();
case 8:
sanitizeMenu();
break;
}
printf("Anymore to Search? (N = No): ");
scanf("%c", &userResponse);
rewind(stdin);
} while (toupper(userResponse) != 'N');
}
void modifyRecord() {
struct SanitizeData data;
struct SanitizeData modify[20];
FILE* modifyPtr;
int i = 0, counter = 0, validate, invalidCounter, emptyRecord = 0, modifyCounter = 0;
char venueID[10], userResponse;
modifyPtr = fopen("Sanitization Record.dat", "rb");
if (modifyPtr == NULL) {
printf("Unable to open Sanitization Record.dat\n");
exit(-1);
}
while (fread(&data, sizeof(data), 1, modifyPtr) != 0) {
modify[modifyCounter] = data;
modifyCounter++;
}
modifyPtr = fopen("Sanitization Record.dat", "wb");
if (modifyPtr == NULL) {
printf("Unable to open Sanitization Record.dat\n");
exit(-1);
}
do {
system("cls");
printf("Modify Sanitize Record\n");
printf("----------------------\n\n");
printf("Enter Venue ID To Modify: ");
scanf("%s", &venueID);
rewind(stdin);
for (i = 0; i < modifyCounter; i++) {
if (strcmp(venueID, modify[i].venueID) == 0) {
printf("Venue ID : %s\n", modify[i].venueID);
printf("Sanitization Date : %02d-%02d-%4d\n", modify[i].sanitizeDate.day, modify[i].sanitizeDate.month, modify[i].sanitizeDate.year);
printf("Starting Time : %02d:%02d\n", modify[i].Start.hours, modify[i].Start.minute);
printf("Ending Time : %02d:%02d\n", modify[i].End.hours, modify[i].End.minute);
printf("Sanitized Company Name : %s\n", modify[i].Details.companyName);
printf("Person In-Charge Name : %s\n", modify[i].Details.personInCharge);
printf("Person In-Charge Gender : %c\n", modify[i].Details.gender);
printf("Person In-Charge Contact Number: %s\n", modify[i].Details.contactNum);
printf("Person In-Charge Temperature : %.2f\n\n", modify[i].Details.temperature);
printf("Sure to Modify? (Y = Yes): ");
scanf("%c", &userResponse);
if (toupper(userResponse) == 'Y') {
counter++;
do {
invalidCounter = 0;
printf("Enter Sanitized Date in [DD/MM/YYYY Format Eg: 19/02/2021] : ");
validate = scanf("%d/%d/%d", &modify[i].sanitizeDate.day, &modify[i].sanitizeDate.month, &modify[i].sanitizeDate.year);
rewind(stdin);
printf("Enter Sanitized Time in [HH:MM Format Eg: 12:51] - \n");
printf("Starting: ");
validate = scanf("%d:%d", &modify[i].Start.hours, &modify[i].Start.minute);
rewind(stdin);
printf("Ending: ");
validate = scanf("%d:%d", &modify[i].End.hours, &modify[i].End.minute);
rewind(stdin);
printf("Enter Santizie Handling Company Details: \n");
printf("Company Name: ");
scanf("%[^\n]", &modify[i].Details.companyName);
rewind(stdin);
printf("Person In-Charge Name: ");
scanf("%[^\n]", &modify[i].Details.personInCharge);
rewind(stdin);
printf("Person In-Charge Gender: ");
scanf("%c", &modify[i].Details.gender);
rewind(stdin);
printf("Person In-Charge Contact Numer: ");
scanf("%s", &modify[i].Details.contactNum);
rewind(stdin);
printf("Person In-Charge Temperature: ");
validate = scanf("%f", &modify[i].Details.temperature);
rewind(stdin);
modify[i].Details.infectionLevel = infectionLevelCheck();
if (modify[i].Details.temperature > 37.8) modify[i].Details.infectionLevel++;
if (validate == 0
|| modify[i].sanitizeDate.day < 1 || modify[i].sanitizeDate.day > 31
|| modify[i].sanitizeDate.month > 12 || modify[i].sanitizeDate.month < 1
|| modify[i].Start.hours > 24 || modify[i].Start.hours < 1
|| modify[i].Start.minute > 60 || modify[i].Start.minute < 1
|| modify[i].End.hours > 24 || modify[i].End.hours < 1
|| modify[i].End.minute > 60 || modify[i].End.minute < 1
|| toupper(modify[i].Details.gender) != 'M' && toupper(modify[i].Details.gender) != 'F')
{
if (modify[i].sanitizeDate.day < 1 || modify[i].sanitizeDate.day > 31 || modify[i].sanitizeDate.month > 12 || modify[i].sanitizeDate.month < 1) {
printf("- Error Found: Invalid Month or Days Entered. -\n");
}
if (modify[i].Start.hours > 24 || modify[i].Start.hours < 1 || modify[i].Start.minute > 60 || modify[i].Start.minute < 1) {
printf("- Error Found: Invalid Starting Hours or Minutes Entered. - \n");
}
if (modify[i].End.hours > 24 || modify[i].End.hours < 1 || modify[i].End.minute > 60 || modify[i].End.minute < 1) {
printf("- Error Found: Invalid Ending Hours or Minutes Entered. - \n");
}
if (toupper(modify[i].Details.gender) != 'M' || toupper(modify[i].Details.gender) != 'F') {
printf("- Error Found: Invalid Gender Entered. -\n");
}
if (validate == 0) {
printf("- Error Found: Kindly Enter Valid Input Only. - \n");
}
invalidCounter++;
system("pause");
system("cls");
}
} while (invalidCounter != 0);
}
else {
break;
}
fwrite(&modify[i], sizeof(data), 1, modifyPtr);
}
else {
emptyRecord++;
}
}
if (emptyRecord == 20) {
printf("No Record Found\n");
}
printf("Continue Modify Record? (N = No): ");
scanf("%c", &userResponse);
} while (userResponse != 'N');
printf("%d Record Modified\n", counter);
fclose(modifyPtr);
}
void displayRecord() {
struct SanitizeData data;
FILE* displayPtr;
int i = 0;
displayPtr = fopen("Sanitization Record.dat", "rb");
if (displayPtr == NULL) {
printf("Unable to open Sanitization Record.dat\n");
exit(-1);
}
system("cls");
printf("Display All Sanitization Record\n");
printf("-------------------------------\n");
tableHeader();
while (fread(&data, sizeof(data), 1, displayPtr) != 0) {
printf("| %-5s | %02d-%02d-%4d %02d:%02d | %02d:%02d | %-13s | %-11s | ", data.venueID, data.sanitizeDate.day, data.sanitizeDate.month, data.sanitizeDate.year,
data.Start.hours, data.Start.minute, data.End.hours, data.End.minute, data.Details.companyName,
data.Details.personInCharge);
switch (toupper(data.Details.gender)) {
case 'F':
printf("Female ");
break;
case 'M':
printf(" Male ");
break;
}
printf("| %-12s | %.2f | ", data.Details.contactNum, data.Details.temperature);
if (data.Details.infectionLevel <= 1) {
printf(" Low Risk |\n");
}
else if (data.Details.infectionLevel <= 3) {
printf(" Mid Risk |\n");
}
else if (data.Details.infectionLevel >= 4) {
printf(" High Risk |\n");
}
i++;
}
printf("------------------------------------------------------------------------------------------------------------------------\n");
printf("%d Record Found\n", i);
fclose(displayPtr);
}
void deleteRecord() {
struct SanitizeData data;
struct SanitizeData delData[20];
FILE* deletePtr;
int i = 0, delCount = 0, position, emptyRecord = 0;
char userResponse;
char venueID[10];
deletePtr = fopen("Sanitization Record.dat", "rb");
if (deletePtr == NULL) {
printf("Unable to open Sanitization.dat\n");
exit(-1);
}
else {
while (fread(&data, sizeof(data), 1, deletePtr) != 0) {
delData[i] = data;
i++;
delCount++;
}
}
fclose(deletePtr);
deletePtr = fopen("Sanitization Record.dat", "wb");
if(deletePtr == NULL) {
printf("Unable to open Sanitization.dat\n");
exit(-1);
}
else {
do {
printf("Delete Record Based On: ");
printf("1. Venue ID\n");
printf("Enter Venue ID: ");
scanf("%s", venueID);
rewind(stdin);
for (i = 0; i < delCount; i++) {
if (strcmp(venueID, delData[i].venueID) == 0) {
printf("Venue ID : %s\n", delData[i].venueID);
printf("Sanitization Date : %02d-%02d-%4d\n", delData[i].sanitizeDate.day, delData[i].sanitizeDate.month, delData[i].sanitizeDate.year);
printf("Starting Time : %02d:%02d\n", delData[i].Start.hours, delData[i].Start.minute);
printf("Ending Time : %02d:%02d\n", delData[i].End.hours, delData[i].End.minute);
printf("Sanitized Company Name : %s\n", delData[i].Details.companyName);
printf("Person In-Charge Name : %s\n", delData[i].Details.personInCharge);
printf("Person In-Charge Gender : %c\n", delData[i].Details.gender);
printf("Person In-Charge Contact Number: %s\n", delData[i].Details.contactNum);
printf("Person In-Charge Temperature : %.2f\n\n", delData[i].Details.temperature);
position = i;
printf("Confirm to Delete? (Y = Yes): ");
scanf("%c", &userResponse);
rewind(stdin);
if (toupper(userResponse) == 'Y') {
for (i = position; i < delCount; i++) {
delData[i] = delData[i + 1];
}
}
}
else {
emptyRecord++;
}
}
if (emptyRecord == 20) {
printf("-Error Found: No Record - \n");
}
printf("Anymore to Delete? (Y = Yes): ");
scanf("%c", &userResponse);
rewind(stdin);
if (toupper(userResponse) == 'N') {
for (int i = 0; i < delCount--; i++) {
fwrite(&delData[i], sizeof(delData[i]), 1, deletePtr);
}
}
} while (toupper(userResponse) != 'N');
}
fclose(deletePtr);
}
void sanitizeMenu() {
int validate, invalidCounter, selection;
char userResponse;
do {
system("cls");
do {
invalidCounter = 0;
printf(" Sanitization Record Module\n");
printf("-------------------------------------\n");
printf(" MENU\n");
printf("[1] - Add Sanitization Record\n");
printf("[2] - Search Sanitization Record\n");
printf("[3] - Modify Sanitization Record\n");
printf("[4] - Display Sanitization Record\n");
printf("[5] - Delete Sanitization Record\n");
printf("[6] - Record \n");
printf("[7] - Quit This Menu\n");
printf("[8] - Exit The Program\n\n");
printf("Enter Your Selection: ");
validate = scanf("%d", &selection);
rewind(stdin);
if (selection < 1 || selection > 8 || validate == 0) {
invalidCounter++;
printf("- Error Found: Please Enter 1 - 7 Only -\n");
system("pause");
system("cls");
}
} while (invalidCounter != 0);
switch (selection) {
case 1:
addRecord();
break;
case 2:
searchRecord();
break;
case 3:
modifyRecord();
break;
case 4:
displayRecord();
break;
case 5:
deleteRecord();
break;
case 6:
menu();
break;
case 7:
footer();
exit(0);
}
printf("Back to Sanitize Menu? (N = No): ");
rewind(stdin);
scanf("%c", &userResponse);
rewind(stdin);
} while (toupper(userResponse) != 'N');
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T17:44:08.167",
"Id": "507090",
"Score": "3",
"body": "To anyone in the Close Vote Queue, this question now meets Code Review Standards."
}
] |
[
{
"body": "<h1>General Observations</h1>\n<p>The function names are descriptive and this is good. The functions themselves are overly complex (do too much) and many of them can be broken up into smaller functions that do specific tasks. (See Error\nChecking below)</p>\n<p>Two functions are not defined within the scope of the code but are called by the code, <code>menu()</code> and <code>footer()</code>. These are both called in <code>sanitizeMenu()</code>. This can make the question off-topic due to the <code>Missing Code Review Context rule</code> it can also make it harder to do a good review of the code.</p>\n<p>It is not clear why the following pre-processor directive is included in the code since it doesn't seem to affect the warning messages from the gcc compiler:</p>\n<pre><code>#pragma warning (disable:4996)\n</code></pre>\n<p>If you are compiling this on Windows using Visual Studio be aware that Visual Studio doesn't necessarily follow the C standards, and therefore the code might not be portable to Linux systems or other platforms.</p>\n<p>It is not clear why there is no <code>typedef</code> for the <code>SanitizeData</code> struct and the <code>Company</code>, <code>Time</code> and <code>Date</code> do have <code>typedef</code>, this seems inconsistent. Leave spaces between operators and symbol or type names, for example there should be a space after <code>}</code> for all the typedefs.</p>\n<p>Don't use the <code>rewind()</code> function on <code>stdin</code>, there is no way to reset to the beginning of <code>stdin</code> since it is a special FILE pointer that you can't open or close. It is recommended to use <a href=\"https://www.geeksforgeeks.org/g-fact-82/\" rel=\"nofollow noreferrer\"><code>fseek()</code> rather than <code>rewind()</code></a> to return to the first record in a file. The function <code>fseek()</code> returns success or failure where the <code>rewind()</code> function does not. The <code>fseek()</code> function also will not work on <code>stdin</code>.</p>\n<h1>DRY Code or Reducing Code Repetition</h1>\n<p>There are several ways to reduce code repetition in this code, one of the best might be to write some utility functions that implement opening and closing files, this would be applying the Single Responsibility Principle. (DRY means Don't Repeat Yourself)</p>\n<p>The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>Have functions specific to each type of data structure that does a certain thing such as reading or writing that data structure. For example for the struct <code>Company</code> :</p>\n<ul>\n<li>getCompanyName()</li>\n<li>getPersonInCharge()</li>\n<li>getGender()</li>\n<li>getContactNumber()</li>\n</ul>\n<p>And for the struct <code>SanitizeData</code> :</p>\n<ul>\n<li>getVenueID()</li>\n<li>getCompanyDetails()</li>\n<li>getDate()</li>\n</ul>\n<p>A second method that would probably improve the performance of the program would be to open the file only once, read all they data into a linked list of <code>SanitizeData</code> structures, close the data file, make all necessary edits to the data and then write out the updated data to the file. Among other things this could allow the data to be sorted. This would improve performance because opening, closing, reading and writing data to files are very expensive operations that make system calls. This would also remove the necessity for opening and closing the file in each function.</p>\n<h1>Recommendations</h1>\n<h2>Magic Numbers</h2>\n<p>There are Magic Numbers throughout the code, it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<p>There is one symbolic constant (MAX) which is good, but there should be at lease 5 symbolic constants to improve maintainability. One symbolic constant that is clearly missing is <code>VENUEID_SIZE</code> since the\nnumber 10 is used in multiple places for this (<code>SanitizeData</code> structure and in the function <code>searchVenueID()</code>. The symbolic constant MAX is only used once, but it seems that many of the for loops could\nuse it.</p>\n<h2>Error Checking</h2>\n<p>There is a distinct lack of error checking on system supplied functions such as <code>scanf()</code>. The function <code>scanf()</code> returns an integer value that indicates the number of characters read.</p>\n<p>This code in <code>infectionLevelCheck()</code> can be made into a function that will force the user to input the correct response.</p>\n<pre><code> printf("\\n\\nRisk Of Infection Check: \\n");\n printf("-----------------------\\n");\n printf("Are you having the 2 or more of the following symptoms listed?\\n");\n printf("- Fever\\n");\n printf("- Sore Throat\\n");\n printf("- Runny Nose\\n");\n printf("- Diarrhea\\n");\n printf("- Headache\\n");\n printf("- Body Ache\\n");\n printf("(Y = Yes, N = No): ");\n scanf("%c", &userResponse);\n rewind(stdin);\n\n if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {\n invalidCounter++;\n }\n else if (toupper(userResponse) == 'Y') {\n infectionLevel++;\n }\n</code></pre>\n<p>Have a loop in the previous code that doesn't return until the response is <code>Y</code> or <code>N</code>. One of the benefits of this is that the variable <code>invalidCounter</code> may not be necessary in the function.</p>\n<p>This code in the same function could also be moved to a smaller function that just returns the response:</p>\n<pre><code> printf("\\n\\nBesides the Symptoms listed above, are you having the following symptoms: \\n");\n printf("- Cough\\n");\n printf("- Difficulty breathing\\n");\n printf("- Loss of smell\\n");\n printf("- Loss of taste\\n");\n printf("(Y = Yes, N = No): ");\n scanf("%c", &userResponse);\n rewind(stdin);\n\n if (toupper(userResponse) != 'Y' && toupper(userResponse) != 'N') {\n invalidCounter++;\n }\n else if (toupper(userResponse) == 'Y') {\n infectionLevel += 4;\n }\n</code></pre>\n<h2>Initialize Variables When They are Declared</h2>\n<p>The code in <code>infectionLevelCheck()</code> contains these variable declarations:</p>\n<pre><code> char userResponse;\n int infectionLevel;\n int invalidCounter;\n</code></pre>\n<p>This allows the variables to be used without being initialized which can cause undefined behavior (bugs). Always initialize variables when you declare them, the C programming language does not assign a default value to variables when they are declared.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T04:20:15.630",
"Id": "507114",
"Score": "0",
"body": "Hi Packmainbw, Thank for your time in reviewing my code. The reason that i decides to put the pragma warning is that I'm doing it on the visual studio, whenever i use scanf it will prompt and tell me that scanf is not safe therefore I'm using it to bypass those warnings. \n\nIt was definitely my fault for not putting the entire code here, I totally forgot that I have those functions in another .c file, I'm so sorry for not pasting the entire code here. I have read all your suggestion and definitely, i will make good use of it by turning all the capturing user's input into multiple functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T04:22:06.307",
"Id": "507115",
"Score": "0",
"body": "So that the function can focus on doing one thing at a time and duplication can be removed. Thanks for telling me that I should always initialized my variable whenever they are declared, I never knew that I need to initialize them and I always encountered some bug due to variable not initialized @_@."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T08:43:22.510",
"Id": "507123",
"Score": "0",
"body": "Oh ya also, the reason i wanna use rewind(stdin) is just to clear the input buffer of the enter key so that the user can keep on continue entering the response, but I've seen both of the answer from two, do i like replace scanf with something else like gets / getchar something like this so that i don't have to use rewind(stdin) anymore?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T21:10:25.813",
"Id": "256823",
"ParentId": "256788",
"Score": "4"
}
},
{
"body": "<p>You have not given us all the code. This makes it hard to try out the program, and it makes it hard to check the online compiler link you helpfully provided.</p>\n<p>(It's not a requirement to provide all the code -- reviews don't depend on it. But it seems like you provided 90%, so why not go the extra 10%?)</p>\n<h1>Eliminate <em>all</em> the compiler warnings!</h1>\n<p>You provided a link to an online compiler service that uses GCC for its compilation backend. But this code appears to be aimed at Windows, and at Microsoft's compiler in particular. You might do well to use a Microsoft-oriented online compiler service.</p>\n<p>Regardless, though, the very first rule for junior C programmers is this one: ELIMINATE ALL THE COMPILER WARNINGS!</p>\n<p>Right now, the compiler is smarter than you are. If it prints a warning, no matter how incomprehensible the warning message is, there's a reason. Figure out what it is telling you, and take whatever steps are required to get rid of the warning.</p>\n<p>You can post small snippets, plus the warning, in questions on Stack Overflow or Reddit or whatever-website, and you'll probably get a solid answer in less than a day. (In many cases, less than an hour.)</p>\n<h1>Improve your layout with vertical spacing</h1>\n<p>Identify "sections" or "paragraphs" and use vertical spacing (aka: blank lines) to separate them from each other. Consider:</p>\n<pre><code>#include <stdio.h> \n#include <stdlib.h> \n#include <ctype.h> \n#include <string.h> \n#pragma warning (disable:4996) \n#define MAX 20 \ntypedef struct { \n char companyName[41], personInCharge[41], gender, contactNum[13]; \n float temperature; \n int infectionLevel; \n}Company; \n</code></pre>\n<p>This would look better, and be slightly more readable, with a few extra newlines:</p>\n<pre><code>#include <stdio.h> \n#include <stdlib.h> \n#include <ctype.h> \n#include <string.h> \n\n#pragma warning (disable:4996) \n\n#define MAX 20 \n\ntypedef struct { \n char companyName[41], personInCharge[41], gender, contactNum[13]; \n float temperature; \n int infectionLevel; \n}Company; \n</code></pre>\n<h1>Adopt a coding standard</h1>\n<p>Your naming and code style is very unpredictable. Find a coding standard that suits you, and adopt it. Be aware that once you've adopted this standard, you will become a dogmatic, unflexible jerkwad, advocating your particular style in preference to all other styles, and you'll likely spend the next 10 years trying to convince all your peers and various strangers you meet on the bus or in airports that your coding style is the right one. So it pays to pick one that has a sensible rationale attached to it.</p>\n<p>Regardless, find a style you like, adopt it, and rewrite all your code in that style.</p>\n<h1>Style: one declarator per declarator-list</h1>\n<p>Yes, I know that C supports multiple declarator names separated by commas.</p>\n<p>But I'm not aware of any coding standard that encourages this, nor am I aware of any experienced coder who thinks it's a good style.</p>\n<p>Rewrite code like this:</p>\n<pre><code>typedef struct { \n int day, month, year; \n}Date; \n</code></pre>\n<p>to look like this:</p>\n<pre><code>typedef struct {\n int day;\n int month;\n int year;\n} Date;\n</code></pre>\n<h1>No 'magic' numbers!</h1>\n<p><a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">Magic numbers</a>, or magic values (in the case of non-numerics) are so universally reviled that there is not even the usual wishy-washy "Discussion" associated with them on Wikipedia. Everybody agrees that magic values are bad. Just don't do it!</p>\n<p>Train yourself to replace all magic values with constants, before you even write them the first time!</p>\n<p>The only two numeric digits that should appear anywhere in your code other than as character/string literals, constant definitions, or as part of an identifier, are <code>0</code> and <code>1</code>.</p>\n<p>Replace this:</p>\n<pre><code>typedef struct { \n char companyName[41], personInCharge[41], gender, contactNum[13]; \n</code></pre>\n<p>with something like this:</p>\n<pre><code>typedef struct {\n char companyName[MAX_NAME_LEN + 1];\n char personInCharge[MAX_NAME_LEN + 1];\n char gender;\n char contactNum[MAX_CONTACT_LEN + 1];\n</code></pre>\n<p><strong>Note:</strong> There are two lengths when dealing with C strings: the length of the string as reported by <code>strlen()</code> and the size of the buffer you will need to store a string. Because of the trailing NUL delimiter, these two numbers differ by 1: to store a string with <code>strlen</code> of 0 requires a buffer with 1 character: <code>[ '\\0' ]</code></p>\n<p>As a result of this, you are faced with declaring constants that are 1-too-big or 1-too-small. If your constants are the string's max length, they are 1-too-small for buffer size. If they are the buffer size, then they are 1-too-big for string length. It is <em>my opinion</em> (this is one of those dogmatic coding-standard things) that using <code>_LEN + 1</code> is the better way because:</p>\n<ul>\n<li>this is what you have to do when dynamically allocating strings using <code>malloc</code> (consistency);</li>\n<li>the <code>_LEN + 1</code> model is intuitive for even junior coders who are aware of how C strings work;</li>\n<li>the <code>_LEN</code> constant is more likely to be useful at runtime (comparing against <code>strlen</code> for example).</li>\n</ul>\n<p>You could certainly choose to do something like:</p>\n<pre><code>typedef struct {\n char companyName[MAX_NAME_BUF];\n char personInCharge[MAX_NAME_BUF];\n char gender;\n char contactNum[MAX_CONTACT_BUF];\n</code></pre>\n<p>and it would also work.</p>\n<h1>Use <code>typedef</code> to save typing!</h1>\n<p>You have this typedef:</p>\n<pre><code>typedef struct { ... } Date;\n</code></pre>\n<p>You have this struct with no typedef:</p>\n<pre><code>struct SanitizeData { ... }; \n</code></pre>\n<p>I run these commands and get these results:</p>\n<pre><code>$ grep '\\<Date' sanitization.c | grep -v 'printf' | wc -l\n2\n\n$ grep '\\<SanitizeData' sanitization.c | grep -v 'printf' | wc -l\n14\n</code></pre>\n<p>If you're not unix-savvy, those lines say "find every line containing start-of-word followed by Date/SanitizeData and print them, then filter out any printed line that also contains the word 'printf', then count the number of resulting lines."</p>\n<p>The two results for <code>Date</code> are for the typedef itself (obviously the word appears where the word is defined) and for where <code>Date</code> is the type of a member inside the <code>SanitizeData</code> structure.</p>\n<p><em>Technically,</em> you would be better off declaring <code>struct Date</code> and using that inside <code>SanitizeData</code>.</p>\n<p>On the other hand, there are 13 places where <code>SanitizeData</code> occurs after you declare the structure. Each of those places would be shorter if <code>struct SanitizeData</code> were replaced by <code>SanitizeData</code>.</p>\n<p>Go ahead and use <code>typedef</code> on SanitizeData.</p>\n<h1>Use C prototypes for C functions</h1>\n<p>C requires <code>(void)</code> to indicate an empty function parameter list. Declaring</p>\n<pre><code>int infectionLevelCheck();\n</code></pre>\n<p>is actually an "old-style" function declaration, that tells the compiler there is a function out there, but doesn't declare any parameters <strong>and</strong> doesn't declare an empty parameter list.</p>\n<p>If you want to create a prototype, use</p>\n<pre><code>int infectionLevelCheck(void);\n</code></pre>\n<h1>Don't <code>rewind(stdin)</code></h1>\n<p>This is a Microsoft-ism, and it's doing you a huge disservice. It claims to "clear the keyboard buffer" but that would only be true if stdin was connected to a keyboard.</p>\n<p>If you want to do some unit tests, a simple way would be to create a text file full of inputs, and feed that to your program. Except that if you have <code>stdin</code> pointing to a file and call <code>rewind(stdin)</code> it would just start the input over again. D'oh!</p>\n<p>I suspect you're doing this because you are using <code>scanf</code> and you haven't figure out how <code>scanf</code> deals with all the various input character (like the newline at the end of an input).</p>\n<p>I'd suggest that you stop using <code>scanf</code> for input, and use something more useful. Then you can use <code>sscanf</code> or something else for processing the input you get -- see below.</p>\n<h1>Write an input module</h1>\n<p>Much of your code consists of printing messages/prompts/menus to the user, and then reading responses back from the user.</p>\n<p>Instead of doing the same thing over and over and over and over and over, why not write some functions to do it for you?</p>\n<p>Write functions like <code>Date get_date()</code>, <code>int get_number(void)</code>, and <code>int get_yn()</code> that loop until they receive a valid input. Then just call the functions.</p>\n<p>You might want to add some output functions as well, and make it a <code>text_ui</code> module.</p>\n<p>These functions can initially just be placed at the top of your program (before other functions that use them) and then you can migrate them to a separate library if you end up re-using them in another program.</p>\n<h1>Change your search model</h1>\n<p>Your <code>search</code> routines presently have an array of 20 <code>struct SanitizeData</code> objects that they try to read in from the data file.</p>\n<p>I suspect you have crashes when you run this code with lots of records, since it seems like your read-in-the-file code overwrites the stack.</p>\n<p>In particular:</p>\n<pre><code> while (fread(&data[i], sizeof(data), 1, searchPtr) != 0) { \n</code></pre>\n<p>In the code above, <code>data</code> is an array of 20 records. So <code>sizeof(data)</code> is <code>20 * sizeof(record)</code>. You're reading 20-records in 1 time, then looping back to do it again at an offset of +1 record in the buffer.</p>\n<p>The first time you do this, you can read up to 20 records no problem. The second time you do this, you will write 20-records worth of data at location <code>data[1]</code>, which only has 19 records worth of space before the data hits the stack.</p>\n<p>So I think if the first read succeeds, and the second read succeeds, you'll get stack corruption. This should happen with 40 or more records in the file.</p>\n<p>There's also the bug that you're overwriting the last 19 records that were read in by the read at <code>data[0]</code>.</p>\n<p>To fix this, just read one record worth of data:</p>\n<pre><code>fread(&data[i], sizeof(data[i]), 1, searchPtr)\n</code></pre>\n<p>The change is from <code>sizeof(data)</code> to <code>sizeof(data[i])</code>. You could use other expressions, like <code>sizeof(struct SanitizeData)</code>. But <code>data</code> is 20 times bigger than you need.</p>\n<p><strong>Regardless</strong> of all that, there is still the fact that you are trying to read in "all the data" and then search it. To quote a famous squirrel: "That trick <em>never</em> works!"</p>\n<p>Instead, put the <code>fread</code> into the loop and just read one record, then check it. This way you won't have to worry about running out of space in memory, even if you have millions of records.</p>\n<h1>Centralize your formatting</h1>\n<p>You have a lot of <code>printf()</code> format strings. Instead of copying those all over the place, write a function or macro that does it for you!</p>\n<p>For macros, you can rely on C's <a href=\"https://docs.microsoft.com/en-us/cpp/c-language/string-literal-concatenation?view=msvc-160\" rel=\"nofollow noreferrer\"><code>adjacent string literal concatenation</code></a> to join everything together:</p>\n<pre><code>#define TBL_VENUE_FMT "| %-5s "\n#define TBL_DATETIME_FMT "| %02d-%02d-%4d %02d:%02d "\n#define TBL_TEMP_FMT "| %.2f "\n</code></pre>\n<p>Then</p>\n<pre><code>printf(TBL_VENUE_FMT \n TBL_DATETIME_FMT\n ...,\n data[i].venueID,\n ...);\n</code></pre>\n<p>For functions, you could have them return strings and just format everything use <code>%s</code>.</p>\n<pre><code>printf("| %s | %s | %s ...",\n format_venue(data[i].venueID,\n format_datetime(data[i].sanitizeDate, data[i].Start),\n ...);\n</code></pre>\n<h1>Replace <code>system("cls")</code></h1>\n<p>There's a lot of people in the world who won't have any idea what that does. So wrap it in a function:</p>\n<pre><code>void \nclear_screen(void)\n{\n system("cls");\n}\n</code></pre>\n<p>Then you can call:</p>\n<pre><code>do {\n clear_screen();\n do {\n</code></pre>\n<p>and everybody knows the score!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T04:15:26.910",
"Id": "507113",
"Score": "0",
"body": "First off, I would like to say that I'm really sorry that It was my mistake I didn't paste the entire code here because I totally forgot about it, it was in another .c file...., I really appreciate your time in reviewing my code and giving me a bunch of suggestion, I will definitely take note on this suggestion by making all of the capturing user's input in a function so that one function only required to do one single task. \n\nYou have a really good point that I can make use of the macro to do the formatting, I really didn't know that I can do it that way... Thanks for pointing it out to me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T04:27:17.233",
"Id": "507116",
"Score": "0",
"body": "Also, I really didn't know that I should always put a void inside the parameter of my function prototype @_@, thanks for letting me know. Yes I will listen to your suggestion and try to be more consistent and adapt to one coding standard, I didn't know that rewind(stdin) is a bad thing and yes i probably will start using like fgets, gets and sscanf i believe for getting user's input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T11:48:01.560",
"Id": "507137",
"Score": "0",
"body": "Is \"appears to target Windows\" comment based on the `#pragma`? If that were inside an `#ifdef`, it's not far from being portable. Oh, we'd have to fix the assumptions where `system()` is called, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T12:36:32.043",
"Id": "507145",
"Score": "0",
"body": "I'm not quite sure on this, all I know is it will just stop me from using scanf or all sorts of commands that he thinks it is unsafe.... so that's why I have to use #pragma warning (disable:4996)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T22:43:08.937",
"Id": "256824",
"ParentId": "256788",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T02:14:45.560",
"Id": "256788",
"Score": "2",
"Tags": [
"c"
],
"Title": "A program to record sanitisation of a venue"
}
|
256788
|
<p>I'm attempting to implement a high resolution class used to time the execution time of functions in Windows. After using <a href="https://docs.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps" rel="nofollow noreferrer">this</a> documentation, I have come up with the following:</p>
<pre><code>#include <iostream>
#include <windows.h>
class Timer {
private:
LARGE_INTEGER start_count;
LARGE_INTEGER stop_count;
LARGE_INTEGER tick_freq;
public:
// Query the tick frequency upon instantiation of the class
Timer() {
QueryPerformanceFrequency(&tick_freq);
}
// Query performance counter at the start of a block of code
void start() {
QueryPerformanceCounter(&start_count);
}
// Query the performance counter at the end of a block of code, then calculate time elapsed in seconds
double stop() {
QueryPerformanceCounter(&stop_count);
return (double)(stop_count.QuadPart - start_count.QuadPart) / tick_freq.QuadPart;
}
};
int main() {
Timer t;
t.start();
// code to be timed
std::cout << t.stop();
}
</code></pre>
<p>I understand that there would be an error of plus or minus the period of each tick. However, various functions I have timed seem to give unexpected results. For example, timing a function that finds the greatest common denominator using Euclid's algorithm consistently uses 100 or 200ns, but appending one int to a vector takes 1600ns. This therefore leads me to the question: <strong>how accurate is this timing class, and what can I do to improve it?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T04:07:23.510",
"Id": "507040",
"Score": "2",
"body": "Raymond Chen from Microsoft wrote up a devblog about it a couple years ago: https://devblogs.microsoft.com/oldnewthing/20170921-00/?p=97057 \"As accurate as the hardware allows\" for those particular functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T04:13:08.000",
"Id": "507041",
"Score": "1",
"body": "It may not be your Timer class...When you timed your functions, did you warm the cache by running the function a few million times before beginning an actual timing and avoid including output in the duration?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T04:13:53.427",
"Id": "507042",
"Score": "2",
"body": "Also, don't profile Debug builds. Make sure you're in Release mode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T01:38:01.900",
"Id": "507099",
"Score": "0",
"body": "@Casey thanks for the tip about warming the cache, will do in the future."
}
] |
[
{
"body": "<h1>Avoid storing data unnecessarily</h1>\n<p>Your class stores the start time, stop time and frequency in member variables, however you only need to store the start time:</p>\n<pre><code>class Timer {\n LARGE_INTEGER start_count;\n\npublic:\n // Query performance counter at the start of a block of code\n void start() {\n QueryPerformanceCounter(&start_count);\n }\n\n // Query the performance counter at the end of a block of code, then calculate time elapsed in seconds\n double stop() {\n LARGE_INTEGER stop_count;\n QueryPerformanceCounter(&stop_count);\n\n LARGE_INTEGER tick_freq_count;\n QueryPerformanceFrequency(&tick_freq);\n return (double)(stop_count.QuadPart - start_count.QuadPart) / tick_freq.QuadPart;\n }\n};\n</code></pre>\n<h1>Consider using <code>std::chrono</code> functions</h1>\n<p>If you can use C++11 or later, then you should be able to get the same timing information in a platform-independent way by using <a href=\"https://en.cppreference.com/w/cpp/chrono/high_resolution_clock\" rel=\"nofollow noreferrer\"><code>std::chrono::high_resolution_clock</code></a>. See <a href=\"https://en.cppreference.com/w/cpp/chrono/high_resolution_clock/now\" rel=\"nofollow noreferrer\">this example</a> for how it can be used.</p>\n<h1>Accuracy</h1>\n<p>The actual accuracy depends on many things. The inherent accuracy depends on the accuracy of the performance counter of the CPU, which can vary between models. However, there are many reasons why the measured time will vary, among them are:</p>\n<ul>\n<li>The state of the cache (as suggested by Casey, you should do a warm-up run before doing the actual performance measurements)</li>\n<li>The CPU frequency changes (the OS will normally adjust the frequency many times per second to ensure your processor runs as energy efficient as possible)</li>\n<li>Other threads might get a timeslice while your code is running</li>\n</ul>\n<p>You could try to address all these issues yourself (many of them are solved by doing a warm-up run, then running your performance measurements many times and taking the average, removing outliers in some way). Alternatively, consider using existing libraries that already solve this problem, for example <a href=\"https://github.com/google/benchmark\" rel=\"nofollow noreferrer\">Google Benchmark</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T01:41:18.510",
"Id": "507100",
"Score": "0",
"body": "Thank you for the link to Google Benchmark. My reasoning behind storing the stop time and frequency in private variables was that it would prevent additional time being used in declaring local variables in the stop function and calling the Windows functions to get their values. Would the time cost of the above be miniscule enough to justify a better coding style as you suggested?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T02:46:57.237",
"Id": "507106",
"Score": "0",
"body": "@GeorgeTian FYI, the `std::chrono::high_resolution_clock` in all cases if just a typedef for one of the other two clocks. Don't let the implementer pick. Just use `std::chrono::steady_clock`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T08:53:53.420",
"Id": "507125",
"Score": "0",
"body": "@GeorgeTian Declaring a `LARGE_INTEGER` locally does not have any runtime cost."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T10:06:45.957",
"Id": "256798",
"ParentId": "256790",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256798",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T03:16:45.850",
"Id": "256790",
"Score": "3",
"Tags": [
"c++",
"windows",
"timer"
],
"Title": "Windows high resolution timing class"
}
|
256790
|
<p>If you ever had to pipe a large amount of data from some program <code>foo</code> into another program <code>bar</code>, you're probably familiar with the <a href="https://sourceforge.net/projects/pipeviewer/" rel="nofollow noreferrer">pipeviewer</a> application. In case you're not familiar with the application, here's a small demonstration of a minimal rewrite:</p>
<p><a href="https://i.stack.imgur.com/iBa68.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iBa68.gif" alt="demonstration of pv's behaviour" /></a></p>
<p>Essentially, <code>pv</code> will take any input from <code>stdin</code> (or files) and forward it to <code>stdout</code> while showing progress on <code>stderr</code>. Note that the original <code>pv</code> has some more features that were non-goals of this project.</p>
<h3>Cargo.toml (dependencies)</h3>
<pre><code>[dependencies]
anyhow = "1.0"
indicatif = "0.15.0"
structopt = "0.3"
</code></pre>
<h3>main.rs</h3>
<pre class="lang-rust prettyprint-override"><code>use anyhow::Result;
use indicatif::{ProgressBar, ProgressStyle};
use std::fs::File;
use std::io::{self, ErrorKind, Read};
use std::path::PathBuf;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(name = "pipeviewer", about = "A pipe inspecting application.")]
struct Opt {
/// Input file, stdin if not specified
#[structopt(parse(from_os_str))]
input: Option<PathBuf>,
}
fn main() -> Result<()> {
let opts = Opt::from_args();
let (mut input, len): (Box<dyn Read>, Option<u64>) = if let Some(file) = opts.input {
let file = File::open(file)?;
let len = file.metadata()?.len();
(Box::new(file), Some(len))
} else {
(Box::new(io::stdin()), None)
};
let pb = if let Some(len) = len {
let pb = ProgressBar::new(len);
pb.set_style(ProgressStyle::default_bar().template(
"[{elapsed_precise}] {bar} {bytes_per_sec} [{bytes}/{total_bytes}] ETA: {eta}",
));
pb
} else {
let pb = ProgressBar::new_spinner();
pb.set_style(
ProgressStyle::default_spinner()
.template("[{elapsed_precise}] {spinner} {bytes_per_sec} [{bytes}]"),
);
pb
};
let mut output = pb.wrap_write(io::stdout());
match io::copy(&mut input, &mut output) {
Ok(_) => Ok(()),
Err(e) if e.kind() == ErrorKind::BrokenPipe => Ok(()),
Err(e) => Err(e.into()),
}
}
</code></pre>
<p>The code is slightly dominated by the styling of the progress bar, unfortunately. However, I didn't want to show a meaningless progress bar on an unknown amount of data (e.g. <code>foo | pv | bar</code>), nor did I want to show no kind of progress <em>if</em> the amount of data is known (e.g. <code>pv somefile</code>).</p>
<p>I'm mostly interested about style issues, hit pitfalls and similar Rust sins. I'm aware that I can add some additional features (e.g. more files as arguments, size hints for STDIN, support for multiple <code>pv</code>'s in a single pipe) and will happily take some inspiration from reviews, but I primarily want to improve my Rust skills :).</p>
<h1>Some additional remarks</h1>
<p>This section only provides some background and is completely optional to read :).</p>
<h2>Motivation</h2>
<p>This rewrite is inspired by the <a href="https://www.udemy.com/course/hands-on-systems-programming-with-rust/" rel="nofollow noreferrer">Udemy course <em>Hands-On System Programming with Rust</em></a>. However, I deviate from the original course by a lot, as it introduces multithreading (via <code>crossbeam</code>) and other (slightly) overkill features.</p>
<h3>Goals of the lazy pipeviewer rewrite</h3>
<ul>
<li><strong>use already existing crates where possible</strong> (don't run into <a href="https://en.wikipedia.org/wiki/Not_invented_here" rel="nofollow noreferrer">NIH</a>)</li>
<li>take either a single file name or use stdin as input</li>
<li>flush everything into stdout (but ignore broken pipes)</li>
<li>don't overengineer, e.g.
<ul>
<li>no multi-threading if single-core performance is good enough</li>
<li>no <code>BufReader</code> or <code>BufWriter</code> if the unbuffered variants seem fast enough</li>
<li>no explicit buffering via <code>Read::read(&mut [u8])</code> if possible, KISS!</li>
</ul>
</li>
</ul>
<h3>Dumbing it down</h3>
<p>There was a point while writing this lazy code where a <code>while let Ok(n) = input.read(&mut buf)</code> was introduced, but given that <code>io::copy</code> seemed fast enough, I didn't bother using it in the final version. Same holds for <code>BufReader</code> and <code>BufWriter</code>, as they didn't improve the behaviour on my machines. Further benchmarks might be necessary, but that could more or less defeat the lazy part ;).</p>
<h3>Getting to know the crates (for other projects)</h3>
<p>This whole project is more or less meant as an exercise for a) searching for appropriate crates and b) using them in the correct manner. Argument parsing? Almost always necessary. Proper error handling? A must. Showing a nice progress bar on the way to completion? A big bonus!</p>
<h2>Dependencies</h2>
<p>For dependencies, I've opted for</p>
<ul>
<li><a href="https://docs.rs/structopt/" rel="nofollow noreferrer"><code>structopt</code></a> to parse the single argument (I originally had more arguments)</li>
<li><a href="https://docs.rs/anyhow/" rel="nofollow noreferrer"><code>anyhow</code></a> to provide error messages</li>
<li><a href="https://docs.rs/indicatif/" rel="nofollow noreferrer"><code>indicatif</code></a> for a progress bar</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T11:31:31.023",
"Id": "507134",
"Score": "0",
"body": "Some additional remarks: the original `pv` application manages up to 8GB/s on `pv < /dev/zero > /dev/null`. Neither `BufReader` nor `BufWriter` change that behaviour. There might be something amiss in `indicatif` but I wasn't able to profile the program yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T12:04:55.880",
"Id": "507142",
"Score": "0",
"body": "Update on above's remark: it seems like `pv`'s `write` call is faster on `/dev/null` for unknown reasons. On actual in-pipeline usage, `pv` yields ~1.2GB/s, which is roughly in the ballpark of the small demo application (~900MB/s)."
}
] |
[
{
"body": "<p>The main sin (accidental pun) is putting it all in <code>fn main</code>. Prefer fancier but readable code over condensed code. This often boils down to adding a function for some assignments. Indeed, we can add a function for getting the content of <code>let (mut input, len)</code> and another for getting <code>let pb</code>.</p>\n<p>A minor sin is failing if <code>fn metadata</code> fails. You only need metadata to get len, which is entirely optional.</p>\n<p>I can't find any other sins. You are forgiven for your transgressions on the art of Rust.</p>\n<ul>\n<li>A bug: I get 0B/s on the use case that's in your post, instead of the number in the gif. Can't imagine why.</li>\n<li>I suggest printing a message with the number of bytes copied on exit, like <code>dd</code> does on linux, so that <em>something</em> happens even for tiny files. You could use <code>fn abandon_with_message</code> on pb.</li>\n</ul>\n<p>That's all. I found the style ok in case we would be limited to one function. But we aren't, so I made an abstraction to minimize the complexity of <code>fn main</code> at the expense of adding 3 functions:</p>\n<p>And last but not least, you could easily avoid dynamic dispatch there, but there's no preference for either type of dispatch in my opinion.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use anyhow::Result;\nuse indicatif::{ProgressBar, ProgressStyle};\nuse std::fs::File;\nuse std::io::{self, ErrorKind, Read};\nuse std::path::PathBuf;\nuse structopt::StructOpt;\n\n#[derive(Debug, StructOpt)]\n#[structopt(name = "pipeviewer", about = "A pipe inspecting application.")]\nstruct Opt {\n /// Input file, stdin if not specified\n #[structopt(parse(from_os_str))]\n input: Option<PathBuf>,\n}\n\nenum PvSource {\n File {\n file: File,\n size: Option<u64>,\n },\n Stdin,\n}\n\nimpl PvSource {\n fn with_path(path: PathBuf) -> Result<Self> {\n let file = File::open(path)?;\n Ok(PvSource::File {\n size: file.metadata().ok().map(|metadata| metadata.len()),\n file,\n })\n }\n\n fn progress_bar(&self) -> ProgressBar {\n if let &PvSource::File { size: Some(len), .. } = self {\n let pb = ProgressBar::new(len);\n pb.set_style(ProgressStyle::default_bar().template(\n "[{elapsed_precise}] {bar} {bytes_per_sec} [{bytes}/{total_bytes}] ETA: {eta}",\n ));\n pb\n } else {\n let pb = ProgressBar::new_spinner();\n pb.set_style(\n ProgressStyle::default_spinner()\n .template("[{elapsed_precise}] {spinner} {bytes_per_sec} [{bytes}]"),\n );\n pb\n }\n }\n\n fn readable<'a>(&'a mut self) -> Box<dyn Read + 'a> {\n if let &mut PvSource::File { ref mut file, .. } = self {\n Box::new(file)\n } else {\n Box::new(io::stdin())\n }\n }\n}\n\nfn main() -> Result<()> {\n let opts = Opt::from_args();\n let mut source = if let Some(input) = opts.input {\n PvSource::with_path(input)?\n } else {\n PvSource::Stdin\n };\n let progress_bar = source.progress_bar();\n let mut input = source.readable();\n let mut output = progress_bar.wrap_write(io::stdout());\n\n match io::copy(&mut input, &mut output) {\n Ok(_) => Ok(()),\n Err(e) if e.kind() == ErrorKind::BrokenPipe => Ok(()),\n Err(e) => Err(e.into()),\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:58:10.860",
"Id": "257239",
"ParentId": "256800",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T11:10:57.020",
"Id": "256800",
"Score": "5",
"Tags": [
"reinventing-the-wheel",
"rust"
],
"Title": "Pipeviewer: A small \"pv\" Rewrite"
}
|
256800
|
<p>Need some advices to create class that handles sql query operations with given array (having full control of the array and obtaining record information). My code works properly (it is just example), but need some check it is safe, or there's a better way to reach result. I want to note that all dangerous characters before adding to array are cleared with other function (to prevent injection). So basic idea is to create array with query structure, then pass to function and do sql query operation. Thanks, appreciate all answers.</p>
<p>**
<strong>THIS IS FOR LEARNING PURPOSES ONLY</strong>
**</p>
<p><strong>Created class that handle operations:</strong></p>
<pre><code>class my_op
{
private $pdo;
private $safe_code = "@@@";
public function __construct($pdo)
{
$this->pdo = $pdo;
}
private function safe_chars($first_string, $second_string)
{
$safe_chars = array(
"A","B","C","D","E","F","G", "H","I","J","K","L","M","N","O","P","Q","R","S",
"T","U","V","W","X","Y","Z","a","b","c","d","e","f","g","h","i","j","k",
"l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","1",
"2","3","4","5","6","7","8","9","0",",","'","?","!"," ","_","-",":","(",
">","<",")"
);
$unsafe_count = null;
if (strlen($first_string) > 0):
foreach (str_split($first_string) as $char_check)
{
if (!in_array($char_check, $safe_chars))
{
$unsafe_count++;
}
}
endif;
if (strlen($second_string) > 0):
foreach (str_split($second_string) as $char_check)
{
if (!in_array($char_check, $safe_chars))
{
$unsafe_count++;
}
}
endif;
return $unsafe_count;
}
private function build_query($my_array)
{
$instances = array(
"UPDATE","DELETE FROM","INSERT INTO","WHERE","SET","FROM","VALUES","SELECT",
"ORDER BY","LIMIT",'INTERSECT','MINUS','UNION','UNION ALL','OR','BETWEEN',
'DISTINCT','GROUP BY','EXISTS','JOIN','LIKE','TRUNCATE','IN','TOP','MINUS',
'IS NULL','IS NOT NULL','EXCEPT','AVG','COUNT','MAX','MIN','SUM'
);
$OOP = [10, 2, 4]; //max arrays,least,most
$KEYS = ["SET-STRUCTURE", "SET-PARAMETERS", "SET-BIND", "SET-EXECUTE", "SET-FMODE"];
if (is_array($my_array) && sizeof($my_array) > 0):
$secure_purposes = implode('|', $instances);
$filtered_array_my_op = filter_var_array($my_array, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$response = false;
$fetch_response = false;
try
{
if (sizeof($my_array) <= $OOP[0]):
$f_mode_type = null;
$gresponse_arr = null;
$exe = [null, null, null, null, "on", "on", "bindvalue"]; //execute,binding,bindingval
foreach (is_array($filtered_array_my_op) || is_object($filtered_array_my_op) ? $filtered_array_my_op : array() as $splited_array):
$parsed_values = array();
$opc = [null, null, null, null];
foreach ($splited_array as $parsed_keys_g => & $parsed_values_g):
foreach ($parsed_values_g as $direct_key => & $direct_value):
switch ($parsed_keys_g)
{
case $KEYS[0]:
if ($parsed_keys_g == $KEYS[0] && strlen($direct_value) > 0 && in_array($direct_key, $instances)):
if ($this->safe_chars($direct_key, $direct_value) <= 0):
$opc[2] .= " $direct_key $direct_value ";
$opc[0]++;
else:
$exe[1]++;
endif;
elseif ($parsed_keys_g == $KEYS[0] && strlen($parsed_s_value) < 0 || $parsed_keys_g == $KEYS[0] && !in_array($parsed_s_key, $instances)):
$exe[2]++;
endif;
break;
case $KEYS[1]:
if ($parsed_keys_g == $KEYS[1] && strlen($direct_value) > 0):
if ($this->safe_chars($direct_key, $direct_value) <= 0):
$parsed_values[$direct_key] = $direct_value;
$opc[3] .= " $direct_key $direct_value";
$opc[1]++;
else:
$exe[1]++;
endif;
elseif ($parsed_keys_g == $KEYS[1] && strlen($direct_value) < 0):
$exe[2]++;
endif;
break;
case $KEYS[2]:
$exe[5] = $direct_value;
$exe[6] = $direct_key;
break;
case $KEYS[3]:
$exe[4] = $direct_value;
break;
case $KEYS[4]:
$exe[3] = $direct_value;
$f_mode_type = $direct_key;
break;
}
endforeach;
endforeach;
$exe[0]++;
if ($opc[0] >= $OOP[1] && $exe[4] == "on" && $opc[0] <= $OOP[2] && $opc[1] > 0 && preg_match("($secure_purposes)", $opc[2]) && array_key_exists($KEYS[0], $splited_array) && $exe[2] <= 0):
try
{
$this
->pdo
->beginTransaction();
$my_operation = $this
->pdo
->prepare($opc[2]);
$bindcount = 0;
switch ($exe[5])
{
case "on":
foreach ($parsed_values as $value_key_parsed => $value_parsed)
{
if ($exe[6] == "bindvalue"):
$my_operation->bindValue($value_key_parsed, $value_parsed);
elseif ($exe[6] == "bindparam"):
$my_operation->bindParam($value_key_parsed, $value_parsed);
endif;
$bindcount++;
}
break;
case "off":
//dosomething
break;
}
switch ($exe[4])
{
case "on":
if ($exe[5] == "on"):
if ($my_operation->execute()):
$status = "Success";
else:
$status = "Failed";
endif;
else:
if ($my_operation->execute($parsed_values)):
$status = "Success";
else:
$status = "Failed";
endif;
endif;
break;
case "off":
//dosomething
break;
}
if (strlen($f_mode_type) > 0):
while ($gresponse_arr = $my_operation->$f_mode_type($exe[3]))
{
$fetch_response[] = $gresponse_arr;
}
else:
throw new Exception("Fetch building failed.");
endif;
$my_operation = null;
$this
->pdo
->commit();
$this->pdo = null;
$response[] = ["operation" => ['status' => $status, 'fmode' => $exe[3], 'op_made' => $exe[0], 'binded_param' => $bindcount, 'sizeof' => sizeof($my_array) , 'scount' => $opc[0], 'vcount' => $opc[1], ], "structure" => ['srecord' => $opc[2]], "setparams" => ['precord' => $opc[3]]];
}
catch(Exception $e)
{
$this
->pdo
->rollback();
throw new Exception('Something wrong: ' . $e->getMessage());
}
else:
if ($exe[4] == "off"):
throw new Exception("Execution is disabled.");
endif;
if ($exe[1] > 0):
throw new Exception("Unsafe chars cannot be tolerated ");
endif;
if ($exe[2] > 0):
throw new Exception("Some keys or values do not match requirements. //v $opc[1] //s $opc[0]");
endif;
if ($s <= $OOP[1]):
throw new Exception("Structure keys count failed (least). //v $opc[1] //s $opc[0]");
endif;
if ($s >= $OOP[2]):
throw new Exception("Structure keys count failed (most). //v $opc[1] //s $opc[0]");
endif;
if ($v <= 0 && preg_match("($secure_purposes)", $opc[2]) && array_key_exists($KEYS[1], $splited_array) && array_key_exists($KEYS[0], $splited_array)):
throw new Exception("Missing some structure.");
endif;
endif;
endforeach;
else:
throw new Exception("Limited operations.");
endif;
}
catch(Exception $e)
{
throw new Exception('Something wrong: ' . $e->getMessage());
}
if (sizeof($response) > 0 && sizeof($fetch_response) > 0):
$output = array_merge($response, $fetch_response);
elseif (sizeof($response) > 0):
$output = $response;
else:
$output = false;
endif;
return $output;
else:
return false;
endif;
}
public function testas()
{
$test = "testas";
return $test;
}
public function get_parsed($arr, $key)
{
$val = null;
foreach ($arr as $v2):
if (!empty($v2[$key]))
{
$val = $v2[$key];
}
foreach ($v2 as $v):
if (!empty($v[$key]))
{
$val = $v[$key];
}
endforeach;
endforeach;
return $val;
}
public function r($op)
{
$r = $op;
foreach ($op as $u):
if (!empty($u))
{
if (is_array($u))
{
foreach ($u as $u2):
if (!empty($u2))
{
$r[] = $u2;
}
endforeach;
}
}
endforeach;
return $r;
}
public function get_info($arr, $key)
{
$val = null;
$infokey = null;
if ($key == "status" || $key == "op_made" || $key == "binded_param" || $key == "sizeof" || $key == "scount" || $key == "vcount"):
$infokey = "operation";
elseif ($key == "srecord"):
$infokey = "structure";
elseif ($key == "precord"):
$infokey = "setparams";
endif;
foreach ($arr as $v):
if (!empty($v[$infokey][$key])):
$val = $v[$infokey][$key];
endif;
endforeach;
return $val;
}
public function handle_query($my_array, $safe_code)
{
$private_safe_code = $this->safe_code;
try
{
if ($private_safe_code == $safe_code): // some user security check
$get_private_func = $this->build_query($my_array);
return $get_private_func;
else:
throw new Exception("Something wrong.");
endif;
}
catch(Exception $e)
{
return $e->getMessage();
}
}
}
</code></pre>
<p><strong>Setting array which generates query.</strong></p>
<pre><code>$operation_examples[] = ["SET-STRUCTURE" => [ // structure // this part safe from inputs
'SELECT' => "user_id FROM dot_users WHERE user_status = :status LIMIT :limit"],
"SET-PARAMETERS" => [ // setting parameters (PDO prepared st.)
":status" => "1",
":limit" => "1"],
"SET-BIND" => ["bindparam" => "on"], // bind options // ON by default bindvalue or bindparam
"SET-EXECUTE" => ["on"], //execution on/off
"SET-FMODE" => [fetchAll => PDO::FETCH_ASSOC] //switch fetch mode
];
</code></pre>
<p><strong>Call class:</strong></p>
<pre><code> $cl = new my_op($pdo);
$op = $cl->handle_query($operation_examples, "@@@");
echo "Operation status: " . $cl->get_info($op, "status");
echo "<br>";
echo "Structure record: " . $cl->get_info($op, "srecord");
echo "<br>";
echo "Params record: " . $cl->get_info($op, "precord");
echo "<br>";
echo "Last id: " . $cl->get_parsed($op, "user_id");
foreach ($cl->r($op) as $u):
if(!empty($u['user_id'])):
echo "<br>ID:" . $u['user_id'] . "<br>";
endif;
endforeach;
var_dump($op);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>Operation status: Success
Structure record: SELECT user_id FROM dot_users WHERE user_status = :status LIMIT :limit
Params record: :status 1 :limit 1
Last id: 57
ID:57
array(2) { [0]=> array(3) { ["operation"]=> array(7) { ["status"]=> string(7) "Success" ["fmode"]=> string(1) "2" ["op_made"]=> int(1) ["binded_param"]=> int(2) ["sizeof"]=> int(1) ["scount"]=> int(1) ["vcount"]=> int(2) } ["structure"]=> array(1) { ["srecord"]=> string(72) " SELECT user_id FROM dot_users WHERE user_status = :status LIMIT :limit " } ["setparams"]=> array(1) { ["precord"]=> string(21) " :status 1 :limit 1 " } } [1]=> array(1) { [0]=> array(1) { ["user_id"]=> int(57) } } }
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:38:18.383",
"Id": "507063",
"Score": "3",
"body": "Is your code normally indented or is this how you always write it. It is almost unreadable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T16:51:59.087",
"Id": "507168",
"Score": "5",
"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": "2021-03-08T08:18:57.093",
"Id": "507221",
"Score": "1",
"body": "Look like you are trying to write a thing called a *Query builder*. It's a fair question but in order to ask it, you need to provide two things: 1. What is the reason you think that you need one. What will be the use case? 2. How it's intended to be used with examples. And yes, the most important one: 3. Above all, please **learn how to format your code** properly. It's the biggest problem you've got at hand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T10:47:32.750",
"Id": "507226",
"Score": "1",
"body": "Can you explain, how and why this elaborate code is [any better than vanilla PDO](https://phpize.online/?phpses=6718aada5d5bc45431d45a8b09106665)? What's the goal? What's the benefit? What problem does it solve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T13:15:29.047",
"Id": "507238",
"Score": "0",
"body": "The main goal for me is learn more about creating and manipulating queries, security principles, and the transmission of the operation. I also think if it were safe way to create class that build queries with specific configuration it would be also great. I edited the post, maybe it will be clearer how things work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:44:56.467",
"Id": "507395",
"Score": "0",
"body": "(Be warned that among those with a formal training in handling moving targets the common minimum goal is to render it ineffective.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:51:02.847",
"Id": "507396",
"Score": "1",
"body": "From title and introduction of this question, I have *no* idea what the code is to accomplish. The code does not seem to contain embedded documentation."
}
] |
[
{
"body": "<p>You have turned simple SQL prepared statements into this monstrosity that is extremely difficult to read and is open to SQL injection. Remove it! Don't go down this path. It is absolutely unnecessary.</p>\n<p>Take a look at how simple prepared statements can be.</p>\n<pre><code><?php\n\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n$mysqli = new mysqli('localhost', 'user', 'password', 'test');\n$mysqli->set_charset('utf8mb4'); // always set the charset\n\n$index = 1;\n$stmt = $mysqli->prepare('UPDATE my_orders SET status = "waiting" WHERE myindex = ?');\n$stmt->bind_param('s', $index);\n$stmt->execute();\n</code></pre>\n<p>You don't need that complicated class. All you need are prepared statements. If you want something simpler with more functionality then you can use PDO. I strongly advise using PDO whenever possible.</p>\n<p>Same code using prepared statements:</p>\n<pre><code><?php\n\n$pdo = new \\PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [\n \\PDO::ATTR_ERRMODE => \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_EMULATE_PREPARES => false\n]);\n\n$index = 1;\n$stmt = $mysqli->prepare('UPDATE my_orders SET status = "waiting" WHERE myindex = ?');\n$stmt->execute([$index]);\n</code></pre>\n<p>On an unrelated note, please use proper IDE with static analysis tool and syntax highlighting and formatting. This code is unreadable at the moment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:07:23.563",
"Id": "507083",
"Score": "0",
"body": "What if i change mysqli_query to pdo prepared statements, but leave same only_update function just modify it with pdo syntax and parameters?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T17:06:09.373",
"Id": "507089",
"Score": "0",
"body": "What's the point? MySQLi also has prepared statements. Don't create functions that will make programming more difficult. PDO is easier compared to MySQLi but if you keep your current code you won't see much improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T14:06:53.430",
"Id": "507148",
"Score": "0",
"body": "My point is to do operations with only functions and arrays. I edit my code, and modify it with pdo, check it out and say what you think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T14:10:08.700",
"Id": "507149",
"Score": "0",
"body": "@ZujisKarolis It's worse than before. You are still not binding any parameters. The variable names mean absolutely nothing. The code is still not formatted. You have very strange `filter_var_array($my_values,FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH);`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T14:24:25.297",
"Id": "507151",
"Score": "0",
"body": "I edited again with bindparam :D maybe you can show some example how to do it right way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:04:29.153",
"Id": "507170",
"Score": "1",
"body": "@ZujisKarolis Just remove that whole class. Trust me, you really do not want to do it this way. Stick to plain old SQL. As for parameter binding, I have no idea what you are doing, but it is still vulnerable to SQL injection. Even if you manage to bind them correctly, the whole class will still be vulnerable to SQL injection. Don't do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:29:07.450",
"Id": "507172",
"Score": "0",
"body": "There no way to find weak spots and fix it? By the way thanks for the answers and time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:30:32.877",
"Id": "507173",
"Score": "0",
"body": "@Karolis There are ways to do it, but I can't recommend proceeding with anything like this with clear conscience. You will only hurt yourself if you try to implement and use such class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:33:21.900",
"Id": "507174",
"Score": "0",
"body": "Well,as I learn, doing something overkilling would be good practice. I don’t like to give up easily, if you have advice on how to fix this mess I would be grateful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:38:39.727",
"Id": "507175",
"Score": "0",
"body": "@Karolis If you want to learn then you can look up how professional query builders are done. e.g. Doctrine https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/query-builder.html#sql-query-builder They have their code on GitHub so you can download and read it. There is also this one https://github.com/nilportugues/php-sql-query-builder but I don't know how good it is."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T14:30:57.627",
"Id": "256809",
"ParentId": "256803",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "256809",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T12:51:58.733",
"Id": "256803",
"Score": "-2",
"Tags": [
"php",
"array",
"sql",
"mysqli"
],
"Title": "Query builder class pdo,sql"
}
|
256803
|
<p>Below source code is my solution of the K&R exercise 1-24.</p>
<blockquote>
<p>Exercise 1-24. Write a program to check a C program for rudimentary syntax errors like unbalanced parentheses, brackets and braces. Don't forget about quotes, both single and double, escape sequences, and comments. (This program is hard if you do it in full generality.)</p>
</blockquote>
<p>My program uses two kinds of state variables. Parentheses(( ), { }, [ ]) and punctuation(' ', " ", /* */). Parentheses are saved in <code>nest[]</code> and punctuation are saved in <code>state</code>. And conditions of if-statement mainly uses these two variables. <br/><br/> I didn't care a case of a curly brace after opening parenthesis and bracket.
<br/><br/>
I'm not sure there is a better variable naming, logic, style, etc. I don't know if my code can be written shorter with the same logic. Any suggestion will be so appreciated.</p>
<pre><code>#include <stdio.h>
/* This program checks if there is unbalanced parentheses, curly braces or brackets.
* This program doesn't check if there is a newline charcter between a single quote or a double quote.
* This program doesn't check if there is non-terminated comment, single quote or double quote.
*/
#define NOTHING 0
#define COMMENT 1
#define SINGLE_QUOTE 2
#define DOUBLE_QUOTE 3
#define PARENTHESIS 1
#define CURLY_BRACE 2
#define BRACKET 3
#define MAX_NESTING_LEVEL 100
void check_paren(void);
void main(void)
{
check_paren();
}
void check_paren(void)
{
int c;
int line;
int state;
int nest[MAX_NESTING_LEVEL] = {NOTHING};
int n;
n = 0;
line = 1;
state = NOTHING;
while ((c = getchar()) != EOF) {
if ( n > MAX_NESTING_LEVEL -1) {
printf("error : line %d : exceed MAX_NESTING_LEVEL\n", line);
return;
} else if (c == '\n') {
++line;
} else if (state != COMMENT) {
if (c == '/')
if ((c = getchar()) == '*')
state = COMMENT;
}
if (state == NOTHING && n == 0) {
if (c == '\'')
state = SINGLE_QUOTE;
else if (c == '\"')
state = DOUBLE_QUOTE;
else if (c == '(')
nest[n++] = PARENTHESIS;
else if (c == '{')
nest[n++] = CURLY_BRACE;
else if (c == '[')
nest[n++] = BRACKET;
else if (c == ')') {
printf("error : line %d : unmatched )\n", line);
return;
} else if (c == '}'){
printf("error : line %d : unmatched }\n", line);
return;
} else if (c == ']'){
printf("error : line %d : unmatched ]\n", line);
return;
}
} else if (state == NOTHING && nest[n-1] == PARENTHESIS) {
if (c == ')')
nest[--n] = NOTHING;
else if (c == '(')
nest[n++] = PARENTHESIS;
else if (c == '[')
nest[n++] = BRACKET;
else if (c == '\'')
state = SINGLE_QUOTE;
else if (c == '\"')
state = DOUBLE_QUOTE;
else if (c == '}') {
printf("error : line %d : ( + }\n", line);
return;
}
else if (c == ']') {
printf("error : line %d : ( + ]\n", line);
return;
}
} else if (state == NOTHING && nest[n-1] == CURLY_BRACE) {
if (c == '}')
nest[--n] = NOTHING;
else if (c == '(')
nest[n++] = PARENTHESIS;
else if (c == '{')
nest[n++] = CURLY_BRACE;
else if (c == '[')
nest[n++] = BRACKET;
else if (c == '\'')
state = SINGLE_QUOTE;
else if (c == '\"')
state = DOUBLE_QUOTE;
else if (c == ')') {
printf("error : line %d : { + )\n", line);
return;
}
else if (c == ']') {
printf("error : line %d : { + ]\n", line);
return;
}
} else if (state == NOTHING && nest[n-1] == BRACKET) {
if (c == ']')
nest[--n] = NOTHING;
else if (c == '(')
nest[n++] = PARENTHESIS;
else if (c == '\'')
state = SINGLE_QUOTE;
else if (c == ')') {
printf("error : line %d : [ + )\n", line);
return;
}
else if (c == '}') {
printf("error : line %d : [ + }\n", line);
return;
}
} else {
if (state == COMMENT && c == '*') {
if ((c = getchar()) == '/')
state = NOTHING;
} else if (c == '\\')
getchar();
else if (state == SINGLE_QUOTE && c == '\'')
state = NOTHING;
else if (state == DOUBLE_QUOTE && c == '\"')
state = NOTHING;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T14:50:26.420",
"Id": "507850",
"Score": "1",
"body": "Next time, please document your test cases in the question as well. The specification of the task is deliberately vague and leaves room for interpretation. Your test cases should then describe and explain why you made the necessary choices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T15:54:49.167",
"Id": "507855",
"Score": "1",
"body": "Your description doesn't state whether nesting of various types of brackets is allowed ( \"([{}])\" vs. \"([{)]}\" ) or not. In typical real scenarios, it's not, but your program seems to check for the latter case only."
}
] |
[
{
"body": "<p>You could assign a number to <code>state</code> instead of just keeping it at a <code>char</code>. You can still use the EOF / zero character value as "magic". It would make debugging a lot easier, and you can simply assign the read character to <code>nest</code> directly. That would remove a lot of code.</p>\n<p>I'd also create a method to get rid of any strings and comments whenever they are encountered. Any parentheses and whatnot in strings should be skipped anyway. Just keep reading in characters until the end is encountered (and if it not encountered: well, there is your problem).</p>\n<p><code>char</code> and <code>int</code> can also be used in <code>switch</code> statements instead of <code>if</code> statements. When you think "state-machine" a loop with a switch is probably what comes first in mind (when not performing functional programming anyway).</p>\n<p>E.g.</p>\n<pre><code>switch(c):\ncase '(':\ncase '[':\n...\n nest[n++] = c;\n break;\n...\n</code></pre>\n<p>In the end the main loop should be as short and intuitive as possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:29:58.140",
"Id": "507060",
"Score": "0",
"body": "Do you mean the variable `c` is useless and then `while ((c = getchar()) != EOF)` can be rewritten by `while ((state = getchar()) != EOF)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:32:47.723",
"Id": "507061",
"Score": "0",
"body": "The fact that you can have escape sequences and two different two-character comments may require some workarounds. But that's the case with your current `int` as well I suppose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:37:20.830",
"Id": "507062",
"Score": "0",
"body": "No, scratch that, lines such as `else if (state == SINGLE_QUOTE && c == '\\'')` would not work; state depends on the past after all. But in many **cases** you could just perform `state = c`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:47:35.810",
"Id": "507066",
"Score": "0",
"body": "I don't know I am 100% understand your comment. I think you're saying `else if (c == '\\\"') state = DOUBLE_QUOTE;` can be `else if (c == '\\\"') state = c` and `else if (c == '(') nest[n++] = PARENTHESIS;` can be `else if (c == '(') nest[n++] = c;` If my thought is right. You actually means that my macro definition can be replaced by the character variable(`c`). It would be a matter of style. The code length will not be changed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:55:15.703",
"Id": "507068",
"Score": "1",
"body": "Added example... less conversion always means less code. For one, you could get rid of most `#define` statements."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:24:01.960",
"Id": "256805",
"ParentId": "256804",
"Score": "3"
}
},
{
"body": "<p>I have not read your whole programm and only a very small suggestion regarding readability:</p>\n<p>n > MAX_NESTING_LEVEL -1</p>\n<p>is the border check for your nest array. If you write it as</p>\n<p>n >= MAX_NESTING_LEVEL</p>\n<p>it has the same result but is more concise. You do not need to keep in mind that the defined size is shifted by one regarding index values.</p>\n<p>You should maybe consider to use two different defines, one for the nesting table size and one for the max nesting level for readability.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T14:09:08.570",
"Id": "257146",
"ParentId": "256804",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256805",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T13:05:49.577",
"Id": "256804",
"Score": "4",
"Tags": [
"c"
],
"Title": "Check unbalanced parentheses"
}
|
256804
|
<p><strong>Task description:</strong>
Write a function <code>commonPrefix</code>, which takes two strings as parameter and returns the common prefix.</p>
<p>Example: parameters <code>abcdef</code> and <code>abc1gv</code> would return <code>abc</code>.</p>
<p><strong>My implementation:</strong></p>
<pre><code>fun commonPrefix(str1: String, str2: String): String {
var sRet = ""
var i = 0
val length = if (str1.length >= str2.length)
str1.length else str2.length
while (i < length) {
if (str1.take(i + 1) != str2.take(i + 1)) {
return sRet
}
sRet += str1[i++]
}
return sRet
}
val first = "abcdef"
val sec = "abc1ef"
println(commonPrefix(first, sec))
</code></pre>
<p>Is my implementation done in a good way? Where could it be optimized?</p>
|
[] |
[
{
"body": "<p>The first thing which stands out to me is that it's typically better to use standard functions than to roll-your-own even for trivial things. For example</p>\n<pre><code>val length = if (str1.length >= str2.length)\n str1.length else str2.length\n</code></pre>\n<p>could be better written as</p>\n<pre><code>val length = maxOf(str1.length, str2.length)\n</code></pre>\n<p>People often talk in circles about this thinking about efficiency, but that's generally a red herring. Modern compilers are pretty good at optimising, and the differences are likely to be minimal if they exist at all.</p>\n<p>Instead, the number one reason for using a named function is readability. In the former example, I have to stop and piece together what it's actually doing. In the latter, I can see at a glance and continue to read the code fluently.</p>\n<p>Following on from that, I can now see that it's the wrong check. Logically, a common prefix cannot be longer than the shorter of the two strings. So now that I can clearly see that the existing code is equivalent to a <code>maxOf</code> call, I realise it should probably instead be a <code>minOf</code> call.</p>\n<hr />\n<p>The second thing that jumps out at me is the efficiencies of your loop. Every time you go through the loop, you are (1) comparing the whole prefix and (2) updating your return value. That is, the first time you're comparing "a" against "a" which is fine. By the third time round you're comparing "abc" against "abc", and so redoing the work of comparing "a" and "b". Then, you're taking your previous <code>sRet</code> object "ab", copying it and the "c" into a new string object, and assigning it back to <code>sRet</code>. If you're familiar with big O notation, that means that your overall function becomes O(n<sup>2</sup>) in the length of the prefix. It also means that you wind up creating and throwing away a lot of little temporary objects.</p>\n<p>You don't need to do either. By the time you get to the third step in the loop, you already know that "ab" matches "ab" so you don't need to check again. Instead of using <code>take</code> to get the prefix, use <code>get</code> to get the actual letter. Then you can just check "c" against "c".</p>\n<p>As to the problem of loads of throwaway <code>sRet</code> objects, the usual advice is to use a <a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/-string-builder/\" rel=\"nofollow noreferrer\">StringBuilder</a>. Unlike a string, a StringBuilder is specifically made with the idea that you'll change it as you go. It's much more efficient for that purpose. <strong>However</strong>, in this case you don't need to do that because you don't need <code>sRet</code> at all! After all, both <code>str1</code> and <code>str2</code> contain the prefix you're after. You already have (and have used!) a function to get the prefix out. So just count along the two strings, comparing one character at a time. Once you know the number of characters that are the same, <code>take</code> it.</p>\n<hr />\n<p>The final thing that I'd mention is testing. You've given one example pair of inputs to your function. That's a good thing, and it helps illustrate the problem. It's also worth thinking about what other examples are worth checking. In general for a function like this, I'd suggest it's worth testing at least the following:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: left;\">str1</th>\n<th style=\"text-align: center;\">str2</th>\n<th style=\"text-align: left;\">reason</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: left;\">abc</td>\n<td style=\"text-align: center;\">xyz</td>\n<td style=\"text-align: left;\">It's easy to have a bug which messes up when the prefix is empty</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">a</td>\n<td style=\"text-align: center;\">b</td>\n<td style=\"text-align: left;\">It's easy to have a bug which messes up single character inputs</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">a</td>\n<td style=\"text-align: center;\">a</td>\n<td style=\"text-align: left;\">Same as above</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">abc</td>\n<td style=\"text-align: center;\">abc</td>\n<td style=\"text-align: left;\">It's easy to have a bug which breaks strings that are identical</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">abxyz</td>\n<td style=\"text-align: center;\">abc</td>\n<td style=\"text-align: left;\">You're trying to support inputs of different lengths, so this should be tested.</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">abc</td>\n<td style=\"text-align: center;\">abxyz</td>\n<td style=\"text-align: left;\">Same as above</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\">abcde</td>\n<td style=\"text-align: center;\">abc</td>\n<td style=\"text-align: left;\">One string being a prefix of the other</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\"></td>\n<td style=\"text-align: center;\"></td>\n<td style=\"text-align: left;\">Empty strings cause no end of problems and need to be tested</td>\n</tr>\n<tr>\n<td style=\"text-align: left;\"></td>\n<td style=\"text-align: center;\">abc</td>\n<td style=\"text-align: left;\">Same as above</td>\n</tr>\n</tbody>\n</table>\n</div>",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:59:39.443",
"Id": "507255",
"Score": "0",
"body": "Great answer. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:59:49.307",
"Id": "256849",
"ParentId": "256806",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256849",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T14:12:57.577",
"Id": "256806",
"Score": "0",
"Tags": [
"strings",
"kotlin"
],
"Title": "Write a Kotlin function \"commonPrefix\""
}
|
256806
|
<p>I am trying to overwrite an object in an array if the <code>title</code> property exists, otherwise just push it to the array. I found two approaches and I wonder which one is the preferred one.</p>
<p>Performance is not really and issue but I wonder whether mutability could be, or just there is a better way to do this altogether.</p>
<p>On this snippet I am using a for loop to edit the original array:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
{
title: 'AAA',
people: [ 'John', 'Megan',]
},{
title: 'BBB',
people: [ 'Emily', 'Tom']
}
]
// If inputTitle is not on any of data's title it will append not overwritte
const inputTitle = 'AAA'
const inputPeople = ['Peter', 'Jane']
for (const obj of data) {
if (obj.title === inputTitle) {
obj.people = inputPeople
break
} else {
data.push({
title: inputTitle,
people: inputPeople
})
break
}
}
console.log(data)</code></pre>
</div>
</div>
</p>
<p>Here I am using high order functions and spread to do the same:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
{
title: 'AAA',
people: [ 'John', 'Megan',]
},{
title: 'BBB',
people: [ 'Emily', 'Tom']
}
]
// If inputTitle is not on any of data's title it will append not overwritte
const inputTitle = 'AAA'
const inputPeople = ['Peter', 'Jane']
let res = []
if (data.some(({ title }) => title === inputTitle)) {
res = data.map(obj => {
if (obj.title === inputTitle)
obj.people = inputPeople
return obj
})
} else {
res = [...data, { title: inputTitle, people: inputPeople}]
}
console.log(res)</code></pre>
</div>
</div>
</p>
<p>In the real task I am reading the <code>data</code> array from a json file with node and writing the changes back to it.</p>
|
[] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li><p>The first snippet does not work, try it with <code>inputTitle = 'BBB'</code></p>\n</li>\n<li><p>You are in essence doing 2 things</p>\n<ol>\n<li>Find a possible match</li>\n<li>Update the match or insert the data</li>\n</ol>\n<p>Ideally, this is done in 1 'loop'</p>\n</li>\n<li><p>If you don't care too much about performance, I would go for a functional approach</p>\n</li>\n</ul>\n<p>This is my counter-proposal (which modifies the data)</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>const data = [\n {\n title: 'AAA',\n people: [ 'John', 'Megan',]\n },{\n title: 'BBB',\n people: [ 'Emily', 'Tom']\n }\n]\n\nfunction mergePeople(data, title, people){\n const target = data.filter(record=>record.title===title);\n if(target.length){\n target.forEach(record => record.people = people);\n }else{\n data.push({title, people});\n }\n return data;\n}\n\nfunction quickClone(o){\n return JSON.parse(JSON.stringify(o));\n}\n\nconsole.log(mergePeople(quickClone(data), \"AAA\", [\"Tom\", \"Jerry\"]));\nconsole.log(mergePeople(quickClone(data), \"BBB\", [\"Ben\", \"Jerry\"]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:29:11.297",
"Id": "507076",
"Score": "0",
"body": "Thanks, this looks really neat, do I really need to clone the data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:29:58.347",
"Id": "507077",
"Score": "1",
"body": "Not all, but in order to keep the test clean, I cloned the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:53:58.083",
"Id": "507081",
"Score": "0",
"body": "One thing I do not understand is that if `target` is a brand new array how comes the `data` array changes when you do the `forEach` on `target`? Is that because of the shallow clone of filter not altering the array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:59:10.217",
"Id": "507082",
"Score": "1",
"body": "`target` is an array of objects which you can think of as pointers to the objects in `data`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:20:35.940",
"Id": "256814",
"ParentId": "256810",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256814",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T14:50:11.600",
"Id": "256810",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"array",
"ecmascript-6"
],
"Title": "Add / Overwrite an object in an array"
}
|
256810
|
<p>I`m trying to make an API for Flask together with MongoDB, before that I used the SQL DB using SQLAlchemy and there I used models for organizing the database.</p>
<p>Now I'm a bit confused how to organize code for working with DB. Since the standard MongoDB client does not provide an opportunity to create models, and I did not like Mongoengine, I decided to move any database methods into a separate class:</p>
<pre class="lang-py prettyprint-override"><code>import uuid
from datetime import datetime
from flask import request
from werkzeug.security import generate_password_hash
from app import mongo
class User:
db = mongo.db.users
def new_user(self):
'''New user Registration.
Request body (JSON):
email (str)
username (str)
password (str)
Returns:
status, result (tuple):
100, user (dict) - in case of successful registration
102, None - one of the parameters is missing
201, None - such user already exists
'''
try:
data = {
'_id': uuid.uuid4().hex,
'email': request.json['email'],
'username': request.json['username'],
'password': generate_password_hash(
request.json['password']),
'createdAt': datetime.utcnow()
}
except KeyError:
return 102, None
user = self.db.find_one({
'$or': [
{'email': data['email']},
{'username': data['username']}
]
})
if not user:
self.db.insert_one(data)
return 100, data
else:
return 201, None
def login(self):
pass
def get_data(self):
pass
</code></pre>
<pre class="lang-py prettyprint-override"><code>from flask import Blueprint, jsonify, request
from app.models import User
users = Blueprint('users', __name__)
@users.route('/users/new_user', methods=['POST'])
def new_user():
'''Adding a new user to the database.
'''
status, user = User().new_user()
if status == 100:
return jsonify({'status': True, 'code': 100, 'result': user})
elif status == 102:
return jsonify({
'status': False, 'code': 102,
'result': 'missing one of parameters'})
elif status == 201:
return jsonify({
'status': False, 'code': 201, 'result': 'user already exists'})
</code></pre>
<p>But it looks very strange to me, if there are many keys in the document and I need to somehow handle them in the route, it will be very unintuitive.</p>
<p>Now I am thinking of making a model by analogy with models from SQLAlchemy, so that class variables represent keys in documents, as well as simple methods for queries in the database. But it can also cause a lot of confusion. I just want to try to avoid code duplication as well as variability for reuse.</p>
<p>I will accept any advice or hints as to how it should be "right". Unfortunately I have not found a project structure using MongoDB.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:25:49.270",
"Id": "507075",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T14:50:42.183",
"Id": "256811",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"flask",
"pymongo"
],
"Title": "Organization of work with MongoDB in Flask"
}
|
256811
|
<p>I've been playing around with Go and finally found a use case for a little web service I could build.</p>
<p>It takes JSON data via an HTTP POST request and sends me an email via Mailgun's API (it's used for a contact form on my website).</p>
<p>I'm new to Go and would love some feedback on what I could do better, anything I missed and where I could do better following the "Go way" of doing things. :)</p>
<p><strong>main.go</strong></p>
<pre><code>package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var mailgunDomain string = os.Getenv("MAILGUN_DOMAIN")
var mailgunAPIKey string = os.Getenv("MAILGUN_API_KEY")
var allowedOrigin string = os.Getenv("ALLOWED_ORIGIN")
var port string = os.Getenv("PORT")
func main() {
if port == "" {
panic("Missing environment variable PORT")
}
if mailgunDomain == "" {
panic("Missing environment variable MAILGUN_DOMAIN")
}
if mailgunAPIKey == "" {
panic("Missing environment variable MAILGUN_API_KEY")
}
if allowedOrigin == "" {
panic("Missing environment variable ALLOWED_ORIGIN")
}
r := mux.NewRouter()
r.Use(handlers.CORS(
handlers.AllowedHeaders([]string{"Content-Type"}),
handlers.AllowedOrigins([]string{allowedOrigin}),
))
r.HandleFunc("/", homeHandler).Methods("GET")
r.HandleFunc("/contact", HandleContact(mailgunDomain, mailgunAPIKey)).Methods("POST", "OPTIONS")
log.Fatal(http.ListenAndServe(":"+port, r))
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "API for maxschmitt.me")
}
</code></pre>
<p><strong>contact.go</strong></p>
<pre><code>package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"time"
"github.com/mailgun/mailgun-go/v4"
)
var mailgunSender string = "email@sender.com"
var mailgunReceiver string = "email@receiver.com"
// HandleContact sends emails to me via the contact form
func HandleContact(mailgunDomain string, mailgunAPIKey string) http.HandlerFunc {
type body struct {
Name string `json:"name"`
Email string `json:"email"`
Message string `json:"message"`
}
mg := mailgun.NewMailgun(mailgunDomain, mailgunAPIKey)
mg.SetAPIBase(mailgun.APIBaseEU)
return func(w http.ResponseWriter, r *http.Request) {
var b body
err := json.NewDecoder(r.Body).Decode(&b)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
message := "From: " + b.Name + "<" + b.Email + ">\n\n"
message += b.Message
fmt.Fprintln(os.Stdout, "## New message!")
fmt.Fprintln(os.Stdout, message+"\n")
mgMsg := mg.NewMessage(mailgunSender, "New contact form submission", message, mailgunReceiver)
mgMsg.SetReplyTo(b.Email)
// Create a 10s timeout for sending the message
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
resp, id, err := mg.Send(ctx, mgMsg)
if err != nil {
fmt.Println("Error sending contact form submission:")
fmt.Println(err)
http.Error(w, "Something went wrong", http.StatusInternalServerError)
return
}
fmt.Fprintln(os.Stdout, "Mailgun response:", resp)
fmt.Fprintln(os.Stdout, "Mailgun ID:", id)
json.NewEncoder(w).Encode(b)
}
}
</code></pre>
<p>I appreciate any feedback! Thanks!</p>
|
[] |
[
{
"body": "<p>A couple thoughts on <code>contact.go</code>.</p>\n<h3>Global Variables</h3>\n<p>In general, it's advised to not use global variables like</p>\n<pre class=\"lang-golang prettyprint-override\"><code>var mailgunSender string = "email@sender.com"\nvar mailgunReceiver string = "email@receiver.com"\n</code></pre>\n<p>Instead, there are a few options. You already have a struct definition inside the <code>HandleContact</code> closure, so you could just move them there. You could also pass them as arguments to <code>HandleContact()</code>.</p>\n<p>The other alternative could be to define a Mailgun struct with those as fields (and could probably include the mailgunDomain and mailgunAPIKey as well). Then define HandleContact as a method on the Mailgun struct, and use the handler by first creating a new Mailgun with the appropriate values like so:</p>\n<p><strong>main.go</strong></p>\n<pre class=\"lang-golang prettyprint-override\"><code>mg := Mailgun{\n Sender: "email@sender.com",\n Receiver: "email@receiver.com",\n Domain: mailgunDomain,\n ApiKey: mailgunAPIKey,\n}\nr.HandleFunc("/contact", mg.HandleContact()).Methods("POST", "OPTIONS")\n</code></pre>\n<p><strong>contact.go</strong></p>\n<pre class=\"lang-golang prettyprint-override\"><code>type Mailgun struct {\n Sender: string\n Receiver: string\n Domain: string\n ApiKey: string\n}\nfunc (m *Mailgun) HandleContact() http.HandlerFunc {\n type body struct {\n Name string `json:"name"`\n Email string `json:"email"`\n Message string `json:"message"`\n }\n\n mg := mailgun.NewMailgun(m.Domain, m.APIKey)\n //etc...\n</code></pre>\n<p>I think the biggest advantage to setting it up this way is that it becomes very testable. You can inject whatever settings are appropriate for testing.</p>\n<h3>Printing</h3>\n<p><code>fmt.Printf()</code> outputs to Stdout by default, so the lines</p>\n<pre class=\"lang-golang prettyprint-override\"><code>fmt.Fprintln(os.Stdout, "## New message!")\nfmt.Fprintln(os.Stdout, message+"\\n")\n// ...\nfmt.Fprintln(os.Stdout, "Mailgun response:", resp)\nfmt.Fprintln(os.Stdout, "Mailgun ID:", id)\n</code></pre>\n<p>are functionally the same as</p>\n<pre class=\"lang-golang prettyprint-override\"><code>// Note 2 newlines to keep output identical to your implementation\nfmt.Printf("## New message!\\n %s\\n\\n", message) \n// ...\nfmt.Printf("Mailgun response: %s\\n", resp)\nfmt.Printf("Mailgun ID: %s\\n", id)\n</code></pre>\n<h3>Errors</h3>\n<p>Don't forget to handle the error from <code>json.NewEncoder(w).Encode(b)</code> at the end of <code>contact.go</code>. As the code is written I don't see any reason why it should ever return an error, you're just re-encoding the body you just decoded and echoing it back to the client. But if you ever change your code and the body is modified in some way it could fail silently and lead to debugging headaches.</p>\n<p>Also wondering what the purpose of re-encoding is, you could just store and re-use the original value of <code>r.Body</code>. Did you mean to encode and return the response from Mailgun?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T11:08:01.820",
"Id": "508506",
"Score": "0",
"body": "Nice first answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T18:29:08.320",
"Id": "257407",
"ParentId": "256812",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:18:08.103",
"Id": "256812",
"Score": "0",
"Tags": [
"go",
"api",
"http"
],
"Title": "Go Web API for Sending Emails via Contact Form"
}
|
256812
|
<p>I'm trying to get into object oriented javascript programming. I have written a class for collapsible elements as a test. These elements all have a certain class and no matter how many elements there are on the page, they should all be collapsible.</p>
<p>It works so far, but I don't think it's very elegant yet. For example, I wonder if the function "checkforCollapsibles" doesn't actually belong in the class? But can a class create instances of itself?</p>
<p>But that's probably not the only thing. I would be very happy if you have any suggestions on how to make this even better, cleaner and more elegant ;-)</p>
<p>--- EDIT: I know you don't need a class for collapsing elements :-)</p>
<pre><code>"use strict";
class bb_Collapsible {
constructor(link, content) {
this.link = link;
this.content = content;
this.content.classList.toggle("bb-collapsed");
this.link.addEventListener("click", this);
}
handleEvent(event) {
if (event.type === "click") {
this.switchStatus();
}
}
switchStatus() {
this.content.classList.toggle("bb-collapsed");
}
}
function checkForCollapsibles() {
const collapsibleLinks = document.querySelectorAll(".bb-collapsible");
const collapsibleContents = document.querySelectorAll(".bb-collapsible-content");
if (collapsibleLinks.length > 0) {
collapsibleLinks.forEach((element, index) => {
new bb_Collapsible(collapsibleLinks[index], collapsibleContents[index]);
});
} else {
console.log("No collapsible Elements");
}
}
document.addEventListener("DOMContentLoaded", checkForCollapsibles);
</code></pre>
<p>EXTENSION
I used this article for event handling. However, I don't quite understand it yet. In the example, only pass this as the callback. I assume javascript interprets this as the eventHandle function of the respective instance. But what if I have different elements that should trigger different functions? In my example, I could only ask which event was triggered and not which element? Or should I then write switches and get it from the respective event object? but that no longer sounds clean and tidy to me.
<a href="https://dev.to/rikschennink/the-fantastically-magical-handleevent-function-1bp4" rel="nofollow noreferrer">https://dev.to/rikschennink/the-fantastically-magical-handleevent-function-1bp4</a></p>
|
[] |
[
{
"body": "<p>This seems over-engineered. If really all you need is <code>this.content.classList.toggle("bb-collapsed");</code> then I would simply go for</p>\n<pre><code>class Collapsible {\n constructor(link, content) {\n this.link = link;\n this.content = content;\n this.content.classList.toggle("bb-collapsed");\n this.link.addEventListener("click", e => content.classList.toggle("bb-collapsed"));\n }\n}\n</code></pre>\n<p>And from there, there really isn't much of a point in having a class. You could do that straight in your <code>checkForCollapsibles</code>.</p>\n<p>Something like this</p>\n<pre><code>function wireCollapsibles() {\n const links = document.querySelectorAll(".bb-collapsible");\n const contents = document.querySelectorAll(".bb-collapsible-content");\n\n links.forEach((link, index) => {\n new bb_Collapsible(collapsibleLinks[index], collapsibleContents[index]);\n link.addEventListener(e => contents[i].classList.toggle("bb-collapsed"));\n });\n}\n</code></pre>\n<p>Note that I drop the <code>console.log</code> thing, ideally you dont have log statements in your production code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:38:42.257",
"Id": "507084",
"Score": "0",
"body": "yes that's clear. i can write this much easier. but then i wouldn't be practising how to use oop javascript ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:40:13.077",
"Id": "507085",
"Score": "0",
"body": "Well in that case, your code is quite good actually, I would just like to see the class name start with an uppercase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:44:28.313",
"Id": "507086",
"Score": "0",
"body": "Thank you :-) I haven't quite understood this event handler function yet. As I wrote this, it only works with an action. But what if I have different elements that should trigger different functions? I got this from this article: https://dev.to/rikschennink/the-fantastically-magical-handleevent-function-1bp4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:53:22.080",
"Id": "507087",
"Score": "0",
"body": "You should add that link in your question, it would make it a beter question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:54:41.223",
"Id": "507088",
"Score": "0",
"body": "i will do that :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:24:27.450",
"Id": "256817",
"ParentId": "256813",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T15:19:45.210",
"Id": "256813",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"ecmascript-6"
],
"Title": "Learning Javascript OOP with a Collapsing Item Class"
}
|
256813
|
<p>Original review here: <a href="https://codereview.stackexchange.com/questions/250017/ai-for-openttd-a-path-finder">AI for OpenTTD - A* Path Finder</a></p>
<p>If you'd like to run the code yourself: <a href="https://github.com/marlonsmith10/empire_ai" rel="nofollow noreferrer">https://github.com/marlonsmith10/empire_ai</a> (use_smart_pointers branch)</p>
<p>Changes have been made based on the previous review. In particular, using std::priority_queue and std::unordered map have dramatically improved performance. However, using std::unique_ptr compared to raw pointers is slowing the code down by about a factor of 2. Since I'm new to unique_ptr, I would appreciate any comments on whether its being used appropriately, and whether performance can be improved. Something that stands out to me is that when using std::unique_ptr, any node in m_closed_nodes must be moved out, checked, and then moved back in. With a raw pointer, this isn't necessary unless the node is going to be re-opened.</p>
<p>The code also now checks to make sure that roads can be actually built based on the slope of the current tile, so there are no longer any broken connections in roads built along the discovered path.</p>
<p>As in the previous review, any comments on good C++ programming practices are welcome as well.</p>
<p>Update: Some notes on why pointers were used instead of objects in m_closed_nodes and m_open_nodes. Any feedback on the reasons here would be much appreciated.</p>
<ol>
<li>Iterator can use nullptr to determine the Node before the start Node, which can't be done using TileIndex since all values of TileIndex are valid. This was a problem I could not find a good solution to, and was the main motivator for storing pointers.</li>
<li>Node member variables can be marked as const, which can't be done if they are stored directly in the containers.</li>
<li>cheapest_open_node can return nullptr instead of having to take in and modify a status variable.</li>
</ol>
<p>I should also add that I'm working with C++11.</p>
<p>path.hh</p>
<pre><code>#ifndef PATH_HH
#define PATH_HH
#include "stdafx.h"
#include "command_func.h"
#include <queue>
#include <unordered_map>
namespace EmpireAI
{
class Path
{
public:
enum Status
{
IN_PROGRESS,
FOUND,
UNREACHABLE
};
Path(const TileIndex start, const TileIndex end);
// Find a partial path from start to end, returning true if the full path has been found
Status find(const uint16_t max_node_count = DEFAULT_NODE_COUNT_PER_FIND);
private:
struct Node
{
Node(TileIndex in_tile_index, int32 in_h)
: tile_index(in_tile_index), h(in_h)
{
}
Node()
: tile_index(0), h(0)
{}
// Update the Node's g and h values, as well as its previous node. Returns true if the
// new values are lower than the previous ones.
bool update_costs(Node* const adjacent_node);
const TileIndex tile_index;
Node* previous_node = nullptr;
int32 g = 0;
const int32 h;
int32 f = -1;
};
struct NodeCostCompare
{
bool operator()(const std::unique_ptr<Node>& node1, const std::unique_ptr<Node>& node2)
{
return node1->f > node2->f;
}
};
void parse_adjacent_tile(Node* const current_node, const int8 x, const int8 y);
// Return the corresponding node or create a new one if none is found
std::unique_ptr<Node> get_node(const TileIndex tile_index);
// Get the cheapest open node, returns nullptr if there are no open nodes
std::unique_ptr<Node> cheapest_open_node();
// Returns true if a road can be built from one node to the next
bool nodes_can_connect_road(const Node* const node_from, const Node* const node_to) const;
// Check this many nodes per call of find()
static const uint16 DEFAULT_NODE_COUNT_PER_FIND = 20;
void open_node(std::unique_ptr<Node> node);
void close_node(std::unique_ptr<Node> node);
Status m_status;
Node* m_start_node;
Node* m_end_node;
const TileIndex m_end_tile_index;
// Containers for open and closed nodes
std::unordered_map<TileIndex, std::unique_ptr<Node>> m_closed_nodes;
std::priority_queue<Node*, std::vector<std::unique_ptr<Node>>, NodeCostCompare> m_open_nodes;
public:
class Iterator
{
public:
Iterator(const Path::Node* node)
: m_iterator_node(node)
{}
bool operator==(const Iterator& iterator) const
{
return m_iterator_node == iterator.m_iterator_node;
}
const Iterator& operator=(const Path::Node* node)
{
m_iterator_node = node;
return *this;
}
bool operator!=(const Iterator& iterator) const
{
return m_iterator_node != iterator.m_iterator_node;
}
const Iterator& operator++()
{
m_iterator_node = m_iterator_node->previous_node;
return *this;
}
Iterator operator++(int)
{
Iterator iterator = *this;
m_iterator_node = m_iterator_node->previous_node;
return iterator;
}
TileIndex operator*() const
{
if(m_iterator_node == nullptr)
{
return 0;
}
return m_iterator_node->tile_index;
}
private:
const Path::Node* m_iterator_node;
};
Iterator begin()
{
return Iterator(m_end_node);
}
Iterator end()
{
return Iterator(m_start_node);
}
};
}
#endif // PATH_HH
</code></pre>
<p>path.cc</p>
<pre><code>#include "path.hh"
#include "script_map.hpp"
#include "script_road.hpp"
#include "script_tile.hpp"
#include "map_func.h"
#include <algorithm>
using namespace EmpireAI;
Path::Path(const TileIndex start, const TileIndex end)
: m_end_tile_index(end)
{
// Create an open node at the start
std::unique_ptr<Node> start_node = get_node(start);
start_node->f = start_node->h;
// Keep a pointer to the start node, for use by the iterator once a path has been found
m_start_node = start_node.get();
open_node(std::move(start_node));
m_status = IN_PROGRESS;
}
Path::Status Path::find(const uint16_t max_node_count)
{
if(m_status != IN_PROGRESS)
{
return m_status;
}
// While not at end of path
for(uint16 node_count = 0; node_count < max_node_count; node_count++)
{
// Get the cheapest open node
std::unique_ptr<Node> current_node = cheapest_open_node();
// If there are no open nodes, the path is unreachable
if(current_node == nullptr)
{
m_status = UNREACHABLE;
break;
}
// If we've reached the destination, return true
if(current_node->tile_index == m_end_tile_index)
{
// Keep a pointer to the end node, for use by the iterator
m_end_node = current_node.get();
close_node(std::move(current_node));
m_status = FOUND;
break;
}
// Calculate the f, h, g, values of the 4 surrounding nodes
parse_adjacent_tile(current_node.get(), 1, 0);
parse_adjacent_tile(current_node.get(), -1, 0);
parse_adjacent_tile(current_node.get(), 0, 1);
parse_adjacent_tile(current_node.get(), 0, -1);
// Mark the current node as closed
close_node(std::move(current_node));
}
return m_status;
}
void Path::parse_adjacent_tile(Node* const current_node, const int8 x, const int8 y)
{
TileIndex adjacent_tile_index = current_node->tile_index + ScriptMap::GetTileIndex(x, y);
std::unique_ptr<Node> adjacent_node = get_node(adjacent_tile_index);
// Check to see if this tile can be used as part of the path
if(nodes_can_connect_road(current_node, adjacent_node.get()))
{
if(adjacent_node->update_costs(current_node))
{
open_node(std::move(adjacent_node));
}
else
{
close_node(std::move(adjacent_node));
}
}
else
{
close_node(std::move(adjacent_node));
}
}
bool Path::nodes_can_connect_road(const Node* const node_from, const Node* const node_to) const
{
// The start node doesn't connect to a previous node, so we can't check it for the correct slope.
// The pathfinder can only ensure that the next node in the path can connect to the start node.
if(node_from->previous_node == nullptr)
{
return true;
}
int32 supports_road = ScriptRoad::CanBuildConnectedRoadPartsHere(node_from->tile_index, node_from->previous_node->tile_index, node_to->tile_index);
if(supports_road <= 0)
{
return false;
}
if(!ScriptTile::IsBuildable(node_to->tile_index) && !ScriptRoad::IsRoadTile(node_to->tile_index))
{
return false;
}
return true;
}
std::unique_ptr<Path::Node> Path::cheapest_open_node()
{
// While there are open nodes available
while(!m_open_nodes.empty())
{
// Remove the cheapest node from the open nodes list
std::unique_ptr<Node> current_node = std::move(const_cast<std::unique_ptr<Node>&>(m_open_nodes.top()));
m_open_nodes.pop();
// If this node has already been closed, discard it and skip to the next one. Duplicates are expected
// here because get_node() doesn't check for duplicates for performance reasons.
if(m_closed_nodes.find(current_node->tile_index) != m_closed_nodes.end())
{
continue;
}
return current_node;
}
// There are no more open nodes
return nullptr;
}
std::unique_ptr<Path::Node> Path::get_node(const TileIndex tile_index)
{
// If the node is not closed, create a new one.
// Duplicate open nodes are considered an acceptable tradeoff since it's not easy to search std::priority_queue for
// an already existing open node
if(m_closed_nodes.find(tile_index) == m_closed_nodes.end())
{
return std::unique_ptr<Node>(new Node(tile_index, ScriptMap::DistanceManhattan(tile_index, m_end_tile_index)));
}
std::unique_ptr<Node> node = std::move(m_closed_nodes.at(tile_index));
// Remove the (now null) node from the closed list
m_closed_nodes.erase(tile_index);
return node;
}
void Path::open_node(std::unique_ptr<Node> node)
{
// Push the node into the open node list. Does not check open nodes, instead allowing
// duplicates to be created in the open node priority queue, since checking for already open nodes is slower
// than just processing a node twice.
m_open_nodes.push(std::move(node));
}
void Path::close_node(std::unique_ptr<Node> node)
{
m_closed_nodes[node->tile_index] = std::move(node);
}
bool Path::Node::update_costs(Node* const adjacent_node)
{
int32 new_g = adjacent_node->g + 1;
int32 new_f = new_g + h;
// If this node is closed but cheaper than it was via previous path, or
// if this is a new node (f == -1), return true to indicate the node should be opened again
if(new_f < f || f == -1)
{
g = new_g;
f = new_f;
previous_node = adjacent_node;
return true;
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Use of pointers in containers</h1>\n<p>In C++, it is often more efficient to store objects directly into a container, instead of just storing pointers to objects in a container. However, if you want to move an object in and out of containers a lot, and they are large, then of course it is better to just store the pointer. In your case, it's a bit of a borderline situation. You move <code>Node</code>s from <code>m_open_nodes</code> to <code>m_closed_nodes</code> and back, however a <code>Node</code> is actually a relatively small data structure. On a 64-bit machine, it looks like it's 24 bytes, which means it's as big as three pointers. Copying and moving a <code>Node</code> should therefore be quite fast, and having a container of <code>Node</code> objects directly will avoid the need for indirection, and possibly lay out objects in memory in a more efficient way. So I recommend trying to change <code>m_open_nodes</code> and <code>m_closed_nodes</code> to:</p>\n<pre><code>struct NodeCostCompare {\n bool operator()(const Node& node1, const Node& node2) {\n return node1.f > node2.f;\n }\n};\n\nstd::unordered_map<TileIndex, Node> m_closed_nodes;\nstd::priority_queue<Node, std::vector<Node>, NodeCostCompare> m_open_nodes;\n</code></pre>\n<p>Of course, this requires changes in other parts of the code as well. I don't think you need to <code>std::move()</code> anything anymore; <code>Node</code> itself doesn't own any memory so there is no need for move operators.</p>\n<p>One drawback is that you no longer have stable pointers to nodes. To get around that, you should use tile indices to refer to nodes; so instead of <code>m_start_node</code> and <code>m_end_node</code>, you just need <code>m_start_tile_index</code> and <code>m_end_tile_index</code>, and instead of <code>previous_node</code> you need <code>previous_tile_index</code>.</p>\n<h1>Choice of containers</h1>\n<p>The chosen containers are OK, however some small changes could be made that might improve performance. First, since a <code>Node</code> already contains a <code>tile_index</code>, it is redundant to store a copy of the tile index as the key in a <code>std::unordered_map</code>. What you could do instead is to use a <a href=\"https://en.cppreference.com/w/cpp/container/set\" rel=\"nofollow noreferrer\"><code>std::set</code></a>, and give it a custom comparison function so it compares on <code>tile_index</code>:</p>\n<pre><code>struct NodeTileCompare {\n using is_transparent = void;\n bool operator()(const Node &node1, const Node &node2) {\n return node1.tile_index < node2.tile_index;\n }\n bool operator()(const Node &node, TileIndex tile_index) {\n return node.tile_index < tile_index;\n }\n bool operator()(TileIndex tile_index, const Node &node) {\n reutrn tile_index < node.tile_index;\n }\n};\n\nstd::set<Node, NodeTileCompare> m_closed_nodes;\n</code></pre>\n<p>The extra overloads are to allow calling <a href=\"https://en.cppreference.com/w/cpp/container/set/find\" rel=\"nofollow noreferrer\"><code>find()</code></a> on the set with just a <code>TileIndex</code> as an argument. This does require C++14 support though, and the <code>is_transparent</code> type has to be defined in order for the second and third overload of <code>operator()</code> to be used.</p>\n<p>Another possible optimization is the priority queue. You told it to use a <code>std::vector<></code> to store the contents, however a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque<></code></a> might be more efficient, depending on the order in which elements are pushed into the queue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T20:33:45.917",
"Id": "507093",
"Score": "1",
"body": "For the custom `std::set` comparator... wouldn't that need a `using is_transparent = void;` typedef? Or is that only needed sometimes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T23:19:28.950",
"Id": "507098",
"Score": "0",
"body": "Good point, that is needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:49:28.770",
"Id": "507269",
"Score": "0",
"body": "@G.Sliepen Thanks very much for your detailed reply! I actually went back on forth on storing object vs pointers, and I wish I had remembered to include the reasons in the original post.\n\nThe main issue I ran into with using objects and TileIndexes was with the iterator. If Nodes cannot keep pointers to each other, the iterator can't use nullptr to indicate one past the start node. All values of TileIndex are valid, so there is no value that can be used to indicate one past the start. This was a problem I couldn't find a good solution to, but would definitely appreciate your thoughts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:51:42.643",
"Id": "507270",
"Score": "0",
"body": "@G.Sliepen The other reasons were smaller; one was being able to mark member variables of Node as const which can't be done when storing them in standard containers. The other was that cheapest_open_node can return a nullptr instead of having to take in a reference to a status variable to indicate no more nodes available. These are more nice to haves though; if I could solve the iterator issue I could work around them. Also should add I'm using C++ 11. I'll update the post with this information as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:59:12.173",
"Id": "507272",
"Score": "0",
"body": "@G.Sliepen Also thanks for your comments on the containers, I will look into that further. Thanks again for all of your feedback, it's very much appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T20:17:05.853",
"Id": "507273",
"Score": "0",
"body": "@MarlonSmith Good point about the \"on past the end\" iterator. Are you sure there is not a good value for TileIndex that could be used for this? For example, `-1` or `~0` for unsigned indices. Maybe there is another way to check if a `Node` is the first/last one of the path? Also, since C++17 you can have `end()` return a different *type* than `begin()`, and overload the iterator comparison operators accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T20:49:46.250",
"Id": "507274",
"Score": "0",
"body": "@G.Sliepen TileIndex is a typedef uint32 so I can't use a negative number, however your comment made me consider digging deeper and I found this defined by the OpenTTD code: static const TileIndex INVALID_TILE = (TileIndex)-1;. I'll try using that to mark past the start node, which means I should be able to store Nodes in the containers instead of pointers. Thanks very much! Could I also ask your thoughts on not being able to use const for Node member variables, and not being able to return nullptr from get_open_nodes? Would you consider that worth the tradeoff to not use pointers?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T19:18:29.007",
"Id": "256820",
"ParentId": "256818",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256820",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T16:54:41.943",
"Id": "256818",
"Score": "3",
"Tags": [
"c++",
"algorithm"
],
"Title": "AI for OpenTTD - A* Path Finder: Follow-up and unique_ptr slow performance"
}
|
256818
|
<p>As a player of the online game Pokéfarm Q, I'm making a fan-made extension to help players search through forum threads and CSS codes/userscripts. So that I can easily fetch data from a Pastebin I created, I added a function that ignores the CORS headers when the user is visiting <a href="https://pokefarm.com" rel="nofollow noreferrer">https://pokefarm.com</a> and the browser extension is requesting a page from pastebin.com.</p>
<p>I based the code off of a much larger extension allowing users to disable CORS on specific pages using the browser extension, by toggling it on/off in a context menu, but there's a lot of unnecessary extra pieces of code that don't need to be in there. Could anyone help me clean up my code a bit? I've done the very best I can so far, but I'm quite new to coding chrome extensions (this is the first one I developed all by myself) so I'm not sure what the best option is right now.</p>
<p>(if it isn't entirely clear, the code below is just the background.js file and not the main content script)</p>
<pre><code>/* Source code based on (but not directly taken from) https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino */
/* CORS has to be unblocked so that PFQ, Pastebin, the PFQ CDN, and the extension can all work together. */
"use strict";
const prefs = {
enabled: true,
"overwrite-origin": true,
methods: ["GET", "PUT", "POST", "DELETE", "HEAD", "OPTIONS", "PATCH", "PROPFIND", "PROPPATCH", "MKCOL", "COPY", "MOVE", "LOCK"],
"remove-x-frame": true,
"allow-credentials": true,
"allow-headers-value": "*",
"allow-origin-value": "*",
"expose-headers-value": "*",
"allow-headers": true,
"unblock-initiator": true,
};
const redirects = {};
chrome.tabs.onRemoved.addListener((tabId) => delete redirects[tabId]);
const cors = {};
cors.onBeforeRedirect = (d) => {
if (d.type === "main_frame") {
return;
}
redirects[d.tabId] = redirects[d.tabId] || {};
redirects[d.tabId][d.requestId] = true;
};
cors.onHeadersReceived = (d) => {
if (d.type === "main_frame") {
return;
}
const { initiator, originUrl, responseHeaders, method, requestId, tabId } = d;
let origin = "";
const redirect = redirects[tabId] ? redirects[tabId][requestId] : false;
if (prefs["unblock-initiator"] && redirect !== true) {
try {
const o = new URL(initiator || originUrl);
origin = o.origin;
} catch (e) {
console.warn("cannot extract origin for initiator", initiator);
}
} else {
origin = "*";
}
if (redirects[tabId]) {
delete redirects[tabId][requestId];
}
if (prefs["overwrite-origin"] === true) {
const o = responseHeaders.find(({ name }) => name.toLowerCase() === "access-control-allow-origin");
if (o) {
o.value = origin || prefs["allow-origin-value"];
} else {
responseHeaders.push({
name: "Access-Control-Allow-Origin",
value: origin || prefs["allow-origin-value"],
});
}
}
if (prefs.methods.length > 3) {
// GET, POST, HEAD are mandatory
const o = responseHeaders.find(({ name }) => name.toLowerCase() === "access-control-allow-methods");
if (o) {
o.value = prefs.methods.join(", ");
} else {
responseHeaders.push({
name: "Access-Control-Allow-Methods",
value: prefs.methods.join(", "),
});
}
}
if (prefs["allow-credentials"] === true) {
const o = responseHeaders.find(({ name }) => name.toLowerCase() === "access-control-allow-credentials");
if (o) {
o.value = "true";
} else {
responseHeaders.push({
name: "Access-Control-Allow-Credentials",
value: "true",
});
}
}
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
if (prefs["allow-headers"] === true) {
const o = responseHeaders.find(({ name }) => name.toLowerCase() === "access-control-allow-headers");
if (o) {
o.value = prefs["allow-headers-value"];
} else {
responseHeaders.push({
name: "Access-Control-Allow-Headers",
value: prefs["allow-headers-value"],
});
}
}
if (prefs["allow-headers"] === true) {
const o = responseHeaders.find(({ name }) => name.toLowerCase() === "access-control-expose-headers");
if (o) {
o.value = prefs["expose-headers-value"];
} else {
responseHeaders.push({
name: "Access-Control-Expose-Headers",
value: prefs["expose-headers-value"],
});
}
}
if (prefs["remove-x-frame"] === true) {
const i = responseHeaders.findIndex(({ name }) => name.toLowerCase() === "x-frame-options");
if (i !== -1) {
responseHeaders.splice(i, 1);
}
}
return {
responseHeaders,
};
};
cors.install = () => {
chrome.webRequest.onHeadersReceived.removeListener(cors.onHeadersReceived);
chrome.webRequest.onBeforeRedirect.removeListener(cors.onBeforeRedirect);
const extra = ["blocking", "responseHeaders"];
if (/Firefox/.test(navigator.userAgent) === false) {
extra.push("extraHeaders");
}
chrome.webRequest.onHeadersReceived.addListener(
cors.onHeadersReceived,
{
urls: ["*://*.pastebin.com/*", "*://*.pokefarm.com/*", "*://*.pfq-static.com/*"],
},
extra
);
chrome.webRequest.onBeforeRedirect.addListener(cors.onBeforeRedirect, {
urls: ["*://*.pastebin.com/*", "*://*.pokefarm.com/*", "*://*.pfq-static.com/*"],
});
};
cors.onCommand = () => {
cors.install();
};
chrome.storage.onChanged.addListener((ps) => {
Object.keys(ps).forEach((name) => (prefs[name] = ps[name].newValue));
cors.onCommand();
});
chrome.browserAction.onClicked.addListener(() =>
chrome.storage.local.set({
enabled: prefs.enabled === false,
})
);
/* init */
chrome.storage.local.get(prefs, (ps) => {
Object.assign(prefs, ps);
cors.onCommand();
});
</code></pre>
<p>The goal of the background script is simply to bypass CORS and the Content Security Policy when a content script on <a href="https://pokefarm.com" rel="nofollow noreferrer">https://pokefarm.com</a> sends a request to <a href="https://pastebin.com" rel="nofollow noreferrer">https://pastebin.com</a>, but the code that I'm basing it on had a lot of configuration options that I'm not 100% sure what to do about.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T19:20:15.840",
"Id": "256821",
"Score": "2",
"Tags": [
"javascript",
"google-chrome"
],
"Title": "Chrome extension for helping players search through a forum"
}
|
256821
|
<p>this is my second post here, and the second project I made. I wanted to know, how to improve my code of connect-4 made in c# for console.</p>
<pre><code>using System;
namespace Connect_4
{
class Program
{
// computer's board, that computer checks if someone wins
static string[] BoardColumn1 = { "a", "b", "c", "d", "e", "f" };
static string[] BoardColumn2 = { "g", "h", "i", "j", "k", "l" };
static string[] BoardColumn3 = { "m", "n", "p", "p", "q", "r" };
static string[] BoardColumn4 = { "t", "u", "v", "w", "i", "y" };
static string[] BoardColumn5 = { "z", "1", "2", "3", "4", "5" };
static string[] BoardColumn6 = { "6", "7", "8", "9", "0", "(" };
static string[] BoardColumn7 = { ")", "-", "_ ", "+", "=", "}" };
// what the user sees
static string[] UserBoardColumn1 = { " ", " ", " ", " ", " ", " " };
static string[] UserBoardColumn2 = { " ", " ", " ", " ", " ", " " };
static string[] UserBoardColumn3 = { " ", " ", " ", " ", " ", " " };
static string[] UserBoardColumn4 = { " ", " ", " ", " ", " ", " " };
static string[] UserBoardColumn5 = { " ", " ", " ", " ", " ", " " };
static string[] UserBoardColumn6 = { " ", " ", " ", " ", " ", " " };
static string[] UserBoardColumn7 = { " ", " ", " ", " ", " ", " " };
static int turn = 0;
static bool playing = true;
static void Main(string[] args)
{
Intro();
while (playing) //stops the game once someone wins
{
Board();
if (turn % 2 == 0) // tells whose turn it is
{
Console.WriteLine("Player 1's turn");
}
else
{
Console.WriteLine("Player 2's turn");
}
int UserChoice;
Console.WriteLine("Type the number you want your token to go in or type restart to restart"); //takes user input
bool IsChoiceInt = int.TryParse(Console.ReadLine(), out UserChoice);
if (IsChoiceInt) //checks if is correct input
{
if (UserChoice == 1) // checks if someone wants to put the token in 1 and puts it there
{
int EmptyLocation = Array.IndexOf(UserBoardColumn1, " ");
if (EmptyLocation == -1)
{
Console.WriteLine("Stop trying to steal other people's places");
System.Threading.Thread.Sleep(2000);
}
else if (turn % 2 == 0)
{
turn++;
BoardColumn1[EmptyLocation] = "o";
UserBoardColumn1[EmptyLocation] = "o";
}
else
{
turn++;
BoardColumn1[EmptyLocation] = "x";
UserBoardColumn1[EmptyLocation] = "x";
}
Board();
VerticalWinCondition();
HorizontalWinCondition();
DiagonalWin();
IsTieGame();
}
else if (UserChoice == 2) // checks if someone wants to put the token in 2 and puts it there
{
int EmptyLocation = Array.IndexOf(UserBoardColumn2, " ");
if (EmptyLocation == -1)
{
Console.WriteLine("Stop trying to steal other people's places");
System.Threading.Thread.Sleep(2000);
}
else if (turn % 2 == 0)
{
turn++;
BoardColumn2[EmptyLocation] = "o";
UserBoardColumn2[EmptyLocation] = "o";
}
else
{
turn++;
BoardColumn2[EmptyLocation] = "x";
UserBoardColumn2[EmptyLocation] = "x";
}
Board();
VerticalWinCondition();
HorizontalWinCondition();
DiagonalWin();
IsTieGame();
}
else if (UserChoice == 3) // checks if someone wants to put the token in 3 and puts it there
{
int EmptyLocation = Array.IndexOf(UserBoardColumn3, " ");
if (EmptyLocation == -1)
{
Console.WriteLine("Stop trying to steal other people's places");
System.Threading.Thread.Sleep(2000);
}
else if (turn % 2 == 0)
{
turn++;
BoardColumn3[EmptyLocation] = "o";
UserBoardColumn3[EmptyLocation] = "o";
}
else
{
turn++;
BoardColumn3[EmptyLocation] = "x";
UserBoardColumn3[EmptyLocation] = "x";
}
Board();
VerticalWinCondition();
HorizontalWinCondition();
DiagonalWin();
IsTieGame();
}
else if (UserChoice == 4) // checks if someone wants to put the token in 4 and puts it there
{
int EmptyLocation = Array.IndexOf(UserBoardColumn4, " ");
if (EmptyLocation == -1)
{
Console.WriteLine("Stop trying to steal other people's places");
System.Threading.Thread.Sleep(2000);
}
else if (turn % 2 == 0)
{
turn++;
BoardColumn4[EmptyLocation] = "o";
UserBoardColumn4[EmptyLocation] = "o";
}
else
{
turn++;
BoardColumn4[EmptyLocation] = "x";
UserBoardColumn4[EmptyLocation] = "x";
}
Board();
VerticalWinCondition();
HorizontalWinCondition();
DiagonalWin();
IsTieGame();
}
else if (UserChoice == 5) // checks if someone wants to put the token in 5 and puts it there
{
int EmptyLocation = Array.IndexOf(UserBoardColumn5, " ");
if (EmptyLocation == -1)
{
Console.WriteLine("Stop trying to steal other people's places");
System.Threading.Thread.Sleep(2000);
}
else if (turn % 2 == 0)
{
turn++;
BoardColumn5[EmptyLocation] = "o";
UserBoardColumn5[EmptyLocation] = "o";
}
else
{
turn++;
BoardColumn5[EmptyLocation] = "x";
UserBoardColumn5[EmptyLocation] = "x";
}
Board();
VerticalWinCondition();
HorizontalWinCondition();
DiagonalWin();
IsTieGame();
}
else if (UserChoice == 6) // checks if someone wants to put the token in 6 and puts it there
{
int EmptyLocation = Array.IndexOf(UserBoardColumn6, " ");
if (EmptyLocation == -1)
{
Console.WriteLine("Stop trying to steal other people's places");
System.Threading.Thread.Sleep(2000);
}
else if (turn % 2 == 0)
{
turn++;
BoardColumn6[EmptyLocation] = "o";
UserBoardColumn6[EmptyLocation] = "o";
}
else
{
turn++;
BoardColumn6[EmptyLocation] = "x";
UserBoardColumn6[EmptyLocation] = "x";
}
Board();
VerticalWinCondition();
HorizontalWinCondition();
DiagonalWin();
IsTieGame();
}
else if (UserChoice == 7)// checks if someone wants to put the token in 7 and put it there
{
int EmptyLocation = Array.IndexOf(UserBoardColumn7, " ");
if (EmptyLocation == -1)
{
Console.WriteLine("Stop trying to steal other people's places");
System.Threading.Thread.Sleep(2000);
}
else if (turn % 2 == 0)
{
turn++;
BoardColumn7[EmptyLocation] = "o";
UserBoardColumn7[EmptyLocation] = "o";
}
else
{
turn++;
BoardColumn7[EmptyLocation] = "x";
UserBoardColumn7[EmptyLocation] = "x";
}
Board();
VerticalWinCondition();
HorizontalWinCondition();
DiagonalWin();
IsTieGame();
}
else if (UserChoice > 7 || UserChoice < 0) //error check
{
Console.WriteLine("Please input a valid number, the valid numbers are 1, 2, 3, 4, 5, 6, 7");
System.Threading.Thread.Sleep(2000);
}
}
else //error check
{
Console.WriteLine("Please input a valid number, the valid numbers are 1, 2, 3, 4, 5, 6, 7");
System.Threading.Thread.Sleep(2000);
}
}
}
static void Board() //makes the board
{
Console.Clear();
Console.WriteLine(" 1 2 3 4 5 6 7");
Console.WriteLine($"| {UserBoardColumn1[5]} | {UserBoardColumn2[5]} | {UserBoardColumn3[5]} | {UserBoardColumn4[5]} | {UserBoardColumn5[5]} | {UserBoardColumn6[5]} | {UserBoardColumn7[5]} |");
Console.WriteLine($"| {UserBoardColumn1[4]} | {UserBoardColumn2[4]} | {UserBoardColumn3[4]} | {UserBoardColumn4[4]} | {UserBoardColumn5[4]} | {UserBoardColumn6[4]} | {UserBoardColumn7[4]} |");
Console.WriteLine($"| {UserBoardColumn1[3]} | {UserBoardColumn2[3]} | {UserBoardColumn3[3]} | {UserBoardColumn4[3]} | {UserBoardColumn5[3]} | {UserBoardColumn6[3]} | {UserBoardColumn7[3]} |");
Console.WriteLine($"| {UserBoardColumn1[2]} | {UserBoardColumn2[2]} | {UserBoardColumn3[2]} | {UserBoardColumn4[2]} | {UserBoardColumn5[2]} | {UserBoardColumn6[2]} | {UserBoardColumn7[2]} |");
Console.WriteLine($"| {UserBoardColumn1[1]} | {UserBoardColumn2[1]} | {UserBoardColumn3[1]} | {UserBoardColumn4[1]} | {UserBoardColumn5[1]} | {UserBoardColumn6[1]} | {UserBoardColumn7[1]} |");
Console.WriteLine($"| {UserBoardColumn1[0]} | {UserBoardColumn2[0]} | {UserBoardColumn3[0]} | {UserBoardColumn4[0]} | {UserBoardColumn5[0]} | {UserBoardColumn6[0]} | {UserBoardColumn7[0]} |");
Console.WriteLine("-----------------------------");
}
static void VerticalWinCondition() //checks if someone won vertially
{
if (BoardColumn1[0] == BoardColumn1[1] && BoardColumn1[0] == BoardColumn1[2] && BoardColumn1[0] == BoardColumn1[3] || BoardColumn1[1] == BoardColumn1[2] && BoardColumn1[1] == BoardColumn1[3] && BoardColumn1[1] == BoardColumn1[4] || BoardColumn1[2] == BoardColumn1[3] && BoardColumn1[2] == BoardColumn1[4] && BoardColumn1[2] == BoardColumn1[5])
{
playing = false;
Winner();
}
else if (BoardColumn2[0] == BoardColumn2[1] && BoardColumn2[0] == BoardColumn2[2] && BoardColumn2[0] == BoardColumn2[3] || BoardColumn2[1] == BoardColumn2[2] && BoardColumn2[1] == BoardColumn2[3] && BoardColumn2[1] == BoardColumn2[4] || BoardColumn2[2] == BoardColumn2[3] && BoardColumn2[2] == BoardColumn2[4] && BoardColumn2[2] == BoardColumn2[5])
{
playing = false;
Winner();
}
else if (BoardColumn3[0] == BoardColumn3[1] && BoardColumn3[1] == BoardColumn3[2] && BoardColumn3[2] == BoardColumn3[3] || BoardColumn3[1] == BoardColumn3[2] && BoardColumn3[1] == BoardColumn3[3] && BoardColumn3[1] == BoardColumn3[4] || BoardColumn3[2] == BoardColumn3[3] && BoardColumn3[2] == BoardColumn3[4] && BoardColumn3[2] == BoardColumn3[5])
{
playing = false;
Winner();
}
else if (BoardColumn4[0] == BoardColumn4[1] && BoardColumn4[1] == BoardColumn4[2] && BoardColumn4[0] == BoardColumn4[3] || BoardColumn4[1] == BoardColumn4[2] && BoardColumn4[1] == BoardColumn4[3] && BoardColumn4[1] == BoardColumn4[4] || BoardColumn4[2] == BoardColumn4[3] && BoardColumn4[2] == BoardColumn4[4] && BoardColumn4[2] == BoardColumn4[5])
{
playing = false;
Winner();
}
else if (BoardColumn5[0] == BoardColumn5[1] && BoardColumn5[1] == BoardColumn5[2] && BoardColumn5[2] == BoardColumn5[3] || BoardColumn5[1] == BoardColumn5[2] && BoardColumn5[1] == BoardColumn5[3] && BoardColumn5[1] == BoardColumn5[4] || BoardColumn5[2] == BoardColumn5[3] && BoardColumn5[2] == BoardColumn5[4] && BoardColumn5[2] == BoardColumn5[5])
{
playing = false;
Winner();
}
else if (BoardColumn6[0] == BoardColumn6[1] && BoardColumn6[1] == BoardColumn6[2] && BoardColumn6[2] == BoardColumn6[3] || BoardColumn6[1] == BoardColumn6[2] && BoardColumn6[1] == BoardColumn6[3] && BoardColumn6[1] == BoardColumn6[4] || BoardColumn6[2] == BoardColumn6[3] && BoardColumn6[2] == BoardColumn6[4] && BoardColumn6[2] == BoardColumn6[5])
{
playing = false;
Winner();
}
else if (BoardColumn7[0] == BoardColumn7[1] && BoardColumn7[1] == BoardColumn7[2] && BoardColumn7[2] == BoardColumn7[3] || BoardColumn7[1] == BoardColumn7[2] && BoardColumn7[1] == BoardColumn7[3] && BoardColumn7[1] == BoardColumn7[4] || BoardColumn7[2] == BoardColumn7[3] && BoardColumn7[2] == BoardColumn7[4] && BoardColumn7[2] == BoardColumn7[5])
{
playing = false;
Winner();
}
}
static void HorizontalWinCondition() // checks if soemone won horizontally
{
if (BoardColumn1[0] == BoardColumn2[0] && BoardColumn1[0] == BoardColumn3[0] && BoardColumn1[0] == BoardColumn4[0])
{
playing = false;
Winner();
}
else if (BoardColumn1[1] == BoardColumn2[1] && BoardColumn1[1] == BoardColumn3[1] && BoardColumn1[1] == BoardColumn4[1])
{
playing = false;
Winner();
}
else if (BoardColumn1[2] == BoardColumn2[2] && BoardColumn1[2] == BoardColumn3[2] && BoardColumn1[2] == BoardColumn4[2])
{
playing = false;
Winner();
}
else if (BoardColumn1[3] == BoardColumn2[3] && BoardColumn1[3] == BoardColumn3[3] && BoardColumn1[3] == BoardColumn4[3])
{
playing = false;
Winner();
}
else if (BoardColumn1[4] == BoardColumn2[4] && BoardColumn1[4] == BoardColumn3[4] && BoardColumn1[4] == BoardColumn4[4])
{
playing = false;
Winner();
}
else if (BoardColumn1[5] == BoardColumn2[5] && BoardColumn1[5] == BoardColumn3[5] && BoardColumn1[5] == BoardColumn4[5])
{
playing = false;
Winner();
}
}
static void DiagonalWin() //checks if a player won diagonally
{
if (BoardColumn1[0] == BoardColumn2[1] && BoardColumn1[0] == BoardColumn3[2] && BoardColumn1[0] == BoardColumn4[3] || BoardColumn1[1] == BoardColumn2[2] && BoardColumn1[1] == BoardColumn3[3] && BoardColumn1[1] == BoardColumn4[4] || BoardColumn1[2] == BoardColumn2[3] && BoardColumn1[2] == BoardColumn3[4] && BoardColumn1[2] == BoardColumn4[5])
{
playing = false;
Winner();
}
else if (BoardColumn1[5] == BoardColumn2[4] && BoardColumn1[5] == BoardColumn3[3] && BoardColumn1[5] == BoardColumn4[2] || BoardColumn1[4] == BoardColumn2[3] && BoardColumn1[4] == BoardColumn3[2] && BoardColumn1[4] == BoardColumn4[1] || BoardColumn1[3] == BoardColumn2[2] && BoardColumn1[3] == BoardColumn3[1] && BoardColumn1[3] == BoardColumn4[0])
{
playing = false;
Winner();
}
else if (BoardColumn2[0] == BoardColumn3[1] && BoardColumn2[0] == BoardColumn4[2] && BoardColumn2[0] == BoardColumn5[3] || BoardColumn2[1] == BoardColumn3[2] && BoardColumn2[1] == BoardColumn4[3] && BoardColumn2[1] == BoardColumn5[4] || BoardColumn2[2] == BoardColumn3[3] && BoardColumn4[2] == BoardColumn2[4] && BoardColumn2[2] == BoardColumn5[5])
{
playing = false;
Winner();
}
else if (BoardColumn2[5] == BoardColumn3[4] && BoardColumn2[5] == BoardColumn4[3] && BoardColumn2[5] == BoardColumn5[2] || BoardColumn2[4] == BoardColumn3[3] && BoardColumn2[4] == BoardColumn4[2] && BoardColumn2[4] == BoardColumn5[1] || BoardColumn2[3] == BoardColumn3[2] && BoardColumn4[3] == BoardColumn2[1] && BoardColumn2[3] == BoardColumn5[0])
{
playing = false;
Winner();
}
else if (BoardColumn3[0] == BoardColumn4[1] && BoardColumn3[0] == BoardColumn5[2] && BoardColumn3[0] == BoardColumn6[3] || BoardColumn3[1] == BoardColumn4[2] && BoardColumn3[1] == BoardColumn5[3] && BoardColumn3[1] == BoardColumn6[4] || BoardColumn3[2] == BoardColumn4[3] && BoardColumn3[2] == BoardColumn5[4] && BoardColumn3[2] == BoardColumn6[5])
{
playing = false;
Winner();
}
else if (BoardColumn3[5] == BoardColumn4[4] && BoardColumn3[5] == BoardColumn5[3] && BoardColumn3[5] == BoardColumn6[2] || BoardColumn3[4] == BoardColumn4[3] && BoardColumn3[4] == BoardColumn5[2] && BoardColumn3[4] == BoardColumn6[1] || BoardColumn3[3] == BoardColumn4[2] && BoardColumn3[3] == BoardColumn5[1] && BoardColumn3[3] == BoardColumn6[0])
{
playing = false;
Winner();
}
else if (BoardColumn4[0] == BoardColumn5[1] && BoardColumn4[0] == BoardColumn6[2] && BoardColumn4[0] == BoardColumn7[3] || BoardColumn4[1] == BoardColumn5[2] && BoardColumn4[1] == BoardColumn6[3] && BoardColumn4[1] == BoardColumn7[4] || BoardColumn4[2] == BoardColumn5[3] && BoardColumn4[2] == BoardColumn6[4] && BoardColumn4[2] == BoardColumn7[5])
{
playing = false;
Winner();
}
else if (BoardColumn4[5] == BoardColumn5[4] && BoardColumn4[5] == BoardColumn6[3] && BoardColumn4[5] == BoardColumn7[2] || BoardColumn4[4] == BoardColumn5[3] && BoardColumn4[4] == BoardColumn6[2] && BoardColumn4[4] == BoardColumn7[1] || BoardColumn4[3] == BoardColumn5[2] && BoardColumn4[3] == BoardColumn6[1] && BoardColumn4[3] == BoardColumn7[0])
{
playing = false;
Winner();
}
}
static void IsTieGame() //checks if game is tie
{
int TieCheker1 = Array.IndexOf(UserBoardColumn1, " ");
int TieCheker2 = Array.IndexOf(UserBoardColumn2, " ");
int TieCheker3 = Array.IndexOf(UserBoardColumn3, " ");
int TieCheker4 = Array.IndexOf(UserBoardColumn4, " ");
int TieCheker5 = Array.IndexOf(UserBoardColumn5, " ");
int TieCheker6 = Array.IndexOf(UserBoardColumn6, " ");
int TieCheker7 = Array.IndexOf(UserBoardColumn7, " ");
if (TieCheker1 == -1 && TieCheker2 == -1 && TieCheker3 == -1 && TieCheker4 == -1 && TieCheker5 == -1 && TieCheker6 == -1 && TieCheker7 == -1)
{
playing = false;
Tie();
}
}
static void Intro() //Intro
{
Console.WriteLine("Welcome to");
Console.WriteLine(@" ______ ______ .__ __. .__ __. _______ ______ .___________. _ _ ");
Console.WriteLine(@" / | / __ \ | \ | | | \ | | | ____| / || | | || | ");
Console.WriteLine(@"| ,----'| | | | | \| | | \| | | |__ | ,----'`---| |----` | || |_ ");
Console.WriteLine(@"| | | | | | | . ` | | . ` | | __| | | | | |__ _| ");
Console.WriteLine(@"| `----.| `--' | | |\ | | |\ | | |____ | `----. | | | | ");
Console.WriteLine(@" \______| \______/ |__| \__| |__| \__| |_______| \______| |__| |_| ");
Console.WriteLine("\nPress a Key to begin");
Console.ReadKey();
Console.Clear();
Rules();
}
static void Rules() //Rules
{
Console.WriteLine("How to Play:");
Console.WriteLine("1. Choose who plays first. Player 1 will be 'o' and Player 2 will be 'x'");
Console.WriteLine("2. Player's will alternate taking turns on putting their token in the board. You will put your token in the board by typing in the number at the top of the column you wish to put it in. ");
Console.WriteLine("3. The first player to get 4 tokens in a row wins. The four in a row can be horizontal, vertical or diagonal");
Console.WriteLine("\nPress a Key to begin");
Console.ReadKey();
}
static void Winner() //message when player wins game
{
if (turn % 2 == 0)
{
Console.WriteLine("Congrats on winning player 2");
}
else
{
Console.WriteLine("Congrats on winning player 1");
}
}
static void Tie() //message when tie game
{
Console.WriteLine("The game is a tie");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T08:24:22.930",
"Id": "507222",
"Score": "3",
"body": "Sorry I don't want to be rude but with 200+ lines `Main` function it does seem like that you haven't learned anything from the previous review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T17:55:27.833",
"Id": "507266",
"Score": "2",
"body": "Confirm that previous review is mostly applicable to this code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-06T20:09:25.480",
"Id": "256822",
"Score": "0",
"Tags": [
"c#",
"beginner",
"game",
"console",
"connect-four"
],
"Title": "C# Console, Connect 4 Game"
}
|
256822
|
<p>As an exercise in learning ARM64 assembly (aka AArch64), I wrote this function to convert 64-bit binary to hexadecimal with SIMD instructions. I'm most interested in feedback on the algorithm, instruction selection, and micro-optimizations for size or speed.</p>
<p>This was inspired by <a href="https://stackoverflow.com/a/53823757/634919">x86 SIMD implementations of this function</a> on Stack Overflow by Peter Cordes.</p>
<p>It's written for armv8-a little-endian without alignment checks, using the GNU assembler. A test driver in Unix C is included at the end.</p>
<p>I am testing and benchmarking on a Raspberry Pi 4B with 1.5 GHz Cortex A-72 CPU. Currently it can do about 1.5e8 repetitions per second, or about 10 clock cycles per rep.</p>
<p><code>u64tohex.s</code>:</p>
<pre class="lang-asm prettyprint-override"><code>// u64tohex: Convert unsigned 64-bit integer to null-terminated ASCII
// hexadecimal.
//
// C declaration: void u64tohex(char *buf, uint64_t value)
//
// Leading zeros are always included, so output is always 16
// characters plus terminating null.
//
// For AArch64 armv8-a little-endian with alignment check disabled.
.text
.global u64tohex
.balign 16
// Lookup table for use by tbl instruction. Should be all the
// hex digits in order.
// Keep this in the .text section, adjacent to u64tohex, so
// PC-relative literal load can be used to load it.
hex_table:
.ascii "0123456789abcdef"
.balign 16
u64tohex:
// x0 = buf
// x1 = value.
// Running example: suppose x1 = 0xdeadbeef12345678.
// This is for little-endian machines, so we have to do some
// sort of reversal to be able to print the most-significant
// nibble first. On the integer side we have the rev
// instruction to reverse bytes; there doesn't seem to be
// anything comparable in SIMD. So start with rev.
rev x1, x1
// Move to SIMD register. d0 is the low dword of v0.
// fmov is faster than mov v0.d[0] or dup v0.2d
fmov d0, x1
// now v0 = 00 00 00 00 00 00 00 00 de ad be ef 12 34 56 78
// Repeat each byte twice.
zip1 v0.16b, v0.16b, v0.16b
// now v0 = de de ad ad be be ef ef 12 12 34 34 56 56 78 78
// Even bytes of the output should correspond to the
// most-significant nibble of each input byte. So each even
// byte needs to be right-shifted by 4. This is done with
// ushl and a negative shift count. Odd bytes should stay
// unchanged for now, so need a shift count of 0.
// Use a 16-bit immediate move, which duplicates across all
// elements, to fill even bytes of v1 with -4 (0xfc) and odd bytes
// with 0.
movi v1.8h, #0x00fc
ushl v0.16b, v0.16b, v1.16b
// now v0 = 0d de 0a ad 0b be 0e ef 01 12 03 34 05 56 07 78
// Mask off all high nibbles. Fill all bytes of v1 with 0xf.
movi v1.16b, #0x0f
and v0.16b, v0.16b, v1.16b
// now v0 = 0d 0e 0a 0d 0b 0e 0e 0f 01 02 03 04 05 06 07 08
// Substitute each byte of v0 with the corresponding byte of
// hex_table. So 00 -> '0', 0a -> 'a' and so on.
ldr q1, hex_table
tbl v0.16b, { v1.16b }, v0.16b
// All done. Store result in buffer. Per tests, st1 is
// slightly faster than the more obvious `str q0, [x0]`.
st1 { v0.16b }, [x0]
// Append the terminating null.
strb wzr, [x0, #16]
ret
</code></pre>
<p>Here is a simple C program to exercise the function. Compile and link with <code>gcc -O3 main.c u64tohex.s</code>. I'm not particularly looking for feedback on the C code, though of course feel free to give some if you like.</p>
<p><code>main.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>// Test driver for u64tohex
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <inttypes.h>
#include <time.h>
// Randomly chosen increment, so that we can rapidly cycle through
// many different test values.
#define INC 0x1928374656473829UL
extern void u64tohex(char *buf, uint64_t val);
// Compare u64tohex with sprintf, to test for correctness
static void test(uint64_t reps) {
uint64_t v = 0;
while (reps--) {
char hex_out[] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
char sprintf_out[] = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
u64tohex(hex_out, v);
sprintf(sprintf_out, "%016" PRIx64, v);
if (strcmp(hex_out, sprintf_out) != 0) {
printf("Fail: bad %s, good %s\n", hex_out, sprintf_out);
exit(1);
}
v += INC;
}
printf("Correctness tests passed\n");
}
static void benchmark(uint64_t reps) {
printf("%" PRId64 " reps:", reps);
fflush(stdout);
struct timespec start, end;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
uint64_t v = 0;
for (uint64_t i = 0; i < reps; i++) {
char buf[100] __attribute__((aligned(16)));
u64tohex(buf, v);
v += INC;
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
double elapsed = (end.tv_sec - start.tv_sec) + 1.0e-9 * (end.tv_nsec - start.tv_nsec);
printf(" %f secs (%e reps per second)\n", elapsed, reps/elapsed);
}
int main(int argc, char *argv[]) {
test(100000);
benchmark(100000000);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T18:24:02.833",
"Id": "507177",
"Score": "0",
"body": "Have you tried doing low/high nibble separation in GPR? Something like this: https://gist.github.com/stepantubanov/1867a3662ba1098a42cf5837870c662c (not tested, may be broken). I am not sure I fully understand what `zip1` does, so may be it's not correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T19:18:04.230",
"Id": "507181",
"Score": "0",
"body": "@stepan: That's a good thought, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T19:23:55.490",
"Id": "507182",
"Score": "0",
"body": "Thinking some more, I realized that one can use `tbl` for general permutation, so that could substitute for the `rev / zip1`. That opens up some approaches for doing the whole thing in SIMD, which would be desirable if we want to convert a large array of values loaded from memory, rather than a single value from an integer register. In particular we can do the shift and masks to two 64-bit inputs at once, keeping even nibbles and odd nibbles in two different registers, and then use two two-register `tbl` instructions to sort all the correct bytes in the correct order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T19:24:49.263",
"Id": "507183",
"Score": "0",
"body": "There's some overhead to load the permutations from static memory, but if we are doing this in a big loop, it can be done just once. I might play with this and post a new version of the question for this setting. (I know to leave this one as it is.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T19:27:13.217",
"Id": "507184",
"Score": "0",
"body": "@stepan: `zip1 vA, vB, vC` takes the elements from the low halves of `vB` and `vC`, interleaves them, and puts the result in `vA`. There is a nice picture in C7.2.403 of the Architecture Reference Manual. `zip2` does the same thing but taking elements from the high halves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T22:43:44.280",
"Id": "507201",
"Score": "0",
"body": "Oh, I just found `rev64` which is the SIMD version of `rev`. I think that plus `zip` is better than `tbl`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T05:29:44.430",
"Id": "256828",
"Score": "1",
"Tags": [
"reinventing-the-wheel",
"assembly",
"number-systems",
"simd",
"arm"
],
"Title": "Binary to hex in ARM64 SIMD assembly"
}
|
256828
|
<p>I need to calculate the average value of points around a given point in a wider field.</p>
<p>For this I have a function:</p>
<pre class="lang-rust prettyprint-override"><code>fn local_average((x,y):(i32,i32),n:i32,(width,height):(i32,i32),space:&[i32]) -> i32 {
let y_range = cmp::max(y-n,0)..cmp::min(y+n+1,height);
let x_range = cmp::max(x-n,0)..cmp::min(x+n+1,width);
println!("y: {:.?}, x: {:.?}",y_range,x_range);
let size = (x_range.end-x_range.start) * (y_range.end-y_range.start);
let mut total: i32 = 0;
for yi in y_range {
for xi in x_range.clone() {
let i = yi * width + xi;
total += space[i as usize];
}
}
println!("{} / {} = {}",total,size,total / size);
total / size
}
</code></pre>
<p>The thing that bothers me here is <code>x_range.clone()</code>, I feel like this is not a good approach.</p>
<p>I could also implement this in a more function manor but I'm unsure if this is better as I find it to be less readable:</p>
<pre class="lang-rust prettyprint-override"><code>fn local_average_functional((x,y):(i32,i32),n:i32,(width,height):(i32,i32),space:&[i32]) -> i32 {
let y_range = cmp::max(y-n,0)..cmp::min(y+n+1,height);
let x_range = cmp::max(x-n,0)..cmp::min(x+n+1,width);
println!("y: {:.?}, x: {:.?}",y_range,x_range);
let size = (x_range.end-x_range.start) * (y_range.end-y_range.start);
let total: i32 = y_range.map(|yl| {
x_range.clone().map(|xl| {
let il = yl * width as i32 + xl;
space[il as usize] as i32
}).sum::<i32>()
}).sum();
println!("{} / {} = {}",total,size,total / size);
total / size
}
</code></pre>
<p>How could I improve this function?</p>
<p>Repl: <a href="https://repl.it/@JonathanWoollet/DraftyTautAdware" rel="nofollow noreferrer">https://repl.it/@JonathanWoollet/DraftyTautAdware</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T08:46:57.610",
"Id": "507124",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>We don't need an <code>x_range</code>. We need a range of proper indices over <code>space</code>, as it enables us to use <code>space[start..stop].iter().sum()</code>. We need a combination of <code>x_range</code> and <code>y_range</code>.</p>\n<p>So let's start by building one from hand:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn local_average((x, y): (i32, i32), n: i32, (width, height): (i32, i32), space: &[i32]) -> i32 {\n let y_range = cmp::max(y - n, 0)..cmp::min(y + n + 1, height);\n let x_range = cmp::max(x - n, 0)..cmp::min(x + n + 1, width);\n\n let size = (x_range.end - x_range.start) * (y_range.end - y_range.start);\n let mut total: i32 = 0;\n\n for yi in y_range {\n let start = (yi * width + x_range.start) as usize;\n let end = start + ((x_range.end - x_range.start) as usize);\n\n total += space[start..end].iter().sum::<i32>();\n }\n\n total / size\n}\n</code></pre>\n<p>Note that the code above was <strong>formatted by <code>rustfmt</code></strong>. The <code>rustfmt</code>-style is very common in Rust projects, and several projects reject contributions until they are properly formatted. For <code>cargo</code> based projects use <code>cargo fmt</code>.</p>\n<p>Either way, we now replaced the inner loop by a single <code>sum()</code>, which is more explicit about our goal. This is also a mixture of both your code styles. At this point, we might as well replace <code>x_range</code> by <code>x_size</code>, but that's a question of style.</p>\n<p>For an easier use of <code>local_average</code>, we could introduce <code>type Point = (i32, i32)</code> and <code>type Rect = (i32, i32)</code>, however, again, that's a matter of preference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T10:49:42.433",
"Id": "507131",
"Score": "0",
"body": "Maybe a little outside scope of question but in a case where `total:i32` and `space:[i8]` for example, would introducing a cast `space[start..end].iter().map(|x|*x as i32).sum::<i32>();` significantly affect performance? Would it be better to simply have `space` be a larger type for performance even if not needed for the data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T11:27:01.150",
"Id": "507133",
"Score": "0",
"body": "@JonathanWoollett-light It's probably [slightly slower as the numbers get unpacked first](https://godbolt.org/z/scf613). However, I cannot give you any estimate how much slower this is going to be, sorry."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T09:47:07.610",
"Id": "256833",
"ParentId": "256832",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "256833",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T08:31:45.073",
"Id": "256832",
"Score": "6",
"Tags": [
"rust"
],
"Title": "Calculating average value of points around given point in a wider field"
}
|
256832
|
<p>I made a simple JavaFX app. It is just a Pomodoro timer, it works as expected.</p>
<p>The Pomodoro study pattern is a technique where you study for 25 minutes and take a 5-minute break and after 4 periods of this, you get a longer 15-minute break (and then repeat the whole thing). I made a simple countdown timer that keeps track of which study session you are on.</p>
<p><a href="https://i.stack.imgur.com/5z7Uw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5z7Uw.png" alt="Here is what the view looks like" /></a></p>
<p>I am just wondering if I implemented the MVC pattern correctly. The Main class seems a bit redundant to me. Are there any other improvements I could make to the code?</p>
<p>Thanks</p>
<pre><code>public class Controller {
public Controller(Model model, View view) {
view.getStartPauseBtn().setOnAction((e) -> {
if (model.isRunning()) {
model.pauseTimer();
model.setRunning(false);
} else {
model.startTimer();
model.setRunning(true);
}
});
}
}
</code></pre>
<pre><code>import javafx.application.Platform;
import javafx.scene.control.Label;
import java.util.Timer;
import java.util.TimerTask;
public class Model {
private boolean isRunning = false;
private boolean isBreak = false;
private Timer timer = new Timer();
private int counter = 60 * 25; // 60 * 25 Testing:10
private final Label timerLbl, studySessionLbl, whatsNextLbl;
private int seconds, minutes, studySessionNum =0;
public Model(Label timerLbl, Label studySessionLbl, Label whatsNextLbl) {
this.timerLbl = timerLbl;
this.studySessionLbl = studySessionLbl;
this. whatsNextLbl = whatsNextLbl;
}
public boolean isRunning() {
return isRunning;
}
public void setRunning(boolean running) {
isRunning = running;
}
public void pauseTimer() {
timer.cancel();
}
public void startTimer() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
Platform.runLater(() -> {
counter--;
seconds = counter % 60;
minutes = counter / 60;
if (seconds < 10 && minutes < 10) {
timerLbl.setText("0" + minutes + ":0" + seconds);
} else if (minutes < 10) {
timerLbl.setText("0" + minutes + ":" + seconds);
} else {
timerLbl.setText(minutes + ":" + seconds);
}
if (counter == 0 && studySessionNum == 4 && !isBreak) { // long break
isBreak = true;
counter = 15 * 60; // 15 * 60 Testing: 5
studySessionNum = 0;
} else if (counter == 0 && !isBreak) { // short break
counter = 5 * 60; // 5 * 60 Testing: 2
isBreak = true;
} else if (counter == 0) { // break finished
counter = 25 * 60; // 25 * 60 Testing: 10
studySessionNum++;
isBreak = false;
}
// update labels
studySessionLbl.setText("Study session number: " + studySessionNum);
if (isBreak) {
whatsNextLbl.setText("Next: Study session (25 minutes)");
} else if (studySessionNum == 4) {
whatsNextLbl.setText("Next: Long study break (15 minutes)");
} else {
whatsNextLbl.setText("Next: Short study break (5 minutes)");
}
});
}
}, 0, 1000);
}
}
</code></pre>
<pre><code>Main class:
import javafx.application.Application;
import javafx.stage.Stage;
public class Pomodoro extends Application {
@Override
public void start(Stage stage) {
View view = new View();
Model model = new Model(view.getTimerLbl(), view.getStudySessionNumLbl(), view.getWhatsNextLbL());
new Controller(model, view);
stage.setTitle("Pomodoro Timer");
stage.setScene(view.getScene());
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p>I did not use a fxml file for the view.</p>
<pre><code>import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
public class View {
private final Label studySessionNumLbl, whatsNextLbL, timerLbl;
private final Button startPauseBtn;
private final Scene scene;
// UI Setup
public View() {
studySessionNumLbl = new Label();
whatsNextLbL = new Label();
HBox hbox = new HBox(studySessionNumLbl, whatsNextLbL);
hbox.setAlignment(Pos.CENTER);
hbox.setSpacing(10);
timerLbl = new Label("25:00");
timerLbl.setFont(Font.font("Verdana", FontWeight.BOLD, 70));
startPauseBtn = new Button("> ||");
VBox vbox = new VBox(timerLbl, startPauseBtn, hbox);
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(20);
scene = new Scene(vbox, 400, 400);
}
public Scene getScene() {
return scene;
}
public Label getStudySessionNumLbl() {
return studySessionNumLbl;
}
public Label getWhatsNextLbL() {
return whatsNextLbL;
}
public Button getStartPauseBtn() {
return startPauseBtn;
}
public Label getTimerLbl() {
return timerLbl;
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T13:24:36.807",
"Id": "256836",
"Score": "3",
"Tags": [
"mvc",
"javafx"
],
"Title": "Pomodoro JavaFX (MVC Pattern) Countdown Timer"
}
|
256836
|
<pre><code>#include <iostream>
#include <cstring>
using namespace std;
int main() {
system("chcp 1251>nul");
int i = 1;
int x;
cin >> x;
if (abs(x) >= 1) { cout << "The series is divergent"; }
else {
double eps = 0.000001;
double sum = 0;
double lastElementOfSequence=1;
do {
sum += lastElementOfSequence;
lastElementOfSequence *= -1 * x * (2 * i + 3) / (2 * i);
i++;
} while (fabs(lastElementOfSequence) > eps);
cout.precision(17);
cout << "sum=" << sum << endl;
}
system("pause>nul");
return 0;
}
</code></pre>
<p><span class="math-container">$$S=(1+x)^{-\frac{5}{2}}=1-\frac{5}{2}x+\frac{5\cdot7}{2\cdot4}x^2-\frac{5\cdot7\cdot9}{2\cdot4\cdot6}x^3+\frac{5\cdot7\cdot9\cdot11}{2\cdot4\cdot6\cdot8}x^4$$</span>
<span class="math-container">$$where\ |x|<1$$</span></p>
<p>The task in the image, and the code from above I will ask to check up whether the correctly solved task I will be grateful, but if an error that specify please or correct.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:00:29.697",
"Id": "507154",
"Score": "0",
"body": "Better use `std::numeric_limits<double>::epsilon` instead of `eps`. And of course, don't use `using namespace std;` it's a bad habit, because it can lead to a conflict of names, use `std::<something>` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:09:22.993",
"Id": "507155",
"Score": "0",
"body": "@Bogdasar But the question of whether the solution of the problem is correct, I will correct the rest"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:21:25.743",
"Id": "507156",
"Score": "0",
"body": "@Bogdasar, I think the `eps` is the \"given accuracy\" of the title, so `std::numeric_limits<double>::epsilon` would be the wrong choice here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:23:06.687",
"Id": "507157",
"Score": "0",
"body": "@TobySpeight yes you are right"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T20:08:13.007",
"Id": "507185",
"Score": "0",
"body": "This part: `-1 * x * (2 * i + 3) / (2 * i)` is fully integer calculation. Does not seem like it was intended to be integer. To resolve this you can do either 1) add `double` conversion somewhere appropriate, e.g. `-1 * x * double(2 * i + 3) / (2 * i)` 2) change type of `i` to double (note: double can represent ~53 bits of whole numbers exactly, so no precision will be lost on increments). Edit: Also your formula says abs(x) should be less than one, but you enter `x` as integer. The only integer value, which `abs` is less than 1 is 0. Did you mean to use fractional number for `x`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T20:13:48.290",
"Id": "507186",
"Score": "0",
"body": "`x` needs to be declared a double as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T07:27:15.810",
"Id": "507214",
"Score": "0",
"body": "@stepan, @1201, those both look to be (partial) reviews. But don't worry - I address the misuse of `int` there in my review."
}
] |
[
{
"body": "<p>We're including the wrong headers. We don't need <code><cstring></code>, but we do need <code><cmath></code> (for <code>std::fabs</code>).</p>\n<p>Don't do this:</p>\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>That might not be so harmful in small programs, but it's a bad habit have because it makes larger programs more difficult to follow, and it increases the risk of identifier collisions, especially as the standard library continues to grow.</p>\n<p>Never ignore the return value from <code>std::system()</code>. There are two uses of this function, and both of them are going to fail here, since I don't have either of the programs installed. Is it right that they both create a file called <code>nul</code>? Or did you just misspell <code>/dev/null</code>?</p>\n<p>Never ignore the return value from stream-reading operations. <code>std::cin >> x</code> leaves <code>x</code> uninitialised (before C++11) or zero (C++11 onwards) if it can't perform the conversion.</p>\n<p>I don't think you wanted an integer as <code>x</code> anyway - shouldn't it be <code>double</code>?</p>\n<p>Error messages should go to <code>std::cerr</code>, not <code>std::cout</code>.</p>\n<p>Instead of multiplying <code>i</code> by 2 all the time, consider incrementing <code>i</code> in steps of 2.</p>\n<p>The addition is being done in the wrong order. When adding floating-point numbers, we want to accumulate the <em>smallest</em> values first, so as not to lose precision.</p>\n<p>Instead of using the <code>precision()</code> function of a stream, consider using <code><iomanip></code>. 17 decimal digits of precision seems too large, given that the value of <code>eps</code> means we won't achieve 6 digits.</p>\n<p>Don't use <code>std::endl</code> except when you genuinely need to flush the stream. That unnecessarily slows programs down.</p>\n<hr />\n<p>Here's a version that's modified to fix the above problems:</p>\n<pre><code>#include <cmath>\n#include <limits>\n#include <iomanip>\n#include <iostream>\n#include <numeric>\n#include <vector>\n\n// FIXME - make this a parameter\nconstexpr double precision = 0.000'001;\n\nint main()\n{\n double x;\n std::cin >> x;\n if (!std::cin) {\n std::cerr << "Invalid input\\n";\n return 1;\n }\n\n if (std::fabs(x) >= 1) {\n std::cerr << "The series is divergent above |x|=1\\n";\n return 1;\n }\n\n std::vector<double> terms;\n double term = 1;\n for (auto i = 2ul; std::fabs(term) >= precision; i += 2) {\n terms.push_back(term);\n term *= -x * (i + 3) / i;\n if (i > std::numeric_limits<decltype(i)>::max() - 2) {\n // overflow\n break;\n }\n }\n // add smallest terms first\n auto sum = std::accumulate(terms.crbegin(), terms.crend(), 0.0);\n\n std::cout << std::setprecision(7) << "sum=" << sum << '\\n';\n}\n</code></pre>\n<hr />\n<p>As suggested by <a href=\"/users/93149\">greybeard</a> in comments, the way the function converges means we can get a good estimate of the rest of the series by halving the last term that we consider, and we can terminate when the sum of two consecutive elements is within our precision value:</p>\n<pre><code>std::vector<double> terms;\ndouble term = 1;\nstd::size_t i = 2;\ndo {\n terms.push_back(term);\n term *= -x * (i + 3) / i;\n i += 2;\n} while (std::abs(term + terms.back()) >= precision);\n\n// term/2 is a good approximation to the rest of the series\nterms.push_back(term / 2);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:25:12.973",
"Id": "507158",
"Score": "0",
"body": "Yes, but I meant either the right idea or the right solution (calculate the sum of the series) and if something is wrong, you could not correct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:30:35.203",
"Id": "507159",
"Score": "0",
"body": "You posted on Code Review. That means that [any aspect of the code posted is fair game for feedback and criticism](/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:34:02.237",
"Id": "507161",
"Score": "0",
"body": "I'm sorry I didn't know, I'm guilty of not correctly specifying the sign for which a review is required"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T00:20:40.660",
"Id": "507204",
"Score": "1",
"body": "(*all non-2 prime factors of the denominator appear at least as often in the numerator*: can this be used to improve accuracy? How?) With x close to one, convergence will be slow: is `int i` safe?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T07:28:46.623",
"Id": "507215",
"Score": "0",
"body": "Nothing to do with sequence points, there, @greybeard - the relevant term is _associativity_ . `*` and `/` have the same precedence and associate to the left, so the promotions do happen in the correct order. Could possibly split into `term /= -i; term *= i + 3;` for inexperienced readers, but I think that harms comprehension for more seasoned C++ programmers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T15:41:12.473",
"Id": "507257",
"Score": "1",
"body": "(While summing up terms in increasing abs value is better than the reverse, I'm afraid it [isn't guaranteed to help with *loads* of similar values](https://en.m.wikipedia.org/wiki/Kahan_summation_algorithm#Further_enhancements). It *is* safe with alternating values as given here.) Oh, and I guess the *sign* [Andrij Matviiv referred to](https://codereview.stackexchange.com/questions/256838/calculate-the-sum-of-a-series-with-a-given-accuracy/256841?noredirect=1#comment507161_256841) is that of the exponent in \\$(1+x)^{-\\frac 5 2}\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:50:18.733",
"Id": "507291",
"Score": "0",
"body": "@greybeard, I've updated with your suggestion to end with `term/2`, and terminate when terms have similar absolute values. And thanks for explaining Andrij's \"sign\"; I'd been struggling to parse that comment, and also confused the expansion wasn't as I dimly remembered from schooldays. It makes more sense now!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T15:20:14.610",
"Id": "256841",
"ParentId": "256838",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T14:12:11.747",
"Id": "256838",
"Score": "1",
"Tags": [
"c++",
"algorithm"
],
"Title": "Calculate the sum of a series with a given accuracy"
}
|
256838
|
<p>I am new to asynchronous programming in python. Below are two scripts(which perform the same operation) one in Fastapi + aiohttp while other is basic Flask + requests library:</p>
<pre><code>## Flask
def fetch1(url):
x = requests.get(url) # First hit to the url
data = x.json() # Grab response
return fetch2(data['uuid']) # Pass uuid to the second function for post request
def fetch2(id):
url2 = "http://httpbin.org/post"
params = {'id': id}
x = requests.post(url2, json=params)
return x.json()
@app.route('/')
def main():
url = 'http://httpbin.org/uuid'
data = fetch1(url)
return {"message":"done"}
</code></pre>
<p>and the <strong>fastapi</strong> couterpart:</p>
<pre><code>async def fetch1(session, url):
async with session.get(url) as resp:
data = await resp.json()
return await fetch2(session, data['uuid'])
async def fetch2(session, id):
url2 = "http://httpbin.org/post"
params = {'id': id}
async with session.post(url2, json=params) as resp:
return await resp.json()
@app.get("/")
async def main():
url = 'http://httpbin.org/uuid'
async with aiohttp.ClientSession() as session:
data = await fetch1(session, url)
return {"message":"done"}
</code></pre>
<p>As a sample benchmark testing (Using Apache Bench), I had fired 500 requests at 100 concurrency, while Flask took 7 seconds(approx) to complete the operation fastapi takes 4.5 to do the same(which is not that great).Is my async code blocking in nature or Am I missing something.Any help will be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T06:20:06.913",
"Id": "507211",
"Score": "0",
"body": "There are too many `async` and `await` keywords when not needed. Try to reduce them and it will work properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T05:48:15.820",
"Id": "507416",
"Score": "0",
"body": "@Vishnudev ,what changes would you suggest in the above code?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T14:25:45.983",
"Id": "256839",
"Score": "0",
"Tags": [
"python",
"asynchronous",
"async-await",
"flask"
],
"Title": "Fastapi with Aiohttp not providing expected results"
}
|
256839
|
<p>I have a class <code>Tcp_Server</code> that implements a TCP server. This is the base class for the other types of servers available in my program. For example <code>Tcp_Chat_Server</code>. <code>Packet</code> is a struct that we send/receive.</p>
<p>Here's the implementation:</p>
<p><code>packet.hpp</code></p>
<pre><code>#ifndef PACKET
#define PACKET
#define MAX_NAME_LEN 24
#include <stdio.h>
struct Packet
{
Packet();
~Packet();
char name[MAX_NAME_LEN];
char buf[BUFSIZ];
};
#endif
</code></pre>
<p><code>packet.cpp</code></p>
<pre><code>#include "packet.hpp"
Packet::Packet() {};
Packet::~Packet() {};
</code></pre>
<p><code>tcp_server.hpp</code></p>
<pre><code>#ifndef TCP_SERVER
#define TCP_SERVER
#include <netinet/in.h>
#include <sys/select.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
struct server_info
{
char ip_str[INET_ADDRSTRLEN] = {'\0'};
int port;
};
class Tcp_Server
{
public:
Tcp_Server(int port); // Initializer
~Tcp_Server(); // Destructor
/***
* select(), blocking method
* Return 0 if it's a listening socket.
* Return 1 if it's a usual socket.
*/
int WaitingForActions();
int NewConnectionHandler(); // If new client. Return socket number.
virtual int NewMessageHandler() = 0;// This method shouldn't be implement, look at the inheritance classes.
struct server_info GetServerInfo(); // Fill and return server_info structure.
int GetCurrentFds();
protected:
int listen_socket; // Listening socket
struct sockaddr_in serv_addr; // Structure with information about socket (adress, port etc.)
struct server_info server_info; // Information about server in readable form, returned by function.
fd_set connections; // Set of clients
int max_socket; // Number of maximum existing descriptor
int current_socket; // Number of the processed descriptor
};
#endif
</code></pre>
<p><code>tcp_server.cpp</code></p>
<pre><code>#include "tcp_server.hpp"
Tcp_Server::Tcp_Server(int port)
{
int param = 1; // Parametr for setsockopt(), maybe we can change it to bool.
char ip_str[INET_ADDRSTRLEN] = {'\0'};
if((listen_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
throw "Can't create a socket!\n";
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
if(setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR, &param, sizeof(param)) < 0)
{
throw "setsockopt() error!\n";
}
if(bind(listen_socket, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
throw "bind() error!\n";
}
listen(listen_socket, 5);
FD_ZERO(&connections);
FD_SET(listen_socket, &connections);
max_socket = listen_socket;
}
Tcp_Server::~Tcp_Server()
{
for(int i = 0; i <= max_socket; i++)
{
if(i == listen_socket)
{
shutdown(i, SHUT_RDWR);
close(i);
FD_CLR(i, &connections);
}
if(FD_ISSET(i, &connections))
{
shutdown(i, SHUT_RDWR);
close(i);
FD_CLR(i, &connections);
}
}
}
int Tcp_Server::WaitingForActions()
{
fd_set tmp_set = connections;
if(select(max_socket + 1, &tmp_set, NULL, NULL, NULL) < 0)
{
throw "error in select \n";
fprintf(stderr, "error in select \n");
}
for(int i = 0; i <= max_socket; i++)
{
if(FD_ISSET(i, &tmp_set))
{
current_socket = i;
if(i == listen_socket) // Если запрос к слушающему сокету
{
return 0;
}
else
{
return 1;
}
}
}
return -1;
};
int Tcp_Server::NewConnectionHandler()
{
int new_sock = accept(listen_socket, NULL, NULL);
if(new_sock < 0)
{
throw "accept() error\n";
}
else
{
FD_SET(new_sock, &connections);
if(new_sock > max_socket)
{
max_socket = new_sock;
}
}
return new_sock;
}
struct server_info Tcp_Server::GetServerInfo()
{
memset(&server_info, 0, sizeof(server_info));
inet_ntop(AF_INET, &(serv_addr.sin_addr), server_info.ip_str, INET_ADDRSTRLEN);
server_info.port = ntohs(serv_addr.sin_port);
return server_info;
}
int Tcp_Server::GetCurrentFds()
{
return current_socket;
}
</code></pre>
<p><code>tcp_chat_server.hpp</code></p>
<pre><code>#ifndef TCP_CHAT_SERVER
#define TCP_CHAT_SERVER
#include "tcp_server.hpp"
#include "packet.hpp"
class Tcp_Chat_Server : public Tcp_Server
{
public:
Tcp_Chat_Server(int port);
virtual int NewMessageHandler();
};
#endif
</code></pre>
<p><code>tcp_chat_server.cpp</code></p>
<pre><code>#include "tcp_chat_server.hpp"
Tcp_Chat_Server::Tcp_Chat_Server(int port) : Tcp_Server(port) {};
int Tcp_Chat_Server::NewMessageHandler()
{
Packet packet;
int bytes = recv(current_socket, &packet, sizeof(packet), 0);
if(bytes <= 0)
{
close(current_socket);
FD_CLR(current_socket, &connections);
return bytes;
}
else
{
for(int i = 0; i <= max_socket; i++)
{
if(i == current_socket || i == listen_socket)
{
continue;
}
if(FD_ISSET(i, &connections))
{
if((send(i, &packet, sizeof(packet), 0)) <= 0)
{
return -1;
}
}
}
fprintf(stdout, "%s : %s", packet.name, packet.buf);
memset(&packet, '\0', sizeof(packet));
}
return bytes;
}
</code></pre>
<p>So, first of all, I would like to hear about:</p>
<ol>
<li>Class interfaces;</li>
<li>Hierarchy of classes;</li>
<li>All about <code>virtual</code> things;</li>
<li>New nuances of the network and data transmission over it.</li>
<li>Supportability of this architecture;</li>
</ol>
<p>Next, and less important:</p>
<ol>
<li>STL and other libraries</li>
<li>naming</li>
</ol>
<p>And last, this class is the part of application for instant messaging. At the moment, code is in private repo. It will be interesting to hear your thoughts on how best to design such applications, particularly the process of send/receive messages.</p>
|
[] |
[
{
"body": "<p>There are a lot of things to discuss here, so I'll just go from line to line and explain all the issues I see:</p>\n<code>#define MAX_NAME_LEN 24</code>\n<p>You really shouldn't be using macros in C++ unless it's necessary. They pollute global namespace and have no type safety. Consider <code>constexpr std::size_t MAX_NAME_LEN</code>instead.</p>\n<code>#include <stdio.h></code>\n<p>Including C headers is deprecated and they might not even exist depending on the implementation. Use <code><cstdio></code> instead.</p>\n<code>Packet()</code>\n<p>Unnecessary constructor (and destructor). If you define it in the header and give it an empty body in the source file, this means that it will still be called like any function, even though it does nothing. These calls won't be optimized away without link-time optimization. Follow either the rule of zero or rule of five.</p>\n<code>char buf[BUFSIZ];</code>\n<p>Buffer with implementation-defined size. Each packet will be quite large if you do this, probably 4096 or 8192 bytes. If you really want such a large size, at least use your own instead of making use of a macro from libc.</p>\n<code>packet.cpp</code>\n<p>This file is not needed once you remove the unnecessary constructor and destructor. You might just want to delete it. Your <code>Packet</code> can be designed as a header-only utility.</p>\n<code>~Tcp_Server();</code>\n<p>Non-virtual destructor in a virtual class. Your compiler should have probably given you a warning about this already with proper warnings enabled. The problem here is that destroying <code>Tcp_Server</code> will not call the destructor of its derived classes, leading to potential memory leaks. Mark it <code>virtual</code></p>\n<code>virtual int NewMessageHandler() = 0;</code>\n<p>It might not be worth making your entire <code>Tcp_Server</code> abstract if the only <code>virtual</code> thing about it is the message handling. Consider using a <code>std::function</code> or a function-pointer callback for message handling which is passed into the class after initialization. This would likely eliminate a lot of boilerplate and would also mean that your server no longer needs to be a virtual class.</p>\n<code>throw "error in select \\n";</code>\n<p>Some people would argue that you should never just throw strings but use the <code>std::exception</code> class hierarchy. Also, why are you throwing in a class that already uses an <code>int</code> result code? Seems like redundant error handling.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T16:03:17.047",
"Id": "507259",
"Score": "0",
"body": "The advice is correct. Use `<cstdio>` not sure the reasoning is true `C headers is deprecated`. The difference is that the C version puts everything in the global namespace (and optionally in the std namespace). While the C++ headers puts everything in the std namespace (and optionally in the global namespace)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T16:11:54.017",
"Id": "507260",
"Score": "0",
"body": "Error codes are great for tracking issues inside your components. But error codes should not be allowed to cross interface boundaries (because people forget to check). Exceptions are great for passing issues that can not be handled locally. If you need to consider the issue in relation to a broader context exceptions are a better choice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T17:40:39.683",
"Id": "507265",
"Score": "0",
"body": "When changing macros to properly typed constants, we should also change the names, too, so we retain attention on the real macros that still need careful handling."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T10:08:15.447",
"Id": "256867",
"ParentId": "256840",
"Score": "3"
}
},
{
"body": "<p>Everything Jan Schultke said:</p>\n<h2>Design</h2>\n<p>I don't see a <code>run()</code> like method. So the user needs to implement that. Is it supposed to look like this:</p>\n<pre><code>void run(Tcp_Server& server)\n{\n while(!finished) {\n int action = server.WaitingForActions();\n if (action == 0) {\n int socket = server.NewConnectionHandler()\n }\n else if (action == 1) {\n int byteCount = server.NewMessageHandler()\n }\n else {\n // error\n }\n }\n}\n</code></pre>\n<p>Which leads to a lot of questions.</p>\n<ol>\n<li>Is this the expected pattern to handle it?</li>\n<li>What am I supposed to do with the values returned from these two methods?</li>\n</ol>\n<ul>\n<li>The <code>NewConnectionHandler()</code> already handles the socket stuff.</li>\n<li>The <code>NewMessageHandler()</code> is virtual so why do I need to write <code>run()</code> and this?</li>\n</ul>\n<ol start=\"3\">\n<li>Why is your <code>NewMessageHandler()</code> fiddling with members of the <code>Tcp_Server</code>?</li>\n</ol>\n<ul>\n<li>Seems like a bad design if you need accesses to the internal members.</li>\n</ul>\n<hr />\n<p>Your code should implement that run method and call the <code>NewMessageHandler()</code> when appropriate passing only the socket that needs to be read from to the handler.</p>\n<hr />\n<p>Why is this being done on a single thread? Basically when you get a connection now your server blocks all other potential connection attempts while it handles the current message on <code>NewMessageHandler()</code>. This means there is no point using <code>select()</code>. You may as well simply block on <code>accept()</code>, handle the resulting request, then go back to block on accept.</p>\n<p>To do this better:</p>\n<ol>\n<li><p>You have a main thread running your version of <code>main()</code>.</p>\n</li>\n<li><p>When the main thread receives a connect or input on any connection it adds a work item to a work queue to be handled separately, and immediately goes back to waiting on <code>select()</code>. Your main thread should do as little work as possible processing data from a connection.</p>\n</li>\n<li><p>You should have a thread pool. All the threads in the pool should be watching the work queue. If a new item is added to the work queue then they start processing.</p>\n</li>\n<li><p>If the worker finishes all work on the socket then it closes and goes back to the work queue.</p>\n</li>\n<li><p>If the worker would block reading or writing to the socket then you put the worker gives the socket back to the main thread so it can wait on the <code>select()</code> and be handled when the socket is ready and the thread goes back to the pool to wait for another piece of work (note: implies state is associated with socket so when you are ready to resume you will need to retrieve the state to continue).</p>\n</li>\n</ol>\n<hr />\n<p>I would design my interface more like this:</p>\n<pre><code>class Tcp_Server\n{\npublic:\n Tcp_Server(int port, ThreadPool workers, WorkQueue queue); \n virtual ~Tcp_Server(); \n void run();\nprivate:\n\n // This function will be called by a worker\n // as defined by the ThreadPool (The thread pool may be empty which\n // means it is called by the main thread).\n //\n // return true to add back to FD_SET to continue listening.\n // return false to indicate connection was closed.\n // Exception: Error on stream. TCP_Server will shut manually close\n // the connection (any errors will be discarded).\n // exception will be logged.\n virtual bool NewMessageHandler(int socket) = 0; // Pass socket\n};\n\nclass ChatServer: public Tcp_Server {\n // Allow the handler to store some state about the connection.\n // Subsequent calls can use this information to continue\n // processing from the last know position (either read or write).\n std::map<int, void*> socketData;\n\n // Handler for Chat protocol.\n // Handler should return on closed connection or a potentially blocking\n // read/write.\n virtual bool NewMessageHandler(int socket); // continue handling data.\n};\n\nint main() {\n WorkQueue workItems;\n ThreadPool workers(5, workItems); // workers read from workItems.\n ChatServer server(45, workers, workItems); // server writes to work Items.\n\n server.run();\n}\n</code></pre>\n<h2>Code Review</h2>\n<p>You don't use a namespace.</p>\n<p>Add a namespace around your code.</p>\n<hr />\n<p>See advice by: Jan Schultke</p>\n<pre><code>#define MAX_NAME_LEN 24\n</code></pre>\n<hr />\n<p>See advice by: Jan Schultke</p>\n<pre><code>#include <stdio.h>\n</code></pre>\n<hr />\n<p>Don't need constructor/destructor here (they don't do anything). Also this object uses arrays so it is not movable. Not sure how you want to use it. But it may be worth using <code>std::vector<></code> here and allow the object to be simply moved around your application.</p>\n<pre><code>struct Packet\n{\n Packet();\n ~Packet();\n char name[MAX_NAME_LEN];\n char buf[BUFSIZ];\n};\n</code></pre>\n<hr />\n<p>These include guards are short. And potentially not unique.</p>\n<pre><code>#ifndef TCP_SERVER\n#define TCP_SERVER\n</code></pre>\n<p>I would add the namespace to the macro guard to make sure that they are unique.</p>\n<hr />\n<p>I understand the need for these.</p>\n<pre><code>#include <netinet/in.h>\n#include <sys/select.h>\n#include <arpa/inet.h>\n#include <unistd.h>\n</code></pre>\n<p>But these are C libraries.</p>\n<pre><code>#include <string.h>\n#include <stdio.h>\n</code></pre>\n<p>What are you using them for? Why not use C++ facilities? The C++ <code>std::string</code> class is great (and less error prone to use). The C++ input/output facilities are less error prone (though I believe the C compiler makes this less of a problem nowadays). But you are in C++ so use the C++ <code>std::cout</code>, <code>std::clog</code> and/or <code>std::cerr</code>.</p>\n<hr />\n<p>Don't write useless comments.</p>\n<pre><code> Tcp_Server(int port); // Initializer\n ~Tcp_Server(); // Destructor\n</code></pre>\n<p>I can see what they are.</p>\n<hr />\n<p>Using integer here is a bad policy.</p>\n<pre><code> /***\n * select(), blocking method\n * Return 0 if it's a listening socket.\n * Return 1 if it's a usual socket.\n */\n int WaitingForActions(); \n</code></pre>\n<p>Create an <code>enum</code> and be specific about it. Using the enum allows you to write better self documenting code.</p>\n<hr />\n<p><code>protected</code> was a mistake in the language design. Don't use it. If you must use it, make sure there are only methods in this section to prevent abuse by your derived types. The variables should always be private.</p>\n<p>Don't make things available through <code>protected</code> if you don't need to. You should tightly control this to only things that are necessary.</p>\n<pre><code>protected:\n int listen_socket; // Listening socket\n struct sockaddr_in serv_addr; // Structure with information about socket (adress, port etc.)\n struct server_info server_info; // Information about server in readable form, returned by function.\n fd_set connections; // Set of clients\n int max_socket; // Number of maximum existing descriptor\n int current_socket; // Number of the processed descriptor\n};\n</code></pre>\n<hr />\n<p>Might be worth including more information in these exceptions.</p>\n<pre><code> throw "Can't create a socket!\\n";\n throw "setsockopt() error!\\n";\n throw "bind() error!\\n";\n</code></pre>\n<p>The user is going to have a hard time correcting the errors from these statements. Add the error number and the specific error message generated. This may lead you to derive an exception class (only do this if the exception allows you to fix the error. Otherwise use a generic exception class).</p>\n<hr />\n<p>That print is never reached:</p>\n<pre><code> throw "error in select \\n"; \n fprintf(stderr, "error in select \\n");\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T17:27:13.900",
"Id": "256884",
"ParentId": "256840",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256884",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T14:51:16.843",
"Id": "256840",
"Score": "4",
"Tags": [
"c++",
"linux",
"socket",
"posix"
],
"Title": "C++ TcpServer class"
}
|
256840
|
<p>I am trying to improve my Java skill, so I wrote a simple ATM program.</p>
<p>I would like a review, to help me make the code more effective.</p>
<h3>Main</h3>
<pre><code>public static void main(String[] args) {
ATM a = new ATM("A", "S", 20000);
Scanner in = new Scanner(System.in);
while(true){
System.out.println("Please choose: " + "\n" +
"1. Deposit" + "\n" + "2. Withdraw" + "\n" + "3. Info" + "\n" + "4. Exit");
int option = in.nextInt();
switch (option) {
case 1:
System.out.println("How much would you like to Deposit?");
double depositValue = in.nextDouble();
a.deposit(depositValue);
System.out.println("Your current balance is : " + a.getBalance() + "\n") ;
break;
case 2:
System.out.println("How much would you like to Withdraw?");
double withdrawValue = in.nextDouble();
a.withdraw(withdrawValue);
break;
case 3:
System.out.println(a.toString() + "\n" );
break;
case 4:
System.exit(0);
}
}
}
</code></pre>
<h3>ATM</h3>
<pre><code>private String name;
private String lastName;
private double balance;
public ATM(String name, String lastName, double balance) {
this.balance = balance;
this.lastName = lastName;
this.name = name;
}
public String getName(){
return this.name;
}
public String getLastName(){
return this.lastName;
}
public double getBalance(){
return this.balance;
}
public void setBalance(int newValue){
this.balance = newValue;
}
public void deposit(double value){
balance += value;
}
public void withdraw(double value){
if(value > balance){
System.out.println("You can't withdraw that amount of money." +"\n"+ "Your balance is: " + getBalance() + "\n");
} else {
balance -= value;
System.out.println("You withdraw " + value +"from your account!" + "\n");
}
}
public String toString(){
return "First name: " + getName() +"\n" + "Last name: " + getLastName() + "\n" + "Your balance: " +getBalance();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T17:13:52.933",
"Id": "507171",
"Score": "2",
"body": "Are you missing one or more `import` statements? You'll probably get better reviews if you post the *complete* code of the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T20:48:54.560",
"Id": "507188",
"Score": "1",
"body": "What exactly do you mean by *\"more effective\"*?"
}
] |
[
{
"body": "<p>This is fairly good for a program in this category for being well formatted and having variable names that mostly make sense. I.e. I have no trouble figuring out what the code tries to do.</p>\n<pre><code>ATM a = new ATM("A", "S", 20000);\n</code></pre>\n<p>Here you create an ATM with a name and balance. If you think about what an ATM does, this does not reflect real life. ATM's have a balance as in how much money they contain but they do not have a first and last name. You may have been thinking of a <code>BankAccount</code> when implementing the code. This is supported by the code not having a step where the user tells the machine who they are and what account to access. But then again, bank accounts are identified by account number, not by the account owner name.</p>\n<pre><code>System.out.println("Please choose: " + "\\n" +\n "1. Deposit" + "\\n" + "2. Withdraw" + "\\n" + "3. Info" + "\\n" + "4. Exit");\n</code></pre>\n<p>This is just hard to read and maintain. In these situations I prefer reflecting the end result in the formatting so that the intended output is more clear.</p>\n<pre><code>System.out.println("Please choose:\\n" +\n "1. Deposit\\n" +\n "2. Withdraw\\n" +\n "3. Info\\n" +\n "4. Exit");\n</code></pre>\n<p>Now it is also instantly clear to the code maintainer what the valid input options are.</p>\n<pre><code>int option = in.nextInt();\n</code></pre>\n<p>Because you have not written any error handling, your program will show an ugly error message to the user and it will immediately exit if they make a wrong choice, such as enterin a letter instead of a number.</p>\n<pre><code>switch (option) {\n ....\n</code></pre>\n<p>Switch statements should always have a default-case. This is especially important as you are handling user input.</p>\n<pre><code> default:\n System.err.println("Invalid input " + option + ". Please choose a value between 1 and 4.");\n break;\n</code></pre>\n<p>This also holds true if the swich handles an enumeration and you have handled all the cases because a change to the enumeration might add a new value and your code would then be unable to handle it. In such cases the default case should throw an IllegalArgumentException with a message describing the problem.</p>\n<pre><code>case 4:\n System.exit(0);\n</code></pre>\n<p>It is pretty much never Ok to exit from a Java program using System.exit(int). It's akin to pulling the power cord from the computer to exit. It exits your program but also takes out everything else that might have been running in the JVM. In this case the correct choice would be to set the loop condition in the while-loop to false.</p>\n<pre><code>boolean exitRequested = false;\nwhile (! exitRequested) {\n ...\n switch (option) {\n ...\n case 4:\n exitRequested = true;\n break;\n }\n}\n</code></pre>\n<p>Now that you have a variable controlling the exit, you can use it to search for the code that makes the program exit. This is a useful feature when the programs that you work with are larger.</p>\n<pre><code>public ATM(String name, String lastName, double balance) {\n</code></pre>\n<p><a href=\"https://husobee.github.io/money/float/2016/09/23/never-use-floats-for-currency.html\" rel=\"noreferrer\">Money should never be handled using floating point numbers</a>. Use either integers and divide the result with 100 to obtain euros and cents or use BigDecimal. For classroom code we can let it pass, but it's really not a good idea to learn that habit. I have seen it in production and it is neither nice to fix the issues nor explain to customers why our software stole a cent of their money.</p>\n<pre><code>public void withdraw(double value){\n if(value > balance){\n System.out.println("You can't withdraw that amount of money." +"\\n"+ "Your balance is: " + getBalance() + "\\n");\n</code></pre>\n<p>You've placed a user interface inside the ATM class (if we call it "BankAccount", it might be more obvious why this is a bad idea, bank accounts don't have a user interface). Instead of placing error messages in the withdraw method, you should throw an exception that describes the error and let the user interface code in your main class to decide what message to show to the user.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T06:22:10.470",
"Id": "256863",
"ParentId": "256846",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "256863",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T16:40:58.747",
"Id": "256846",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Automated Teller Machine (ATM) implementation in Java"
}
|
256846
|
<p>I have a series of images ("1.bmp", "2.bmp", "3.bmp",... ,"30.bmp" in "F:\Images" folder) and I am trying to insert these images one by one into Microsoft PowerPoint with VBA program. The base slide (as template) has been set down in page 2. The image object which is named <code>Image1</code> in that template slide is going to be replaced into "F:\Images\1.bmp", "F:\Images\2.bmp"... separately in new slides after the base slide.</p>
<p><strong>The experimental implementation</strong></p>
<p>The main entry method is <code>InsertFigures</code>.</p>
<pre><code>Sub InsertFigures()
'Reference: (Show object name) https://stackoverflow.com/a/52088805
'Reference: (Replace image) https://stackoverflow.com/a/18083223
Dim BaseSlideNumber As Integer
Dim StartNum, EndNum As Integer
StartNum = 1
EndNum = 30
BaseSlideNumber = 2
Dim LoopNumber As Integer
For LoopNumber = StartNum To EndNum
Set newSlide = ActivePresentation.Slides(BaseSlideNumber).Duplicate
Next LoopNumber
For LoopNumber = StartNum To EndNum
NewPictureFilename = "F:\Images\" & CStr(LoopNumber) & ".bmp" ' Source Image Path
Dim TargetSlideNumber As Integer
TargetSlideNumber = BaseSlideNumber + (LoopNumber - StartNum + 1)
Set ObjectForGettingProperties = getShapeByName("Image1", TargetSlideNumber)
'Capture properties of exisitng picture such as location and size
With ObjectForGettingProperties
TopProperty = .Top
LeftProperty = .Left
HeightProperty = .Height
WidthProperty = .Width
'SoftEdgeProperty = .SoftEdge
End With
ObjectForGettingProperties.Delete ' Delete origin placeholder
Set NewImageObject = ActivePresentation.Slides(TargetSlideNumber).Shapes.AddPicture(NewPictureFilename, msoFalse, msoTrue, LeftProperty, TopProperty, WidthProperty, HeightProperty)
NewImageObject.Name = "NewImage" ' Set image name
NewImageObject.SoftEdge.Radius = 8.86
Next LoopNumber
End Sub
Function getShapeByName(shapeName As String, Slide As Integer)
'Reference: https://stackoverflow.com/a/5527604
Set getShapeByName = ActivePresentation.Slides(Slide).Shapes(shapeName)
End Function
</code></pre>
<p>All suggestions are welcome.</p>
|
[] |
[
{
"body": "<p>Overall, there's not much to comment on for the code logic -- it does what you need it to do. But there are some details to pay attention to that will help in this and future code.</p>\n<ol>\n<li><a href=\"https://www.excel-easy.com/vba/examples/option-explicit.html\" rel=\"nofollow noreferrer\">Always use <code>Option Explicit</code></a>. There are a couple of undeclared variables/objects in your code that leads me to believe this directive is not present. Turn it on and leave it on.</li>\n<li>Be careful when <a href=\"https://bettersolutions.com/vba/variables/declaring-multiple-variables.htm\" rel=\"nofollow noreferrer\">declaring multiple variables on a single line</a>.</li>\n</ol>\n<p>In your code where you have</p>\n<pre><code>Dim StartNum, EndNum As Integer\n</code></pre>\n<p>Then <code>StartNum</code> will be a <code>Variant</code> and <code>EndNum</code> will be an <code>Integer</code>, which is not exactly what you want. It might be a pain, but save yourself and declare each variable on a separate line (once it's a habit, it's not as bad as you think).</p>\n<ol start=\"3\">\n<li>Declare your number variables as <code>Long</code>, not <code>Integer</code>. <a href=\"https://stackoverflow.com/a/26409520/4717755\">This answer</a> gives a very detailed explanation, but just know it's considered a "best practice" to always use <code>Long</code>.</li>\n<li>This point is more of a stylistic convention, but it's considered "standard" (personal preferences apply) to declare variables with <strong>camelCase</strong> and procedure names with <strong>PascalCase</strong> and constants with <strong>SHOUTY_SNAKE_CASE</strong> (<a href=\"https://riptutorial.com/vba/example/3832/variable-names\" rel=\"nofollow noreferrer\">reference</a>). If you read that reference, PLEASE don't fall down the <a href=\"https://www.joelonsoftware.com/2005/05/11/making-wrong-code-look-wrong/\" rel=\"nofollow noreferrer\">Hungarian case rabbit hole</a>. <em>(These conventions can lead to highly entertaining comments and emotional battles about the merits of these conventions. Do what I do: get some popcorn and enjoy the show ;) )</em></li>\n<li>Pay attention to the arguments in your functions or subs and identify each parameters as <code>ByRef</code> or <code>ByVal</code>. <a href=\"https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/passing-arguments-by-value-and-by-reference\" rel=\"nofollow noreferrer\">Microsoft explains the difference</a> (using Visual Basic, but it's essentially the same in VBA), and there are <a href=\"http://www.tushar-mehta.com/publish_train/xl_vba_cases/1004%20ByVal%20ByRef.shtml\" rel=\"nofollow noreferrer\">other</a> good <a href=\"https://stackoverflow.com/a/46960121/4717755\">references</a> to read to learn more about it.</li>\n<li>This is really my own personal preference, but I do try to limit the line length of each statement to around 80 characters. It it's longer, I add the continuation character. This is more of a guideline than a hard rule (for me), but it does make code easier to read.</li>\n</ol>\n<p>The example below is my implementation of your code, as modified by my comments.</p>\n<pre><code>Option Explicit\n\nSub InsertFigures()\n 'Reference: (Show object name) https://stackoverflow.com/a/52088805\n 'Reference: (Replace image) https://stackoverflow.com/a/18083223\n \n Dim baseSlideNumber As Long\n Dim startNum As Long\n Dim endNum As Long\n startNum = 1\n endNum = 30\n baseSlideNumber = 2\n \n Dim loopNumber As Long\n Dim newSlide As SlideRange\n For loopNumber = startNum To endNum\n Set newSlide = ActivePresentation.Slides(baseSlideNumber).Duplicate\n Next loopNumber\n \n For loopNumber = startNum To endNum\n Dim newPictureFilename As String\n Dim targetSlideNumber As Long\n newPictureFilename = "F:\\Images\\" & CStr(loopNumber) & ".bmp" ' Source Image Path\n targetSlideNumber = baseSlideNumber + (loopNumber - startNum + 1)\n \n Dim topProperty As Double\n Dim leftProperty As Double\n Dim heightProperty As Double\n Dim widthProperty As Double\n Dim softEdgeProperty As Double\n \n 'Capture properties of exisitng picture such as location and size\n Dim objectForGettingProperties As Shape\n Set objectForGettingProperties = GetShapeByName("Image1", targetSlideNumber)\n With objectForGettingProperties\n topProperty = .Top\n leftProperty = .Left\n heightProperty = .Height\n widthProperty = .Width\n 'SoftEdgeProperty = .SoftEdge\n End With\n objectForGettingProperties.Delete ' Delete origin placeholder\n \n Dim newImageObject As Object\n Set newImageObject = ActivePresentation.Slides(targetSlideNumber) _\n .Shapes.AddPicture(newPictureFilename, _\n msoFalse, msoTrue, _\n leftProperty, _\n topProperty, _\n widthProperty, _\n heightProperty)\n newImageObject.Name = "NewImage" 'Set image name\n newImageObject.SoftEdge.Radius = 8.86\n Next loopNumber\nEnd Sub\n\nFunction GetShapeByName(ByVal shapeName As String, ByVal Slide As Long) As Shape\n 'Reference: https://stackoverflow.com/a/5527604\n Set GetShapeByName = ActivePresentation.Slides(Slide).Shapes(shapeName)\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T19:11:26.200",
"Id": "257198",
"ParentId": "256850",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257198",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T18:27:36.010",
"Id": "256850",
"Score": "3",
"Tags": [
"beginner",
"vba",
"image",
"powerpoint"
],
"Title": "Batch Insert Figures Into Powerpoint Slides with VBA"
}
|
256850
|
<p>In a Node app where there is a messaging service, I've added a method to add a conversation and a member. The method functionality is that when a new request hit an API for messaging, that calls a method called <code>JoinConversation</code>. In the request there are some inputs from a client and based on those inputs the method do a check based on some conditions</p>
<ol>
<li>There is a first check if a conversations of the same already exist in the DB. If that exists then checks if the member already exist. If the member input info are presents in DB for that conversations it is returning the conversation related but if the member not preset then is creating a new member for that conversation.</li>
<li>If above is false means the conversation does not exist then a new conversation is created and also a new member is created also</li>
</ol>
<p>The method is doing fine the job but the way I wrote it sounds redundant to me and was seeking a better way to write it and in less lines if that would be possible.</p>
<p>The code of it and ignore <code>DAO</code> is a security external plugin I cannot explain.
The method uses KnexJS and Apollo.</p>
<pre><code> joinConversation({ input }) {
const { ApolloError } = this.errors;
return this.withDAO(async ({ conversation, member }) => {
const { originId, memberId, memberType, name, originType } = input;
const existingConversation = await conversation.selectFirst({
originId,
originType,
});
if (existingConversation) {
const existingMemberPerDocument = await member.selectFirst({
memberId,
});
if (!isEmpty(existingMemberPerDocument)) {
await conversation.selectFirst({
conversationId: existingConversation.conversationId,
originType: existingConversation.originType,
});
return existingConversation;
}
await member.insert({
conversationId: existingConversation.id,
memberId,
memberType,
name,
});
if (isEmpty(member)) {
throw new ApolloError('Error while Adding new conversation member!');
}
return existingMemberPerDocument;
}
const createdConversation = await conversation.insert({
...input,
});
if (isEmpty(createdConversation)) {
throw new ApolloError('Error while Adding new conversation!');
}
await member.insert({
conversationId: createdConversation.id,
memberId,
memberType,
name,
});
return createdConversation;
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T12:00:12.063",
"Id": "507322",
"Score": "0",
"body": "Hi Jakub, looks like the end of the code is not valid JS. Did something happen during copy pasting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T12:04:46.927",
"Id": "507323",
"Score": "0",
"body": "The last part action is not part of it I don't know why that happen i will edit and paste again to be sure about it is right thanks for catch"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T18:33:39.440",
"Id": "256851",
"Score": "0",
"Tags": [
"javascript",
"node.js"
],
"Title": "Create conversations and add new members while avoiding duplicates"
}
|
256851
|
<p>I am working on an online newspaper/blogging application with <strong>CodeIgniter 3.1.8</strong> and <strong>Twig</strong>. (I use the Twig template engine only for the front-end views).</p>
<p>The application, of course, has a <strong>registration and login</strong> system, which includes the password reset functionality.</p>
<p>The <strong>Passwordreset</strong> controller:</p>
<pre><code>class Passwordreset extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
private $sender_email = "noreply@yourdomain.com";
private $sender_name = "Razvan Zamfir";
private $user_email = '';
private $subject = 'Pasword reset link';
private $token = '';
private $reset_url = '';
private $reset_link = '';
private $body = '';
public function index()
{
// Display form
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['tagline'] = 'Reset your password';
$data['categories'] = $this->Categories_model->get_categories();
// Form validation rules
$this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if (!$this->form_validation->run()) {
$this->load->view('dashboard/partials/header', $data);
$this->load->view('auth/passwordreset');
$this->load->view('dashboard/partials/footer');
} else {
if ($this->Usermodel->email_exists()) {
//Get user email
$this->user_email = $this->input->post('email');
//create token
$this->token = md5(str_shuffle($this->user_email));
//create url
$this->reset_url = base_url('newpassword/') . $this->token;
//create reset link
$this->reset_link = '<a href="' . $this->reset_url . '">password reset link</a>';
$this->body = "Here is your <strong>" . $this->reset_link . "</strong>. After clicking it you will be redirected to a page on the website where you will be able to set a new pasword.";
// Update paswword reset token
$this->updateToken($this->user_email, $this->token);
// Send mail and rediect
$this->sendResetMail();
} else {
$this->session->set_flashdata('email_non_existent', "The email you provided does not exist in our database");
}
redirect('newpassword');
}
}
public function updateToken($user_email, $token)
{
$user_email = $this->user_email;
$token = $this->token;
$this->Usermodel->update_token($user_email, $token);
}
public function sendResetMail()
{
$config = array();
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'smtp.yourdomain.com';
$config['smtp_user'] = 'noreply@yourdomain.com';
$config['smtp_pass'] = '******';
$config['smtp_port'] = 25;
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['newline'] = "\r\n";
if (!$this->load->is_loaded('email')) {
$this->load->library('email', $config);
} else {
$this->email->initialize($config);
}
// Build the body and meta data of the email message
$this->email->from($this->sender_email, $this->sender_name);
$this->email->to($this->user_email);
$this->email->subject($this->subject);
$this->email->message($this->body);
if ($this->email->send()) {
$this->session->set_flashdata('reset_mail_confirm', "A pasword reset link was send to the email address $this->user_email");
} else {
$this->session->set_flashdata('reset_mail_fail', "Our atempt to send a pasword reset link to $this->user_email has failed");
}
}
}
</code></pre>
<p>The <strong>passwordreset.php</strong> view:</p>
<pre><code><?php echo form_open(base_url(' ')); ?>
<div class="form-group <?php if(form_error('email')) echo 'has-error';?>">
<input type="text" name="email" id="email" class="form-control" placeholder="Email" value="<?php echo set_value('email')?>">
<?php if(form_error('email')) echo form_error('email'); ?>
</div>
<div class="form-group mb-2">
<input type="submit" value="Reset password" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
</code></pre>
<p>The <strong>Newpassword</strong> controller:</p>
<pre><code>class Newpassword extends CI_Controller
{
public function index($token = NULL)
{
$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['tagline'] = 'New password';
$data['categories'] = $this->Categories_model->get_categories();
$data['token'] = $token;
// Form validation rules
$this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
$this->form_validation->set_rules('cpassword', 'Confirm password', 'required|matches[password]');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if (!$this->form_validation->run()) {
$this->load->view('dashboard/partials/header', $data);
$this->load->view('auth/newpassword');
$this->load->view('dashboard/partials/footer');
} else {
// Encrypt new password
$enc_password = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
if ($this->Usermodel->set_new_password($token, $enc_password)) {
$this->session->set_flashdata("new_password_success", "Your new password was set. You can login");
redirect('login');
} else {
$this->session->set_flashdata("new_password_fail", "We have failed updating your password");
redirect('/newpassword/' . $token);
}
}
}
}
</code></pre>
<p>The <strong>newpassword.php</strong> view:</p>
<pre><code><?php echo form_open(base_url('newpassword/'. $token)); ?>
<div class="form-group <?php if(form_error('password')) echo 'has-error';?>">
<input type="password" name="password" id="password" class="form-control" placeholder="Password">
<?php if(form_error('password')) echo form_error('password'); ?>
</div>
<div class="form-group <?php if(form_error('cpassword')) echo 'has-error';?>">
<input type="password" name="cpassword" id="cpassword" class="form-control" placeholder="Confirm password">
<?php if(form_error('cpassword')) echo form_error('cpassword'); ?>
</div>
<div class="form-group mb-2">
<input type="submit" value="Set password" class="btn btn-block btn-md btn-success">
</div>
<?php echo form_close(); ?>
</code></pre>
<p>In the model I have:</p>
<pre><code>public function email_exists() {
$query = $this->db->get_where('authors', ['email' => $this->input->post('email')]);
return $query->num_rows() > 0;
}
//more code
public function update_token($user_email, $token) {
return $this->db
->where('email', $user_email)
// insert token (make it diffrent from NULL)
->update('authors', array('token' => $token));
}
public function set_new_password($token, $enc_password) {
return $this->db
->where('token', $token)
// set new password and reset token to NULL
->update('authors', array('password' => $enc_password, 'token' => NULL));
}
</code></pre>
<p>My main concern is <em>security</em>, but I will appreciate <em>any constructive criticism</em>. Thanks! :)</p>
|
[] |
[
{
"body": "<p>Some food for thought:</p>\n<ul>\n<li><p>I don't see any benefit to <code>str_shuffle()</code> why bother? Why bother referencing the email? If you need a random string, populate one in the shortest way with satisfactory randomness for the task.</p>\n</li>\n<li><p>I generally advise against any html markup being generated anywhere other than the view. I'd rather see your controller's properties contain raw data only.</p>\n</li>\n<li><p><code>updateToken()</code> needs a rethink.\nWhy would you bother passing any values into the method if you are going to immediately and unconditionally overwrite them? Do you mean the inverse of those declarations? You should also avoid declaring single-use variables unless there is an obvious benefit in doing so.</p>\n</li>\n<li><p>You are making repeated calls of <code>form_error()</code> (containing the same string instead of calling it once and using its value multiple times). This isn't about performance, it is about not repeating yourself.</p>\n</li>\n<li><p>Model method <code>email_exists()</code> should never receive any superglobals directly. You need to optimize your methods for utility. Imagine if you need to call this method elsewhere -- you may or may not have a <code>$_POST</code> element with that exact name. So, you absolutely need to collect all submitted values in the controller and the controller distributes the data to the models.</p>\n<pre><code> public function email_exists(string $email): bool\n {\n return (bool)this->db->where(['email' => $email])->count_all_results('authors');\n }\n</code></pre>\n<p>Apply this advice consistently throughout your project.</p>\n</li>\n<li><p>CodeIgniter's <code>update()</code> method can receive the <code>where</code> data as its third parameter. Use the third parameter to afford the removal of the <code>where()</code> call.</p>\n</li>\n<li><p>Use data type declarations for all inputs and return values for all methods -- this really improves the readability and maintainability of a project.</p>\n</li>\n<li><p>I recommend always returning <em>something</em> when a method attempts to change the database. For INSERTs, I return the autogenerated id (primary key). When performing a UPDATE or DELETE, I return the affected rows.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T10:41:23.467",
"Id": "256868",
"ParentId": "256853",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T19:58:11.420",
"Id": "256853",
"Score": "2",
"Tags": [
"php",
"codeigniter"
],
"Title": "Password reset functionality in Codeigniter 3"
}
|
256853
|
<p>Would you be so kind as to review my TicTacToe implementation I wrote in C? I wrote this blind (not looking up other implementations). You can find it on Github <a href="https://github.com/SteffanDavies/TicTacToe/blob/main/main.c" rel="nofollow noreferrer">here</a>.</p>
<p>Any input and/or suggestions would be appreciated. Any pointers on style would also be appreciated.</p>
<p>I have used <code>fflush(stdin);</code> to clear input buffer between prompts (it was suggested in a C book I'm studying) but have also heard it was <strong>bad practice</strong>. Seems to work great though for when the user inputs more characters than he should. Clean Code guy suggests putting reused variables as global (i, j, counterX, counterY) but I've also been told globals should be avoided like the plague, so should I really?</p>
<pre><code>#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
typedef enum{
Playing = 0,
Player1Wins = 1,
Player2Wins = 2,
Draw = 3
} gameState;
const char emptyboard[8][8] = {
{'-','-','-','-','-','-','-',' '},
{'|',' ','|',' ','|',' ','|','3'},
{'-','-','-','-','-','-','-',' '},
{'|',' ','|',' ','|',' ','|','2'},
{'-','-','-','-','-','-','-',' '},
{'|',' ','|',' ','|',' ','|','1'},
{'-','-','-','-','-','-','-',' '},
{' ','a',' ','b',' ','c',' ',' '}
};
void clearScreen();
void resetBoard(char* board[8][8], int* turn);
void drawBoard(char* board[8][8]);
void addToBoard(char* board[8][8], int* player, int* turn, char* posX, char* posY);
void declareWinner(gameState currentGameState);
int getPlayerInput(int player, char* posX, char* posY); //Returns 1 if valid
int checkWin(char* (board)[8][8], int* turn);
int checkVerticalVictory(char* board[8][8]);
int checkHorizontalVictory(char* board[8][8]);
int checkDiagonalVictory(char* board[8][8]);
int checkDraw(int* turn);
int promptReplay();
int main()
{
char board[8][8] = {
};
char posX, posY;
int player = 1; //Can be 1 or 2
int turn = 0; //Draw at 9
gameState currentGameState = Playing;
int restart = 0;
do{
resetBoard(board, &turn);
do{
clearScreen();
drawBoard(board);
while(!getPlayerInput(player, &posX, &posY)); //Keep prompting until input is valid
addToBoard(board, &player, &turn, &posX, &posY);
currentGameState = checkWin(board, &turn);
}while(currentGameState == Playing);
clearScreen();
drawBoard(board);
declareWinner(currentGameState);
restart = promptReplay();
}while(restart);
return 0;
}
void drawBoard(char* board[8][8])
{
for(int i=0; i<8; i++)
{
for(int j=0; j<8; j++)
{
putchar(board[i][j]);
}
putchar('\n');
}
}
int getPlayerInput(int player, char* posX, char* posY)
{
char _posX;
char _posY;
char input[3];
printf("\nPlayer %d, What position do you want to play? (ex. a3) ", player);
fgets(input, 3, stdin);
_posX = input[0];
_posY = input[1];
fflush(stdin);
//check if input is valid
switch(_posX)
{
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C': *posX = _posX; break;
default:
printf("\nWrong horizontal input (%c), try again!\n", _posX);
return 0;
}
switch(_posY)
{
case '1':
case '2':
case '3': *posY = _posY; break;
default:
printf("\nWrong vertical input (%c), try again!\n", _posX);
return 0;
}
return 1;
}
void addToBoard(char* board[8][8], int* player, int* turn, char* posX, char* posY)
{
int arrayRow, arrayCol;
switch(*posX)
{
case 'a':
case 'A': arrayCol = 1; break;
case 'b':
case 'B': arrayCol = 3; break;
case 'c':
case 'C': arrayCol = 5; break;
}
switch(*posY)
{
case '1': arrayRow = 5; break;
case '2': arrayRow = 3; break;
case '3': arrayRow = 1; break;
}
if(board[arrayRow][arrayCol] == ' ')
{
if(*player == 1)
{
board[arrayRow][arrayCol] = 'X';
*player = 2;
}
else
{
board[arrayRow][arrayCol] = 'O';
*player = 1;
}
(*turn)++;
}
}
int checkWin(char* board[8][8], int* turn)
{
/* Returns 0, 1, 2, 3:
0 - No victory
1 - Player 1 Victory
2 - Player 2 Victory
3 - Draw
*/
/*
Valid positions:
[1][1], [1][3], [1][5],
[3][1], [3][3], [3][5],
[5][1], [5][3], [5][5],
*/
int winCondition = 0;
winCondition = checkHorizontalVictory(board);
if(winCondition) return winCondition;
winCondition = checkVerticalVictory(board);
if(winCondition) return winCondition;
winCondition = checkDiagonalVictory(board);
if(winCondition) return winCondition;
winCondition = checkDraw(turn);
if(winCondition) return winCondition;
return winCondition;
}
int checkHorizontalVictory(char* board[8][8])
{
int counterX;
int counterO;
for(int i=1; i<=5; i+=2)
{
counterX = 0;
counterO = 0;
for(int j=1; j<=5; j+=2)
{
if(board[i][j] == ' ')
{
break;
}
else if(board[i][j] == 'X')
{
counterX++;
}
else if(board[i][j] == 'O')
{
counterO++;
}
}
if (counterX == 3) return 1;
else if (counterO == 3) return 2;
}
return 0;
}
int checkVerticalVictory(char* board[8][8])
{
int counterX;
int counterO;
for(int j=1; j<=5; j+=2)
{
counterX = 0;
counterO = 0;
for(int i=1; i<=5; i+=2)
{
if(board[i][j] == ' ')
{
break;
}
else if(board[i][j] == 'X')
{
counterX++;
}
else if(board[i][j] == 'O')
{
counterO++;
}
}
if (counterX == 3) return 1;
else if (counterO == 3) return 2;
}
return 0;
}
int checkDiagonalVictory(char* board[8][8])
{
int counterX = 0;
int counterO = 0;
//Left to Right
for(int i=1; i<=5; i+=2)
{
if(board[i][i] == ' ')
{
break;
}
else if(board[i][i] == 'X')
{
counterX++;
}
else if(board[i][i] == 'O')
{
counterO++;
}
}
if (counterX == 3) return 1;
else if (counterO == 3) return 2;
//Right to Left
counterX = 0;
counterO = 0;
for(int k=0, i=1, j=5; k<3; k++, i+=2, j-=2)
{
if(board[i][j] == ' ')
{
break;
}
else if(board[i][j] == 'X')
{
counterX++;
}
else if(board[i][j] == 'O')
{
counterO++;
}
}
if (counterX == 3) return 1;
else if (counterO == 3) return 2;
else return 0;
}
checkDraw(int* turn)
{
if(*turn == 9)
{
return 3;
}
return 0;
}
int promptReplay()
{
char choice;
puts("\n\nPlay Again? (y/n): ");
choice = getchar();
if(choice == 'y')
{
fflush(stdin);
return 1;
}
else if(choice == 'n')
{
fflush(stdin);
return 0;
}
else
{
fflush(stdin);
puts("\nWrong input.\n");
promptReplay();
}
}
void resetBoard(char* board[8][8], int* turn)
{
*turn = 0;
for(int i=0; i<8; i++)
{
for(int j=0; j<8; j++)
{
board[i][j] = emptyboard[i][j];
}
}
}
void declareWinner(gameState currentGameState)
{
switch (currentGameState)
{
case Player1Wins:
puts("Player 1 wins!"); break;
case Player2Wins:
puts("Player 2 wins!"); break;
case Draw:
puts("Player 2 wins!"); break;
}
}
void clearScreen()
{
#ifdef _WIN32
system("cls");
#elif __linux__
system("clear");
#endif
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T23:16:16.530",
"Id": "507276",
"Score": "1",
"body": "Global variables creates chaos when project gets bigger. It's like throwing your clothes middle of room, instead of putting them in wardrobe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T16:04:25.410",
"Id": "507356",
"Score": "1",
"body": "That's a worthwhile _answer_ @Kao, so shouldn't be a comment. You would earn reputation if you turn that into an answer, too."
}
] |
[
{
"body": "<h1>How I Review Code</h1>\n<p>I have performed Code Reviews for over 30 years both on the Code Review Community and professionally. I have also had to maintain code written by others and this generally requires a thorough code inspection before starting.</p>\n<p>The criteria I use for code reviews is:</p>\n<ol>\n<li>Does the code compile without errors and warnings?</li>\n<li>Does the code work as expected?</li>\n<li>Is the code easy to maintain, especially by others?</li>\n<li>Is the code portable (will it compile and run on multiple systems, Window, Linux and Unix)?</li>\n<li>Does the code follow best practices? Usually this goes hand in hand with number 3.</li>\n<li>How complex is the code? (Really also part of number 3)</li>\n<li>Is the code extendable?</li>\n</ol>\n<h1>General Observations</h1>\n<p>The best thing I can pick out is that the code does seem to be portable, the one case where there might be a portability issue has <code>#ifdef</code> statements that allow it to run on both Windows and Linux.</p>\n<p>The code is pretty easy to read, it is not all that easy to modify or maintain. The code doesn't follow best practices and clearly ignores the C programming standard in at least one case.</p>\n<p>I am building and running this on Window 10 using Visual Studio 2019 professional with fairly strict warning checking equivalent to <code>-wall</code>.</p>\n<blockquote>\n<p>Does the code compile without errors and warnings?</p>\n</blockquote>\n<p>No. There is one error message and multiple warning messages. The one error message has to do with this line in <code>main()</code>.</p>\n<pre><code> char board[8][8] = {};\n</code></pre>\n<p>The braces <code>{</code> and <code>}</code> require a value.</p>\n<p>There are also multiple warning messages about the use of <code>char* board[8][8]</code> in the function prototypes, see below.</p>\n<blockquote>\n<p>Does the code work as expected?</p>\n</blockquote>\n<p>No, the code runs, but there are issues in the function <code>getPlayerInput()</code>.</p>\n<p>I'm not sure why you mention this since you only have one global variable</p>\n<blockquote>\n<p>Clean Code guy suggests putting reused variables as global (i, j, counterX, counterY) but I've also been told globals should be avoided like the plague, so should I really?</p>\n</blockquote>\n<p>I think your code is better the way it is, you only have one global variable and that is just used to start or restart the game. It would be better if you declared that variable <code>static</code> so that if this program ever gets broken into multiple source files then there won't be any linking errors.</p>\n<h1>BUG, Buffer Overflow</h1>\n<blockquote>\n<p>I have used <code>fflush(stdin);</code></p>\n</blockquote>\n<p>The problem with the input does not need <code>fflush(stdin);</code> You need to make the <code>input</code> array bigger. Currently the code</p>\n<pre><code>char input[3];\nfgets(input, 3, stdin);\n</code></pre>\n<p>Has an array of 3 characters and is only getting 3 characters, however, fgets() should really be returning 4 characters, the column, the row, end of line and a termination character. What input actually contains is <code>column</code>, <code>row</code>, <code>end of line</code>, it is not terminated with a <code>'\\0'</code>. This is possibly causing all kinds of unknown behavior in the program.</p>\n<p>The input array should be at least 4 characters. When creating arrays of chars it is always best to use a size of some power of two, and generally use some multiple of the word size of the compiler.</p>\n<h1>Suggested Corrections</h1>\n<h2>Fix All the Compiler Warning Messages, Compile with <code>-wall</code></h2>\n<p>There are a lot of compiler warning messages, these should all be addressed before the code is posted on Code Review.</p>\n<blockquote>\n<p>1>C2TicTacTo07012021.c(48,25): warning C4047: 'function': 'char <em>(</em>)[8]' differs in levels of indirection from 'char [8][8]'<br />\n1>C2TicTacTo07012021.c(48,20): warning C4024: 'resetBoard': different types for formal and actual parameter 1<br />\n1>C2TicTacTo07012021.c(51,28): warning C4047: 'function': 'char <em>(</em>)[8]' differs in levels of indirection from 'char [8][8]'<br />\n1>C2TicTacTo07012021.c(51,23): warning C4024: 'drawBoard': different types for formal and actual parameter 1<br />\n1>C2TicTacTo07012021.c(53,29): warning C4047: 'function': 'char <em>(</em>)[8]' differs in levels of indirection from 'char [8][8]'<br />\n1>C2TicTacTo07012021.c(53,24): warning C4024: 'addToBoard': different types for formal and actual parameter 1<br />\n1>C2TicTacTo07012021.c(54,46): warning C4047: 'function': 'char <em>(</em>)[8]' differs in levels of indirection from 'char [8][8]'<br />\n1>C2TicTacTo07012021.c(54,41): warning C4024: 'checkWin': different types for formal and actual parameter 1<br />\n1>C2TicTacTo07012021.c(58,24): warning C4047: 'function': 'char <em>(</em>)[8]' differs in levels of indirection from 'char [8][8]'<br />\n1>C2TicTacTo07012021.c(58,19): warning C4024: 'drawBoard': different types for formal and actual parameter 1<br />\n1>C2TicTacTo07012021.c(74,32): warning C4047: 'function': 'int' differs in levels of indirection from 'char *'<br />\n1>C2TicTacTo07012021.c(74,29): warning C4024: 'putchar': different types for formal and actual parameter 1<br />\n1>C2TicTacTo07012021.c(138,41): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(142,44): warning C4047: '=': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(147,44): warning C4047: '=': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(199,35): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(203,40): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(207,40): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(232,35): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(236,40): warning C4047: '==': 'char *' differs in levels of indirection from 'int'\n1>C2TicTacTo07012021.c(240,40): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(261,31): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(265,36): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(269,36): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(284,31): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(288,36): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(292,36): warning C4047: '==': 'char *' differs in levels of indirection from 'int'<br />\n1>C2TicTacTo07012021.c(343,43): warning C4047: '=': 'char *' differs in levels of indirection from 'const char'<br />\n1>C2TicTacTo07012021.c(333): warning C4715: 'promptReplay': not all control paths return a value</p>\n</blockquote>\n<h2>Follow the C Coding Standard</h2>\n<p>The function <code>getPlayerInput()</code> has 2 variables that start with underscores.</p>\n<pre><code> char _posX;\n char _posY;\n</code></pre>\n<p>Variables that start with underscore may be reserved.</p>\n<p>These temporary variables aren't really needed since the <code>input</code> array already exists.</p>\n<pre><code> switch (input[0])\n {\n case 'a':\n case 'A':\n case 'b':\n case 'B':\n case 'c':\n case 'C': *posX = input[0]; break;\n default:\n printf("\\nWrong horizontal input (%c), try again!\\n", _posX);\n return 0;\n }\n switch (input[1])\n {\n case '1':\n case '2':\n case '3': *posY = input[1]; break;\n default:\n printf("\\nWrong vertical input (%c), try again!\\n", _posX);\n return 0;\n }\n</code></pre>\n<h2>Code Organization</h2>\n<p>Function prototypes are very useful in large programs that contain multiple source files, and that in case they will be in header files. In a single file program like this it is better to put the main() function at the bottom of the file and all the functions that get used in the proper order above main(). Keep in mind that every line of code written is another line of code where a bug can crawl into the code.</p>\n<p>In the case of this program the function prototypes cause warning statements during compilation.</p>\n<h2>Separate Data From Display</h2>\n<p>It is generally better to separate the data from the display. This would make the <code>check</code> functions that check for a win easier to write and maintain, the for loops could increment by one rather than two. It would also make the <code>resetBoard()</code> function easier to write and maintain. It would make the <code>drawboard()</code> function a little more difficult, but that is 5 functions simplified and 1 function made more complex.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T05:24:23.017",
"Id": "520617",
"Score": "0",
"body": "`fflush(stdin)` is not only unnecessary - it's UB! N1570 para 7.21.5.2.2 says \"_If `stream` points to an output stream or an update stream in which the most recent operation was not input, …; __otherwise, the behavior is undefined.___\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T12:05:58.273",
"Id": "520636",
"Score": "0",
"body": "Oh, I thought I had upvoted; fixed that now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-01T20:08:09.807",
"Id": "263683",
"ParentId": "256860",
"Score": "2"
}
},
{
"body": "<p>What's <code><conio.h></code>? It's not mentioned in the C standard, and if I remove it, the code kind of compiles, so I guess it's not required.</p>\n<p>I say "kind of" because of the warnings it generates, which shouldn't be ignored:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -std=c17 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion 256860.c -o 256860\n256860.c:23:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n 23 | void clearScreen();\n | ^~~~\n256860.c:34:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n 34 | int promptReplay();\n | ^~~\n256860.c:38:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n 38 | int main()\n | ^~~~\n256860.c: In function ‘main’:\n256860.c:40:24: warning: ISO C forbids empty initializer braces [-Wpedantic]\n 40 | char board[8][8] = {\n | ^\n256860.c:49:20: warning: passing argument 1 of ‘resetBoard’ from incompatible pointer type [-Wincompatible-pointer-types]\n 49 | resetBoard(board, &turn);\n | ^~~~~\n | |\n | char (*)[8]\n256860.c:24:23: note: expected ‘char * (*)[8]’ but argument is of type ‘char (*)[8]’\n 24 | void resetBoard(char* board[8][8], int* turn);\n | ~~~~~~^~~~~~~~~~~\n256860.c:52:23: warning: passing argument 1 of ‘drawBoard’ from incompatible pointer type [-Wincompatible-pointer-types]\n 52 | drawBoard(board);\n | ^~~~~\n | |\n | char (*)[8]\n256860.c:25:22: note: expected ‘char * (*)[8]’ but argument is of type ‘char (*)[8]’\n 25 | void drawBoard(char* board[8][8]);\n | ~~~~~~^~~~~~~~~~~\n256860.c:54:24: warning: passing argument 1 of ‘addToBoard’ from incompatible pointer type [-Wincompatible-pointer-types]\n 54 | addToBoard(board, &player, &turn, &posX, &posY);\n | ^~~~~\n | |\n | char (*)[8]\n256860.c:26:23: note: expected ‘char * (*)[8]’ but argument is of type ‘char (*)[8]’\n 26 | void addToBoard(char* board[8][8], int* player, int* turn, char* posX, char* posY);\n | ~~~~~~^~~~~~~~~~~\n256860.c:55:41: warning: passing argument 1 of ‘checkWin’ from incompatible pointer type [-Wincompatible-pointer-types]\n 55 | currentGameState = checkWin(board, &turn);\n | ^~~~~\n | |\n | char (*)[8]\n256860.c:29:21: note: expected ‘char * (*)[8]’ but argument is of type ‘char (*)[8]’\n 29 | int checkWin(char* (board)[8][8], int* turn);\n | ~~~~~~~^~~~~~~~~~~~\n256860.c:59:19: warning: passing argument 1 of ‘drawBoard’ from incompatible pointer type [-Wincompatible-pointer-types]\n 59 | drawBoard(board);\n | ^~~~~\n | |\n | char (*)[8]\n256860.c:25:22: note: expected ‘char * (*)[8]’ but argument is of type ‘char (*)[8]’\n 25 | void drawBoard(char* board[8][8]);\n | ~~~~~~^~~~~~~~~~~\n256860.c: In function ‘drawBoard’:\n256860.c:75:29: warning: passing argument 1 of ‘putchar’ makes integer from pointer without a cast [-Wint-conversion]\n 75 | putchar(board[i][j]);\n | ~~~~~~~~^~~\n | |\n | char *\nIn file included from 256860.c:2:\n/usr/include/stdio.h:528:25: note: expected ‘int’ but argument is of type ‘char *’\n 528 | extern int putchar (int __c);\n | ~~~~^~~\n256860.c: In function ‘addToBoard’:\n256860.c:140:34: warning: comparison between pointer and integer\n 140 | if(board[arrayRow][arrayCol] == ' ')\n | ^~\n256860.c:144:39: warning: assignment to ‘char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]\n 144 | board[arrayRow][arrayCol] = 'X';\n | ^\n256860.c:149:39: warning: assignment to ‘char *’ from ‘int’ makes pointer from integer without a cast [-Wint-conversion]\n 149 | board[arrayRow][arrayCol] = 'O';\n | ^\n256860.c: In function ‘checkHorizontalVictory’:\n256860.c:201:28: warning: comparison between pointer and integer\n 201 | if(board[i][j] == ' ')\n | ^~\n256860.c:205:33: warning: comparison between pointer and integer\n 205 | else if(board[i][j] == 'X')\n | ^~\n256860.c:209:33: warning: comparison between pointer and integer\n 209 | else if(board[i][j] == 'O')\n | ^~\n256860.c: In function ‘checkVerticalVictory’:\n256860.c:234:28: warning: comparison between pointer and integer\n 234 | if(board[i][j] == ' ')\n | ^~\n256860.c:238:33: warning: comparison between pointer and integer\n 238 | else if(board[i][j] == 'X')\n | ^~\n256860.c:242:33: warning: comparison between pointer and integer\n 242 | else if(board[i][j] == 'O')\n | ^~\n256860.c: In function ‘checkDiagonalVictory’:\n256860.c:263:24: warning: comparison between pointer and integer\n 263 | if(board[i][i] == ' ')\n | ^~\n256860.c:267:29: warning: comparison between pointer and integer\n 267 | else if(board[i][i] == 'X')\n | ^~\n256860.c:271:29: warning: comparison between pointer and integer\n 271 | else if(board[i][i] == 'O')\n | ^~\n256860.c:286:24: warning: comparison between pointer and integer\n 286 | if(board[i][j] == ' ')\n | ^~\n256860.c:290:29: warning: comparison between pointer and integer\n 290 | else if(board[i][j] == 'X')\n | ^~\n256860.c:294:29: warning: comparison between pointer and integer\n 294 | else if(board[i][j] == 'O')\n | ^~\n256860.c: At top level:\n256860.c:306:1: warning: return type defaults to ‘int’ [-Wimplicit-int]\n 306 | checkDraw(int* turn)\n | ^~~~~~~~~\n256860.c:316:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n 316 | int promptReplay()\n | ^~~~~~~~~~~~\n256860.c: In function ‘promptReplay’:\n256860.c:320:14: warning: conversion from ‘int’ to ‘char’ may change value [-Wconversion]\n 320 | choice = getchar();\n | ^~~~~~~\n256860.c: In function ‘resetBoard’:\n256860.c:348:25: warning: assignment to ‘char *’ from ‘char’ makes pointer from integer without a cast [-Wint-conversion]\n 348 | board[i][j] = emptyboard[i][j];\n | ^\n256860.c: In function ‘declareWinner’:\n256860.c:355:5: warning: enumeration value ‘Playing’ not handled in switch [-Wswitch]\n 355 | switch (currentGameState)\n | ^~~~~~\n256860.c: At top level:\n256860.c:366:6: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n 366 | void clearScreen()\n | ^~~~~~~~~~~\n256860.c: In function ‘promptReplay’:\n256860.c:338:1: warning: control reaches end of non-void function [-Wreturn-type]\n 338 | }\n | ^\n</code></pre>\n<p>There are some serious problems there, in particular where we pass a matrix of <code>char</code> to functions expecting a matrix of <code>char*</code>.</p>\n<p>I suggest creating a typedef for the frequently-used matrix:</p>\n<pre><code>#define BOARD_WIDTH 8\n#define BOARD_HEIGHT 8\ntypedef char game_board[BOARD_HEIGHT][BOARD_WIDTH];\n</code></pre>\n<p>That makes our declarations much easier to keep consistent.</p>\n<pre><code>const game_board emptyboard = {\n {'-','-','-','-','-','-','-',' '},\n {'|',' ','|',' ','|',' ','|','3'},\n {'-','-','-','-','-','-','-',' '},\n {'|',' ','|',' ','|',' ','|','2'},\n {'-','-','-','-','-','-','-',' '},\n {'|',' ','|',' ','|',' ','|','1'},\n {'-','-','-','-','-','-','-',' '},\n {' ','a',' ','b',' ','c',' ',' '}\n};\n\nvoid clearScreen(void);\nvoid resetBoard(game_board board, int* turn);\nvoid drawBoard(game_board board);\nvoid addToBoard(game_board board, int* player, int* turn, char* posX, char* posY);\nvoid declareWinner(gameState currentGameState);\nint getPlayerInput(int player, char* posX, char* posY); //Returns 1 if valid\nint checkWin(game_board board, int* turn);\nint checkVerticalVictory(game_board board);\nint checkHorizontalVictory(game_board board);\nint checkDiagonalVictory(game_board board);\nint checkDraw(int* turn);\nint promptReplay(void);\n</code></pre>\n<p>Normally, I'd make the board 3✕3, since the other entries in the matrix are for presentation rather than actual state.</p>\n<hr />\n<blockquote>\n<pre><code>char choice;\nputs("\\n\\nPlay Again? (y/n): ");\nchoice = getchar();\n</code></pre>\n</blockquote>\n<p>Here, we not only fail to check for EOF, but we can no longer do so, as we converted the input to <code>char</code>. Use <code>int</code>, or turn to <code>scanf()</code>:</p>\n<pre><code>for (;;) {\n puts("Play Again? (y/n): ");\n char choice;\n if (scanf(" %c%*[^\\n]", &choice) < 1) {\n /* EOF */\n return 0;\n }\n switch (choice) {\n case 'y': case 'Y':\n return 1;\n case 'n': case 'N':\n return 0;\n }\n puts("\\nWrong input.\\n");\n /* loop; ask again */\n}\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>#ifdef _WIN32\nsystem("cls");\n\n#elif __linux__\nsystem("clear");\n\n#endif\n</code></pre>\n</blockquote>\n<p>Use <code>system()</code> with care. <code>system("/usr/bin/clear")</code> would be better, since you can't rely on users having a sane <code>PATH</code>. And on other platforms, is this function really supposed to do nothing? Perhaps:</p>\n<pre><code>#else\n#error Please add support for clearing screen\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-02T13:00:14.700",
"Id": "263696",
"ParentId": "256860",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T22:37:56.103",
"Id": "256860",
"Score": "3",
"Tags": [
"c",
"game",
"console",
"tic-tac-toe"
],
"Title": "Console TicTacToe in C"
}
|
256860
|
<p>I've created a two-player number guessing game in Haskell. My main objective was to practice dealing with "state" in a purely functional language (such as player scores, whose turn it is, etc.).</p>
<p>Here are the rules:</p>
<h3>Gameplay:</h3>
<p>Two players will take turns guessing a random number between 1 and 10. Answers will be typed into the command line.</p>
<h3>Scoring:</h3>
<ul>
<li>If a player guesses the number correctly, they will be awarded 5 points<br></li>
<li>If a player is within two (inclusive) from the answer, the player will be awarded 3 points.</li>
<li>If a player is within three (inclusive) from the answer, they will be awarded 1 point.</li>
<li>If a player is 7 or more points off, they will lose a point. The score may not be negative.</li>
<li>All other offsets will result in zero points.</li>
<li>The game will continue until the one of the players reaches 10 points.</li>
</ul>
<h3>Caveats:</h3>
<ol>
<li>This is was not designed to be an exercise in enjoyable game design -- obviously the optimal solution is to always choose five, which doesn't make for a lot of excitement. :D</li>
<li>I am aware that <code>Control.Monad.State</code> exists, but I want to practice tracking state without it.</li>
<li>I know that the "mutual recursion" is difficult to follow. I would love some suggestions for getting rid of that which do not involve nesting <code>if</code> statements.</li>
</ol>
<pre class="lang-hs prettyprint-override"><code>import Data.Char
import System.Random
main = do
stdGen <- getStdGen
play 0 0 P1 stdGen
play :: Int -> Int -> Player -> StdGen -> IO ()
play p1Score p2Score player stdGen
| p1Score < 10 && p2Score < 10 = continueGame p1Score p2Score player stdGen
| otherwise = putStrLn $ show (determineWinner p1Score p2Score) ++ " wins!"
continueGame :: Int -> Int -> Player -> StdGen -> IO ()
continueGame p1Score p2Score player stdGen = do
putStr $ show player ++ "'s turn. Pick a number between 1 and 10: "
chosenNumber <- getLine
if isInteger chosenNumber
then do
let (randomNumber, newGen) = randomR (1, 10) stdGen :: (Int, StdGen)
putStrLn $ "The answer is " ++ show randomNumber
let pointsEarned = calcPointsEarned randomNumber (read chosenNumber)
let newP1Score = min (max (p1Score + calcPointsEarnedForPlayer player P1 pointsEarned) 0) 10
let newP2Score = min (max (p2Score + calcPointsEarnedForPlayer player P2 pointsEarned) 0) 10
putStrLn $ "P1 Score: " ++ show newP1Score
putStrLn $ "P2 Score: " ++ show newP2Score
play newP1Score newP2Score (changeTurn player) newGen
else do
putStrLn "The input must be an integer"
play p1Score p2Score player stdGen
data Player = P1 | P2 deriving (Show, Eq)
isInteger :: String -> Bool
isInteger = and . map isNumber
changeTurn :: Player -> Player
changeTurn player
| player == P1 = P2
| otherwise = P1
calcPointsEarned :: Int -> Int -> Int
calcPointsEarned actualAnswer chosenAnswer
| offset == 0 = 5
| offset <= 2 = 3
| offset <= 3 = 1
| offset >= 7 = (-1)
| otherwise = 0
where offset = abs $ chosenAnswer - actualAnswer
calcPointsEarnedForPlayer :: Player -> Player -> Int -> Int
calcPointsEarnedForPlayer actualTurn player pointsEarned
| actualTurn == player = pointsEarned
| otherwise = 0
determineWinner :: Int -> Int -> Player
determineWinner p1Score p2Score
| p1Score > p2Score = P1
| otherwise = P2
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I'd contend that <code>State</code> is pure and functional, but I think translating your current code to use <code>State</code> is an excellent exercise so I'll leave that up to you.</p>\n<p>The first thing I'd address is making your types do more of the bookkeeping. Well designed types lend themselves to correct-by-construction solutions.</p>\n<pre><code>data Player = P1 | P2 deriving Show\n\ndata Game = Game { turn :: Player, p1 :: Int, p2 :: Int } deriving Show\n</code></pre>\n<p>Prefer pattern matching to equality testing, it is frequently more terse. Decreased line noise often means increased readability.</p>\n<pre><code>changeTurn :: Player -> Player\nchangeTurn P1 = P2\nchangeTurn P2 = P1\n</code></pre>\n<p>Your <code>determineWinner</code> function has a (currently unreachable) logic error. If both player's scores are equal then it prefers handing victory to player two. This may not matter in your code as written, but if your code changes or you begin property testing or some other unforeseeable future event comes to pass, it could begin mattering unexpectedly. Handling ties is “morally” the right thing to do.</p>\n<p>Also as-is it isn't really determining a winner by the rules of the game, only which player's score is higher.</p>\n<pre><code>winner :: Game -> Maybe Player\nwinner (Game _ p1 p2) =\n case (max p1 p2 >= 10, p1 > p2, p2 > p1) of\n (True, True, False) -> Just P1\n (True, False, True) -> Just P2\n (_, _ , _) -> Nothing\n</code></pre>\n<p>Don't validate and then parse, parse and allow for failure. If your validation code is separate from your parsing code you risk them drifting out of sync and causing errors. In this case, use <code>Text.Read.readMaybe</code> from <code>base</code> and leave out your <code>isInteger</code> function entirely.</p>\n<p>It's a good idea to separate as much of your pure game logic from IO actions as possible. It's easier to test, easier to understand, and enables you to reuse functionality you otherwise couldn't.</p>\n<pre><code>updateRound :: Int -> Game -> Game\nupdateRound n (Game P1 p1 p2) = Game P2 (boundScore $ p1 + n) p2\nupdateRound n (Game P2 p1 p2) = Game P1 p1 (boundScore $ p2 + n)\n\nclamp :: Ord a => a -> a -> a -> a\nclamp lo val hi = lo `max` val `min` hi\n\nboundScore :: Int -> Int\nboundScore n = clamp 0 n 10\n</code></pre>\n<p>This also obviates the need for <code>changeTurn</code>.</p>\n<p>It's also usually handy to separate your display logic from your control logic, even if both are <code>IO</code> actions. It might be useful to you if you make use of the REPL while developing, your types often shouldn't include multiple copies of the same information (e.g., two numbers and their difference) as that carries a risk of the values getting out of sync. Those derived values might be all you want to see while working though.</p>\n<pre><code>displayGame :: Game -> IO ()\ndisplayGame (Game _ p1 p2) = do\n putStrLn $ "P1 Score: " ++ show p1\n putStrLn $ "P2 Score: " ++ show p2\n</code></pre>\n<p>That said, it's good to separate your control logic from your sources of input and output also. It makes your program testable without needing to muck about with piping stdin and stdout. There's also a very elegant transformation when you decide to begin using <code>State</code>, but I'll leave that to you to figure out.</p>\n<pre><code>gameRound :: Int -> Int -> Game -> (Maybe Player, Game)\ngameRound guess answer game =\n let\n score = calcPointsEarned guess answer\n nextGame = updateRound score game\n in\n (winner nextGame, nextGame)\n\nreceiveGuess :: Player -> IO Int\nreceiveGuess player = do\n putStr $ show player ++ "'s turn. Pick a number between 1 and 10: "\n input <- getLine\n case readMaybe input of\n Nothing -> do\n putStrLn "The input must be an integer"\n receiveGuess player\n Just guess -> pure guess\n\nplay :: Game -> IO ()\nplay game = do\n answer <- randomRIO (1, 10)\n guess <- receiveGuess (turn game)\n putStrLn $ "The answer is " ++ show answer\n let (mPlayer, nextGame) = gameRound guess answer game\n displayGame nextGame\n case mPlayer of\n Just player -> putStrLn $ show player ++ " wins!"\n Nothing -> play nextGame\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T07:15:22.040",
"Id": "507719",
"Score": "1",
"body": "So much good advice here! I especially like your point about separating IO and control logic -- combining them diminishes the benefits of using a purely functional language. \nAlso, I took your advice to create the Game abstraction, and suddenly my type signatures are lot easy easier to understand. Thanks for the detailed response, it will be enough to keep me busy for a while :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T17:01:02.650",
"Id": "507859",
"Score": "0",
"body": "Glad I could help!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:14:01.653",
"Id": "256890",
"ParentId": "256861",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256890",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T22:41:49.067",
"Id": "256861",
"Score": "5",
"Tags": [
"beginner",
"haskell",
"functional-programming",
"random"
],
"Title": "Two player random number guessing game"
}
|
256861
|
<p>I work with the Oracle JGeometry method which returns (or takes as method argument) 2D segments as double array (x1,y1,x2,y2 ... xn,yn). I need to extend this array to contain 3D segments as double array (x1,y1,z1,x2,y2,z2 ... xn,yn,zn) by default Z value or reduce to 2D (by removing of all Z coordinate). I wrote simple utility methods for making this. Is there any easier or smarter way to do this?</p>
<p>The conversion from 2D to 3D:</p>
<pre><code>public static double[] to3D(double z, double[] inputArray) {
List<Double> convertedItems = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
convertedItems.add(inputArray[i]);
if ((i + 1) % 2 == 0) {
convertedItems.add(z);
}
}
return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}
</code></pre>
<p>The conversion from 3D to 2D:</p>
<pre><code>public static double[] to2D(double[] inputArray) {
List<Double> convertedItems = new ArrayList<>();
for (int i = 0; i < inputArray.length; i++) {
if ((i + 1) % 3 == 0) {
continue;
}
convertedItems.add(inputArray[i]);
}
return convertedItems.stream().mapToDouble(Double::doubleValue).toArray();
}
</code></pre>
|
[] |
[
{
"body": "<p>I would go with primitive Arrays, instead of using Collections and Streams in this case.</p>\n<pre><code>public static double[] to3D(double z, double[] in) {\n // Pre-allocated array 1.5 size of the original array\n double[] out = new double[in.length * 3 / 2];\n //loop with a step 2\n for (int i = 0, j = 0; i < in.length; i += 2) {\n out[j++] = in[i];\n out[j++] = in[i + 1];\n out[j++] = z;\n }\n return out;\n}\n\npublic static double[] to2D(double[] in) {\n // Pre-allocated array 2/3 size of the original array\n double[] out = new double[in.length * 2 / 3];\n //loop with a step 3\n for (int i = 0, j = 0; i < in.length; i += 3) {\n out[j++] = in[i];\n out[j++] = in[i + 1];\n }\n return out;\n}\n</code></pre>\n<p>Reasons for using arrays instead of lists: Input and output both are arrays, the target size is known, we only need basic operations and they would be faster in this case.</p>\n<p>I hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T11:59:15.847",
"Id": "507232",
"Score": "0",
"body": "Just a small remark: Starting with `j = -1` seems a bit ugly. Using post increment (`j++`) and starting with `j = 0` seems \"nicer\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:04:00.427",
"Id": "507247",
"Score": "0",
"body": "You are right, I just do it to avoid last unused post-increment, If you think it still should have that then you can edit it or tell me if I must, Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T15:49:01.087",
"Id": "507258",
"Score": "0",
"body": "You can include `int j = 0` directly inside the loop and you could explain why you are using arrays instead of lists (fixed cardinality of arrays)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:49:55.693",
"Id": "507290",
"Score": "0",
"body": "In this case `int j = 0` cannot be initialised inside loop because it needs incremented value in each iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:27:32.240",
"Id": "507298",
"Score": "0",
"body": "I badly explained it, I meant `for (int i = 0, j = 0; i < in.length; i += 3)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:34:04.250",
"Id": "507301",
"Score": "0",
"body": "If you want send a message to an user you have to use `@username` in your message , see [how-do-comment-replies-work](https://meta.stackexchange.com/questions/43019/how-do-comment-replies-work)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T11:23:19.740",
"Id": "507318",
"Score": "0",
"body": "@dariosicily - sure, thanks, edited the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T13:23:17.503",
"Id": "507336",
"Score": "0",
"body": "You are welcome."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T09:54:46.320",
"Id": "256865",
"ParentId": "256864",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T09:22:55.600",
"Id": "256864",
"Score": "1",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Java array extension/reduction"
}
|
256864
|
<p>I use the following code which works ok!</p>
<p>The code is installing helm charts in loop in k8s cluster, and I want to verify that I'm writing it ok.</p>
<pre><code>tmpfile, err := ioutil.TempFile(kp, kcp)
if err != nil {
log.Error(err, "error")
}
defer os.Remove(tmpfile.Name())
if _, err := tmpfile.Write(cfg); err != nil {
return err
}
if err := tmpfile.Close(); err != nil {
return err
}
kcfgFilePath := tmpfile.Name()
settings := cli.New()
ac := new(action.Configuration)
clientGetter := genericclioptions.NewConfigFlags(false)
clientGetter.KubeConfig = &kcfgFilePath
for _, chartInstallation := range charts {
chart, err := loader.Load(chartInstallation.Path)
if err != nil {
return err
}
releaseName := releaseName + "-" + chartInstallation.Name
if err := ac.Init(clientGetter, settings.Namespace(), os.Getenv("HELM_DRIVER"), func(format string, v ...interface{}) {
}); err != nil {
return err
}
releasePresent := true
statusAction := action.NewStatus(ac)
status, err := statusAction.Run(releaseName)
if err != nil {
if strings.Contains(err.Error(), driver.ErrReleaseNotFound.Error()) {
releasePresent = false
} else {
return err
}
}
if !releasePresent {
// install chart
installAction := action.NewInstall(ac)
installAction.CreateNamespace = true
installAction.Namespace = chartInstallation.Namespace
installAction.ReleaseName = releaseName
_, err := installAction.Run(chart, nil)
if err != nil {
return err
}
log.Info("chart installed: ", "releaseName", releaseName)
}
if status != nil {
if releasePresent && status.Info.Status.String() == release.StatusFailed.String() {
upgradeAction := action.NewUpgrade(ac)
upgradeAction.Wait = true
upgradeAction.ReuseValues = false
upgradeAction.Recreate = false
_, err := upgradeAction.Run(releaseName, chart, nil)
if err != nil {
return err
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>The error from <code>ioutil.TempFile</code> is unhandled, should also <code>return err</code> since everything after it won't work if the temporary file\ncouldn't be created.</li>\n<li>The <code>strings.Contains</code> check is definitely the least preferred option\nto check for the kind of error. If at all possible avoid it since\nit's actually fairly easy for that string to change with, say, a\nlibrary upgrade without any notice, which would break the logic here.</li>\n<li>Same with <code>status.Info.Status.String() == release.StatusFailed</code> - are\nyou sure it can't just be compared without the <code>String()</code> conversion?</li>\n<li><code>tmpfile.Name()</code> is used twice, could already be moved to a variable.</li>\n<li>In fact, one of <code>tmpfile</code> and <code>kcfgFilePath</code> is redundant, I'd suggest\ndirectly assigning to <code>kcfgFilePath</code>.</li>\n<li>IMO <code>new</code> is obsolete and could very well be replaced by a regular\nvariable declaration.</li>\n<li><code>statusAction</code> could be inlined.</li>\n</ul>\n<p>Actually it would be great if the imports were mentioned, that would\ngive readers a chance to find the actual signatures and such. Without\nthat I'll leave it at those points.</p>\n<p>Apart from these details it looks okay, though at some point you might\nwant to refactor things into smaller functions to bring a little order\ninto it. Right now it's still a rather long block of code. E.g. it\nmight be worth moving the inner part of the loop into a new function.\nOr creating functions for each "action" that's currently only marked\nwith a comment, say <code>runInstall</code>, <code>runUpgrade</code>. The temporary file bit\nat the start could also very well be its own function (keeping the\n<code>os.Remove</code> call at this level of course).</p>\n<p>Edit: As requested to elaborate on the second point, it's better to do a\ndirect comparison of error values instead of string comparisons, since\nthey're just values too, this will be faster and not depend on string\nvalues which might change in unexpected ways, like so:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>// this is defined in the helm API\nvar ErrReleaseNotFound error = errors.New("release: not found")\n\n// ...\n\n// some time later, we get an error\n{\n statusAction := action.NewStatus(ac)\n status, err := statusAction.Run(releaseName)\n if err != nil {\n if err == driver.ErrReleaseNotFound {\n releasePresent = false\n } else {\n return err\n }\n }\n\n // ...\n}\n</code></pre>\n<p><strong>But, actually</strong>, we should all probably <a href=\"https://tip.golang.org/pkg/errors/\" rel=\"nofollow noreferrer\">start using\n<code>errors.Is</code></a> so that even nested\nerrors would be correctly handled:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>// ...\nif errors.Is(err, ErrReleaseNotFound) {\n releasePresent = false\n} else {\n return err\n}\n// ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:44:51.020",
"Id": "507472",
"Score": "1",
"body": "Thanks a lot, 1+ , one remark, could you please provide an example for the second option ?`strings.Contains` how its better to use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T09:54:38.617",
"Id": "507570",
"Score": "0",
"body": "@bredstraruts added some, hope that helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T12:14:18.957",
"Id": "507586",
"Score": "1",
"body": "Thanks I learn a lot from you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-17T06:18:05.463",
"Id": "512200",
"Score": "0",
"body": "HI again , i've another question in that domain could you please have a look? thanks!https://codereview.stackexchange.com/questions/259652/installing-charts-in-parallel-using-go"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:26:05.723",
"Id": "256962",
"ParentId": "256869",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256962",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T10:42:34.637",
"Id": "256869",
"Score": "2",
"Tags": [
"beginner",
"go"
],
"Title": "Install helm chart automatically"
}
|
256869
|
<p>I'm just getting started with frontend development. I tried to make a pretty barebones cookie consent notice. I still don't fully understand flexbox and positioning, so the code is messy.</p>
<p>HTML:</p>
<pre><code> <button id="shownotice">Click to ask</button>
<div id="consent_elem" class="consent_notice" hidden="true">
<p>Are you fine with cookies?</p>
<div id="buttons">
<button class="consent_button" id="yes">Yes</button>
<button class="consent_button" id="no">No</button>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>#shownotice {
background-color: cyan;
border:0;
padding: 5px;
}
[hidden] { display: none !important; }
.consent_notice {
display: flex;
align-items: center;
justify-content: space-between;
position: fixed;
background-color: red;
bottom:0px;
left: 0px;
right: 0px;
overflow: auto;
}
#buttons {
display: flex;
margin-right: 10px;
flex-direction: column;
padding: 5px;
}
.consent_button {
margin: 5px;
background-color: gray;
border: 0;
padding: 3px;
}
</code></pre>
<p>JS:</p>
<pre><code>show_button = document.querySelector("#shownotice");
consent_elem = document.getElementById("consent_elem");
show_button.onclick = (e) => {
consent_elem.hidden = consent_elem.hidden ? false : true;
}
</code></pre>
|
[] |
[
{
"body": "<h1>IDs</h1>\n<p>Avoid IDs for styling. It's ok to use them to identify elements with JavaScript, but the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity\" rel=\"nofollow noreferrer\">specificity</a> in CSS can make structuring the styles tricky.</p>\n<p>Names such as <code>buttons</code>, <code>yes</code> and <code>no</code> are very generic, that could easily be needed more than once in a document.</p>\n<p>Also try to be more consistant with the style of classes/names/IDs. For example, <code>shownotice</code> has no underline, but <code>consent_notice</code> does. Consider using hyphens instead of an underlines in order to match the general style of CSS, which uses hyphens, as in <code>background-color</code>.</p>\n<h1>HTML</h1>\n<p><code>"true"</code> is not a valid value for the attribute for the attribute <code>hidden</code>. As a <a href=\"https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attribute\" rel=\"nofollow noreferrer\">boolean attribute</a> <code>hidden</code> is either present without a value (or, if you prefer use the value <code>"hidden"</code> as in <code>hidden="hidden"</code>) or not present. <code>hidden="false"</code>, for example, would still hide the element.</p>\n<h1>JavaScript</h1>\n<p>Declare your variables with <code>const</code> or <code>let</code> (or <code>var</code> if you need to support very old browsers).</p>\n<p>In JavaScript it is convention to write variable names in camelCase and not with underlines.</p>\n<p>You could be more consistent when retrieving elements by ID and use either <code>querySelector</code> or <code>getElementById</code>, but not both.</p>\n<p>Don't use <code>on...</code> properties to assign event handlers. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>addEventListener</code></a>.</p>\n<p>Use the boolean negator <code>!</code> to toggle boolean values:</p>\n<pre><code>consent_elem.hidden = !consent_elem.hidden;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T11:41:57.410",
"Id": "256873",
"ParentId": "256870",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256873",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T11:00:15.930",
"Id": "256870",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"html",
"css"
],
"Title": "Cookie consent box on button click"
}
|
256870
|
<p>In my application I have a class responsible to save in a file the current status of the application (model) when it change :</p>
<pre><code>public class BackupAgent
{
private readonly Model _model;
public BackupAgent(Model model)
{
_model = model;
_model.Changed += Save;
}
private void Save()
{
// serialize model and save it to a file
...
}
}
</code></pre>
<p>It works fine but when there is a lot of modification the file is written again and again.</p>
<p>I came out with a <code>RecurringActionHandler</code> that ensure that</p>
<ul>
<li>the <code>Save</code> method is not called twice in a minimum amount of time.</li>
<li>the <code>Save</code> method is always called (sooner or later) after a modification.</li>
</ul>
<p>It is used like that:</p>
<pre><code>public class BackupAgent
{
private readonly Model _model;
private readonly RecurringActionHandler _saveHandler;
public BackupAgent(Model model)
{
_model = model;
_saveHandler = new RecurringActionHandler(Save, TimeSpan.FromMilliseconds(100));
_model.Changed += RequestSave;
}
private void RequestSave() => _saveHandler.RequestCall();
private void Save()
{
// serialize model and save it to a file
...
}
}
</code></pre>
<p>Here is my current implementation:</p>
<pre><code>public class RecurringActionHandler
{
// Action to call recurrently
private readonly Action _action;
// a lock to protect _hasTask and _isCallRequested
private readonly object _lock = new();
// minimum time span between two calls to _action
private readonly TimeSpan _minimumRestTime;
// a boolean indicating whether a task is already running or not
private bool _hasTask;
// a boolean indicating whether a call to _action is request or not
private bool _isCallRequested;
public RecurringActionHandler(Action action, TimeSpan minimumRestTime)
{
_action = action;
_minimumRestTime = minimumRestTime;
}
public void RequestCall()
{
lock (_lock)
{
_isCallRequested = true;
if (_hasTask)
return;
_hasTask = true;
Task.Run(Work);
}
}
private async Task Work()
{
for (;;)
{
lock (_lock)
{
if (!_isCallRequested)
{
_hasTask = false;
break;
}
_isCallRequested = false;
}
_action();
await Task.Delay(_minimumRestTime).ConfigureAwait(false);
}
}
}
</code></pre>
<p>I'm looking for advice on the code and the method / class names. Is <code>Throttling</code> a matching name here ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:04:10.473",
"Id": "507248",
"Score": "0",
"body": "Why do you use re-entrant locking?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:28:43.260",
"Id": "507251",
"Score": "0",
"body": "@PeterCsala in case of a race on `RequestCall` (two calls from two differents threads), `Task.Run` can be called twice.Which is not desirable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:31:24.513",
"Id": "507252",
"Score": "0",
"body": "[Double-checked locking](https://en.wikipedia.org/wiki/Double-checked_locking) can prevent that to happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:48:00.737",
"Id": "507253",
"Score": "0",
"body": "@PeterCsala locking prevent that, Double-checked locking is an optimization of locking. I don't think I need it at this point but I can add it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T23:32:35.717",
"Id": "507526",
"Score": "0",
"body": "`save in a file the current status` why not just lock the file itself while it's open ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T23:32:36.000",
"Id": "507527",
"Score": "0",
"body": "`save in a file the current status` why not just lock the file itself while it's open ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T07:42:13.077",
"Id": "507555",
"Score": "0",
"body": "@iSR5 that is a detail in the implementation of the `Save` method. It's not related to the subject: the idea of postpone/\"merge\" calls to this method."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T11:05:57.900",
"Id": "256871",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Recurring action handler"
}
|
256871
|
<p>I work on a small Web Component that converts an amount of money to another currency. For that, I use an API that returns the exchange rates.</p>
<p>I want to use the component multiple times on a page and thought that it would be a waste of traffic if every component fetches the same exchange rates. So I wrote some logic that only the first handled component fetches it, stores the results in a window variable. The other components notice that some already loads the data and store a callback in that window variable. When the fetching is done all callbacks will be resolved.</p>
<p>This works great but I wonder if this is a bad practice or whether this is even unnecessary because maybe it is cached etc.</p>
<p>Code (the described part is in the "connectedCallback" function):</p>
<pre class="lang-js prettyprint-override"><code>const template = document.createElement('template');
template.innerHTML = `
<style>
.curr-shell {
color: #262626;
background: #F1F5F9;
border-radius: 16px;
padding: 4px 8px;
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
}
</style>
<span class="curr-shell"></span>`;
class CurrencyConverter extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
async fetchApi() {
return new Promise((resolve, reject) => {
fetch(`https://api.exchangeratesapi.io/latest?base=${this.baseCurrency}`)
.then((response) => response.json())
.then((data) => resolve(data))
.catch((err) => reject(err));
});
}
renderData() {
const browserLocale = navigator.language;
const originFormat = new Intl.NumberFormat(browserLocale, {
style: 'currency',
currency: this.baseCurrency,
});
const conversionFormat = new Intl.NumberFormat(browserLocale, {
style: 'currency',
currency: this.conversionCurrency,
});
const originAmount = originFormat.format(this.value);
this.convertedAmount =
this.value *
window.rates[this.baseCurrency].data.rates[this.conversionCurrency];
const conversionAmount = conversionFormat.format(this.convertedAmount);
this.shadowRoot.querySelector(
'.curr-shell'
).innerText = `${originAmount} | ${conversionAmount}`;
}
async connectedCallback() {
this.baseCurrency = this.getAttribute('base-currency');
this.value = parseFloat(this.getAttribute('value'));
this.conversionCurrency = this.getAttribute('conversion-currency');
if (!window.rates) window.rates = {};
if (!window.rates[this.baseCurrency]) {
// first one -> fetch api
window.rates[this.baseCurrency] = {
status: 'fetching',
data: null,
callbacks: [],
};
window.rates[this.baseCurrency].data = await this.fetchApi();
window.rates[this.baseCurrency].status = 'loaded';
this.renderData();
// resolve all callbacks from the waiting ones
window.rates[this.baseCurrency].callbacks.forEach((cb) => cb());
} else if (window.rates[this.baseCurrency].status === 'fetching') {
// currently some else is fetching -> add callback to be called when done
window.rates[this.baseCurrency].callbacks.push(() => this.renderData());
} else {
// all data loaded
this.renderData();
}
}
}
window.customElements.define('currency-converter', CurrencyConverter);
</code></pre>
<p>Demo: <a href="https://phartenfeller.github.io/currency-converter-wc/demo/" rel="nofollow noreferrer">https://phartenfeller.github.io/currency-converter-wc/demo/</a></p>
|
[] |
[
{
"body": "<p>From a super short review;</p>\n<ul>\n<li><p>I would attach the style tag to the head element, especially if you can have this element several times on the page (and ensure that you only add it once)</p>\n</li>\n<li><p>When all a fat arrow function does is call an another function with the provided parameter(s), then you might as well</p>\n<pre><code> .then(resolve)\n .catch(reject);\n</code></pre>\n<p>instead of</p>\n<pre><code> .then((data) => resolve(data))\n .catch((err) => reject(err));\n</code></pre>\n</li>\n<li><p>This will not work in a rainy day scenario;</p>\n<pre><code> window.rates[this.baseCurrency].data.rates[this.conversionCurrency];\n</code></pre>\n<p>Consider how you would handle this if <code>window.rates[this.baseCurrency]</code> is missing.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T11:57:18.280",
"Id": "256922",
"ParentId": "256874",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T12:25:11.953",
"Id": "256874",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Web Component prevent multiple API fetches"
}
|
256874
|
<p><strong>Task description:</strong></p>
<p>Declare a function twoInThree(a: Set, b: Set, c: Set), which returns the set of all elements, which are contained in <strong>exactly</strong> two of the three given sets a, b, c.</p>
<p><strong>My solution:</strong></p>
<pre><code>fun main(args: Array<String>) {
var a = setOf<Int>(1, 2, 5)
var b = setOf<Int>(2, 7, 0)
var c = setOf<Int>(3, 5)
val result = twoInThree(a, b, c)
println(result) // [2, 5]
}
fun twoInThree(a: Set<Int>, b: Set<Int>, c: Set<Int>): MutableSet<Int> {
var results = mutableSetOf<Int>()
var intersectOfAll = a.intersect(b).intersect(c)
val aIntersectB = a.intersect(b)
val aIntersectC = a.intersect(c)
val bIntersectC = b.intersect(c)
results.addAll(aIntersectB)
results.addAll(aIntersectC)
results.addAll(bIntersectC)
results.removeAll(intersectOfAll)
return results
}
</code></pre>
<p>If got the same result as the instructor and tried it with other sets. It always returned the expected result. So, I guess my solution is formally correct.</p>
<p>But: <strong>Could the exercise become solved in a better way?</strong></p>
|
[] |
[
{
"body": "<p>Before I go into another possible solution I will give you some suggestions on your current code:</p>\n<ul>\n<li><p>Use <code>val</code> instead of <code>var</code> whenever possible. This is possible for all variables in your code.</p>\n</li>\n<li><p>No need to specify <code><Int></code> on <code>setOf</code>, Kotlin can figure out the best applicable type itself.</p>\n</li>\n<li><p>The function <code>twoInThree</code> is capable of handling any kinds of sets, not just ints. You can use a generic type parameter for this.</p>\n<p>Change the method to <code>fun <T> twoInThree(a: Set<T>, b: Set<T>, c: Set<T>): MutableSet<T></code></p>\n<p>And naturally also <code>val results = mutableSetOf<T>()</code></p>\n</li>\n<li><p>Prefer to return immutable types unless you really need to do otherwise, in this case prefer to return a <code>Set</code> over <code>MutableSet</code> (callers don't need to care about the fact that you are using a MutableSet in your implementation)</p>\n</li>\n</ul>\n<hr />\n<h3>The approach</h3>\n<p>Your approach involves checking for multiple intersections and then creating a union of all sets and removing the intersection of all sets.</p>\n<p>The assignment is about finding elements which exists in <strong>exactly two</strong> of the three given sets a, b, c.</p>\n<p>Your approach is fine, there's nothing wrong with it, <em>but</em>... Will it scale?</p>\n<p>If you would check for elements which exists in all three of the sets, or in exactly one set, that could be done quite easily by returning different intersections and unions and so on. But what if there would be five sets?</p>\n<p>The assignment is about <strong>exactly two</strong> of the three sets.</p>\n<p>One, <strong>two,</strong> three.</p>\n<p>We can use counting!</p>\n<p>By counting the number of times each element appears, we can iterate over all sets (no matter if it's three, five, or twenty) exactly once.</p>\n<p>By counting the number of times each element appears, we can easily change the code to return elements that occur only once, twice, or three times.</p>\n<p>So how to do this?</p>\n<hr />\n<h3>My approach</h3>\n<p>Start with creating a list of all sets. <code>listOf(a, b, c)</code></p>\n<p>Then go through the list and map each set to all its elements. <code>.flatMap { it }</code> which can also be written as <code>.flatten()</code></p>\n<p>Then create a grouping of the elements <code>.groupingBy { it }</code></p>\n<p>Then create a map with the counts of each element <code>.eachCount()</code></p>\n<pre><code>listOf(a, b, c).flatten().groupingBy { it }.eachCount()\n</code></pre>\n<p>This gives you a map <code>Map<Int, Int></code> where the keys are the elements and the values are the number of times each element occurs.</p>\n<p>Now you can filter this map and return the keys which matches your requirement <code>.filter { it.value == 2 }.map { it.key }</code></p>\n<p>Full code:</p>\n<pre><code>val result = listOf(a, b, c).flatten()\n .groupingBy { it }\n .eachCount()\n .filter { it.value == 2 }\n .map { it.key }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T18:06:36.753",
"Id": "256885",
"ParentId": "256875",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256885",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:33:24.837",
"Id": "256875",
"Score": "2",
"Tags": [
"collections",
"kotlin"
],
"Title": "An exercise concering Kotlin Set"
}
|
256875
|
<p>I am doing exercise 1-13 of K&R. The problem is to print a histogram of the lengths of words in the input. This is the easier problem, printing the histogram with horizontal bars. This is what I came up with. Is there a better way to do this? Are there any bugs?</p>
<pre><code>#include <stdio.h>
#define MAXLEN 10
int main(){
int c,length;
int hist[MAXLEN+1];
length=0;
for(int i=0;i<MAXLEN+1;i++) hist[i]=0;
while((c=getchar())!=EOF){
if((c==' ' || c=='\t' || c=='\n') && length){
if(length>MAXLEN)
hist[MAXLEN]++;
else
hist[length-1]++;
length=0;
}
else if(c!=' ' && c!='\t' && c!='\n')
length++;
}
//to deal with situations in which input doesn't end in a space or newline or tab
if(length>MAXLEN)
hist[MAXLEN]++;
else if(length)
hist[length-1]++;
//printing the histogram horizontally
putchar('\n');
for(int i=0;i<MAXLEN;i++){
printf("%3d|",i+1);
for(int j=0;j<hist[i];j++) putchar('x');
putchar('\n');
}
printf(">%d|",MAXLEN);
for(int i=0;i<hist[MAXLEN];i++) putchar('x');
putchar('\n');
}
</code></pre>
|
[] |
[
{
"body": "<h1>Declare and initialize variables in one go</h1>\n<p>You can initialize a value at the same time you declare it. This even works for <code>struct</code>s and arrays. For example:</p>\n<pre><code>int main() { \n int c = 0;\n int length = 0;\n int hist[MAXLEN+1] = {0}; // Initializes all elements to 0\n\n while ((c = getchar()) != EOF) {\n ...\n</code></pre>\n<h1>Use <code>isspace()</code></h1>\n<p>Instead of manually checking against spaces, tabs and newlines, use <a href=\"https://en.cppreference.com/w/c/string/byte/isspace\" rel=\"nofollow noreferrer\"><code>isspace()</code></a> from <code><ctype.h></code>.</p>\n<h1>Split your code into multiple functions</h1>\n<p>Even for a simple program like this, it is a good exercise to split the code into multiple functions, and reduce the responsibility of each function as much as possible. This way for example, <code>main()</code> could be reduced to:</p>\n<pre><code>int main() {\n int hist[MAXLEN + 1] = {0};\n\n build_histogram(hist, MAXLEN);\n print_histogram(hist, MAXLEN);\n}\n</code></pre>\n<p>Then <code>build_histogram()</code> could be written like this:</p>\n<pre><code>static void build_histogram(int hist[], size_t hist_size) {\n int c;\n int length = 0;\n\n while ((c=getchar())!=EOF) {\n if (isspace(c)) {\n add_word(hist, hist_size, length);\n length = 0;\n } else {\n length++;\n }\n }\n\n add_word(hist, hist_size, length);\n}\n</code></pre>\n<p>So its main function is to scan for words. Then <code>add_word()</code> does the actual work of recording the length of a word in the histogram:</p>\n<pre><code>static void add_word(int hist[], size_t hist_size, size_t length) {\n if (length > hist_size)\n hist[hist_size]++;\n else if (length)\n hist[length - 1]++;\n}\n</code></pre>\n<p>You can use a similar approach for <code>print_histogram()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T04:08:03.287",
"Id": "507282",
"Score": "0",
"body": "I would like to use all of these and i know functions too but at this point of the book those features haven't been taught"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:58:15.887",
"Id": "507294",
"Score": "1",
"body": "I noticed you wrote `for (int i=0; ...)`, that is not K&R C, but C99. Are you sure you are only using features taught by the book, and does that even matter in the long run?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T12:31:36.623",
"Id": "507325",
"Score": "0",
"body": "No it doesn't matter. But i am just trying follow along with the book. and i am realizing that it doesn't matter in this example, more so, bcz encapsulating the code into functions isn't providing any extra functionality to me so it is valid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T21:19:52.637",
"Id": "511209",
"Score": "0",
"body": "@aritra Encapsulating the code into functions may not provide any value to _you_. That's ok since you are in a unique position, as you are the author of this code. Everyone else isn't, and splitting the code into functions is a benefit for these readers. When they read such a function they can quickly see what the function is supposed to do and can guess whether it really does that. This is much more difficult if a large function consists entirely of fine-grained variable assignments that repeat over and over."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T18:56:52.640",
"Id": "256887",
"ParentId": "256876",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T14:52:50.553",
"Id": "256876",
"Score": "3",
"Tags": [
"c"
],
"Title": "K&R histogram of length of words"
}
|
256876
|
<p>I have a following abstract class <code>Listener</code> which encapsulates boiler plate code for a client. I can then have multiple listener for various events.</p>
<p>As a self learning excersice I converted this to functional way.</p>
<ol>
<li>Is this is correct way to implement in functional way?</li>
<li>I am trying to avoid creating class for each type of listener</li>
<li>Should I use type or interface. As this is used for type checking of parameters, I am not sure if one is prefered over other</li>
<li>Any other comments on implementing functional way (currying, higher order functions)? As a noob I am trying to learn if those are applicable here and how.</li>
</ol>
<pre><code>abstract class Listener {
abstract subject: string;
private client: Client;
abstract groupName: string;
protected ackTimeout = 5 * 1000;
abstract onMessage(data: any, msg: Message): void;
constructor(client: Client) {
this.client = client;
}
private subscriptionOptions(): SubscriptionOptions {
return this.client.subscriptionOptions()
.setOption1()
.setOption2(this.ackTimeout)
.setOption2(true)
.setDurableName(this.groupName);
}
listen(): void {
const subscription = this.client.subscribe(this.subject, this.groupName, this.subscriptionOptions())
subscription.on('message', (msg: Message) => {
console.log(`Message Received: ${this.subject}/${this.groupName}`);
const parsedData = this.parseMessage(msg);
this.onMessage(parsedData, msg);
});
}
private parseMessage(msg: Message): any {
const data = msg.getData();
return typeof data === 'string' ? JSON.parse(data) : JSON.parse(data.toString('utf-8'));
}
}
// EventType Listener
class EventCreated extends Listener {
groupName: string = 'event:created';
subject: string = 'event-service';
onMessage(data: any, msg: Message): void {
// Do something with data
console.log(`Received `, data);
msg.acknowledge();
}
}
</code></pre>
<p>Functional Way</p>
<pre><code>type Listener = {
client: Client,
subject: string,
groupName: string,
ackTimeout: number
onMessage(data: string, msg: Message): void;
listen(): void;
parseMessage(msg: Message): string;
clientOptions(): ClientOptions
}
interface ListenerOptions {
subject: string,
groupName: string,
onMessage(data: any, msg: Message): void;
parseMessage(msg: Message): string
ackTimeout?: number,
}
const createListener = (client: Client, options: ListenerOptions): Listener => {
options.ackTimeout = options.ackTimeout || 5 * 1000;
return {
client,
groupName: options.groupName,
ackTimeout: options.ackTimeout,
subject: options.subject,
onMessage: options.onMessage,
listen: function () {
const subscription = this.client.subscribe(this.subject, this.groupName, this.clientOptions())
subscription.on('message', (msg: Message) => {
console.log(`Message Received: ${this.subject}/${this.groupName}`);
const parsedData = this.parseMessage(msg);
this.onMessage(parsedData, msg);
},
parseMessage: options.parseMessage || function (msg: Message): string {
const data = msg.getData();
return typeof data === 'string' ? JSON.parse(data) : JSON.parse(data.toString('utf-8'));
},
clientOptions: function (): ClientOptions {
// this.client.clientOptions to set various options as per external library
return this.client.clientOptions()
.setOption1(true)
.setOption2()
.setAckTimeout(this.ackTimeout)
.setGroup(this.groupName);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T05:25:22.943",
"Id": "507283",
"Score": "0",
"body": "What do you do with the listener object once it is created?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:51:40.670",
"Id": "507473",
"Score": "0",
"body": "@selpic: `listen` method on the object is called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:28:21.217",
"Id": "507501",
"Score": "0",
"body": "called by who? Please show some consumer code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T15:22:16.693",
"Id": "256877",
"Score": "0",
"Tags": [
"functional-programming",
"typescript"
],
"Title": "Typescript from Class to functional programming"
}
|
256877
|
<p>I've done a program and it works fine as I want to but I feel it could be better and more advanced so I want some master advice on my program which is going to take many numbers and return the number with the most prime divisors and the number of its divisors in front of the number like this <code>678 3</code> as the output</p>
<p>code :</p>
<pre><code>list_of_inputs = []
for elements in range(5):
list_of_inputs.append(int(input()))
list_of_inputs = list(set(list_of_inputs))
def _check_prime_sample_(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
def find_integer_with_most_divisors(input_list):
from operator import itemgetter
lis = []
dic = {}
for elements in input_list:
sub_lis = []
for items in range(1, elements):
if elements % items == 0 and _check_prime_sample_(items) == True:
sub_lis.append(items)
lis.append(len(sub_lis))
dic[elements] = len(sub_lis)
tup = [(k, v) for k, v in dic.items()]
sup = max(tup, key=itemgetter(1, 0))
print('{} {}'.format((sup)[0], (sup)[1]))
find_integer_with_most_divisors(list_of_inputs)
</code></pre>
|
[] |
[
{
"body": "<p>In this example, your code is used as the starting point. I moved the logic\naround a bit -- notably, separating things into other functions -- and\nsuggested various other changes for you to consider.</p>\n<pre><code># Except for special reasons, put all imports at the top.\nimport math\nimport sys\n\n# Put almost all code inside functions.\n\ndef main(args):\n\n # When feasible, use variable names that sound like ordinary English (eg,\n # inputs) rather than awkward computer-science-like names (eg,\n # list_of_inputs). Similarly, if a variable holds one thing, use a singular\n # variable name (eg, num, book, or x). And if the variable holds a\n # collection of things, use plural (eg, nums, books, or xs).\n\n # Also, list/set/dict comprehensions can often make code easier to\n # understand, especially when they are fairly short.\n\n # For scripts like this, it's often useful to allow the possibility for\n # command-line arguments.\n\n if args:\n nums = [int(a) for a in args]\n else:\n # Provide users at least some minimal guidance.\n prompt = 'Integer: '\n nums = [int(input(prompt)) for _ in range(5)]\n\n # Computing the number with the most divisors is pure mathematical\n # algorithm: keep it that way. The function should do its work and return a\n # value. Do the printing elsewhere -- for example, in main().\n\n # By default, print() takes a list of values and prints them\n # separated by spaces. If that's all you need, there's\n # no reason to use a format string.\n\n num, n_divisors = find_integer_with_most_divisors(nums)\n print(num, n_divisors)\n\n# If a function returns True/False, intuitive names often take the\n# form of is_X, has_X, contains_X, and so forth.\n\ndef is_prime(n):\n if n < 2:\n return False\n # You don't need to check beyond the square root of N.\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return False\n return True\n\n# Your version of this function used some good techniques, but it was more\n# complex and harder to understand than necessary, mostly because the function\n# was doing too many jobs at the same time: computing divisors for each number,\n# finding the number with the most divisors, and reporting to the user. Keeping\n# things separate often increases flexibly and code clarity.\n\n# Let's start by moving the divisor computation to its own function. Again, we\n# only need to check up to square root. There are faster ways to compute\n# divisors, but this example prioritizes simplicity.\n\ndef divisors(n):\n divs = {1, n}\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n divs.add(i)\n divs.add(n // i)\n return sorted(divs)\n\n# Now the program's primary function because very easy to write and understand.\n# Also, we continue with the theme of selecting variable names that approximate\n# ordinary English-language usage.\n\ndef find_integer_with_most_divisors(nums):\n counts = []\n for num in nums:\n divs = divisors(num)\n primes = [d for d in divs if is_prime(d)]\n # If you put the count first in the tuple, functions like\n # sort(), max(), min() will work exactly as desired.\n counts.append((len(primes), num))\n count, num = max(counts)\n return (num, count)\n\n# Invoke main() with any command-line arguments, if the code was executed as a\n# script. If the code is imported, main() won't be called. This device makes\n# your script easier to test.\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T18:32:34.453",
"Id": "256886",
"ParentId": "256878",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256886",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T15:26:44.003",
"Id": "256878",
"Score": "1",
"Tags": [
"python"
],
"Title": "number with the most prime divisors"
}
|
256878
|
<p>I want to execute a number of tasks that may enqueue other tasks, and do all that in parallel, ending only once all tasks are finished.</p>
<p>For example, some sort of crawler that starts with node A, discovers B, C, and D, then visits each of those and discovers other adjacent nodes.</p>
<p>If one task has an error, that error should be raised on the main thread.</p>
<p>My primary concerns are correctness and simplicity.</p>
<p>AFAIK, this is simplest way to do that, even with the new standard libraries like <code>concurrent.futures</code>.</p>
<pre class="lang-py prettyprint-override"><code>import queue
import threading
class WorkerRunner:
"""
Runner
:param int parallelism: Number of workers to run in parallel
:param handler: Handler that receives work and optionally yields other work
"""
def __init__(self, parallelism: int, handler):
self._handler = handler
self._parallelism = parallelism
def run(self, items):
queue_ = queue.Queue()
threads = []
for _ in range(self._parallelism):
thread = WorkerThread(queue_, self._handler)
thread.start()
threads.append(thread)
for item in items:
queue_.put(WorkItem(item))
queue_.join()
for _ in range(self._parallelism):
queue_.put(END_ITEM)
for thread in threads:
thread.result()
"""
End item
"""
END_ITEM = None
class WorkItem:
def __init__(self, value):
self.value = value
class WorkerThread(threading.Thread):
def __init__(self, queue: queue.Queue, handler):
super().__init__()
self._queue = queue
self._exception = None
self._handler = handler
def run(self):
try:
self._work()
except Exception as e:
self._exception = e
while True:
try:
self._queue.get(False)
except queue.Empty:
break
else:
self._queue.task_done()
print("here")
def result(self):
self.join()
if self._exception is not None:
raise self._exception
def _work(self):
while True:
item = self._queue.get()
try:
if item is END_ITEM:
break
result = self._handler(item.value)
if result is not None:
for item in result:
self._queue.put(WorkItem(item))
finally:
self._queue.task_done()
</code></pre>
<h2>Example</h2>
<pre class="lang-py prettyprint-override"><code>def work(x: int):
print(x)
while 0 < x:
x -= 1
yield x
runner = WorkerRunner(2, work)
runner.run([3])
# 3
# 2
# 1
# 0
# 0
# 1
# 0
# 0
</code></pre>
|
[] |
[
{
"body": "<p>Perhaps I got off track somehow, but I found <code>run()</code> and\n<code>_work()</code> difficult to understand. I was puzzled by the decision to use\ntwo methods rather than one, I did not immediately grasp why two layers\nof exception handling were needed, and the intent behind\nthe <code>while True</code> loop in <code>run()</code> wasn't immediately obvious.</p>\n<p>Here are a few possible edits intended to simplify and clarify. Unless\nI overlooked a detail, the edits:</p>\n<ol>\n<li>do little more than move your\nlines of code around, putting everything under <code>run()</code> other than\nthe completely separable stuff moved to <code>_drain_queue()</code>;</li>\n<li>rename\n<code>result</code> to <code>work_items</code> for clarity; and</li>\n<li>add a few short comments to\nprovide some simple narrative guidance to any future code readers.</li>\n</ol>\n\n<pre><code>def run(self):\n while True:\n # Get next work item, stopping on the sentinel.\n item = self._queue.get()\n if item is END_ITEM:\n break\n\n # Run the handler, enqueuing any work items it yields.\n try:\n work_items = self._handler(item.value)\n if work_items:\n for item in work_items:\n self._queue.put(WorkItem(item))\n\n # On error, store exception and drain queue.\n except Exception as e:\n self._exception = e\n self._drain_queue()\n\n # Either way, mark current task done.\n finally:\n self._queue.task_done()\n\ndef _drain_queue(self):\n while True:\n try:\n self._queue.get(False)\n except queue.Empty:\n break\n else:\n self._queue.task_done()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T01:20:14.703",
"Id": "256906",
"ParentId": "256881",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T17:02:06.963",
"Id": "256881",
"Score": "5",
"Tags": [
"python",
"multithreading"
],
"Title": "Dynamic number of runnable tasks"
}
|
256881
|
<p>I have the function below, I want to access the context globally and I don't know if it's a good idea, I'm getting the context from the Application, I have TestAppliction in the test environment and I don't have access to the Application class, so I decided to add an optional context parameter to my function.</p>
<pre class="lang-dart prettyprint-override"><code>String getErrorMessage(DioError error, {BuildContext context}) {
String rawMessage = _getAnalyzedMessage(error);
GlobalKey navKey = Application.navKey;
if (navKey != null && navKey.currentContext != null)
context = Application.navKey.currentContext;
if (context != null)
return AppLocalizations.of(context).translate(rawMessage);
else
return rawMessage;
}
</code></pre>
<p>Is this a good idea?</p>
|
[] |
[
{
"body": "<p>By adding separate logic for your test case you are making it less representative of the code you are trying to test.</p>\n<p>If <code>AppLocalizations.of(null)</code> returned an identity translator, then you could remove the final if statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T22:19:53.553",
"Id": "256899",
"ParentId": "256888",
"Score": "1"
}
},
{
"body": "<p>Do it the other way around. Pass the second argument always from outside - in both the tests and the real use case.</p>\n<p>It doesn't have to be a second parameter of a static function though. You can promote it to an instance method and pass the context to constructor of such class, if that makes it easier to consume...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T05:16:54.000",
"Id": "256909",
"ParentId": "256888",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256909",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:08:39.163",
"Id": "256888",
"Score": "-1",
"Tags": [
"unit-testing",
"dart",
"flutter"
],
"Title": "Should I add optional parameter to my function for test cases?"
}
|
256888
|
<p>I have took the advice on some people and improved my dhondt method calculator, which is a system that takes a file of data for a number of political parties and try to find which party to assign seats too, and this all depending on how many seats the data file wants to assign and the total votes for each party. Can someone tell me if i have used encapsulation and abstraction efficiently and if not any further tips would help thanks.</p>
<p>MAIN</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Voting_System
{
class Program
{
static void Main(string[] args)
{
// Make new object of file handler to get all required data and get the file path
FileHandler partiesData = new FileHandler();
string filePath = partiesData.getFilePath();
// Make list of party classes to hold all parties from the sorted data
List<Party> parties = partiesData.SortPartiesData();
// Calculations for Dhond't method, takes list of parties and file path
CalculateDhondt(parties, partiesData.TitleOfElection, partiesData.NumOfSeatAllocation);
// Safely exit out the console once finished
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey(true);
Environment.Exit(0);
}
// Main method which calculaties which party to award seats too,and display those parties
private static void CalculateDhondt(List<Party> parties, string electionTitle, int numOfSeatAllocations)
{
// Find total votes for all parties and number of seats to be allocated
// Keep looping through partys and applying dhond't method until all seats are taken
int totalSeatsCount = 0;
while (totalSeatsCount != numOfSeatAllocations)
{
// If we havent reached desired seats count reset the total seats variable
totalSeatsCount = 0;
Party biggestVotes = parties.Aggregate((v1, v2) => v1.NewVotes > v2.NewVotes ? v1 : v2);
biggestVotes.SeatsAmount += 1;
biggestVotes.DivideParty();
// Check total seats for all parties
foreach (Party party in parties)
{
totalSeatsCount += party.SeatsAmount;
}
}
Console.WriteLine($"\n{numOfSeatAllocations} seats successfully allocated :\n{electionTitle}");
// Display parties who are awarded a seat
foreach(Party p in parties)
{
if(p.HasSeats())
{
Console.WriteLine(p);
}
}
}
}
}
</code></pre>
<p>FILE HANDLER class</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Voting_System
{
class FileHandler
{
public string FilePath { get; private set; }
public string TitleOfElection { get; private set; }
public int NumOfSeatAllocation { get; private set; }
// Takes input of the name of the data file and outputs the required data
public List<Party> SortPartiesData()
{
// Reads from the data file the user inputs
List<string> file = File.ReadAllLines(Path.GetFullPath(Path.Combine(@"..\..\..\..\" + FilePath))).ToList();
List<Party> parties = new List<Party>();
NumOfSeatAllocation = Convert.ToInt32(file[1]);
TitleOfElection = file[0];
// Store required values from data file for each party in a list of Party class
foreach (string line in file.Skip(3))
{
string[] items = line.Split(',');
Party p = new Party(items[0], Convert.ToInt32(items[1]), items.Skip(2).ToArray());
parties.Add(p);
}
return parties;
}
public string getFilePath()
{
Console.WriteLine("Type the name of the text file your data is held : ");
string fileName = Console.ReadLine() + ".txt";
FilePath = fileName;
return FilePath;
}
}
}
</code></pre>
<p>PARTY class</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Voting_System
{
class Party
{
// Fields
public string Name { get; private set; }
public int Votes { get; private set; }
public int NewVotes { get; private set; }
public string[] SeatsCodeValues { get; private set; }
private int _seatsAmount;
// Properties
public int SeatsAmount
{
get { return _seatsAmount; }
set
{
if (value > 0)
{
_seatsAmount = value;
}
}
}
// Constructor for party class,which takes inputs and assigns them to properties
public Party(string name, int votes, string[] seatsCodeValues)
{
Name = name;
Votes = votes;
NewVotes = votes;
SeatsCodeValues = seatsCodeValues;
}
// Returns percentage of votes for your party
public double PercentOfVotes(double totalVotes) => (Votes / totalVotes) * 100;
// When ever you print the object of this class return this
public override string ToString()
{
return $"Name: {Name}, Votes: {Votes} - {string.Join(",", SeatsCodeValues.Take(SeatsAmount))};";
}
// Applies Dhond't method of division
public void DivideParty() => NewVotes = Votes / (1 + SeatsAmount);
public bool HasSeats() => SeatsAmount > 0 ? true : false;
}
}
</code></pre>
<p>INPUT DATA FILE</p>
<pre><code>#East Midlands (European Parliament Constituency)
5
1183227
Brexit Party,452321,BP1,BP2,BP3,BP4,BP5;
Liberal Democrats,203989,LD1,LD2,LD3,LD4,LD5;
Labour,164682,LAB1,LAB2,LAB3,LAB4,LAB5;
Conservative,126138,CON1,CON2,CON3,CON4,CON5;
Green,124630,GR1,GR2,GR3,GR4,GR5;
UKIP,58198,UKP1,UKP2,UKP3,UKP4,UKP5;
Change UK,41117,CUK1,CUK2,CUK3,CUK4,CUK5;
Independent Network,7641,INET1,INET2,INET3,INET4,INET5;
Independent,4511,IND1;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:35:07.533",
"Id": "507311",
"Score": "0",
"body": "@BCdotWEB my bad,fixed now"
}
] |
[
{
"body": "<p>Here are some of my observations:</p>\n<h3><code>Main</code></h3>\n<ul>\n<li><code>string filePath = partiesData.getFilePath();</code>\n<ul>\n<li><code>filePath</code> is unused because the method has a side effect (it sets the <code>FilePath</code> property)</li>\n<li><code>getFilePath</code> should be renamed to <code>GetFilePath</code></li>\n</ul>\n</li>\n<li><code>//Make list of party classes to hold all parties from the sorted data</code>\n<ul>\n<li>Please do not comment each line</li>\n<li>If you think that your method does not have expressive name than rename it</li>\n<li>Comment should capture the <strong>why</strong>s and <strong>why not</strong>s</li>\n<li>The <strong>what</strong> and <strong>how</strong> should be clear from your code</li>\n</ul>\n</li>\n<li><code>Environment.Exit(0);</code>\n<ul>\n<li>It is unnecessary because that's the default return value</li>\n<li>This method is useful when you early exit (for example some precondition is not met)</li>\n</ul>\n</li>\n</ul>\n<h3><code>CalculateDhondt</code></h3>\n<ul>\n<li><code>List<Party> parties</code>: If you want to express your intent that you don't want to change the parameter then you can use <code>IReadOnlyCollection<Party> parties</code></li>\n<li>The calculation and the display logic are still inside the same method.\n<ul>\n<li>Either split it or rename it to reflect its implementation.</li>\n</ul>\n</li>\n<li><code>totalSeatsCount</code> calculation can be simplified:\n<ul>\n<li><code>totalSeatsCount = parties.Sum(party => party.SeatsAmount)</code></li>\n</ul>\n</li>\n<li><code>foreach</code> + <code>if</code> can be combined:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (var party in parties.Where(p => p.HasSeats())) Console.WriteLine(party);\n</code></pre>\n<h3><code>FileHandler</code></h3>\n<ul>\n<li>Its name is way too general although its implementation is way too specific</li>\n<li><code>SortPartiesData</code>: I can't see any sorting so its name is misleading\n<ul>\n<li><code>ParseParties</code> might be sufficient</li>\n</ul>\n</li>\n<li><code>List<string> file</code>: <code>ReadAllLines</code> returns an array of string, which is sufficient in this case\n<ul>\n<li>So, do not call <code>ToList</code></li>\n</ul>\n</li>\n<li><code>Path.Combine(@"..\\..\\..\\..\\" + FilePath)</code>:\n<ul>\n<li>This is super fragile and super specific</li>\n<li>You have assumed that the <code>FilePath</code> has been set via <code>getFilePath</code>.</li>\n<li>You can't make this kind of assumptions because you don't know how your users will call your methods.\n<ul>\n<li>Will they call at all?</li>\n<li>Will they call in the appropriate order?????</li>\n</ul>\n</li>\n<li>If you allow to your users to specify the file name then please make sure that the given file exist before you try to work with it.\n<ul>\n<li><a href=\"https://learning.oreilly.com/library/view/writing-secure-code/0735617228/ch10.html\" rel=\"nofollow noreferrer\">all input is evil until proven otherwise</a>.</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><code>NumOfSeatAllocation = Convert.ToInt32(file[1])</code>: Yet again extremely fragile.\n<ul>\n<li>You trust blindly on the position of the data and its type as well.</li>\n<li>Don't do that please check, check and check.</li>\n</ul>\n</li>\n<li>The whole <code>foreach</code> can be rewritten with the following LINQ:\n<ul>\n<li><em>It has a lots of assumptions as well</em></li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>return file.Skip(3)\n .Select(line => line.Split(','))\n .Select(items => new Party(items[0], Convert.ToInt32(items[1]), items.Skip(2).ToArray()))\n .ToList();\n</code></pre>\n<h3><code>Party</code></h3>\n<ul>\n<li><code>private set</code>: You can remove all of these except the one which is used at the <code>NewVotes</code></li>\n<li><code>//Fields</code>: These are properties as well</li>\n<li><code>PercentOfVotes</code>: This method is unused</li>\n<li><code>if (value > 0)</code>: Why do you need this?</li>\n</ul>\n<hr />\n<p><strong>UPDATE</strong>: <code>List</code> vs <code>IReadOnlyCollection</code></p>\n<p>There is a well-known security principle: <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_privilege\" rel=\"nofollow noreferrer\">least privilege</a>. It says that we should aim for the minimal set of rights. For example: if we don't want to modify something then it is enough for acquiring only read rights.</p>\n<p>In this particular case IReadOnlyCollection says that the collection itself is immutable from the method perspective. So, we can't add new items or remove existing ones from it.</p>\n<p>Why is this good? In case of concurrency multiple threads can read the same collection if they are not modifying it. If the method itself tells to the consumer that it won't change the collection then it will help the consumer to be able to decide whether or not additional synchronization is needed or not.</p>\n<p>On the other hand there is another well-known principle: <a href=\"https://devopedia.org/postel-s-law\" rel=\"nofollow noreferrer\">Postel's Law</a> : <em>Be liberal in what you accept, and conservative in what you send</em>. In other words you should accept <code>IEnumerable</code> and return with <code>IReadOnlyCollection</code>.</p>\n<p>At the first sight it may seem contradictory. But if you return with an IReadOnlyCollection from the <code>SortPartiesData</code> then it make sense.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T16:38:58.090",
"Id": "507367",
"Score": "0",
"body": "Thanks for the help! , regarding the IReadOnlyCollection<Party> parties can you explain why this is needed? bit confused.Also the data given to us has been said it will always been in the exact same format so that why its kind of hard coded. But thank you for all the other adivce!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T16:41:21.077",
"Id": "507369",
"Score": "0",
"body": "Would you suggest changing Path.Combine(@\"..\\..\\..\\..\\\" + FilePath): and putting the file into bin>debug and just using File.ReadAllLines(\"input.txt\"); instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:19:49.170",
"Id": "507420",
"Score": "0",
"body": "@Mj_ I've extended my answer with details about `List` vs `IReadOnlyCollection`, please check it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:23:51.557",
"Id": "507421",
"Score": "0",
"body": "If you specify the `Copy to Output Directory` to `Copy Always` then the file reside next to the application. If you want to provide flexibility then accept absolute path (as the user input) and then call [File.Exists](https://docs.microsoft.com/en-us/dotnet/api/system.io.file.exists). If it does not exist then ask a new one until the user provides a valid file path."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:36:59.597",
"Id": "507423",
"Score": "1",
"body": "Or even simpler: `parties.Where(x => x.HasSeats()).Select(x => Console.WriteLine(x))`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T15:59:59.933",
"Id": "256932",
"ParentId": "256891",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:32:15.390",
"Id": "256891",
"Score": "0",
"Tags": [
"c#",
"object-oriented"
],
"Title": "My Updated dhondt (political voting system) method implementation in C#"
}
|
256891
|
<p>I am messing around with the sklearn ML library to see if i can "predict" stocks with it, currently when it takes all the datapoints i have, it "predicts" it but i am trying to get it to predict into like the future.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import AdaBoostRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR
from numpy import loadtxt
from matplotlib.dates import datestr2num
from datetime import datetime, date
from sklearn.ensemble import AdaBoostRegressor
import csv
print("imported libraries")
amt = 2516
forecast = 230
#converters = {0: datestr2num}
X = np.loadtxt(fname="dates.csv", dtype="float", delimiter=",")
y = np.loadtxt(fname="PredictionEngineTestDatabase.csv", dtype='float', delimiter=",")
print("imported y and X")
from sklearn.model_selection import train_test_split
validation_size = 0.15
seed = 7
X_train, X_validation, Y_train, Y_validation = train_test_split(X, y, test_size=validation_size, random_state=seed)
print("Test Train Split Created")
#import csv
#with open('dates2.csv', newline='') as datesfile:
# datereader = csv.reader(datesfile, delimiter=',', quotechar='|')
# for dt in datereader:
# datetime_object = datetime.strptime(dt, "%Y-%m-%d")
# timestamp = datetime.timestamp(datetime_object)
# np.append(y, int(timestamp))
# print("DateTime Stored")
svm = SVR(kernel='rbf', C=1e3, gamma=0.2, cache_size=6000)
print("created SVR with 6GB cache")
from sklearn.metrics import mean_squared_error
print("fitting svr")
svm.fit(X, y)
print("fitted svr")
svmconf = svm.score(X, y)
print("SVM Prediction Confidence", svmconf, '%')
y_1=svm.predict(X)
print("prediction complete")
print(y_1)
print(mean_squared_error(y, y_1))
fig=plt.figure(figsize=(24,12))
plt.plot(X, c="k", label="X")
plt.plot(y, c="r", label="Y")
plt.plot(y_1, c="b", label="SVR")
plt.xlabel("time")
plt.ylabel("price")
plt.title("test")
plt.legend()
plt.show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:21:24.507",
"Id": "507288",
"Score": "1",
"body": "Can you confirm that the code is complete and that it functions correctly? If so, I recommend that you [edit] to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see [help/on-topic]) and the question may be deleted."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:41:51.567",
"Id": "256892",
"Score": "0",
"Tags": [
"python-3.x"
],
"Title": "Scikit-learn SVR stock prediction"
}
|
256892
|
<p>I am uploading and selecting code from my MySQL DB and I have a feeling some of it could be written in a much shorter way but I don't know how. Can someone tell me if this is clean code or if it's too much?</p>
<pre><code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'config/connect.php';
$con = new mysqli(...$dbCredentials);
if (isset($_POST['add_execise'])) {
# code...
$create_exercise = $con->prepare("INSERT INTO exercises (exercise_name, difficulty) VALUES (?, ?)");
$create_exercise->bind_param("ss", $_POST['exercise_creation'], $_POST['difficulty']);
$create_exercise->execute();
}
if (isset($_POST['beginner'])) {
# code...
$get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
$get_exercises->bind_param("s", $_POST['beginner']);
$get_exercises->execute();
$get_exercises->store_result();
$num_of_rows = $get_exercises->num_rows;
$get_exercises->bind_result($exercise_selected, $difficulty);
}
if (isset($_POST['intermediate'])) {
# code...
$get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
$get_exercises->bind_param("s", $_POST['intermediate']);
$get_exercises->execute();
$get_exercises->store_result();
$num_of_rows = $get_exercises->num_rows;
$get_exercises->bind_result($exercise_selected, $difficulty);
}
if (isset($_POST['advanced'])) {
# code...
$get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");
$get_exercises->bind_param("s", $_POST['advanced']);
$get_exercises->execute();
$get_exercises->store_result();
$num_of_rows = $get_exercises->num_rows;
$get_exercises->bind_result($exercise_selected, $difficulty);
}
?>
<form action="create.php" method="POST">
<input type="text" name="exercise_creation" placeholder="exercise">
<input type="text" name="difficulty" placeholder="difficulty">
<input type="submit" name="add_execise">
</form>
<p>Choose level of difficulty:</p> &nbsp;&nbsp;
<form action="create.php" method="POST">
<button id="beginner" name="beginner" value="beginner">Beginner</button><br><br>
<button id="intermediate" name="intermediate" value="intermediate">Intermediate</button><br><br>
<button id="advanced" name="advanced" value="advanced">Advanced</button>
</form><br><br><br>
<?php
while ($get_exercises->fetch()) {
# code...
echo $exercise_selected . "<br>";
}
?>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p><em>Can someone tell me if this is clean code...</em></p>\n</blockquote>\n<p>The code is somewhat easy to read (e.g. it appears to somewhat align with the recommendations of <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>. It is also great that parameters are bound to the queries so SQL injection should be less likely to occur.</p>\n<blockquote>\n<p><em>...or if it's too much?</em></p>\n</blockquote>\n<p>The mixing of PHP within HTML is not great. It is recommended to have the PHP fetch data and then within the HTML just output any data that might have been retrieved.</p>\n<p>There are quite a few duplicate lines in these three blocks:</p>\n<blockquote>\n<pre><code>if (isset($_POST['beginner'])) {\n # code...\n $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");\n $get_exercises->bind_param("s", $_POST['beginner']);\n $get_exercises->execute();\n $get_exercises->store_result();\n $num_of_rows = $get_exercises->num_rows;\n $get_exercises->bind_result($exercise_selected, $difficulty);\n}\n\nif (isset($_POST['intermediate'])) {\n # code...\n $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");\n $get_exercises->bind_param("s", $_POST['intermediate']);\n $get_exercises->execute();\n $get_exercises->store_result();\n $num_of_rows = $get_exercises->num_rows;\n $get_exercises->bind_result($exercise_selected, $difficulty);\n}\n\nif (isset($_POST['advanced'])) {\n # code...\n $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");\n $get_exercises->bind_param("s", $_POST['advanced']);\n $get_exercises->execute();\n $get_exercises->store_result();\n $num_of_rows = $get_exercises->num_rows;\n $get_exercises->bind_result($exercise_selected, $difficulty);\n}\n</code></pre>\n</blockquote>\n<p>It appears that only two of each eight lines in each block changes - i.e. the <code>if</code> condition and the second parameter passed to <code>$get_exercises->bind_param()</code>.</p>\n<p>A commonly accepted principle is the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself. principle</a>. The common lines could be abstracted to a function, or even a simple check for common values:</p>\n<p>Instead of setting the <code>name</code> attribute uniquely on each button</p>\n<blockquote>\n<pre><code><button id="beginner" name="beginner" value="beginner">Beginner</button><br><br>\n</code></pre>\n</blockquote>\n<p>Set the name on all three the same - e.g. <code>name=“difficulty”</code>. That can make the query logic much simpler:</p>\n<pre><code>//initialize to avoid undefined variables if POST not set\n$exercise_selected = $difficulty = null;\nif (isset($_POST['difficulty']) {\n $get_exercises = $con->prepare("SELECT exercise_name, difficulty FROM exercises WHERE difficulty = ?");\n $get_exercises->bind_param("s", $_POST['difficulty']);\n $get_exercises->execute();\n $get_exercises->store_result();\n $num_of_rows = $get_exercises->num_rows;\n $get_exercises->bind_result($exercise_selected, $difficulty);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:51:02.660",
"Id": "507292",
"Score": "0",
"body": "oh *come on*! How it's even a loop? that's literally just a **single query** with a single input variable!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:24:17.960",
"Id": "507297",
"Score": "0",
"body": "While it may not be *plausible* it is *possible* that the OPs code could execute multiple queries. However I took your suggestion and updated it to have a function to get the level and if such a value exists it will run the query."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:28:23.370",
"Id": "507299",
"Score": "0",
"body": "I should be *just* `if (isset($_POST['difficulty'])) {` without any functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:37:02.520",
"Id": "507302",
"Score": "0",
"body": "Good call- thanks for your suggestion. I revised it again."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T21:29:47.473",
"Id": "256895",
"ParentId": "256893",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256895",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:42:35.973",
"Id": "256893",
"Score": "2",
"Tags": [
"php",
"html",
"mysql",
"mysqli"
],
"Title": "Input text upload to MySQL DB"
}
|
256893
|
<p>The following is my attempt at writing a <code>getline()</code> function that makes it a bit easier to work with. I suppose an easier way would be to use <code>fgets</code>, but hopefully the following is good enough for some feedback:</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#define TITLE_MAX 50
void mygets(char buffer[], size_t limit)
{
// first non-space char until newline or EOF,
// eating any extra chars in buffer
// will add \0 at the end, so will get up to N-1 chars
int c, idx=0;
bool started=false;
while ((c=getchar()) != EOF && c != '\n')
{
if (!started && isspace(c));
if (idx < limit-1) {
started = true;
buffer[idx++] = c;
}
}
buffer[idx] = '\0';
}
int main(void)
{
char tbuffer[TITLE_MAX];
while (true)
{
printf("Enter the name of the film (empty line to stop)\n");
mygets(tbuffer, TITLE_MAX);
if (*tbuffer=='\0') break;
printf("The title is: %s\n", tbuffer);
}
}
</code></pre>
<p>Working example <a href="https://onlinegdb.com/rJufsGVQd" rel="nofollow noreferrer">on onlinegdb</a></p>
<p>How does it look? How could it be improved? Additionally, how are comments usually done in C code? It is usually within the function braces? Before the function? etc.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T02:37:41.320",
"Id": "507533",
"Score": "0",
"body": "David542, how do you want to distinguish between end-of-file and reading only `\"\\n\"`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T02:50:06.923",
"Id": "507538",
"Score": "0",
"body": "What is the goal with code like `if (!started && isspace(c));`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T02:54:45.263",
"Id": "507539",
"Score": "0",
"body": "@chux-ReinstateMonica to skip leading whitespace (`\\s` being used to mean space): `\\s\\s\\s Hello, chux` --> `Hello, chux`. But it looks like that's bad code and there's an error within it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T02:59:58.780",
"Id": "507540",
"Score": "0",
"body": "David542 Why skip all leading white-space and not symmetrically all trailing white-space (aside from 1 `'\\n'`) as with `\" ABC \\n\"`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T03:11:16.407",
"Id": "507541",
"Score": "0",
"body": "@chux-ReinstateMonica no reason, I suppose doing both would be better as you suggest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T04:55:39.313",
"Id": "507546",
"Score": "0",
"body": "@chux-ReinstateMonica hm to be honest I hadn't thought about that. Perhaps the function can return a code, such as `NULL` if nothing was read or the size of the read data (or maybe just 0 if empty or 1 if non-empty). What is the suggested way to usually do this?"
}
] |
[
{
"body": "<ul>\n<li><p>You should be getting a warning (at least I do):</p>\n<pre><code>warning: if statement has empty body [-Wempty-body]\n if (!started && isspace(c));\n ^\n</code></pre>\n<p>This line does absolutely nothing. Judging from the comment, you probably meant</p>\n<pre><code> if (!started && isspace(c))\n continue;\n</code></pre>\n</li>\n<li><p>The loop looks overcomplicated. Its logic cries to be split into two independent actions: <code>skip_initial_spaces</code> and <code>actually_read_data</code>, performed sequentially (again, assuming that I read the comment correctly).</p>\n<p>Factoring them out into the functions of their own will also make your code comply with a single responsibility principle.</p>\n</li>\n<li><p>I strongly advise against <code>void</code> functions. Do not discard the information you have already computed; it is very likely the caller will need it. In this case, returning <code>idx</code> will spare the caller an additional call to <code>strlen</code>.</p>\n</li>\n</ul>\n<p>EDIT. On splitting up the functionality, something along these lines:</p>\n<pre><code>int skip_leading_whitespaces()\n{\n int c;\n while (((c = getchar()) != EOF) && isspace(c)) {\n }\n return c;\n}\n\nint actually_read_data(int c, char buffer[], size_t limit)\n{\n int idx = 0;\n while ((c != EOF) && (c != '\\n')) {\n buffer[idx++] = c;\n c = getchar();\n }\n buffer[idx] = 0;\n return idx;\n}\n\nint mygets(char buffer[], size_t limit)\n{ \n int c = skip_leading_whitespaces();\n return actually_read_data(c, buffer[], limit);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T01:57:00.937",
"Id": "507279",
"Score": "0",
"body": "thanks for this. Could you describe how it might be split up into `skip_initial_spaces` and `actually_read_data` in a couple lines of code or so?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T02:10:09.273",
"Id": "507280",
"Score": "0",
"body": "@David542 see edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T02:43:19.113",
"Id": "507535",
"Score": "0",
"body": "OP's code only reads up to 1 line. This code may read multiple lines with `skip_leading_whitespaces()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T02:45:46.617",
"Id": "507536",
"Score": "0",
"body": "`actually_read_data()` does not use `limit`. As you say \" something along these lines:\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T01:51:40.387",
"Id": "256908",
"ParentId": "256896",
"Score": "2"
}
},
{
"body": "<p><strong>Incorrect code to skip leading white space</strong></p>\n<p><strong>Asymmetrically attempts to skip leading white-spaces but not all trailing ones</strong></p>\n<p><strong>Mixed types</strong></p>\n<p>Rather than <code>size_t limit, int idx</code>. Use the same type. Recommend <code>size_t</code></p>\n<p><strong>Edge cases behavior woe</strong></p>\n<p><code>idx < limit-1</code> is like <code>idx < SIZE_MAX</code> when <code>limit == 0</code>. Better as <code>idx + 1 < limit</code>.</p>\n<p><strong>No return</strong></p>\n<p>No clear what to distinguish end-of-file from reading <code>"\\n"</code>.</p>\n<hr />\n<p>I'd set aside the skip leading white-space goal for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T04:13:48.900",
"Id": "507544",
"Score": "0",
"body": "thanks. Would you want to post an updated version of the code with how it can be improved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T04:34:20.763",
"Id": "507545",
"Score": "1",
"body": "@David542 Still waiting on [question](https://codereview.stackexchange.com/questions/256896/getline-function/257003?noredirect=1#comment507533_256896)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T03:29:19.103",
"Id": "257003",
"ParentId": "256896",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T21:44:02.303",
"Id": "256896",
"Score": "0",
"Tags": [
"c",
"io"
],
"Title": "Getline function"
}
|
256896
|
<p>I reimplemented the functions <a href="https://rdrr.io/cran/fclust/man/RI.F.html" rel="nofollow noreferrer">https://rdrr.io/cran/fclust/man/RI.F.html</a>, <a href="https://rdrr.io/cran/fclust/man/ARI.F.html" rel="nofollow noreferrer">https://rdrr.io/cran/fclust/man/ARI.F.html</a> and <a href="https://rdrr.io/cran/fclust/man/JACCARD.F.html" rel="nofollow noreferrer">https://rdrr.io/cran/fclust/man/JACCARD.F.html</a> of the R package <a href="https://rdrr.io/cran/fclust/" rel="nofollow noreferrer">https://rdrr.io/cran/fclust/</a> in Python. However, it seems - even though I use numpy a lot, that the result is pretty slow. Much slower than I though. E.g. for data where I expected 0.2 secs at most, it took 2 secs. What could be the reason? What am I missing, what could I improve?</p>
<p>The PyCharm profiler shows that <code>amax</code> takes about 30% of the time, but I am not sure how to improve that. Next are <code>outer</code> (13%) and <code>einsum</code> (9%).</p>
<pre><code>import numpy as np
import collections
partition_comp_return = collections.namedtuple('partition_comp_return', ["Rand_F", "adjRand_F", "Jaccard_F"])
def partition_comp_fast_short(HardClust: np.ndarray, Fuzzy: np.ndarray, minimum_instead_of_product: bool = True) -> partition_comp_return:
if HardClust.ndim == 1:
outliers = HardClust < 0
HardClust[outliers] = -1
HardClust_unique, HardClust_inverse = np.unique(HardClust, return_inverse=True)
HardClust = np.zeros((HardClust.size, HardClust_unique.size), dtype=int)
HardClust[range(0, HardClust.shape[0]), HardClust_inverse] = 1
if np.any(outliers):
HardClust = HardClust[:, 1:]
assert HardClust.ndim == 2
assert Fuzzy.ndim == 2
assert HardClust.shape[0] == Fuzzy.shape[0]
R: np.ndarray = HardClust
Q: np.ndarray = Fuzzy
nb_obj, nb_class = R.shape
nb_clust = Q.shape[1]
m = np.minimum(R[np.newaxis, :, :], R[:, np.newaxis, :]) if minimum_instead_of_product else R[np.newaxis, :, :] * R[:, np.newaxis, :]
V = m.max(axis=-1)
V[np.tril_indices(nb_obj)] = 0.0
m = np.minimum.outer(R, R) if minimum_instead_of_product else np.einsum('io,jp->iojp', R, R)
m[:, np.arange(nb_class), :, np.arange(nb_class)] = 0.0
X = np.amax(m, axis=(1, 3))
X[np.tril_indices(nb_obj)] = 0.0
m = np.minimum(Q[np.newaxis, :, :], Q[:, np.newaxis, :]) if minimum_instead_of_product else Q[np.newaxis, :, :] * Q[:, np.newaxis, :]
Y = m.max(axis=-1)
Y[np.tril_indices(nb_obj)] = 0.0
m = np.minimum.outer(Q, Q) if minimum_instead_of_product else np.einsum('io,jp->iojp', Q, Q)
m[:, np.arange(nb_clust), :, np.arange(nb_clust)] = 0.0
Z = np.amax(m, axis=(1, 3))
Z[np.tril_indices(nb_obj)] = 0.0
if minimum_instead_of_product:
a = np.minimum(V, Y).sum()
b = np.minimum(V, Z).sum()
c = np.minimum(X, Y).sum()
d = np.minimum(X, Z).sum()
else:
a = (V * Y).sum()
b = (V * Z).sum()
c = (X * Y).sum()
d = (X * Z).sum()
Rand_F = (a + d) / (a + b + c + d)
ARand_F = (2 * (a * d - b * c)) / ((pow(b, 2)) + (pow(c, 2)) + (2 * a * d) + ((a + d) * (c + b)))
Jaccard_F = a / (a + b + c)
return partition_comp_return(Rand_F=Rand_F, adjRand_F=ARand_F, Jaccard_F=Jaccard_F)
HardClust = VC = np.array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
Fuzzy = U = np.array([[0.0076787166, 7.113048e-03, 5.736663e-04, 8.412011e-04, 5.764825e-04, 9.832169e-01],
[0.0057712212, 2.872151e-03, 3.961336e-04, 5.816540e-04, 2.172711e-04, 9.901616e-01],
[0.0034208846, 3.050199e-03, 3.589399e-04, 6.086319e-04, 3.139661e-04, 9.922474e-01],
[0.0279150737, 8.779513e-03, 9.568724e-04, 1.851549e-03, 6.226982e-04, 9.598743e-01],
[0.0019726466, 1.861342e-03, 2.266066e-04, 3.723195e-04, 1.861308e-04, 9.953810e-01],
[0.0217428288, 2.218815e-02, 3.433951e-03, 4.792441e-03, 2.781921e-03, 9.450607e-01],
[0.1615720209, 4.214874e-02, 9.118115e-03, 1.452836e-02, 8.501583e-03, 7.641312e-01],
[0.0600584649, 4.323160e-02, 4.124345e-03, 8.649931e-03, 4.302435e-03, 8.796332e-01],
[0.0557432560, 3.884050e-02, 3.367109e-03, 7.601076e-03, 3.847401e-03, 8.906007e-01],
[0.0211994239, 2.590075e-02, 3.655883e-03, 6.272988e-03, 3.443107e-03, 9.395278e-01],
[0.0006062638, 4.403985e-04, 4.811967e-05, 7.791419e-05, 3.942910e-05, 9.987879e-01],
[0.0225039734, 1.068112e-02, 3.015998e-03, 4.895759e-03, 1.256603e-03, 9.576465e-01],
[0.9893402312, 3.221614e-03, 1.258685e-03, 1.992848e-03, 3.556565e-04, 3.830965e-03],
[0.8072825402, 4.402183e-02, 4.313880e-02, 3.991697e-02, 4.887156e-03, 6.075271e-02],
[0.9445378991, 2.115730e-02, 2.683231e-03, 6.099076e-03, 1.090781e-03, 2.443171e-02],
[0.7607765170, 7.492751e-02, 2.108496e-02, 3.280546e-02, 4.144342e-03, 1.062612e-01],
[0.9972648979, 9.878626e-04, 2.320282e-04, 3.614420e-04, 8.663132e-05, 1.067138e-03],
[0.8502374014, 4.208990e-02, 2.498097e-02, 2.404460e-02, 3.807866e-03, 5.483926e-02],
[0.9876004761, 4.728819e-03, 1.011830e-03, 1.693659e-03, 4.591506e-04, 4.506065e-03],
[0.9902351342, 3.780967e-03, 5.828589e-04, 1.068010e-03, 2.643451e-04, 4.068685e-03],
[0.9696105676, 1.154675e-02, 1.943744e-03, 5.277962e-03, 8.883482e-04, 1.073263e-02],
[0.9614931237, 1.801615e-02, 1.993549e-03, 3.634203e-03, 9.752303e-04, 1.388774e-02],
[0.6806979493, 1.420196e-01, 2.953315e-02, 3.200260e-02, 1.376224e-02, 1.019844e-01],
[0.9151662384, 2.573136e-02, 1.545858e-02, 1.715242e-02, 3.215249e-03, 2.327615e-02],
[0.7922914311, 9.595908e-02, 2.059959e-02, 2.233133e-02, 9.106945e-03, 5.971163e-02],
[0.6081442334, 1.836722e-01, 3.252763e-02, 4.358491e-02, 1.815709e-02, 1.139139e-01],
[0.1253379793, 6.593496e-01, 2.904808e-02, 4.463583e-02, 1.393875e-02, 1.276898e-01],
[0.2117828527, 3.886916e-01, 1.932635e-02, 3.680607e-02, 3.526595e-02, 3.081272e-01],
[0.0399338067, 8.917992e-01, 5.688628e-03, 9.069212e-03, 4.930668e-03, 4.857848e-02],
[0.0145935206, 9.651403e-01, 1.641272e-03, 2.454668e-03, 2.864280e-03, 1.330600e-02],
[0.2549469315, 3.650576e-01, 2.280736e-02, 3.351912e-02, 1.280618e-01, 1.956071e-01],
[0.0378589642, 9.157816e-01, 3.709495e-03, 5.018086e-03, 7.382535e-03, 3.024928e-02],
[0.0325314090, 9.442939e-01, 2.247034e-03, 5.083816e-03, 1.897973e-03, 1.394585e-02],
[0.7192770918, 1.426605e-01, 1.150844e-02, 2.977222e-02, 2.395716e-02, 7.282461e-02],
[0.0097196605, 9.847744e-01, 4.671710e-04, 9.843888e-04, 4.411863e-04, 3.613147e-03],
[0.0418776051, 9.107750e-01, 6.617200e-03, 8.042554e-03, 5.911076e-03, 2.677652e-02],
[0.1009396098, 8.606003e-01, 4.936793e-03, 7.626892e-03, 3.700602e-03, 2.219580e-02],
[0.0016298188, 1.263283e-03, 3.076376e-04, 9.214896e-04, 9.947889e-01, 1.088826e-03],
[0.5739998066, 7.433837e-02, 5.305344e-02, 1.833748e-01, 2.960194e-02, 8.563165e-02],
[0.9402506893, 2.334657e-02, 3.784468e-03, 1.206866e-02, 3.172323e-03, 1.737729e-02],
[0.0371007566, 9.036780e-01, 2.152564e-03, 3.186572e-03, 2.670612e-03, 5.121152e-02],
[0.7799436329, 1.133283e-01, 8.338929e-03, 1.167779e-02, 1.110773e-02, 7.560364e-02],
[0.0408534276, 9.216228e-01, 2.001232e-03, 3.308181e-03, 1.967015e-03, 3.024739e-02],
[0.4469709279, 1.358457e-01, 1.228568e-01, 1.007856e-01, 7.886580e-02, 1.146752e-01],
[0.1439993585, 3.531563e-02, 3.047881e-01, 4.578719e-01, 1.697605e-02, 4.104897e-02],
[0.0020298426, 9.474874e-04, 9.928119e-01, 2.907400e-03, 2.766365e-04, 1.026779e-03],
[0.0075241433, 2.198371e-03, 9.825371e-01, 5.073278e-03, 4.065325e-04, 2.260567e-03],
[0.0032096198, 1.117871e-03, 9.915901e-01, 2.644219e-03, 2.181051e-04, 1.220082e-03],
[0.0058390748, 2.900377e-03, 9.771325e-01, 9.925009e-03, 9.179128e-04, 3.285112e-03],
[0.0016969194, 5.190993e-04, 9.956088e-01, 1.509492e-03, 1.029136e-04, 5.628123e-04],
[0.0017098054, 6.265384e-04, 9.950579e-01, 1.762449e-03, 1.304945e-04, 7.128089e-04],
[0.0072687741, 3.376713e-03, 9.744052e-01, 9.839404e-03, 1.317107e-03, 3.792781e-03],
[0.0067838794, 1.745023e-03, 9.845139e-01, 4.628078e-03, 4.303587e-04, 1.898777e-03],
[0.0019331928, 5.975788e-04, 9.950722e-01, 1.572958e-03, 1.471497e-04, 6.769124e-04],
[0.0088429051, 3.590130e-03, 9.659274e-01, 1.626815e-02, 1.312687e-03, 4.058729e-03],
[0.1700967967, 1.175906e-01, 2.529414e-01, 2.626294e-01, 7.304362e-02, 1.236981e-01],
[0.1132191453, 3.108558e-02, 2.038415e-01, 6.029075e-01, 1.390396e-02, 3.504226e-02],
[0.9828429894, 8.037918e-03, 7.089755e-04, 1.573363e-03, 4.677252e-04, 6.369028e-03],
[0.9506949785, 1.734455e-02, 4.652054e-03, 7.685413e-03, 9.992133e-04, 1.862379e-02],
[0.9827122045, 8.142491e-03, 6.875906e-04, 1.466719e-03, 4.417760e-04, 6.549219e-03],
[0.9486784724, 1.941422e-02, 4.480298e-03, 6.977198e-03, 9.718182e-04, 1.947800e-02],
[0.9274426398, 3.975402e-02, 2.204948e-03, 4.472365e-03, 1.843656e-03, 2.428237e-02],
[0.9785789273, 9.539753e-03, 1.309212e-03, 2.029959e-03, 3.574182e-04, 8.184730e-03],
[0.0501320878, 3.027312e-02, 5.269740e-03, 7.981853e-03, 4.365882e-03, 9.019773e-01],
[0.3491308150, 1.305319e-01, 1.104979e-01, 1.161382e-01, 1.690700e-01, 1.246313e-01],
[0.0013259843, 4.388210e-04, 9.900583e-04, 9.965949e-01, 1.398863e-04, 5.103753e-04],
[0.0010000144, 3.818781e-04, 9.017760e-04, 9.971793e-01, 1.282587e-04, 4.087553e-04],
[0.0026944112, 9.814845e-04, 1.353360e-03, 9.933426e-01, 4.824645e-04, 1.145645e-03],
[0.0011870826, 4.382037e-04, 7.885286e-04, 9.969268e-01, 1.927880e-04, 4.665496e-04],
[0.0014449851, 5.028457e-04, 1.400346e-03, 9.958792e-01, 2.252785e-04, 5.473215e-04],
[0.1350226531, 1.015236e-01, 5.752991e-02, 7.809351e-02, 5.333599e-01, 9.447039e-02],
[0.0103180013, 1.206290e-02, 3.385997e-03, 7.096829e-03, 9.563710e-01, 1.076523e-02],
[0.0015640286, 1.548431e-03, 3.997652e-04, 9.765905e-04, 9.941919e-01, 1.319290e-03],
[0.0533482161, 4.712243e-02, 1.246132e-02, 3.920942e-02, 8.104133e-01, 3.744533e-02],
[0.0538531714, 1.345452e-02, 1.120729e-01, 7.994274e-01, 5.125327e-03, 1.606672e-02],
[0.0047903044, 2.119704e-03, 2.319098e-03, 9.873113e-01, 1.188173e-03, 2.271456e-03],
[0.0002620750, 8.125551e-05, 1.447590e-04, 9.993888e-01, 3.155190e-05, 9.157041e-05],
[0.0071613091, 3.093923e-03, 3.355745e-03, 9.803475e-01, 1.716550e-03, 4.325015e-03],
[0.0027432974, 1.018156e-03, 2.427727e-03, 9.919502e-01, 3.991500e-04, 1.461454e-03],
[0.0049388231, 2.339685e-03, 2.854995e-03, 9.863335e-01, 1.060640e-03, 2.472382e-03],
[0.0025401470, 9.412550e-04, 1.125002e-03, 9.939489e-01, 3.982413e-04, 1.046472e-03]])
Rand_F, adjRand_F, Jaccard_F = partition_comp_fast(HardClust, Fuzzy, minimum_instead_of_product=True)
assert np.allclose(np.array([Rand_F, adjRand_F, Jaccard_F]), np.array([0.7987886, 0.3959664, 0.3538935]))
Rand_F, adjRand_F, Jaccard_F = partition_comp_fast(HardClust, Fuzzy, minimum_instead_of_product=False)
assert np.allclose(np.array([Rand_F, adjRand_F, Jaccard_F]), np.array([0.803873, 0.4055851, 0.3595149]))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T22:01:03.500",
"Id": "256897",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"numpy",
"r"
],
"Title": "Reimplemented R function(s) is surprisingly slow"
}
|
256897
|
<p>I am attempting to create a Linked List where someone can enter in some movie titles and their rating for it. Here is what I have thus far:</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define TITLE_MAX 50
void mygets(char buffer[], size_t limit);
// linked list
struct film {
char title[TITLE_MAX];
int rating;
struct film *next;
};
int main(void)
{
struct film *head = NULL, *current = NULL;
char tbuffer[TITLE_MAX];
while (true)
{
printf("Enter the name of the film (empty line to stop)\n");
mygets(tbuffer, TITLE_MAX);
if (*tbuffer=='\0') break;
if (!head)
current = head = malloc (sizeof(struct film));
else
// assignment associates right-to-left so can do this trick
current = current->next = malloc (sizeof(struct film));
current->next = NULL;
strcpy(current->title, tbuffer);
printf("Now enter in your rating for it: ");
scanf("%d", &(current->rating));
for (int c; (c=getchar()) != '\n' && c != EOF; ); // clean up garbage in scanf -- should probably write a function for this
}
// print the Linked List
current = head;
for (int i=1; current != NULL; current=current->next)
printf("Linked List Item #%d: %s (Rating: %d)\n",
i++, current->title, current->rating
);
for(struct film *current=head, *next; current != NULL; current=next) {
next = current->next;
free(current);
}
}
void mygets(char buffer[], size_t limit)
{
// first non-space char until newline or EOF,
// eating any extra chars in buffer
// will add \0 at the end, so will get up to N-1 chars
int c, idx=0;
bool started=false;
while ((c=getchar()) != EOF && c != '\n')
{
if (!started && isspace(c));
if (idx < limit-1)
buffer[idx++] = c;
}
buffer[idx] = '\0';
}
</code></pre>
<p>How does it look so far? What can be improved? Additionally, in real-world implementations of a linked list, what sort of additional metadata is stored -- for example, things like List Size and such.</p>
<p>Also, how does the <code>free</code> look in there. For a linked list does it matter which direction I free the data?</p>
|
[] |
[
{
"body": "<h1>Bugs</h1>\n<ul>\n<li><p>A quick bug: <code>if (!started && isspace(c));</code> has no effect. Did you want <code>continue;</code> or something there? As it is, you will store leading spaces in the buffer after all, which apparently is not what you want.</p>\n<p><code>gcc -Wextra</code> gives a warning, btw.</p>\n<p>(Did you test the program on input lines with leading spaces? I don't think it could ever have worked.)</p>\n<p>And you currently have no way for <code>started</code> to ever become true...</p>\n</li>\n</ul>\n<h1>Code quality improvements</h1>\n<ul>\n<li><p><code>mygets</code> is not a great choice for your function name. A reader will incorrectly guess that it behaves like the standard <code>fgets</code> (or worse, the formerly standard <code>gets</code>), but it differs in that it (is supposed to) strip leading spaces. I'd choose something more like <code>get_film_title</code>. You could try to explain in the function name that it strips spaces but that may make it awkwardly long.</p>\n</li>\n<li><p>I'd split the three tasks of populating the list, printing it out, and freeing it, into three separate functions, instead of dumping them all in <code>main</code>.</p>\n</li>\n<li><p>The <code>while (true)</code> idiom with a <code>break;</code> makes the reader have to hunt through the loop body for the termination condition. See if you can think of a clean way to restructure to avoid this. If not, at least add a comment to explain when the loop will terminate.</p>\n</li>\n<li><p>See if you can restructure the <code>if (!head)</code> to avoid writing out the <code>malloc</code> call twice, which is a danger point if you eventually want to change it but miss updating both instances.</p>\n</li>\n<li><p>Some would suggest <code>malloc(sizeof *current)</code> instead of <code>sizeof(struct film)</code>. I don't have strong feelings either way, myself.</p>\n</li>\n<li><p>Any time you need a comment to explain a "trick", where the comment is longer than the extra code it avoids having to type, you are probably trying to be too clever. (And I found it confusing even with the comment.) Just write out the two statements.</p>\n</li>\n<li><p>Consider moving the task of reading the rating and "cleaning up the input stream" into its own function. It's awkward when some of the I/O work is farmed out to a subroutine (<code>mygets</code>) and some is left behind.</p>\n</li>\n<li><p><code>for (int c; ...)</code>: A <code>for</code> loop that doesn't need to do anything in <em>either</em> of the <em>init-clause</em> or the <em>iteration-expression</em> should probably just be a <code>while</code>.</p>\n</li>\n<li><p>In the printing code, it's nice to keep the <code>for</code> focused on the actual loop iterator, which here is <code>current</code>, rather than mixing it between <code>current</code> and <code>i</code> (and since the latter is not the iterator, it could use a different name). And there's no need to bury the increment of <code>i</code> inside a statement that does something else. I would write:</p>\n</li>\n</ul>\n<pre><code>int film_number = 1;\nfor (current = head; current != NULL; current = current->next) {\n printf("...", film_number, current->title, current->rating);\n film_number++;\n}\n</code></pre>\n<ul>\n<li><p>In the freeing code, why do you declare a new variable named <code>current</code>, shadowing the existing one?</p>\n</li>\n<li><p>The <code>for</code> loop and use of the variable <code>next</code> in the freeing code is maybe more clever than readable. I would write more simply:</p>\n</li>\n</ul>\n<pre><code>current = head;\nwhile (current) {\n struct film *tmp = current;\n current = current->next;\n free(tmp);\n}\n</code></pre>\n<ul>\n<li><p>I think your plan of freeing the list from beginning to end is fine. With a single-linked list, it's not so easy to do it the other way. (Unless you want to build a double-linked list instead.</p>\n</li>\n<li><p>Error checking on every input and memory allocation function. Yes, it's boring, but essential for any real program, and even for toy programs it is very helpful for debugging.</p>\n</li>\n</ul>\n<h1>Suggested enhancements</h1>\n<ul>\n<li><p>As to additional metadata: store only what you have a use for. If knowing the size or the last element becomes useful for your application, add it then. But I don't suggest overdesigning a fully general and heavily featureful linked list for a specific program; if you want to reinvent a generic linked list container, that's a separate project (and one that might be better for a language that actually supports generic programming).</p>\n</li>\n<li><p>Using <code>scanf</code> to read user input is not ideal outside toy programs, as it makes it hard to detect and recover from improper input. A better design is usually to read an entire input line and parse it out with <code>sscanf</code>.</p>\n</li>\n<li><p>Consider using dynamic allocation so as to allow the film titles to be of arbitrary length. Otherwise the user who wants to rate <a href=\"https://www.imdb.com/title/tt0112966/?ref_=nv_sr_srsg_0\" rel=\"nofollow noreferrer\"><em>The Englishman Who Went Up a Hill But Came Down a Mountain</em></a> (57) is going to be peeved.</p>\n</li>\n<li><p>Command line programs that prompt for interactive input, and terminate on something like an empty line, are rare outside of toy examples. For one thing, they are hard to adapt for batch processing or pipelines. Useful command-line programs more often don't prompt, and read input until end-of-file is encountered.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T05:13:13.340",
"Id": "256951",
"ParentId": "256898",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T22:15:59.557",
"Id": "256898",
"Score": "0",
"Tags": [
"c"
],
"Title": "Linked list for array of movies"
}
|
256898
|
<p>This is a rewrite of the Dependencies program submitted previously at https://codereview.stackexchange.com/questions/255635/detecting-dependencies-in-common-lisp-project-files/256336?noredirect=1#comment506766_256336 that incorporates the many insightful changes recommended there.</p>
<p>I'm requesting another review to check that the changes are implemented correctly, and to see if they raise other issues.</p>
<p>To quickly recap, the program creates a dependency graph for the symbols in a project's files, and tracks down inter-file dependencies and cycles.</p>
<p><strong>UPDATED USER INTERFACE FUNCTIONS</strong></p>
<pre><code>get-all-dependencies (&key (pathspec #P"*.lisp") (stream *standard-output*)
(print nil))
"Returns (or prints) all inter-file dependencies and codependencies."
file1-depends-on-file2 (file1 file2 &key (stream *standard-output*)
(print nil))
"Returns (or prints) all of the symbols in file1 that depend on definitions in file2."
file-depends-on-what (file1 &key (pathspec #P"*.lisp")
(stream *standard-output*) (print nil))
"Returns (or prints), for a given file1, all of the files and definitions it depends on."
</code></pre>
<p>For example, <code>(dep:get-all-dependencies :print t)</code> is the simplest way to get everything at once in a user-friendly format. Assumes <code>*default-pathname-defaults*</code> has been set to the project directory. The keyword :print determines if the output is in data structure format or user-friendly format.</p>
<p><strong>ASDF DEFINITION FILE</strong></p>
<pre><code>;;; Filename: dependencies.asd
(defsystem "dependencies"
:description "dependencies: A Common Lisp system for detecting dependencies
between a project's files."
:version "1.1"
:author "David Brown <davypough@gmail.com>"
:licence "Public Domain"
:depends-on ("alexandria" "cl-ppcre")
:components ((:file "dependencies")))
</code></pre>
<p><strong>COMMENTS</strong></p>
<p>The program requires cl-ppcre simply to pre-process a project's files. The function <code>purify-file</code> removes quoted expressions, so they will not interfere with the lisp reader subsequently reading a file's forms into a big string. A previous suggestion was to reconfigure the lisp reader to obviate the problem. The <code>cl-ppcre</code> package and pre-processing then could be eliminated. But I can't figure out how to do this. Setting <code>*read-suppress*</code> seems promising--any further guidance is welcome.</p>
<p>Detecting the appropriate symbols associated with <code>defstruct</code> definitions is more complicated than for the other kinds of definitions covered (namely, <code>defun, defmacro, defparameter, defvar, defmethod</code>). And <code>defclass</code> is not covered at all. The accessor function names for a defstruct can be altered by the <code>:nconc-name</code> option, but the program assumes the standard hyphenation for project files. (ps: If someone wanted to include class definitions and accessors, would <code>closer-mop</code> be the best way to go?)</p>
<p>The basic format for a dependency used throughout the program is a list of three items <code>(file1 file2 dependents)</code>, which means file1 depends on file2, and dependents is a list of the symbols in file1 that depend on definitions in file2. Filenames are stored as strings--eg, "my-file.lisp". The format for codependencies is a list which contains sublists of files that depend on each other--ie, contain cycles of dependency.</p>
<p>The dependency graph is searched using the recursive backtrack algorithm in <code>backtrack-search</code>. The original brute-force search broke down when tested on a large project of 47 substantial lisp files. The revised algorithm does not repeat searching from a node that was previously searched.</p>
<p>I have often used <code>alexandria:flatten</code> on code trees, before working on them with the sequence functions. But, as previously pointed out, it can involve a lot of consing. I'm wondering if it's generally better to search the tree directly to process the items of interest, assuming walking the tree is as efficient as alexandria. I found an interesting way to do this at https://lisptips.com/post/43404489000/the-tree-walkers-of-cl:</p>
<pre><code>(defun walk-tree-atoms (fun tree)
(tree-equal tree tree
:test (lambda (element-1 element-2)
(declare (ignore element-2))
(funcall fun element-1)
t)))
</code></pre>
<p>Is this a better approach than <code>alexandria:flatten</code>? Thanks for your time.</p>
<p><strong>PROGRAM FILE</strong></p>
<pre><code>;;; Filename: dependencies.lisp
; Finds the dependencies among files (ie, inter-file references) in a Common
; Lisp project directory. Assumes the project files have already been loaded,
; and that *default-pathname-defaults* points to the project directory.
(defpackage :dependencies
(:use :cl :alexandria :cl-ppcre)
(:nicknames :dep)
(:export #:file1-depends-on-file2 #:file-depends-on-what
#:get-all-dependencies))
(in-package :dep)
; Function Specs
(declaim
(ftype (function (string) (values t t)) ;ideal: (values string boolean)
purify-file)
(ftype (function (list) list)
collect-symbols)
(ftype (function (t) list)
collect-defs)
(ftype (function (t) list)
collect-defstructs)
(ftype (function (list) list)
delete-duplicate-cycles)
(ftype (function (string) list)
pseudo-load)
(ftype (function (string string &key (:stream stream) (:print t))
list)
file1-depends-on-file2)
(ftype (function (string &key (:pathspec pathname) (:stream stream)
(:print t))
list)
file-depends-on-what)
(ftype (function (list hash-table hash-table) list)
backtrack-search)
(ftype (function (list list) list)
search-for-codependents)
(ftype (function (list) list)
get-codependencies)
(ftype (function (&key (:pathspec pathname) (:stream stream) (:print t))
(values list list))
get-all-dependencies))
(defmacro prt (&rest vars)
"For debugging: Print the names & values of given variables or accessors.
Can also wrap around an expression, returning its value."
`(progn ,@(loop for var in vars
collect `(format t "~& ~S => ~S~%" ',var ,var))
,@(last `,vars)))
(defun purify-file (file)
"Transforms problematic symbols to benign NIL in file, before reading.
Returns a string of altered file content."
(let ((file-string (alexandria:read-file-into-string file))
(modified-file-string ""))
(setf modified-file-string
(ppcre:regex-replace-all
"[ \t\r\n]'[A-Za-z0-9!@$%&*_+:=<.>/?-]+"
file-string " NIL"))
(ppcre:regex-replace-all
"[(][qQ][uU][oO][tT][eE][ \t\r\n]+[A-Za-z0-9!@$%&*_+:=<.>/?-]+[)]"
modified-file-string "NIL")))
(defun collect-symbols (form)
"Collects all of the unique symbols in a form."
(let ((all-items (alexandria:flatten form)))
(delete-if (lambda (item)
(or (not (symbolp item))
(find-symbol (symbol-name item) :cl)))
(delete-duplicates all-items))))
(defun collect-defs (forms)
"Collects all of the defined names in forms, excluding defstructs."
(loop for form in forms
when (and (consp form)
(member (first form)
'(defun defmacro defparameter defvar defmethod)))
collect (second form)))
(defun collect-defstructs (forms)
"Collects all of the defined defstruct names in forms."
(loop for form in forms
when (and (consp form)
(member (first form)
'(defstruct)))
if (symbolp (second form))
collect (second form)
else if (listp (second form))
collect (first (second form))))
(defun collect-struct-fns (defstruct-syms all-syms)
"Collects all of the structure access function names in all-syms
that are associated with the structure names in defstruct-syms."
(delete-if #'null
(alexandria:map-product
(lambda (defstruct-sym sym)
(when (and (not (eql defstruct-sym sym))
;only std :conc-name structure prefix
;with hyphen recognized
(search (format NIL "~S-" defstruct-sym)
(format NIL "~S" sym)))
sym))
defstruct-syms all-syms)))
(defun delete-duplicate-cycles (cycles)
"Deletes any duplicate dependency cycles found during search."
(delete-duplicates cycles
:test (lambda (cyc1 cyc2)
(alexandria:set-equal cyc1 cyc2 :test #'equal))))
(defun pseudo-load (file)
"Attempt to read a file doing what LOAD would do. May not always do
the right thing. Returns list of all forms, including package prefixes.
Based on a function provided by tfb on Stack Overflow."
(let ((file-string (purify-file file))
(*package* *package*))
(with-input-from-string (in-stream file-string)
(loop for form = (read in-stream NIL in-stream)
while (not (eql form in-stream))
when (and (consp form)
(eql (first form) 'in-package))
do (let ((file-pkg (find-package (second form))))
(if file-pkg
(setf *package* file-pkg)
(error "~%Unknown package name: ~A in file: ~A
~&Make sure project files are loaded.~%"
(second form) file)))
collect form))))
(defun file1-depends-on-file2 (file1 file2 &key (stream *standard-output*)
(print nil))
"Returns or prints those symbols in file1 that are defined in file2."
(let* ((forms1 (pseudo-load file1))
(all-syms1 (collect-symbols forms1))
(def-syms1 (collect-defs forms1)) ;eg, (defun sym ...
(defstruct-syms1 (collect-defstructs forms1)) ;eg, (defstruct sym ...
(struct-fns1 (collect-struct-fns defstruct-syms1 ;eg, (sym-slot ...
all-syms1))
(active-syms1 (set-difference all-syms1
(append def-syms1 defstruct-syms1
struct-fns1)))
(forms2 (pseudo-load file2))
(def-syms2 (collect-defs forms2))
(defstruct-syms2 (collect-defstructs forms2))
(all-defs2 (append def-syms2 defstruct-syms2))
;collect dependent structure fn names in active-sims1
;for structures defined in forms2
(dep-struct-fns1 (collect-struct-fns defstruct-syms2 active-syms1)))
(let ((dependent-symbols
(append (set-difference (intersection active-syms1 all-defs2)
defstruct-syms2)
dep-struct-fns1)))
(if print
(format stream "~%~S symbols dependent on ~S definitions:~%~S~2%"
file1 file2 dependent-symbols)
(when dependent-symbols
(list file1 file2 dependent-symbols))))))
(defun file-depends-on-what (file1 &key (pathspec #P"*.lisp")
(stream *standard-output*) (print nil))
"Returns a list of, or prints, all dependencies of a file
in directory = *default-pathname-defaults*."
(loop with files = (mapcar #'file-namestring (directory pathspec))
for file2 in files
unless (equal file1 file2)
collect (file1-depends-on-file2 file1 file2 :stream stream)
into dependencies
finally (let ((actual-dependencies (delete-if #'null dependencies)))
(if print
(dolist (dep actual-dependencies)
(format stream
"~%~S symbols dependent on ~S definitions:~%~S~2%"
(first dep) (second dep) (third dep)))
(return actual-dependencies)))))
(defun backtrack-search (current-path adjacency-table visited)
"Recursively follow dependency paths from all file nodes, detecting cycles."
(let* ((node (first current-path))
(cycle (member node (reverse (cdr current-path)) :test #'equal)))
(if cycle
(progn (setf (gethash node visited) T)
(list cycle))
(let ((children (gethash node adjacency-table)))
(if children
(loop for child in children
unless (gethash child visited)
nconc (backtrack-search (cons child current-path)
adjacency-table visited)
finally (setf (gethash node visited) T))
(not (setf (gethash node visited) T)))))))
(defun search-for-codependents (node-list dependencies)
"Detects & returns all dependent cycles for all nodes
in a dependency network."
(let* ((node-count (length node-list))
(adjacency-table (make-hash-table :test #'equal :size node-count))
(visited (make-hash-table :test #'equal :size node-count)))
(loop for (file1 file2 *) in dependencies
do (push file2 (gethash file1 adjacency-table)))
(loop for node in node-list
do (clrhash visited)
nconc (backtrack-search (list node) adjacency-table visited)
into all-cycles
finally (return (delete-duplicate-cycles all-cycles)))))
(defun get-codependencies (dependencies)
"Returns all codependencies among a group of inter-dependent files."
(let ((file-list (delete-duplicates
(loop for (file1 file2 *) in dependencies
collect file1 collect file2)
:test #'equal)))
(search-for-codependents file-list dependencies)))
(defun get-all-dependencies (&key (pathspec #P"*.lisp")
(stream *standard-output*) (print nil))
"Returns or prints dependencies and codependencies of every pathspec file in
directory = *default-pathname-defaults*."
(let* ((files (mapcar #'file-namestring (directory pathspec)))
(dependencies (delete-if #'null
(alexandria:map-product
(lambda (file1 file2)
(unless (equal file1 file2)
(file1-depends-on-file2 file1 file2)))
files files)))
(codependencies (get-codependencies dependencies)))
(cond (print
(dolist (dep dependencies)
(format stream "~%~S symbols dependent on ~S definitions:~%~S~%"
(first dep) (second dep) (third dep)))
(format stream "~2%Codependent files (with circular references):~%")
(dolist (codep codependencies)
(format stream "~S~%" codep)))
(t (values dependencies codependencies)))))
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T22:29:51.167",
"Id": "256900",
"Score": "3",
"Tags": [
"file-system",
"common-lisp"
],
"Title": "Detecting Dependencies in Common Lisp Project Files (Part 2)"
}
|
256900
|
<p>I originally posted this on Stack overflow and was told to post it here, so here it is. Here's the stack overflow question: <a href="https://stackoverflow.com/questions/66528393/generic-class-for-a-gson-linkedhashmap">https://stackoverflow.com/questions/66528393/generic-class-for-a-gson-linkedhashmap</a></p>
<p>I have been working on this solution for months and I have come to the conclusion that there is no clean way to achieve what I am trying to achieve. I feel as though my education in polymorphism is failing me, so I've come to StackOverflow to get a second opinion. Sorry if this seems long and convoluted. That's been my brain for the past couple of months and at this point I'm out of ideas. I'm hoping somebody can take a look and see that I could've avoided all this mess by doing it some other way.</p>
<p>What I am trying to achieve is two generic classes: One that can represent any "saveable" object, and one that can represent a list of saveable objects (or what I call a "store"). A saveable object can save itself using GSON, and a store can also save itself using GSON to a JSON file. The difference being that saveable objects are generically representing any GSON object that can be saved, whereas stores are extending from saveables to become a saveable hash map of objects via IDs.</p>
<p>An example output I am looking for is as so:</p>
<p>Imagine I have an object with a uuid string field and a name string field. I want to be able to create a Store, which is a LinkedHashMap, of these objects, but also extend a Saveable to allow the objects to be saved as so:</p>
<p>test.json</p>
<pre><code>{"dbf39199209e466ebed0061a3491ed9e":{"uuid":"dbf39199209e466ebed0061a3491ed9e","name":"Example Name"}}
</code></pre>
<p>I would also like to be able to load this JSON back into the objects via the Store's load method.</p>
<p>An example code usage would be like so:</p>
<pre class="lang-java prettyprint-override"><code>Store<User> users = new Store<>();
users.load();
users.add(new User("dbf39199209e466ebed0061a3491ed9e", "Example Name"));
users.save();
</code></pre>
<h2>My Attempts</h2>
<h3>Saveables</h3>
<p>What I expect a "saveable" object to be able to do is as follows: provide a non-argumented method for saving and provide a non-argumented method for loading. A saveable object represents any object that can be saved via GSON. It contains two fields: a Gson gson object and a Path location. I provide those in the constructor of my saveable. I then want to provide two methods: a <code>Saveable#save()</code> method and a <code>Saveable#load()</code> method (or a static <code>Saveable#load()</code> method, I am indifferent). The way you use a Saveable object is by extending it (so it is abstract) to another object representing something, say, <code>TestSaveable</code>, and then the usage is as so:</p>
<pre class="lang-java prettyprint-override"><code>TestSaveable saveable = new TestSaveable(8);
saveable.save(); // Saves data
saveable.setData(4);
saveable = saveable.load(); // Loads old data
</code></pre>
<p>I also would like a saveable object to be able to handle a generic, such as an integer (think of the last example but with an integer generic). This would allow me to execute my next plan for Stores.</p>
<p>My attempt at an implementation was the following:</p>
<pre class="lang-java prettyprint-override"><code>public abstract class Saveable {
private transient Gson gson;
private transient Path location;
public Saveable(Gson gson, Path location) {
this.gson = gson;
this.location = location;
}
@SuppressWarnings("unchecked")
public <T extends Saveable> T save() throws IOException {
if (location.getParent() != null) {
Files.createDirectories(location.getParent());
}
Files.write(location, gson.toJson(this).getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, LinkOption.NOFOLLOW_LINKS);
return (T) this;
}
protected <T extends Saveable> T load(Class<T> clazz, @NotNull Class<?>... generics) throws IOException {
if (!Files.exists(location)) {
return this.save();
} else {
InstanceCreator<Saveable> creator = type -> this;
Type type = TypeToken.getParameterized(clazz, generics).getType();
Gson newGson = gson.newBuilder().registerTypeAdapter(type, creator).create();
return newGson.fromJson(Files.newBufferedReader(location), type);
}
}
}
</code></pre>
<p>Unfortunately, this attempt failed in my goal, because upon making my TestSaveable class users still had to pass the generic through for loading:</p>
<pre class="lang-java prettyprint-override"><code>public class TestSaveable<T> extends Saveable {
public boolean testBool = false;
public T value;
public TestSaveable(T value) {
super(new Gson(), Path.of("test.json"));
this.value = value;
}
public final TestSaveable<T> load(Class<T> generic) throws IOException {
return super.load(TestSaveable.class, generic);
}
}
</code></pre>
<p>However, through this I did get a fairly clean implementation with the exception of little to no type checking at all and constantly having to add supressions for it:</p>
<pre class="lang-java prettyprint-override"><code>public class Test {
public static void main(String[] args) {
try {
TestSaveable<Integer> storeB4 = new TestSaveable<>(5).save();
storeB4.value = 10;
TestSaveable<Integer> store = storeB4.load(Integer.class);
System.out.println("STORE: " + store);
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<h3>Stores</h3>
<p>Stores are an extension of saveables. A store is a LinkedHashMap which will quickly and easily save all of the objects in it as a map in GSON. Unfortunately, I'm not even sure where to start on this. I cannot extend two objects (the two being a LinkedHashMap<String, T> and a Saveable), but I also cannot use interfaces for the Saveable object.</p>
<p>I previously tried the following using the IStorable and ISaveable classes as an alternative to the abstract Saveable class I've shown you above, but this resulted in another very ugly and non-robust solution to my issue.</p>
<p>Saveable.java</p>
<pre class="lang-java prettyprint-override"><code>public class Saveable {
// Suppress default constructor
private Saveable() {}
// Save a class to the specified location using the specified gson
public static <T extends ISaveable> T save(T instance) throws IOException {
Files.createDirectories(instance.getLocation().getParent());
Files.write(instance.getLocation(), instance.getGson().toJson(instance).getBytes(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, LinkOption.NOFOLLOW_LINKS);
return instance;
}
// Load a file from the specified location using the specified gson and cast it to the specified class using the specified generic
public static <T extends ISaveable> ISaveable load(Path location, Gson gson, Class<T> clazz, Class<?> genericClazz) throws IOException {
if (!Files.exists(location)) {
return null;
} else {
TypeToken<?> type = genericClazz == null ? TypeToken.get(clazz) : TypeToken.getParameterized(clazz, genericClazz);
ISaveable saveable = gson.fromJson(Files.newBufferedReader(location), type.getType());
saveable.setGson(gson);
saveable.setLocation(location);
return saveable;
}
}
}
</code></pre>
<p>ISaveable.java</p>
<pre class="lang-java prettyprint-override"><code>public interface ISaveable {
// Gson
Gson getGson();
void setGson(Gson gson);
// Location
Path getLocation();
void setLocation(Path location);
}
</code></pre>
<p>IStorable.java</p>
<pre class="lang-java prettyprint-override"><code>public interface IStoreable {
String getUuid();
}
</code></pre>
<p>Store.java</p>
<pre class="lang-java prettyprint-override"><code>public class Store<T extends IStoreable> extends LinkedHashMap<String, T> implements ISaveable {
private transient Path location;
private transient Gson gson;
public Store(Path location, Gson gson) {
this.location = location;
this.gson = gson;
}
public Store() {
this.location = null;
this.gson = null;
}
public Store<T> put(T value) {
this.put(value.getUuid(), value);
return this;
}
public Store<T> remove(T value) {
this.remove(value.getUuid());
return this;
}
public Store<T> save() throws IOException {
return Saveable.save(this);
}
@SuppressWarnings("unchecked")
public static <T extends IStoreable> Store<T> load(Path location, Gson gson, Class<T> genericClazz) throws IOException {
ISaveable saveable = Saveable.load(location, gson, Store.class, genericClazz);
if (saveable == null) {
return new Store<T>(location, gson).save();
} else {
return (Store<T>) saveable;
}
}
}
</code></pre>
<p>This solution achieved me almost the result I was looking for, but fell short quickly on the loading process as well as just not being a robust solution, excluding the hundreds of Java practices I'm sure to have ruined at this point:</p>
<pre class="lang-java prettyprint-override"><code>Store<ExampleStoreable> store = Store.load(Paths.get("storetest.json"), new Gson(), ExampleStoreable.class);
store.put(new ExampleStoreable("Example Name"));
store.save();
</code></pre>
<p>And before I get any comments saying I shouldn't be posting this on StackOverflow: if not here, where else? Please help point me in the right direction, I'd love to not be left in the dark.</p>
<p>Thanks if anyone is able to help and if not I understand. This isn't the easiest question by any means.</p>
|
[] |
[
{
"body": "<p>Why do you need to provide a non-argument save and load methods? This means that you are packing storage logic into the data object and it violates the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>.</p>\n<p>Personally I do not even want to see annotations that are specific to certain storage mechanism in a data objects (and I am aware that it is a level of fundamentalism not shared by many people). Why should the data object know about the storage mechanism? Data should not be aware of how or where it is stored. That is the responsibility of the persistence layer. And once the persistence layer changes to <em>the newest fashionable serialization format</em>, all the data objects would have to change even though their main purpose and responsibility has not changed a bit.</p>\n<p>Because your <code>ISaveable</code> interface requires the <code>Path</code> parameter it is also very limited in where the data can be stored. E.g. everything has to go to a file in a file system. Should someone want to store the data to a generic OutputStream, a completely different implementation has to be written, so the framework isn't very flexible.</p>\n<p>So I suggest that unless you have very good reasons for the way you are implementing the storage (the convenience of calling one method is not it, that can be achieved with other designs too), I suggest that you move the storage mechanism into a separate persistence layer and implement the serialization by writing a <code>TypeAdapter</code> to each class that you or whoever uses the storage mechanism, stores to the system. Most likely the majority of data can use the default TypeAdapters that come with Gson but for complex types you have to provide a way to do custom serialization. And if your data objects change, you have to be able to provide a transformation from the now-incompatible-storage-format to the data model.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:54:47.517",
"Id": "507293",
"Score": "0",
"body": "I appreciate the insightful response. I actually found a working solution that I think may help explain what I was seeking for better. This is actually what I was going for - I wanted the Saveable object to not have any knowledge of the objects it needs to save, allowing for any object extending Saveable to simply run .save() and .load() without any knowledge of the upper classes (only handling the responsibility of saving and loading). GSON handles all type conversation and mapping. See my stackoverflow answer for what I'm talking about, I'll update it to include an example usage too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:40:19.883",
"Id": "256913",
"ParentId": "256901",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256913",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T00:35:18.883",
"Id": "256901",
"Score": "1",
"Tags": [
"java",
"json",
"generics",
"gson"
],
"Title": "Generic Class for a GSON LinkedHashMap"
}
|
256901
|
<p>I'm a Python beginner.</p>
<p>I have the following array of <strong>unique</strong> tuples I'm playing with:</p>
<pre><code>array = [(1, 2), (1, 7), (1, 5), (2, 5), (2, 7), (2, 9), (3, 4), (3, 5), (4, 5), (4, 7), (5, 8), (6, 7), (8, 9)]
</code></pre>
<p>I want to find the index of a given tuple (u, v) in this array. I wrote the following line which I believe can be improved, probably from removing the enumerate() to get simpler if conditions but can't figure it out...</p>
<p>Example for the tuple (6, 7) - Inputs are: 6 and 7</p>
<pre><code>array = [(1, 2), (1, 7), (1, 5), (2, 5), (2, 7), (2, 9), (3, 4), (3, 5), (4, 5), (4, 7), (5, 8), (6, 7), (8, 9)]
# Inputs: 6 and 7
position = [i for i, tupl in enumerate(array) if (tupl[0] == 6 and tupl[1] == 7)]
print(position)
# Output: [11]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T21:25:27.180",
"Id": "507399",
"Score": "0",
"body": "You state `I want to find the index …`. You set `position` to a *list comprehension*, `print(position)` shows a list."
}
] |
[
{
"body": "<p>You're looking for the <a href=\"https://docs.python.org/3/tutorial/datastructures.html\" rel=\"nofollow noreferrer\"><code>list.index</code></a> function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> array = [(1, 2), (1, 7), (1, 5), (2, 5), (2, 7), (2, 9), (3, 4), (3, 5), (4, 5), (4, 7), (5, 8), (6, 7), (8, 9)]\n>>> array.index((6, 7))\n11\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T01:36:35.407",
"Id": "507278",
"Score": "0",
"body": "thank you ^^ so obvious..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T01:02:09.243",
"Id": "256904",
"ParentId": "256903",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T00:57:33.843",
"Id": "256903",
"Score": "2",
"Tags": [
"python",
"beginner"
],
"Title": "Find the index of a tuple in a list of tuples in Python"
}
|
256903
|
<p>This cipher takes a byte array and applies a relatively 'random' offset for each byte. In order to keep track of the offsets, to allow the encryption to be reversed, I decided against maintaining a list of offsets, like the old school one-time pads, and went with using the first byte of the hash of the key, then rehashing the hash. To increase the complexity of the encryption, I used the 1st bit of the second element of the hash, to set the direction of the offset.</p>
<p>The offsets aren't truly random, but the encrypted bytes of a 2mb text file, do pass all the tests in the NIST test suite</p>
<pre><code>class Cipher
{
private enum EncryptionMode
{
Encrypt = 1,
Decrypt = -1
}
public static byte[] Encrypt(string key, byte[] data)
{
return DeEncrypt(key, data, EncryptionMode.Encrypt);
}
public static byte[] Decrypt(string key, byte[] data)
{
return DeEncrypt(key, data, EncryptionMode.Decrypt);
}
private static byte[] DeEncrypt(string key, byte[] data, EncryptionMode mode)
{
if(key == null)
{
key = "";
}
if(data == null)
{
data = new byte[] { 0 };
}
var temp = HashCode(Encoding.ASCII.GetBytes(key));
var newData = new byte[data.Length];
for (int i = 0; i < data.Length; ++i)
{
newData[i] = GetNewValue(data[i], temp, mode);
temp = HashCode(temp);
}
return newData;
}
private static byte[] HashCode(byte[] input)
{
var hash = Sha3.Sha3512().ComputeHash(input);
return hash;
}
private static byte GetNewValue(byte value, byte[] hash, EncryptionMode mode)
{
//This determines the direction of the offset based on the 1st bit of the second byte in the hash
//and switches it according to the encryption mode.
var direction = (((hash[1] & 1) * 2) - 1) * (int)mode;
var offset = hash[0] * direction;
return (byte)ShiftMod256((ulong)(value + 256 + offset));
}
//Since only mod 256 is used I figured bit shifting would be better than division.
public static ulong ShiftMod256(ulong num)
{
return (num << 56) >> 56;
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T01:49:13.487",
"Id": "256907",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Enhanced Caesar Cipher"
}
|
256907
|
<p>I'm writing a comparison of a simple word-counting program in various languages. The task is to count the frequencies of unique, space-separated words in the input, and output the results most frequent first. Case should be normalized to lowercase (ASCII is okay).</p>
<p>But it's been a long time since I've written C++ (before the C++11 days). Is this idiomatic modern C++? Any improvements I could make to make this more idiomatic or simpler (I'm not looking for efficiency improvements here). I want to stick to the standard library.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm>
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
string word;
unordered_map<string, int> counts;
while (cin >> word) {
transform(word.begin(), word.end(), word.begin(),
[](unsigned char c){ return tolower(c); });
counts[word]++;
}
vector<pair<string, int>> ordered(counts.begin(), counts.end());
sort(ordered.begin(), ordered.end(), [](auto &a, auto &b) {
return a.second > b.second;
});
for (auto count : ordered) {
cout << count.first << " " << count.second << "\n";
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T11:58:52.627",
"Id": "507321",
"Score": "1",
"body": "When the article is ready, it would be great if you were to link to it from here (assuming it will be on the Web)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T23:18:34.543",
"Id": "507406",
"Score": "2",
"body": "@TobySpeight Good idea -- will do!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:02:40.073",
"Id": "507491",
"Score": "1",
"body": "I spent more time that I should have trying to answer this question using `std::make_heap` since it brings the largest value to the top automatically. It did not go well..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T09:32:26.403",
"Id": "507908",
"Score": "0",
"body": "Published article: https://benhoyt.com/writings/count-words/"
}
] |
[
{
"body": "<p>Mainly this looks fine.</p>\n<ul>\n<li><p><code>using namespace std;</code> is a bad habit to get into due to potential name collisions. Instead prefer to type <code>std::</code> where necessary.</p>\n</li>\n<li><p><code>counts[word]++;</code>. We don't need an un-incremented copy of the count, so we should use pre-increment here instead: <code>++counts[word];</code></p>\n</li>\n<li><p><code>sort(ordered.begin(), ordered.end(), [](auto &a, auto &b)</code> we don't alter <code>a</code> or <code>b</code> in the lambda, so these should be <code>const&</code>.</p>\n</li>\n<li><p><code>for (auto count : ordered)</code> copies the pairs. Again, we should be using <code>auto const&</code> here.</p>\n</li>\n<li><p><code>return 0;</code> we don't need this, as the compiler will add it for us automatically. We might also use a named constant instead of <code>0</code>, specifically <code>EXIT_SUCCESS</code> from <code><cstdlib></code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:35:20.217",
"Id": "507312",
"Score": "3",
"body": "You missed the failure to include `<cctype>`, needed for `std::tolower()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T19:05:53.937",
"Id": "507381",
"Score": "0",
"body": "Thank you -- appreciate these tweaks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:40:07.747",
"Id": "256916",
"ParentId": "256910",
"Score": "12"
}
},
{
"body": "<p><a href=\"/a/256916/75307\">user673679's answer</a> deals with low-level review; I'll look at the algorithm.</p>\n<p>First, top marks for avoiding the most common error with functions from <code><cctype></code> - it's vitally important to pass the value as <strong><code>unsigned char</code> promoted to int</strong>, rather than plain <code>char</code>.</p>\n<p>Rather than writing my own loop for reading the words, I would consider <code>transform()</code> from an input-stream iterator to a map inserter. That said, we'd need to construct a custom iterator for the inserter we want. It would be very straightforward if we were using a <code>std::multiset</code>, but that would use more memory (as it stores all the added objects). We could create a "counter" class with appropriate <code>push_back()</code>, if we were likely to use it again.</p>\n<p>After the <code>while</code> loop, we should test <code>std::cin.bad()</code> (or set the stream to throw on error). At present, any stream error is ignored, and we proceed as if we'd read the entire input, giving misleading results.</p>\n<p>Instead of populating a vector, and subsequently sorting it, we might prefer to insert directly into an ordered container (<code>std::set</code> perhaps).</p>\n<p>Something we can do in modern C++ is to write nested functions, by assigning a lambda expression to a variable. This may be clearer than writing the lambda inline. Or we can use the anonymous namespace for functions with static linkage.</p>\n<p>Here's my modification of the code to have no explicit loops, or indeed any flow-control statements:</p>\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <iostream>\n#include <iterator>\n#include <set>\n#include <string>\n#include <unordered_map>\n#include <utility>\n</code></pre>\n<pre><code>namespace {\n auto downcase(std::string s) {\n std::transform(s.begin(), s.end(), s.begin(),\n [](unsigned char c){ return std::tolower(c); });\n return s;\n }\n}\n</code></pre>\n<pre><code>int main()\n{\n using counter = std::unordered_map<std::string, unsigned>;\n using in_it = std::istream_iterator<std::string>;\n using out_it = std::ostream_iterator<std::string>;\n\n counter counts;\n auto insert = [&](std::string s) { ++counts[downcase(std::move(s))]; };\n\n // read words into counter\n std::cin.exceptions(std::istream::badbit);\n std::for_each(in_it{std::cin}, in_it{}, insert);\n\n // sort by frequency, then alphabetical\n auto by_freq_then_alpha = [](const auto &a, const auto &b) {\n return std::pair{ b.second, a.first } < std::pair{ a.second, b.first};\n };\n const std::set ordered{counts.begin(), counts.end(), by_freq_then_alpha};\n\n // write the output\n auto format = [](const auto& count) {\n return count.first + ' ' + std::to_string(count.second) + '\\n';\n };\n std::transform(ordered.begin(), ordered.end(), out_it{std::cout}, format);\n}\n</code></pre>\n<hr />\n<p>For a more modern take, C++20 includes the Ranges library, which lets us use views to transform collections:</p>\n<pre><code>int main()\n{\n using counter = std::unordered_map<std::string, unsigned>;\n\n counter counts;\n auto insert = [&counts](std::string s) { ++counts[downcase(std::move(s))]; };\n\n // read words into counter\n std::cin.exceptions(std::istream::badbit);\n auto input_words = std::ranges::istream_view<std::string>(std::cin);\n std::ranges::for_each(input_words, insert);\n\n // sort by frequency, then alphabetical\n auto by_freq_then_alpha = [](const auto &a, const auto &b) {\n return std::pair{ b.second, a.first } < std::pair{ a.second, b.first};\n };\n const std::set ordered{counts.begin(), counts.end(), by_freq_then_alpha};\n\n // write the output\n auto write_out = [](const auto& count) {\n std::cout << count.first << ' ' << count.second << '\\n';\n };\n std::ranges::for_each(ordered, write_out);\n}\n</code></pre>\n<hr />\n<p>I'm not saying that either of these is necessarily what you <em>should</em> write; at least for now, the range-based loops are more familiar to most C++ programmers, and so probably clearest.\nHowever, it showcases some of the options we have in modern C++.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T14:42:57.267",
"Id": "507339",
"Score": "4",
"body": "While correct and very idiomatic C++, I actually slightly prefer OPs code for readability, it's slightly shorter and easier to scan, then again I have 20 years of habit/experience reading for loops and they just read clearer to me than transform/for_each and company from <algorithm>. They do have their place tho."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T19:09:01.977",
"Id": "507382",
"Score": "0",
"body": "Well, this has been an education, thank you! Definitely a very different, more functional approach. I do prefer the plainer, for-loop approach (perhaps because this reminds me of Scala, which I don't have warm fuzzy feelings for). And thanks for the tip about error handling."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T11:02:58.243",
"Id": "256920",
"ParentId": "256910",
"Score": "9"
}
},
{
"body": "<p>Added: structured bindings</p>\n<p>Changed: to using range based algorithms. (C++20) This removes the need for begin()/end() and you can use a projection in the sort call.</p>\n<p>Removed: lambdas - not needed</p>\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <string>\n#include <unordered_map>\n#include <vector>\n\nusing namespace std;\n\nint main()\n{\n unordered_map<string, int> counts;\n\n string word;\n while (cin >> word) {\n ranges::transform(word, word.begin(), ::tolower);\n counts[word]++;\n }\n\n using word_count = pair<string, int>;\n\n vector<word_count> ordered(counts.begin(), counts.end());\n ranges::sort(ordered, greater{}, &word_count::second);\n\n for (auto [word, count] : ordered) {\n cout << word << " " << count << "\\n";\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T17:32:25.297",
"Id": "507487",
"Score": "1",
"body": "The lambda wrapping `std::tolower` is very definitely needed - using the `<cctype>` functions by directly promoting their arguments from plain `char` to `int` leads to UB on platforms where `char` is signed. Always convert to `unsigned char` before converting to `int`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T17:33:32.053",
"Id": "507488",
"Score": "0",
"body": "The range stuff is great - thanks for helping me get more proficient with that part of the Library!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T02:57:50.923",
"Id": "256948",
"ParentId": "256910",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256916",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T06:12:17.617",
"Id": "256910",
"Score": "13",
"Tags": [
"c++",
"sorting",
"hash-map"
],
"Title": "Count word frequencies, and print them most-frequent first"
}
|
256910
|
<p>In this program, I'm going to take some information about student's height, weight, and age and return the average of all of them to compare. there are 2 classes to compare and the program works fine but I want to know, is there any way to improve this program and make it better?</p>
<pre><code>information = []
for i in range(8):
information.append(input().split())
information = [[int(x) for x in line] for line in information]
class Student_A:
def __init__(self, age, height, weight, age_b, height_b, weight_b):
self.age = age
self.height = height
self.weight = weight
self.age_b = age_b
self.height_b = height_b
self.weight_b = weight_b
def get_info(self):
a = (sum(self.age) / len(self.age))
b = (sum(self.height) / len(self.height))
c = (sum(self.weight) / len(self.weight))
e = (sum(self.age_b) / len(self.age_b))
f = (sum(self.height_b) / len(self.height_b))
g = (sum(self.weight_b) / len(self.weight_b))
yield a
yield b
yield c
yield e
yield f
yield g
if b == f and c == g:
print('Same')
elif b == f:
if c < g:
print('A')
else:
print('B')
elif b > f:
print('A')
else:
print('B')
class_a = Student_A(information[1], information[2], information[3], information[5], information[6], information[7])
class_a = class_a.get_info()
for item in class_a:
print(item)
</code></pre>
<p>input should be like this :</p>
<pre><code># inputs must be entered line by line not every single number
5 # number of students
16 17 15 16 17
180 175 172 170 165
67 72 59 62 55
5
15 17 16 15 16
166 156 168 170 162
45 52 56 58 47
</code></pre>
<p>output should be like this :</p>
<pre><code>16.2
172.4
63.0
15.8
164.4
51.6
A # the best class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:52:50.073",
"Id": "507304",
"Score": "0",
"body": "my bad sorry let me fix it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T09:01:23.027",
"Id": "507306",
"Score": "1",
"body": "it should work right now"
}
] |
[
{
"body": "<p>A critical rule to remember about coding is: If a bunch of your lines look basically the same, you can probably simplify your program using for-loops.</p>\n<p>This is true for your code as well. If, instead of storing all the information in different variables, you just store them in a single tuple for each student, you can greatly shorten your code using for-loops.</p>\n<pre class=\"lang-py prettyprint-override\"><code>information = []\nfor i in range(8):\n information.append(input().split())\n\ninformation = [[int(x) for x in line] for line in information]\n\n\n\nclass Student_A:\n\n def __init__(self, age, height, weight, age_b, height_b, weight_b):\n self.student_a = (age, height, weight)\n self.student_b = (age_b, height_b, weight_b)\n\n def get_info(self):\n abc = []\n efg = []\n for i in range(len(self.student_a)): \n abc.append(sum(self.student_a[i]) / len(self.student_a[i]))\n efg.append(sum(self.student_b[i]) / len(self.student_b[i]))\n\n for info in abc:\n yield info\n for info in efg:\n yield info\n\n if abc[1] == efg[1] and abc[2] == efg[2]:\n print('Same')\n elif abc[1] == efg[1]:\n if abc[2] < efg[2]:\n print('A')\n else:\n print('B')\n elif abc[1] > efg[1]:\n print('A')\n else:\n print('B')\n\nclass_a = Student_A(information[1], information[2], information[3], information[5], information[6], information[7])\nclass_a = class_a.get_info()\nfor item in class_a:\n print(item)\n</code></pre>\n<p>Note that <code>for i in range(len(self.student_a)):</code> only works because <code>self.student_a</code> and <code>self.student_b</code> are defined to be the same length. It just does the <code>sum / len</code> calculation for every piece of information.</p>\n<p>Also, instead of yielding every variable, now just iterate through <code>abc</code> and <code>efg</code>!</p>\n<p>The last complicated if-statement also needs to use indexes instead of variables, but thanks to my informative list names it should be simple to understand.</p>\n<p>If there's anything else you would like to clarify, feel free to ask me!</p>\n<p>Note: If you want to shorten your code even more, you can just have 1 tuple for both students. In my opinion, though, that's not particularly readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T17:48:08.223",
"Id": "256937",
"ParentId": "256914",
"Score": "2"
}
},
{
"body": "<p>If I understand things correctly, the <code>Student_A</code> class is a strange creature:\n(1) it stores lists of ages, heights, and weights for two groups of students;\n(2) it computes the age, height, and weight averages each of the groups; and\n(3) it does some logic to compare the averages. If we ask what meaningful\nreal-world entity a <code>Student_A</code> instance is supposed to represent, there isn't\none. That suggests that there is a problem with the design.</p>\n<p>Here's a class that does make sense in the real world:</p>\n<pre><code>class StudentGroup:\n\n def __init__(self, ages, heights, weights):\n # Note the use of plural variable names.\n # Don't call it an "age" if it's really a list of ages.\n self.ages = ages\n self.heights = heights\n self.weights = weights\n</code></pre>\n<p>Each <code>StudentGroup</code> instance would hold the ages, heights, and weights for\n<strong>one group</strong>. The program would create two instances of the class and\nthen perform the other calculations and comparisons.</p>\n<p>The class needs a way to obtain the averages. This is a good use case for a\n<code>@property</code> and the standard library's <code>statistics</code> module.</p>\n<pre><code>from statistics import mean\n\nclass StudentGroup:\n\n @property\n def avg_age(self):\n return mean(self.ages)\n\n # Do the same for height and weight.\n</code></pre>\n<p>To compare the groups, you just need to implement two methods on the class, and\ninclude the <code>total_ordering</code> decorator. It allows you to directly\ncompares two instances of a class in various ways (<code><</code>, <code><=</code>, <code>==</code>, <code>>=</code>, <code>></code>),\nprovided that you implement the two methods shown below.</p>\n<pre><code>from functools import total_ordering\n\n@total_ordering\nclass StudentGroup:\n\n def __eq__(self, other):\n return (\n self.avg_height == other.avg_height and\n self.avg_weight == other.avg_weight\n )\n\n def __lt__(self, other):\n # You can implement this one. Return True if self < other.\n</code></pre>\n<p>Regarding input parsing, I suggest that you organize the parsing to align with\nthe program's larger goal: don't collect 8 input lines; instead collect 4 input\nlines twice. Also, put all of your code inside functions:</p>\n<pre><code>def line_to_ints(line):\n # A utility function to parse one line of user input.\n return [int(x) for x in line.split()]\n\ndef main():\n # Create two StudentGroup instances.\n sgs = []\n for _ in range(2):\n # Get lines of input from user. Don't parse here.\n lines = [input() for _ in range(4)]\n\n # Parse the needed lines into a list-of-list of ints.\n params = [line_to_ints(line) for line in lines[1:]]\n\n # Create a new StudentGroup instance.\n sgs.append(StudentGroup(*params))\n\n # Compare them.\n msg = (\n 'Same' if sgs[0] == sgs[1] else\n 'A' if sgs[0] > sgs[1] else\n 'B'\n )\n\n # Report.\n print(msg)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T09:05:20.757",
"Id": "507435",
"Score": "0",
"body": "is it ok to do the printing inside a function? because once you said to do the printing outside the function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T09:27:54.550",
"Id": "507436",
"Score": "2",
"body": "@Xus Printing inside functions is fine -- definitely the way to go. The key question is what type of function is it? Functions with computations should not print; they should return data or modify data. Printing should occur in the outer shell of a program inside of a function that doesn't do anything complicated (usually that means the `main()` function). To review my own code in the answer above, one could argue that most of the work should be delegated to two helper functions: `get_user_input()` and `parse()`. But still print in `main()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T09:33:19.560",
"Id": "507437",
"Score": "1",
"body": "thank you I got it"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:05:53.187",
"Id": "256939",
"ParentId": "256914",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "256939",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T07:48:48.527",
"Id": "256914",
"Score": "2",
"Tags": [
"python",
"classes"
],
"Title": "health care program"
}
|
256914
|
<p>I've created a simple worker service, which uses FluentFTP to sync either files or directories from one ftp client to another, or simply to a local machine, depending on how appsettings.json is configured. Overall I'm pretty happy with the code, but there's certain points I find the code repeats itself or looks a bit messy. This is the first micro-service I've finished, would love some thoughts on how I can improve it.</p>
<pre><code>public class FtpWorker : IFtpWorker
{
private readonly ILogger<FtpWorker> _logger;
private TransferSettingsOptions _options;
private string _localDirectory;
public FtpWorker(ILogger<FtpWorker> logger)
{
_logger = logger;
}
public async Task RunAsync(TransferSettingsOptions options)
{
_options = options;
_localDirectory = _options.LocalPath;
if (!_options.LocalPathIsFile)
{
Directory.CreateDirectory(_options.LocalPath);
}
switch (DetermineRunMode())
{
case RunMode.DownloadDir:
await RunDownloadDirAsync();
break;
case RunMode.DownloadFile:
await RunDownloadFileAsync();
break;
case RunMode.UploadDir:
await RunUploadDirAsync();
break;
case RunMode.UploadFile:
await RunUploadFileAsync();
break;
case RunMode.SyncDirs:
await RunSyncDirsAsync();
break;
case RunMode.SyncFile:
await RunSyncFileAsync();
break;
default:
break;
};
}
private async Task RunDownloadDirAsync()
{
if (_options.Source is not null && !string.IsNullOrWhiteSpace(_options.Source.Server))
{
try
{
await DownloadDirectoryFromSourceAsync();
}
catch (Exception ex)
{
_logger.LogError("Exception in RunDownloadDirAsync: {Message}", ex.Message);
}
}
}
private async Task RunDownloadFileAsync()
{
if (_options.Source is not null && !string.IsNullOrWhiteSpace(_options.Source.Server))
{
try
{
await DownloadFileFromSourceAsync();
}
catch (Exception ex)
{
_logger.LogError("Exception in RunDownloadDirAsync: {Message}", ex.Message);
}
}
}
private async Task RunUploadDirAsync()
{
throw new NotImplementedException();
}
private async Task RunUploadFileAsync()
{
if (_options.Destination != null && !string.IsNullOrWhiteSpace(_options.Destination.Server))
{
try
{
await UploadFileToDestinationAsync();
}
catch (Exception ex)
{
_logger.LogError("Exception in RunUploadFileAsync: {Message}", ex.Message);
}
}
else
{
_logger.LogError("Destination or DestinationServer empty in RunUploadFile");
}
}
private async Task RunSyncDirsAsync()
{
if (_options.Source != null || !string.IsNullOrWhiteSpace(_options.Source.Server))
{
try
{
await DownloadDirectoryFromSourceAsync();
}
catch (Exception ex)
{
_logger.LogError("Exception in DownloadFromSource: {Message}", ex.Message);
}
}
else
{
_logger.LogDebug("No source configured.");
}
foreach (var opt in _options.ChangeExtensions)
{
ChangeFileExtensions(opt);
}
if (_options.Destination != null || !string.IsNullOrWhiteSpace(_options.Destination.Server))
{
try
{
await UploadDirectoryToDestinationAsync();
}
catch (Exception ex)
{
_logger.LogError("Exception in UploadToDestination: {Message}", ex.Message);
}
}
else
{
_logger.LogDebug("No destination configured.");
}
}
private Task RunSyncFileAsync()
{
throw new NotImplementedException();
}
private async Task<List<FtpResult>> DownloadDirectoryFromSourceAsync()
{
var token = new CancellationToken();
using (var ftp = new FtpClient(_options.Source.Server, _options.Source.Port, _options.Source.User, _options.Source.Password))
{
ftp.OnLogEvent += Log;
await ftp.ConnectAsync(token);
var rules = new List<FtpRule>
{
new FtpFileExtensionRule(true, _options.Source.FileTypesToDownload)
};
var results = await ftp.DownloadDirectoryAsync(_options.LocalPath, _options.Source.RemotePath, FtpFolderSyncMode.Update,
FtpLocalExists.Skip, FtpVerify.None, rules);
if (_options.Source.DeleteOnceDownloaded)
{
foreach (var download in results)
{
if (download.IsSuccess && download.Type == FtpFileSystemObjectType.File)
{
await ftp.DeleteFileAsync(download.RemotePath);
}
}
}
foreach (var download in results)
{
if (download.IsFailed)
{
_logger.LogWarning("Download of {Name} failed: {Exception}", download.Name, download.Exception);
}
}
return results;
}
}
private async Task<FtpStatus> DownloadFileFromSourceAsync()
{
var token = new CancellationToken();
using (var ftp = new FtpClient(_options.Source.Server, _options.Source.Port, _options.Source.User, _options.Source.Password))
{
ftp.OnLogEvent += Log;
await ftp.ConnectAsync(token);
var overwriteExisting = _options.Source.OverwriteExisting ? FtpLocalExists.Overwrite : FtpLocalExists.Skip;
string localPath = _options.Destination.RemotePath;
if (!_options.LocalPathIsFile)
{
var fileName = Path.GetFileName(_options.Source.RemotePath);
localPath = $"{_options.LocalPath}/{fileName}";
}
var result = await ftp.DownloadFileAsync(localPath, _options.Source.RemotePath, overwriteExisting);
if (_options.Source.DeleteOnceDownloaded)
{
if (result.IsSuccess())
{
try
{
await ftp.DeleteFileAsync(_options.Source.RemotePath, token);
}
catch (Exception ex)
{
_logger.LogWarning("Error deleting {RemotePath}: {Message}", _options.Source.RemotePath, ex.Message);
}
}
}
return result;
}
}
private void ChangeFileExtensions(ChangeExtensionsOptions options)
{
foreach (var file in Directory.GetFiles(_localDirectory, $"*.{options.Source}"))
{
var newFileName = @$"{_localDirectory}\{Path.GetFileNameWithoutExtension(file)}.{options.Target}";
try
{
File.Move(file, newFileName, true);
}
catch (Exception ex)
{
_logger.LogWarning("Moving file {file} failed: {Message}", file, ex.Message);
}
}
}
private async Task<FtpStatus> UploadFileToDestinationAsync()
{
var token = new CancellationToken();
using (var ftp = new FtpClient(_options.Destination.Server, _options.Destination.Port, _options.Destination.User, _options.Destination.Password))
{
ftp.OnLogEvent += Log;
await ftp.ConnectAsync(token);
var overwriteExisting = _options.Destination.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip;
string remotePath = _options.Destination.RemotePath;
if (!_options.Destination.RemotePathIsFile)
{
var fileName = Path.GetFileName(_options.LocalPath);
remotePath = $"{_options.Destination.RemotePath}/{fileName}";
}
var result = await ftp.UploadFileAsync(_options.LocalPath, remotePath, overwriteExisting);
if (_options.Destination.DeleteOnceUploaded)
{
if (result.IsSuccess())
{
try
{
if (_options.LocalPathIsFile)
{
File.Delete(_options.LocalPath);
}
}
catch (Exception ex)
{
_logger.LogWarning("Error deleting {LocalPath}: {Message}", _options.LocalPath, ex.Message);
}
}
}
return result;
};
}
private async Task<List<FtpResult>> UploadDirectoryToDestinationAsync()
{
var token = new CancellationToken();
using (var ftp = new FtpClient(_options.Destination.Server, _options.Destination.Port, _options.Destination.User, _options.Destination.Password))
{
ftp.OnLogEvent += Log;
await ftp.ConnectAsync(token);
var results = await ftp.UploadDirectoryAsync(_options.LocalPath, _options.Destination.RemotePath, FtpFolderSyncMode.Update,
FtpRemoteExists.Skip, FtpVerify.None);
if (_options.Destination.DeleteOnceUploaded)
{
foreach (var upload in results)
{
if (upload.IsSuccess)
{
try
{
File.Delete(upload.LocalPath);
_logger.LogInformation("File deleted: {LocalPath}", upload.LocalPath);
}
catch (Exception ex)
{
_logger.LogWarning("Error deleting file {LocalPath}: {Message}", upload.LocalPath, ex.Message);
}
}
}
}
foreach (var upload in results)
{
if (upload.IsFailed)
{
_logger.LogWarning("Upload of {LocalPath} failed: {Exception}", upload.LocalPath, upload.Exception);
}
}
return results;
}
}
private RunMode DetermineRunMode()
{
if (_options.LocalPathIsFile)
{
_logger.LogDebug("Local Path: {LocalPath} is file, RunMode determined as UploadFile", _options.LocalPath);
return RunMode.UploadFile;
}
else if (_options.Source is not null && _options.Destination is not null)
{
if (_options.Source.RemotePathIsFile)
{
_logger.LogDebug("Source & Destination defined, Source.RemotePath: {RemotePath} is file, RunMode determined as SyncFile", _options.Source.RemotePath);
return RunMode.SyncFile;
}
else
{
_logger.LogDebug("Source & Destination defined, Source.RemotePath: {RemotePath} is directory, RunMode determined as SyncDirs", _options.Source.RemotePath);
return RunMode.SyncDirs;
}
}
else if (_options.Source is null && _options.Destination is not null)
{
if (_options.Destination.RemotePathIsFile)
{
_logger.LogDebug("Only Destination defined, Destination.RemotePath: {RemotePath} is file, RunMode determined as UploadFile", _options.Destination.RemotePath);
return RunMode.UploadFile;
}
else
{
_logger.LogDebug("Only Destination defined, Destination.RemotePath: {RemotePath} is directory, RunMode determined as UploadDir", _options.Destination.RemotePath);
return RunMode.UploadDir;
}
}
else
{
if (_options.Source.RemotePathIsFile)
{
_logger.LogDebug("Only Source defined, Source.RemotePath: {RemotePath} is file, RunMode determined as DownloadFile", _options.Source.RemotePath);
return RunMode.DownloadFile;
}
else
{
_logger.LogDebug("Only Source defined, Source.RemotePath: {RemotePath} is directory, RunMode determined as DownloadDir", _options.Source.RemotePath);
return RunMode.DownloadDir;
}
}
}
</code></pre>
<p>I'm curious if there's an easier way to handle the using statements, as I seem to be passing in params in the same way every time, is there a better way?</p>
|
[] |
[
{
"body": "<p>Quick remarks:</p>\n<ul>\n<li><p>I notice you always use <code>ex.Message</code>. However, what if you've got an <code>InnerException</code>? I'd recommend an approach <a href=\"https://github.com/BJMdotNET/code-samples/blob/master/ExceptionMessageRetriever.cs\" rel=\"nofollow noreferrer\">like this</a> (I've copied the code of the method below; note that you can adapt the <code>string.Join</code> to your own liking, of course). Also, I'd also recommend to log the entire stack trace as well, in case you run into an exception where the message doesn't tell you enough.</p>\n<pre><code> public static string Execute(Exception exc)\n {\n var messages = new List<string>();\n do\n {\n messages.Add(exc.Message);\n exc = exc.InnerException;\n }\n while (exc != null);\n\n return string.Join(" - ", messages);\n }\n</code></pre>\n</li>\n<li><p>In several places you use <code>new FtpClient(_options.Source.Server, _options.Source.Port, _options.Source.User, _options.Source.Password)</code>. Move this to a method and call that method. Same with <code>new FtpClient(_options.Destination.Server, _options.Destination.Port, _options.Destination.User, _options.Destination.Password)</code>.</p>\n<p>Matter of fact, if <code>_options.Source</code> and <code>_options.Destination</code> are the same type (which I'd expect, but you haven't posted this class), I'd recommend a method that accepts this class as a parameter and returns an <code>FtpClient</code>.</p>\n</li>\n<li><p><code>DetermineRunMode()</code> is too noisy and repetitive and inelegant for me. I'd favor an approach where you'd determine various factors (e.g. whether both <code>Source</code> and <code>Destination</code> are defined) and at the end compile a message, e.g.</p>\n<pre><code>var sourceIsNotNull = _options.Source is not null;\nvar destinationIsNotNull = _options.Destination is not null;\nvar message = (sourceIsNotNull && destinationIsNotNull)\n ? "Source & Destination defined"\n : sourceIsNotNull\n ? "Only Source defined"\n : "Only Destination defined";\n</code></pre>\n<p>Maybe you could have a method for each "factor" e.g. which is defined, what the <code>RunMode</code> is, whether <code>RemotePath</code> is a file or a folder,..., perhaps even move all that to a separate class (called <code>RunModeRetriever</code> or alike).</p>\n<p>(Also, considering you're doing a <code>return</code>, I don't think all those <code>else</code>s are even necessary.)</p>\n</li>\n<li><p>You check too much in the methods themselves. In <code>RunDownloadDirAsync</code> you already know that <code>_options.Source is not null</code> (because that is checked in <code>DetermineRunMode</code> and <code>RunDownloadDirAsync</code> is called due to the result of that method call) so there is no need to be "extra careful": this only adds noise to your logic. You aren't even consistent: you log <code>_logger.LogError("Destination or DestinationServer empty in RunUploadFile");</code>, but there is no equivalent for <code>string.IsNullOrWhiteSpace(_options.Source.Server)</code>.</p>\n<p>You should move all those checks before executing <code>DetermineRunMode</code>, perhaps even rethink that logic into a "data check" class which looks at the <code>TransferSettingsOptions</code>, verifies all the necessary data is in there, returns a "fail" if there is required data missing combined with a report of what is missing, and returns a "success" when all is OK, and perhaps also determines the <code>RunMode</code> while doing all those checks.</p>\n<p>Or perhaps you should group the data checks, return a report, and based on that report either you stop execution of the method and report to the user why you have stopped execution, or you continue the execution by determining the <code>RunMode</code> (using the data in the data check report), and then call the relevant method without having to worry that a certain setting is missing.</p>\n<p><strong>The important point is to group your functionality, that way you can remove redundant code and improve the logic flow of the method.</strong></p>\n</li>\n<li><p>Each method has a <code>try...catch</code>. Why not put the <code>try...catch</code> around the <code>switch (DetermineRunMode())</code> instead? Just make sure to include the <code>RunMode</code> when you log any eventual <code>Exception</code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T13:08:39.167",
"Id": "507331",
"Score": "0",
"body": "Thank you, the extension method for exceptions is very useful, I hadn't even considered that, and I knew there was an easier way to set up the using statements, thanks again.\n\nRegarding your comments on `DetermineRunMode()`, I'm not sure I understand how your proposed changes would improve things, isn't adding a load of inline conditionals just confusing things further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T13:16:44.770",
"Id": "507335",
"Score": "0",
"body": "Ah, actually I see, redundant calls, you're just putting the booleans in variables so they don't have to go `if source is null` then next time `if source is not null`, got it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T17:54:30.650",
"Id": "507376",
"Score": "1",
"body": "@GaryMacGregor-Manzi It's not only the redundancy of the calls, but also the constant switching of functionality: you check the data, then you determine the RunMode, then you call a specific method based on the RunMode, which then does more data checking. Group the functionality: first check the data, because there is no point in doing the rest of the actions if that is incomplete. Then determine the RunMode, then execute the relevant method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T10:39:51.470",
"Id": "507576",
"Score": "0",
"body": "I've removed some extraneous checks, but the reason `DetermineRunMode()` checks if source/destination are null, is my aim is to use appsettings.json to automatically determine which mode to use - so for example if the user leaves the destination out completely, the code will determine it only wants to download, so it's perfectly valid to not have a destination or source depending on the situation. Unsure how to break it down further without performing the same checks repeatedly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:41:10.453",
"Id": "507582",
"Score": "0",
"body": "@GaryMacGregor-Manzi If the destination is optional, then it shouldn't be part of the data checks (or it can be but it shouldn't be a cause to stop the execution). My point is that you do `_options.Source is not null` inside the method that is only called if `_options.Source` isn't null, so that check is redundant. Then you check `!string.IsNullOrWhiteSpace(_options.Source.Server)` which isn't in the right place, because if that is a required value it should be checked before the method is called, i.e. before `DetermineRunMode` is called. Group your functionality instead of mixing it all over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T13:26:33.303",
"Id": "507591",
"Score": "0",
"body": "Ah, I understand now, thank you for your patience!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T10:44:11.127",
"Id": "256919",
"ParentId": "256915",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "256919",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T08:31:05.073",
"Id": "256915",
"Score": "4",
"Tags": [
"c#",
".net-5"
],
"Title": "FtpEasyTransfer - .NET5 Worker Service for Easy FTP Sync'ing"
}
|
256915
|
<p>I'm trying to solve the sorting problem but I always get TLE(Time Limit Exceeded/ 1s) so... can you guys suggest a more efficient way to solve this problem?
(i can't link the exercise because it is on the closed server)</p>
<p>code reads test count <em>t</em> , <em><int, string></em> pairs then sorts by <em>integer</em> in ascending order and prints <em>median</em></p>
<pre><code>#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
vector< pair <int,string> > median;
int t; cin >> t;
int num; string name;
for(int i=0;i<t;i++) {
cin>>name; cin>>num;
median.push_back( make_pair(num,name));
}
sort(median.begin(), median.end());
if(t%2!=0){
cout << median[t/2].second << " " << median[t/2+1].first << endl;
}else{
cout << median[t/2-1].second << " " << median[t/2+1].first << endl;
cout << median[t/2].second << " " << median[t/2+1].first << endl;
}
}
</code></pre>
<p><strong>input:</strong></p>
<pre><code>Gilbert 35
Anna 35
Anna 15
Mary 15
Joseph 40
</code></pre>
<p><strong>output:</strong></p>
<pre><code>Anna 35
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T16:39:58.330",
"Id": "507368",
"Score": "0",
"body": "sort depends only on integer/ it is working as expected but getting very slow on high count test cases"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:04:51.013",
"Id": "507389",
"Score": "0",
"body": "`cout << median[t/2].second << \" \" << median[t/2+1].first << endl;` kid me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:07:26.920",
"Id": "507390",
"Score": "0",
"body": "`code does X` Your code does not document the problem to solve. Your post does not describe the problem to solve."
}
] |
[
{
"body": "<p>I don’t do programming challenges, so my review will be more from the point of view of actually writing decent C++ rather than the programming challenge mindset (which, in my humble opinion, encourages terrible coding practices). Nevertheless, if it’s performance you want, I can give you some tips on how to get some huge speed increases.</p>\n<p>So let’s dive in.</p>\n<pre><code>#include <bits/stdc++.h>\n</code></pre>\n<p>I’ve heard this is standard practice in programming challenge circles. Nevertheless, it is terrible practice in real life. Instead, look at all the standard library components you use, and include the headers for them. In your case, you use <code>cin</code>/<code>cout</code>, vectors, strings, pairs, and the sort function, so you’ll need their headers. Including <em>only</em> those headers should speed up compilation measurably, but I don’t know if compilation time is counted in total time, so I don’t know how much that will help.</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>Never do this, even in a programming challenge. It’s just a terrible habit that will eventually bite you in the ass. Just put <code>std::</code> where needed. Just get used to it.</p>\n<pre><code>int main(int argc, char *argv[]) {\n</code></pre>\n<p>Since you don’t actually read the command line, you can just use the simpler form of <code>main()</code>.</p>\n<p>Now you’ve packed your entire program into <code>main()</code>. That’s okay for this very trivial program, but you should really get in the habit of writing better code. Isn’t that what programming challenges are for, after all?</p>\n<p>Break the program into logical steps, and put each major step into its own function. It costs nothing; even the most basic level of optimization will eliminate all the overhead (and anything it doesn’t isn’t worth eliminating).</p>\n<p>The first step is to read the number of pairs in the data set… so it should be a function called <code>read_dataset_size()</code>, or something like that. It could look something like this:</p>\n<pre><code>auto read_dataset_size() -> int;\n</code></pre>\n<p>Or, even better, take the input stream as a parameter:</p>\n<pre><code>auto read_dataset_size(std::istream&) -> int;\n</code></pre>\n<p>Why would you do that? Because it makes the function easier to test. You should <em>always</em> program with testing in mind, even for off-the-cuff code like this. Because if something doesn’t work—and we all make stupid mistakes—you want to be able to do tests to figure out what the problem is. With the function written like above, you can read the input from a file, or even directly from memory, and see whether you get the expected result.</p>\n<p>So, refactored that way, the <code>read_dataset_size()</code> function looks like this:</p>\n<pre><code>auto read_dataset_size(std::istream& in) -> int\n{\n int t; in >> t;\n\n return t;\n}\n</code></pre>\n<p>(This is just your code exactly as you’ve written it, except I replaced <code>cin</code> with <code>in</code>. And of course, added the return statement.)</p>\n<p>Now, you should never write two statements on a single line. Space costs nothing, but being able to read code clearly is the difference between having silly hidden bugs or not. So:</p>\n<pre><code>auto read_dataset_size(std::istream& in) -> int\n{\n int t;\n in >> t;\n\n return t;\n}\n</code></pre>\n<p>Even better would be to give clear names to the variables:</p>\n<pre><code>auto read_dataset_size(std::istream& in) -> int\n{\n int size;\n in >> size;\n\n return size;\n}\n</code></pre>\n<p>Normally you’d do error checking to make sure you actually read a proper number and all… but okay, I get this is just challenge code. So we’ll skip the error checking.</p>\n<p>That’ll do for this bit.</p>\n<p>Your next function should be something like <code>read_data_pairs()</code> or something. It should look something like this:</p>\n<pre><code>auto read_data_pairs(std::istream&, int) -> std::vector<std::pair<int, std::string>>;\n</code></pre>\n<p>And with your code refactored into it:</p>\n<pre><code>auto read_data_pairs(std::istream& in, int size) -> std::vector<std::pair<int, std::string>>\n{\n std::vector< std::pair <int,std::string> > median;\n\n int num; std::string name;\n for(int i=0;i<size;i++) {\n in>>name; in>>num;\n median.push_back( std::make_pair(num,name));\n }\n\n return median;\n}\n</code></pre>\n<p>(Note this is exactly your code with the <code>std::</code>s added, <code>cin</code> replaced with <code>in</code>, and <code>t</code> replaced with <code>size</code>, and of course the return statement added.)</p>\n<p>Alright, now let’s talk performance.</p>\n<p>Here’s the problem: <code>vector</code> automatically resizes to accommodate more data. When it does, it has to allocate a new chunk of memory (usually twice the size of the existing capacity), and then copy all the old data into the new memory. If there are 1,000 pairs in the vector, then the vector would have to allocate space for 2,000 pairs, and then do 1,000 copies (technically, moves). In modern C++, that all happens <em>very</em> quickly… but it’s still not free; there’s still a cost. And if you’ve got <em>millions</em> of pairs….</p>\n<p>Even worse, it will probably happen many, many times as you read in the data. Your vector will start empty, and then have to allocate space for a couple elements. You’ll read in a couple elements, then run out of space again… so the vector will have to allocate a new block of memory, and copy everything over. Now you’ll read in a few more elements… but soon run out of space again. So the vector will have to reallocate and copy <em>again</em>. And it will have to do it over and over and over. And as the number of elements becomes huge, all that allocating and copying will add up quickly.</p>\n<p>Here’s the key to fixing that problem. You already know the size of the input data. So you can just pre-allocate all the space you need, and avoid the need for all that reallocation and copying. The technically correct way would be to do this:</p>\n<pre><code>auto read_data_pairs(std::istream& in, int size) -> std::vector<std::pair<int, std::string>>\n{\n std::vector< std::pair <int,std::string> > median; // median probably\n // isn't a great name\n // for this variable,\n // because it isn't\n // the median... it's\n // all the input data\n //\n // maybe call it\n // "pairs" instead?\n\n median.reserve(size); // this is the magical line that will probably fix\n // all your performance problems\n\n int num;\n std::string name;\n for(int i=0; i < size; ++i)\n {\n in >> name;\n in >> num;\n\n median.push_back( std::make_pair(num,name));\n }\n\n return median;\n}\n</code></pre>\n<p>That one line alone will probably fix your timeout errors.</p>\n<p>But we can do even better.</p>\n<p>Although we’re reserving all the memory we’re going to need, we’re still pushing elements on to the vector. Now it is going be <em>very</em> quick… but, again, still not free.</p>\n<p>So instead of just reserving space and then pushing elements in to the vector over and over… why not create the elements right away, and then read the data <em>directly</em> into them? No extra copies needed.</p>\n<p>This is technically not <em>good</em> practice in general… but it is a valid hack for efficiency. And efficiency is what you’re gunning for.</p>\n<p>So:</p>\n<pre><code>auto read_data_pairs(std::istream& in, int size) -> std::vector<std::pair<int, std::string>>\n{\n std::vector<std::pair<int,std::string>> median;\n\n median.resize(size); // note: reSIZE, not reSERVE\n // this will fill the entire vector with the\n // right number of pairs in a single shot\n\n // note: no more need for temporaries to read input!\n // we'll be reading *directly* into the proper place\n\n // note: we can use the much safer range-for loop now\n for (auto&& element : median)\n {\n in >> element.first;\n in >> element.second;\n }\n\n return median;\n}\n</code></pre>\n<p>That’s about as fast as that can be, I think.</p>\n<p>The sorting is just a call to <code>std::sort()</code>… not much we can do to improve that, or speed that up.</p>\n<p>Now, the way the output is printed is a bit weird. Why do you do <code>median[t/2].second</code> and then <code>median[t/2+1].first</code>? Are you sure that’s correct? Have you tested it with more data than what is shown? (Seriously, <em><strong>TEST YOUR CODE!!!</strong></em> That’s the biggest thing that separates the shitty coders from the good ones. You should test your code with multiple data sets, including edge cases likely to cause problems (like a 1-element data set, for example).)</p>\n<p>I have a hunch you have a bug, but can’t be sure because you haven’t given the actual program requirements. So I’m just going to assume your code isn’t broken (but I think it is!).</p>\n<p>Now, the output could be slightly faster. Instead of:</p>\n<pre><code>cout << median[t/2].second << " " << median[t/2+1].first << endl;\n</code></pre>\n<p>You could do:</p>\n<pre><code>std::cout << median[t / 2].second << ' ' << median[(t / 2) + 1].first << '\\n';\n</code></pre>\n<p>There are two things I changed (other than the spacing to make it more readable, and adding the <code>std::</code>):</p>\n<ol>\n<li>The space is now a single character, rather than a string. In theory, this should be much faster, because a single character is a single character… while a string requires reading multiple characters with a loop and a conditional (to search for the <code>NUL</code>). (In reality, the compiler probably optimizes this for you anyway.)</li>\n<li>Don’t use <code>std::endl</code>. <code>std::endl</code> prints a newline… and then flushes the stream, which is <em>expensive</em>. The stream is going to be flushed automatically anyway, so there’s no sense paying for it multiple times.</li>\n</ol>\n<p>There’s one final trick I can think of that might gain you a bit more speed: <a href=\"https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio\" rel=\"nofollow noreferrer\"><code>std::ios::sync_with_stdio(false);</code></a>. This is a high-level trick, but with a cost: if you do this, <em>you cannot use any of the C <code>stdio</code> library</em>. That means no <code>printf()</code>, no <code>fopen()</code>, none of that. What’s going on is that, by default, the C++ I/O streams will synchronize with the C <code>stdio</code> streams. This is a handy convenience that allows you to mix <code>std::cout</code> and <code>printf()</code>. <em>BUT!</em> That comes with a heavy cost. It slows down <code>std::cin</code> and <code>std::cout</code> a <em>LOT</em>. If you never use any C <code>stdio</code> stuff, then you can turn that synchronization off, and get a <em>huge</em> performance boost. It might make a difference for you, or it might not. Either way, just stick <code>std::ios::sync_with_stdio(false);</code> right after the beginning of <code>main()</code>.</p>\n<p>Okay, in summary, I think the reason you’re getting timeouts is all due to the way you’re reading the input. By <em>not</em> pre-allocating the vector, it is forced to constantly re-allocate and copy (move) all of its contents, over and over and over. Just be pre-allocating the vector with <code>reserve()</code>, you will spare yourself all that wastage by doing one single allocation, and avoiding all the copying (moving) entirely. Even better, you can just size the vector one time up front, and then read the data <em>directly</em> into its elements, so now you don’t even need to read into temporaries then copy into the vector.</p>\n<p>Adding <code>std::ios::sync_with_stdio(false);</code> <em>may</em> help, too.</p>\n<p>But most importantly: <em><strong>TEST YOUR CODE!!!</strong></em> I <em>think</em> you have a bug. You say your code works, so I assume you know what you’re doing… but I’m still skeptical. <em><strong>TEST YOUR CODE!!!</strong></em> See for yourself whether it really works the way you think it does. You just need simple tests, like this (using the <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2 test framework</a>):</p>\n<pre><code>TEST_CASE("dataset size is read correctly")\n{\n auto const test_data = R"(\n3\n1 Alice\n2 Bob\n3 Carol\n)";\n\n auto iss = std::istringstream{test_data};\n\n CHECK(read_dataset_size(iss) == 3);\n}\n\nTEST_CASE("simple data is read correctly")\n{\n auto const test_data = R"(\n3\n1 Alice\n2 Bob\n3 Carol\n)";\n\n auto iss = std::istringstream{test_data};\n\n // just assume this works and throw the result away, because it is tested\n // in the other test case\n [[maybe_unusued]] auto const data_size = read_dataset_size(iss);\n\n auto const data = read_data_pairs(iss, 3);\n\n CHECK(data.size() == 3);\n\n CHECK(data.at(0) == "Alice");\n CHECK(data.at(1) == "Bob");\n CHECK(data.at(2) == "Carol");\n}\n</code></pre>\n<p>Then you just need a couple more tests to make sure sorting produces the right result, and that you print the right output for the median. After that, you could add more tests with different test data to test different potential problems. Get in the habit of testing your code. You may even find benefits with this very program….</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T01:27:37.543",
"Id": "256946",
"ParentId": "256928",
"Score": "4"
}
},
{
"body": "<p>In your post, you write</p>\n<blockquote>\n<p>code reads test count <code>t</code> , <code><int, string></code> pairs then sorts by integer in ascending order and prints median.</p>\n</blockquote>\n<p>However, the call to sort the <code>std::vector</code> does not do that. It sorts by using both the <code>first</code> (an <code>int</code>) and <code>second</code> (a <code>string</code>) of the elements of the vector. If you want to sort by just the <code>first</code> of the elements, use a custom comparator.</p>\n<pre><code>std::sort(median.begin(), median.end(), [](std::pair<int, std::string> const& item1,\n std::pair<int, std::string> const& item2) -> bool\n { return item1.first < item2.first});\n</code></pre>\n<p>That change will improve performance too -- you are comparing just <code>int</code>s for sorting not <code>int</code>s plus <code>std::string</code>s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T20:38:46.367",
"Id": "507515",
"Score": "0",
"body": "If you do that, you might not get the expected output. Instead of `Anna 35` you might get `Gilbert 35`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:11:39.907",
"Id": "256979",
"ParentId": "256928",
"Score": "1"
}
},
{
"body": "<p>In addition to the other answers:</p>\n<h1>Use <code>std::nth_element()</code> instead of <code>std::sort()</code></h1>\n<p><code>std::sort()</code> will completely sort the input. However, you are only interested in the middle (two) element(s). The standard library has a function for that, which will do only a partial sort until it guarantees that the element at a given position has the value you would expect if the input was sorted: <a href=\"https://en.cppreference.com/w/cpp/algorithm/nth_element\" rel=\"nofollow noreferrer\"><code>std::nth_element()</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:11:39.223",
"Id": "256987",
"ParentId": "256928",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T14:49:15.380",
"Id": "256928",
"Score": "0",
"Tags": [
"c++",
"algorithm",
"array",
"sorting",
"c++14"
],
"Title": "sorting vector of pair in efficient way"
}
|
256928
|
<p>I have a flat list of rectangles, in the following format (id, x co-ord, y co-ord, height and width):</p>
<pre><code>[ { id: 4206, x: 360, y: 700, width: 60, height: 50 } ,
{ id: 6621, x: 1260, y: 1100, width: 60, height: 50 } ]
</code></pre>
<p>I want to index this by range of X values, and then use that indexed object to speed up a search for a point inside.</p>
<p>My full code is <a href="https://tio.run/##dVNNb5tAED3Dr5hTtBsIwkrTStjkFvVUteqlB8QBw9psRMCCJXFk8dvT@cAWiRIf8Mxj3sybt8tj8VwMZW8P7mZbbE1z03aVeSu7dnCw720FKWT52hegNnZfO4Tu4jP0YitXI/IdkcY4sG1ljphjuut6UIT13QsjHGzgNpYwCDScfIBLXdk1UkfBXIeh1HmkJuP2OVadbJVwEsIxmVVcU3UIr8lZ6DWNCeVtKNi09j3mBcEaZ0/@NC9y6GzrBlr3hA2/xTE3@hHHUwiIrG4FWa3iuymfDeJGpvopPpHAqDfVWBqlirIMoRz7XkN6T/LtDhTlEbqTpjAidWdbU2nojRv7FpBB2nZEzaQy58W9BRANdXEwQ3QYh5rb6fWHAtNWD9XepPCrcHX0VBzVJ29FWiS2BZIcte9NvmeawcCCQl7L0AQyroQ8hMEVvaNOyUwOYW6dfNaaXF@uSZ5O2n/nIpHJ/9/bR1O66LloRjOohcUatzkoxMlRdWIJCWAeXdSwCsFmOZPW56vq6sL9oVPGIXLa3ND3FGda2qKdnIaA0fFv0dJKS4nRzjbO9MjzPIMA05iCR3ufEiSC4OoKzvgGGEdRmnj0wP09PSuQkf@sq3kgtVwsnr1/G4mqLM5lzuVSLIQxMt88/M3eqw@NRN0rqgYmYIiav6ragJqrAvmXL0prXgmvDq2l1/xtdI2Jmm6vLp7rt/8" rel="nofollow noreferrer">here</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>// arbitrary setup, no need to review
const grid = [];
const height = 50;
const width = 60;
let index = 0;
for (let row = 0; row < 300; row++) {
for (let col = 0; col < 300; col++) {
grid[index] = {
id: index,
x: width * col,
y: height * row,
width,
height
};
index++;
}
}
// try and find these points
const points = [{
x: 400,
y: 700
}, {
x: 1300,
y: 1105
}]
// body - please review approach, style less important
const indexedGrid = grid.reduce((acc, curr) => {
if (curr.x === undefined) return acc;
if (acc[curr.x]) {
acc[curr.x].shapes.push(curr);
acc[curr.x].endEdge = Math.max(acc[curr.x].endEdge, curr.width + curr.x)
} else acc[curr.x] = {
shapes: [curr],
startEdge: curr.x,
endEdge: curr.width + curr.x
};
return acc;
}, {})
const indexedEdges = Object.values(indexedGrid).map(val => ({
start: val.startEdge,
end: val.endEdge
}));
const shapesContainingPoints = points.map(
(point) => ({
point,
xRange: indexedEdges.filter(
edge => (point.x >= edge.start && point.x < edge.end)
)
})
).map(
pointWithRange => indexedGrid[pointWithRange.xRange[0].start].shapes.filter(
shape => {
return (pointWithRange.point.y >= shape.y && (pointWithRange.point.y < (shape.y + shape.height)))
}
)
);
//footer - purely to show results in the this question, no need to review
console.log(shapesContainingPoints)</code></pre>
</div>
</div>
</p>
<p>I'm fully aware this code could be tidied up a lot, but the main thing I was hoping to ascertain, is if this 'index and search' pattern suits the following use case.</p>
<p>I'm drawing a load of rectangles in a html <code>canvas</code> element, and I want to be able to find which rectangle was clicked on using the <code>x, y</code> co-ords of the mouse. So I plan to create a flat list of the squares, and then index them by their X value. And from that X value, look along the row, filtering by Y value.</p>
<p>Currently the data only includes perfectly tiling rectangles, but in the future I may have to handle an alternating offset (every other row is shifted by a small value) or other less standard layouts.</p>
<p>Here are some example grids (all right angled) that I need to handle:<br />
<a href="https://algorist.com/images/figures/bin-packing-R.png" rel="nofollow noreferrer">https://algorist.com/images/figures/bin-packing-R.png</a><br />
<a href="https://i.stack.imgur.com/JG3iT.png" rel="nofollow noreferrer">https://i.stack.imgur.com/JG3iT.png</a><br />
<a href="https://codeincomplete.com/articles/bin-packing/packed.png" rel="nofollow noreferrer">https://codeincomplete.com/articles/bin-packing/packed.png</a></p>
<p>I have no plans to have the number, size or position of the rectangles to change over time. I don't have a good grasp of quite how many total rectangles I will need to look over, but I'm expecting anything from 4 to 4000 say.</p>
<p>But it feels very clunky (overly complicated, and thus hard to comprehend/maintain), and that there should be a better approach to this problem? I'm also interested in performance, but that's secondary to maintainability at the moment.</p>
<p>If there is not a better alternative, is there anyway of improving my current approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T12:31:58.457",
"Id": "507459",
"Score": "0",
"body": "@Peilonrayz, the rectangles are static and I'm aiming for maintainability over performance (but would like to keep an eye on both). No idea how many rectangles, so I've speculated at 4 to 4000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T05:02:23.827",
"Id": "507663",
"Score": "2",
"body": "Are you looking for something like [kd-trees](https://en.wikipedia.org/wiki/K-d_tree)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T08:35:30.993",
"Id": "507670",
"Score": "0",
"body": "@neil I think so?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T19:31:37.423",
"Id": "507706",
"Score": "0",
"body": "@Neil I originally thought of [quadtree](https://en.wikipedia.org/wiki/Quadtree) (don't need an octree or kd-tree for 2 dimensions) but such trees store points not rects (bipoints). How'd you effectively tell if a point is in a rect? I can only think of \\$O(n)\\$ solutions not \\$O(\\log(n))\\$. However seems like a [min/max kd-tree](https://en.wikipedia.org/wiki/Min/max_kd-tree) or [R-tree](https://en.wikipedia.org/wiki/R-tree) may fit the bill."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T21:07:20.533",
"Id": "507716",
"Score": "0",
"body": "@Peilonrayz quadtree is the variant I was thinking, too. I think it's natural given axis-aligned boxes, and a static scene is beneficial. Related to [Doom](https://twobithistory.org/2019/11/06/doom-bsp.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T09:31:45.327",
"Id": "507729",
"Score": "0",
"body": "@Neil currently the rectangles are 'axis-aligned' but I think in the future I may have to work with less regular layouts: \"Currently the data only includes perfectly tiling rectangles, but in the future I may have to handle an alternating offset (every other row is shifted by a small value) or other less standard layouts.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T05:48:01.003",
"Id": "507812",
"Score": "0",
"body": "One could generalise a kd-tree into a bsp-tree to have arbitary angles, if that were the case. I speak about your first example, but I think, if you were to have tightly packed, tiled, or intersecting, it would make a difference in the choice of partitioning. If you had about the same size objects in a bounded area, in my experience, the simplest is to divide them into a grid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:39:36.497",
"Id": "507842",
"Score": "1",
"body": "@neil, I don't even mean arbitrary angles. here are some example grids (all right angled): https://algorist.com/images/figures/bin-packing-R.png https://i.stack.imgur.com/JG3iT.png https://codeincomplete.com/articles/bin-packing/packed.png I would edit them in, but I don't know if my algorithm works on those, so i worry it would change it from a code review problem to a code not working (aka Stackoverflow) problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T21:25:53.180",
"Id": "507886",
"Score": "1",
"body": "They are already tiled; that's useful to know. Kd-tree seems like an even better suggestion. Maybe someone knows a better representation for your data. I would say that those images are relevant to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T18:16:51.047",
"Id": "508239",
"Score": "0",
"body": "@Neil the bounty is ending soon, do you have an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T16:19:07.210",
"Id": "508341",
"Score": "0",
"body": "Will the boxes ever overlap?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T16:19:39.840",
"Id": "508342",
"Score": "0",
"body": "@Peilonrayz as per the examples, no they should never overlap"
}
] |
[
{
"body": "<h1>One way to solve the problem with trees</h1>\n<h2>A simplified look at binary trees</h2>\n<blockquote>\n<p>the rectangles are static</p>\n</blockquote>\n<blockquote>\n<p>[the rectangles] should never overlap</p>\n</blockquote>\n<p>As such we can build a simple tree.\nBefore looking at 2d points we can look at a solution for 1d points.</p>\n<p>Say we have the following line segments. Beginnings are inclusive ends are not.</p>\n<ul>\n<li>A: 0 - 2</li>\n<li>B: 2 - 3</li>\n<li>C: 3 - 4</li>\n<li>D: 4 - 8</li>\n</ul>\n<p>We could describe the values as a really simple binary tree.</p>\n<p><a href=\"https://i.stack.imgur.com/Bd7iL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Bd7iL.png\" alt=\"Image of complete binary tree.\" /></a></p>\n\n<p>With the example I gave we can reduce the amount of leaf nodes to just 4.</p>\n<p><a href=\"https://i.stack.imgur.com/1QaGi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1QaGi.png\" alt=\"Image of a truncated binary tree.\" /></a></p>\n\n<p>We do need to assign multiple leaves to the same node at times.\nFor example if we had the following line segments:</p>\n<ul>\n<li>A: 0 - 3</li>\n<li>B: 3 - 8</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/km6bq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/km6bq.png\" alt=\"Image of truncated binary tree with multiple leaf nodes with the same value.\" /></a></p>\n\n<h2>An algorithm for the above</h2>\n<p>As such we can just use a simple binary tree.\nWith two major changes:</p>\n<ol>\n<li>We need to make the intermediary nodes when building the leaves.</li>\n<li>We may need to add multiple leaf nodes to account for the end of the rect.</li>\n</ol>\n<p>As such we can build a simple algorithm:</p>\n<ul>\n<li><p>When building the nodes we need to know the index of the node.</p>\n<p>Each node has a range for the values the children can be.\nIn our above 8 leaf node tree, the the values for node 4 can range from 0-8.\nWhere the 2 node's range is 0-4 and the 5 node's range is 4-6.</p>\n</li>\n<li><p>If the range of the line segment is greater than the range of the node we can stop recursing.</p>\n</li>\n<li><p>Otherwise we need to recursively append to the left or right child node. (Can be both.)</p>\n<ul>\n<li>If the start of the line segment's range is less than the node's index we recurse left.</li>\n<li>If the end of the line segment's range is greater than the node's index we recurse right.</li>\n</ul>\n<p>Before recursing:</p>\n<ul>\n<li><p>Build the child node if one doesn't exist.\nThe index will be:</p>\n<p><strong>Left</strong>: (node's index + node's start) // 2<br />\n<strong>Right</strong>: (node's index + node's end) // 2</p>\n</li>\n<li><p>We also need to adjust one of the start or end of the child node's range.</p>\n<p><strong>Left</strong>: The end of the child node's range is the current node's index.<br />\n<strong>Right</strong>: The start of the child node's range is the current node's index.</p>\n</li>\n</ul>\n<p>We then recurse into the children.</p>\n</li>\n</ul>\n<p>Here is an example implementation of such a binary tree in Python:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nimport dataclasses\nimport textwrap\nfrom typing import Iterator, Optional, TypeVar, Generic\n\nT = TypeVar("T")\n\n\n@dataclasses.dataclass\nclass Node(Generic[T]):\n index: int\n left: Optional[Node[T]] = None\n right: Optional[Node[T]] = None\n value: Optional[T] = None\n\n def get_point(self, point: int) -> Optional[T]:\n if self.value is not None:\n return self.value\n child = self.left if point < self.index else self.right\n return child.get_point(point)\n\n def add_range(\n self,\n value: T,\n range_start: int,\n range_end: int,\n node_start: int,\n node_end: int,\n ) -> None:\n if range_start <= node_start and node_end <= range_end:\n self.value = value\n return\n if range_start < self.index:\n if self.left is None:\n self.left = Node((self.index + node_start) // 2)\n self.left.add_range(value, range_start, range_end, node_start, self.index)\n if self.index < range_end:\n if self.right is None:\n self.right = Node((self.index + node_end) // 2)\n self.right.add_range(value, range_start, range_end, self.index, node_end)\n\n # So I can show the code works\n def tree_format(self, join="──", top=" ", bottom=" ") -> Iterator[str]:\n if self.left is not None:\n for value in self.left.tree_format("┌─", bottom="│ "):\n yield top + value\n if self.value is None:\n yield f"{join}{self.index}"\n else:\n yield f"{join}{self.value}"\n if self.right is not None:\n for value in self.right.tree_format("└─", top="│ "):\n yield bottom + value\n\n\nclass Tree(Generic[T]):\n _size: int\n _root: Node\n\n def __init__(self, size: int) -> None:\n self._size = size\n self._root = Node(size // 2)\n\n def __str__(self) -> None:\n return "\\n".join(self._root.tree_format())\n\n def add_range(self, value: T, start: int, stop: int):\n self._root.add_range(value, start, stop, 0, self._size)\n\n def get_point(self, point: int) -> Optional[T]:\n try:\n return self._root.get_point(point)\n except AttributeError:\n return None\n\n\nif __name__ == "__main__":\n print("Tree1:")\n tree_1 = Tree(8)\n tree_1.add_range("A", 0, 2)\n tree_1.add_range("B", 2, 3)\n tree_1.add_range("C", 3, 4)\n tree_1.add_range("D", 4, 8)\n print(tree_1)\n print(3, "==", tree_1.get_point(3))\n\n print("\\nTree2:")\n tree_2 = Tree(8)\n tree_2.add_range("A", 0, 3)\n tree_2.add_range("B", 3, 8)\n print(tree_2)\n print(3, "==", tree_2.get_point(3))\n\n print("\\nTree3:")\n tree_3 = Tree(8)\n tree_3.add_range("A", 0, 3)\n tree_3.add_range("B", 4, 8)\n print(tree_3)\n print(3, "==", tree_3.get_point(3))\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>Tree1:\n ┌─A\n ┌─2\n │ │ ┌─B\n │ └─3\n │ └─C\n──4\n └─D\n3 == C\n\nTree2:\n ┌─A\n ┌─2\n │ │ ┌─A\n │ └─3\n │ └─B\n──4\n └─B\n3 == B\n\nTree3:\n ┌─A\n ┌─2\n │ │ ┌─A\n │ └─3\n──4\n └─B\n3 == None\n</code></pre>\n<p>We can abstract the binary tree (1D) to a quad tree (2D) and perform the same algorithm.</p>\n<p>The quad tree will have a top-left, top-right, bottom-left and bottom-right but otherwise would work the same way.</p>\n<h2>Problems</h2>\n<p>The above solution isn't just rainbows and sunshine</p>\n<ul>\n<li><p>The tree's size must never change.<br />\nIf the tree ever needs to resize you must build one from scratch again.</p>\n</li>\n<li><p>Currently the tree cannot have overlapping boxes.<br />\nAdding the capability doesn't seem impossible however.</p>\n<ol>\n<li>You would need to change <code>Node.value</code> to a list and append to the list in <code>Node.add_range</code>.</li>\n<li>Adjust <code>Node.get_point</code> to not eagerly exit and return the children's values (if applicable) along with the current node's values.</li>\n</ol>\n</li>\n<li><p>Your tree can have lots of cruft leaf nodes because of bad index selection.</p>\n<pre class=\"lang-none prettyprint-override\"><code>(node_end + self.index) // 2\n</code></pre>\n<p>Say you want to put 9 equally sized squares into a 3x3 grid, you won't have a nice 9 leaf nodes.\nYou'd have 36 leaf nodes.</p>\n<p>We see a less severe version of the problem in "Tree2".\nHad we selected 3 to be the first index to split on, rather than 4, we'd only have 2 nodes not 4.</p>\n<pre class=\"lang-none prettyprint-override\"><code> ┌─A\n──3\n └─B\n</code></pre>\n<p>To solve the issue I'd move the index generation code out into a separate binary or quad tree.\nFor example we could abstract the index generation as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class IndexNode:\n def __init__(self, index, start, end):\n self.index = index\n self.start = start\n self.end = end\n\n def left(self):\n start, end = self.start, self.index\n return Node((start + end) // 2, start, end)\n\n def right(self):\n start, end = self.index, self.end\n return Node((start + end) // 2, start, end)\n</code></pre>\n<p>We can now easily change the index generation for the 3x3 grid without having to mangle the other tree.</p>\n<p>We could also manually define the tree.\nBut you'd have to manually build the entire tree.\nOr have a hybrid where you define the top nodes and let the class generate the rest.</p>\n</li>\n</ul>\n<h1>Maintainability</h1>\n<blockquote>\n<p>I'm aiming for maintainability over performance</p>\n</blockquote>\n<p>As you can probably see using a tree can get you better performance.\nSince the tree could find the rects in <span class=\"math-container\">\\$O(\\log(n))\\$</span> time.\nTo improve the performance and to get good memory usage may require more thought; depending on the intricate patterns you use.</p>\n<p>However do you really get much from building an intricate quad-tree?\nEven my simple binary tree is double your line count.\nIf you have come on CR without caring about speed then I can't imagine your current solution is performing poorly.\nAs such the cost to maintainability doesn't really seem worth the gain in speed at the moment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T20:37:05.473",
"Id": "257364",
"ParentId": "256930",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "257364",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T15:12:44.353",
"Id": "256930",
"Score": "4",
"Tags": [
"javascript",
"search"
],
"Title": "Indexing and searching an list of rectangles to see if they contain a point"
}
|
256930
|
<p>i have recently built this simple <a href="https://github.com/refatalsakka/weather-app" rel="nofollow noreferrer">weather-app</a>.
I would be happy to get some criticisms to improve my code.</p>
<p>Structure:</p>
<p><a href="https://i.stack.imgur.com/Uiw6F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uiw6F.png" alt="Structure" /></a></p>
<p>app.js:</p>
<pre><code>import '../sass/style.scss';
import '@fortawesome/fontawesome-free/js/all.min';
import 'regenerator-runtime/runtime';
import elements from './modules/elements';
import update from './modules/document';
(() => {
function run(cityName) {
update(cityName);
setInterval(() => update(cityName), (60000 * 10));
}
run('homs');
elements.form.addEventListener('submit', (e) => {
e.preventDefault();
run(elements.search.value);
});
})();
</code></pre>
<p>modules/apis.js</p>
<pre><code>/* eslint-disable no-undef */
import axios from 'axios';
const apiWeather = {
base: 'http://api.openweathermap.org/data/2.5/',
key: process.env.API_TOCKEN_WEATHER,
query: '&units=metric',
};
const apiTime = {
base: 'http://api.openweathermap.org/data/2.5/',
key: process.env.API_TOCKEN_WEATHER,
query: '&units=metric',
};
export function getWeather(city) {
return axios
.get(`${apiWeather.base}weather?q=${city}&appid=${apiWeather.key}${apiWeather.query}`)
.then((response) => response.data).catch(() => false);
}
export function getTime(uluru) {
return axios
.get(`${apiTime.base}onecall?lat=${uluru.lat}&lon=${uluru.lon}&exclude=hourly,minutely,daily,current&appid=${apiTime.key}`)
.then((response) => response.data).catch(() => false);
}
export function getMap(uluru, mode, id) {
const mapId = mode === 'dark' ? process.env.API_TOCKEN_MAP_DARK_ID : false;
const { lat, lon: lng } = uluru;
const map = new google.maps.Map(id, {
zoom: 8,
center: { lat, lng },
mapId,
});
// eslint-disable-next-line no-unused-vars
const marker = new google.maps.Marker({
position: { lat, lng },
map,
});
}
</code></pre>
<p>modules/document.js</p>
<pre><code>import elements from './elements';
import icons from './icons';
import { getWeather, getTime, getMap } from './apis';
import {
count,
getMode,
getIconWeather,
getIconCountry,
innerHTML,
getCurrentDate,
formatDate,
information,
} from './helpers';
function addClassNameToBody(className) {
if (!elements.body.classList.contains(className)) {
elements.body.classList = '';
elements.body.classList = className;
}
}
export default async function update(cityName) {
elements.error.classList.remove('active');
elements.loading.classList.add('active');
const city = await getWeather(cityName);
if (!city) {
elements.error.classList.add('active');
elements.loading.classList.remove('active');
return;
}
const info = information(city);
const time = await getTime(info.uluru);
const currentDate = getCurrentDate(time.timezone);
const mode = getMode(currentDate, { uluru: info.uluru, sunset: info.sunset });
const weatherIcon = getIconWeather(icons, { status: info.status, mode });
const countryIcon = getIconCountry(info.country);
elements.loading.classList.remove('active');
addClassNameToBody(mode);
innerHTML(elements.city, (`${info.name},${info.country} ${countryIcon}`));
innerHTML(elements.date, formatDate(currentDate));
innerHTML(elements.description, info.description);
innerHTML(elements.icon, weatherIcon);
innerHTML(elements.pressure, Math.round(info.pressure));
innerHTML(elements.humidity, Math.round(info.humidity));
innerHTML(elements.wind, Math.round(info.wind));
innerHTML(elements.visibility, Math.round(info.visibility / 1000));
count(elements.temp_main, Math.round(info.temp));
count(elements.temp_min, Math.round(info.temp_min));
count(elements.temp_max, Math.round(info.temp_max));
count(elements.feels_like, Math.round(info.feels_like));
getMap(info.uluru, mode, elements.map);
}
</code></pre>
<p>modules/elements.js</p>
<pre><code>export default {
body: document.querySelector('body'),
form: document.querySelector('.search form'),
search: document.querySelector('.search form input'),
loading: document.querySelector('.loading'),
error: document.querySelector('.error'),
city: document.querySelector('.city'),
date: document.querySelector('.date'),
temp_main: document.querySelector('.main'),
temp_min: document.querySelector('.temp-min'),
temp_max: document.querySelector('.temp-max'),
feels_like: document.querySelector('.feels-like'),
pressure: document.querySelector('.pressure'),
humidity: document.querySelector('.humidity'),
wind: document.querySelector('.wind'),
visibility: document.querySelector('.visibility'),
description: document.querySelector('.description'),
icon: document.querySelector('.icon'),
map: document.querySelector('.map'),
};
</code></pre>
<p>modules/helpers.js</p>
<pre><code>export function innerHTML(elm, value) {
elm.innerHTML = value;
}
export function information(city) {
return {
name: city.name,
country: city.sys.country,
status: city.weather[0].main,
description: city.weather[0].description,
temp: city.main.temp,
temp_min: city.main.temp_min,
temp_max: city.main.temp_max,
feels_like: city.main.feels_like,
pressure: city.main.pressure,
humidity: city.main.humidity,
wind: city.wind.speed,
visibility: city.visibility,
uluru: { lat: city.coord.lat, lon: city.coord.lon },
sunset: city.sys.sunset,
};
}
export function count(elm, _new) {
let finish = false;
let old = Number(elm.innerText);
const counting = setInterval(() => {
if (old > _new) {
old -= 1;
} else if (old < _new) {
old += 1;
} else {
finish = true;
clearInterval(counting);
}
innerHTML(elm, old);
if (finish) elm.classList.toggle('active');
}, 100);
}
export function dateToTimestamp(date) {
return new Date(date).getTime() / 1000;
}
export function formatDate(data) {
return new Date(data).toLocaleString('en-US', {
day: '2-digit',
month: 'long',
year: 'numeric',
weekday: 'long',
hour12: false,
hour: 'numeric',
minute: 'numeric',
});
}
export function getCurrentDate(timeZone) {
return new Date().toLocaleString('en-US', { timeZone });
}
export function getMode(currentDate, city) {
return city.sunset >= dateToTimestamp(currentDate) ? 'light' : 'dark';
}
export function getIconWeather(icons, city) {
const { status, mode } = city;
const index = icons.natural[status.toLowerCase()] ? 'natural' : mode;
return icons[index][status.toLowerCase()];
}
export function getIconCountry(code) {
return `<img src="https://openweathermap.org/images/flags/${code.toLowerCase()}.png" title="${code.toLowerCase()}"/>`;
}
</code></pre>
<p>modules/icons.js</p>
<pre><code>export default {
light: {
clear: '<i class="fas fa-sun"></i>',
clouds: '<i class="fas fa-cloud-sun"></i>',
rain: '<i class="fas fa-cloud-sun-rain"></i>',
},
dark: {
clear: '<i class="fas fa-moon"></i>',
clouds: '<i class="fas fa-cloud-moon"></i>',
rain: '<i class="fas fa-cloud-moon-rain"></i>',
},
natural: {
snow: '<i class="fas fa-snowflake"></i>',
fog: '<i class="fas fa-smog"></i>',
mist: '<i class="fas fa-smog"></i>',
smog: '<i class="fas fa-smog"></i>',
drizzle: '<i class="fas fa-cloud-rain"></i>',
storm: '<i class="fas fa-poo-storm"></i>',
bolt: '<i class="fas fa-bolt"></i>',
wind: '<i class="fas fa-wind"></i>',
rainbow: '<i class="fas fa-rainbow"></i>',
},
};
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T16:24:48.677",
"Id": "256933",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"modules"
],
"Title": "Weather app using es6 modules"
}
|
256933
|
<p>As a general rule of thumb, it is required to run baseline models on the dataset. I know <a href="http://docs.h2o.ai/h2o-tutorials/latest-stable/h2o-world-2017/automl/index.html" rel="nofollow noreferrer">H2O- AutoML</a> and other AutoML packages do this. But I want to try using Scikit-learn Pipeline,</p>
<p>Here is what I have done so far,</p>
<pre><code>from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import BernoulliNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import Pipeline
from xgboost import XGBClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import os
rs = {'random_state': 42}
</code></pre>
<pre><code># Train-test Split
X_train, X_test, y_train, y_test = train_test_split(X,
y,
test_size = 0.33,
random_state = 42)
</code></pre>
<pre><code># Classification - Model Pipeline
def modelPipeline(X_train, X_test, y_train, y_test):
log_reg = LogisticRegression(**rs)
nb = BernoulliNB()
knn = KNeighborsClassifier()
svm = SVC(**rs)
mlp = MLPClassifier(max_iter=500, **rs)
dt = DecisionTreeClassifier(**rs)
et = ExtraTreesClassifier(**rs)
rf = RandomForestClassifier(**rs)
xgb = XGBClassifier(**rs, verbosity=0)
clfs = [
('Logistic Regression', log_reg),
('Naive Bayes', nb),
('K-Nearest Neighbors', knn),
('SVM', svm),
('MLP', mlp),
('Decision Tree', dt),
('Extra Trees', et),
('Random Forest', rf),
('XGBoost', xgb)
]
pipelines = []
scores_df = pd.DataFrame(columns=['Model', 'F1_Score', 'Precision', 'Recall', 'Accuracy', 'ROC_AUC'])
for clf_name, clf in clfs:
pipeline = Pipeline(steps=[
('scaler', StandardScaler()),
('classifier', clf)
]
)
pipeline.fit(X_train, y_train)
y_pred = pipeline.predict(X_test)
# F1-Score
fscore = skm.f1_score(y_test, y_pred)
# Precision
pres = skm.precision_score(y_test, y_pred)
# Recall
rcall = skm.recall_score(y_test, y_pred)
# Accuracy
accu = skm.accuracy_score(y_test, y_pred)
# ROC_AUC
roc_auc = skm.roc_auc_score(y_test, y_pred)
pipelines.append(pipeline)
scores_df = scores_df.append({
'Model' : clf_name,
'F1_Score' : fscore,
'Precision' : pres,
'Recall' : rcall,
'Accuracy' : accu,
'ROC_AUC' : roc_auc
},
ignore_index=True)
return pipelines, scores_df
</code></pre>
<p>I have a nagging feeling that there's something I might be overlooking, or missing, or that there might be a more efficient way to do this.</p>
<p>Is there a better / more elegant / more accurate way to run multiple classifiers for ML classification?
Efficiency is also good, though we never call this on large datasets, it is not a huge concern.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T16:35:22.007",
"Id": "256934",
"Score": "1",
"Tags": [
"python",
"machine-learning"
],
"Title": "Model Pipeline to run multiple Classifiers for ML Classification"
}
|
256934
|
<p>So I received the following prompt for a code interview:</p>
<blockquote>
<p>"Please create an iOS app that downloads a text file from our server, parses the
contents, and displays the results. The file is a standard Apache web server access log. We’re interested in knowing the most common three-page sequences in the file. A three-page sequence is three consecutive requests from the same user.</p>
</blockquote>
<p>This is a sample log entry:</p>
<blockquote>
<p>123.4.5.8 - - [03/Sep/2013:18:35:38 -0600] "GET /products/phone/ HTTP/1.1" 500 821 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.65 Safari/537.36"</p>
</blockquote>
<p>My ViewController.swift is as follows:</p>
<pre><code>//
// ViewController.swift
// InspriingAppsTest
//
// Created by *** on 3/2/21.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var loadingWindow: UIView!
@IBOutlet weak var dataViewer: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("Count is "+String(sequenceTally.count))
return sequenceTally.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let currentCell = dataViewer.dequeueReusableCell(withIdentifier: "cellTemplate") as! PageOccurenceCell
currentCell.pageOne.text = sequenceTally.sorted(by: {$0.value > $1.value})[indexPath.row].key.split(separator: " ")[0].replacingOccurrences(of: " ", with: "")
currentCell.pageTwo.text = sequenceTally.sorted(by: {$0.value > $1.value})[indexPath.row].key.split(separator: " ")[1].replacingOccurrences(of: " ", with: "")
currentCell.pageThree.text = sequenceTally.sorted(by: {$0.value > $1.value})[indexPath.row].key.split(separator: " ")[2].replacingOccurrences(of: " ", with: "")
currentCell.countLabel.text = String(sequenceTally.sorted(by: {$0.value > $1.value})[indexPath.row].value)
return currentCell
}
var sequenceTally: [String:Int] = [:]
var sortedNumbers: [String:Int] = [:]
var userCount: [String:[String]]=[:]
//var counter: Int = 0
func processResponse(responseString: String)
{
let lines = responseString.components(separatedBy: "\n")
let ipStartIndex = lines[0].index(lines[0].startIndex,offsetBy: 0)
let ipEndIndex = lines[0].index(lines[0].startIndex,offsetBy: 9)
let pageStartIndex = lines[0].index(lines[0].startIndex,offsetBy: 48)
let ipRange: Range = ipStartIndex..<ipEndIndex
for line in lines
{
guard let hIndex = line.firstIndex(of: "H") else{return }
let pageRange = pageStartIndex..<hIndex
if(userCount[String(line[ipRange])] == nil)
{
userCount[String(line[ipRange])] = []
}
if(userCount[String(line[ipRange])]?.count == 3)
{
var stringKey: String = ""
for items in userCount[String(line[ipRange])]!
{
stringKey.append(items + " ")
}
if(sequenceTally[stringKey] == nil)
{
sequenceTally[stringKey] = 0
}
sequenceTally[stringKey]! += 1
userCount[String(line[ipRange])] = []
}
userCount[String(line[ipRange])]?.append(String(line[pageRange]).replacingOccurrences(of: " ", with: ""))
}
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://logfilehere")!
URLSession.shared.dataTask(with: url) { (data, response, error) in
self.processResponse(responseString: String(data: data!, encoding: String.Encoding.utf8)!)
DispatchQueue.main.async {
print(self.sequenceTally.count)
self.dataViewer.delegate = self
self.dataViewer.dataSource = self
self.dataViewer.reloadData()
self.loadingWindow.isHidden = true
}
}.resume()
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><code>ProcessResponse</code> is in the <code>ViewController</code> - it shouldn't be. It's a model responsibility.</p>\n<p>It's signature is <code>String -> Void</code> (it returns no values) but it mutates values that it closes over: sequenceTally, userCount. That's not a good idea: It's not testable, because you can't feed the function a known response and assert that the values you get back are what you expect.</p>\n<p>Its name is not named following the "Swift API design guidelines".\n<code>ViewController</code> is not a descriptive name for a specific ViewController.</p>\n<p>The parsing of each line into an ip address is brittle, because the index offset doesn't cope well with different length ip addresses. Looking for an "H" or stopping the entire parse early is brittle, too.</p>\n<p>It doesn't parse the line into a suitable data structure, instead you have dictionaries of Strings, Int's etc.</p>\n<p>Making a data structure(s) (e.g. <code>struct User</code>, <code>struct PageRequest</code>) to fit your data means processing the data will become simpler. For example when populating a table view cell, you shouldn't have to be futher processing your data like <code>.key.split(separator: " ")[1].replacingOccurrences(of: " ", with: "")</code> - you should have something readable like <code>cell.title = threePageSequence.user.name</code></p>\n<p>The processing algorithm is incorrect - take ABCDBCDBCD, the most common triple sequence in that is BCD, but you chunk it into ABC, DBC, DBC and you would say DBC is the most common triple subsequence.</p>\n<p>Your code repeats itself a lot, e.g. <code>String(line[ipRange])</code> - and in places performance is poor because of it. For example in <code>CellForRowAtIndexPath</code> you sort <code>sequenceTally.sorted(by: {$0.value > $1.value}</code> multiple times, and that's called for each row in the tableView. Instead you could sort an array once, and use that sorted array as the table view's data source.</p>\n<p>Using just the ip address to identify a user is questionable too, the combination of browser and ip address might be better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T10:25:25.463",
"Id": "257334",
"ParentId": "256935",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T16:42:02.053",
"Id": "256935",
"Score": "2",
"Tags": [
"swift",
"ios",
"server"
],
"Title": "Swift code to extract most common page sequences from an Apache server log"
}
|
256935
|
<p>I have a product that needs to have users put content in a form that potentially contains HTML and display it back to other users. I'd like to mitigate the risk as much as possible, and I can limit users to a subset of html. My primary goal is to make sure that users can't compromise each other, and that the page itself is not compromised by poorly-formatted html (e.g. omitted closing tags).</p>
<p>My backend is Python. Unfortunately I've been asked to not include use a third party solution.</p>
<p>I'm structuring my approach based on this regular expression:</p>
<pre><code>(?P<content>.*?) # Content up to next tag
(?P<markup> # Entire tag
<!\[CDATA\[(?P<cdata>.+?)]]>| # <![CDATA[ ... ]]>
<!--(?P<comment>.+?)-->| # <!-- Comment -->
</\s*(?P<close_tag>\w+)\s*>| # </tag>
<(?P<tag>\w+) # <tag ...
(?P<attributes>
(?P<attribute>\s+
# <snip>: Use this part to get the attributes out of 'attributes' group.
(?P<attribute_name>\w+)
(?:\s*=\s*
(?P<attribute_value>
[\w:/.\-]+| # Unquoted
(?=(?P<_v> # Quoted
(?P<_q>['\"]).*?(?<!\\)(?P=_q)))
(?P=_v)
))?
# </snip>
)*
)\s*
(?P<is_self_closing>/?) # Self-closing indicator
>) # End of tag
</code></pre>
<p>Here is my full code:</p>
<pre class="lang-py prettyprint-override"><code>import re
_html_regex = r"""
(?P<content>.*?) # Content up to next tag
(?P<markup> # Entire tag
$| # End of document
<!\[CDATA\[(?P<cdata>.+?)]]>| # <![CDATA[ ... ]]>
<!--(?P<comment>.+?)-->| # <!-- Comment -->
</\s*(?P<close_tag>\w+)\s*>| # </tag>
<(?P<tag>\w+) # <tag ...
(?P<attributes>
(?P<attribute>\s+
# <snip>: Use this part to get the attributes out of 'attributes' group.
(?P<attribute_name>[\w\-]+)
(?:\s*=\s*
(?P<attribute_value>
[\w:/.\-]+| # Unquoted
(?=(?P<_v> # Quoted
(?P<_q>'|\"|\\\").*?(?<!\\)(?P=_q)))
(?P=_v)
))?
# </snip>
)*
)\s*
(?P<is_self_closing>/?) # Self-closing indicator
>) # End of tag
"""
_html_attr_regex = r"""
(?P<attribute_name>\w+)
(?:\s*=\s*
(?P<attribute_value>
[\w:/.\-]+| # Unquoted
(?=(?P<_v> # Quoted
(?P<_q>['\"]).*?(?<!\\)(?P=_q)))
(?P=_v)
))?
"""
def _check_href(href):
href = href.strip()
if href[0] == '"' or href[0] == "'":
href = href[1:-1].strip()
if href.startswith('javascript:'):
return '"#"'
return '"' + href + '"'
_no_attributes = {}
_allowed_tags = {
'a': {'href': _check_href},
'b': _no_attributes,
'blockquote': _no_attributes,
'div': _no_attributes,
'h1': _no_attributes,
'h2': _no_attributes,
'h3': _no_attributes,
'h4': _no_attributes,
'h5': _no_attributes,
'h6': _no_attributes,
'hr': _no_attributes,
'i': _no_attributes,
'li': _no_attributes,
'ol': _no_attributes,
'p': _no_attributes,
'pre': _no_attributes,
'table': _no_attributes,
'tbody': _no_attributes,
'td': _no_attributes,
'th': _no_attributes,
'tr': _no_attributes,
'u': _no_attributes,
'ul': _no_attributes,
}
_self_closing_tags = [
'hr',
]
def cleanup_html(html):
if not html:
return html
tag_stack = []
output = ""
for match in re.finditer(_html_regex, html, re.DOTALL | re.VERBOSE):
content = match.group('content')
tag = match.group('tag')
attributes = match.group('attributes')
close_tag = match.group('close_tag')
is_self_closing = match.group('is_self_closing')
if content:
output += content
if close_tag and close_tag in tag_stack:
while tag_stack[-1] != close_tag:
output += '</%s>' % tag_stack.pop()
elif tag and tag in _allowed_tags:
output += '<' + tag
for attr in re.finditer(_html_attr_regex, attributes, re.DOTALL | re.VERBOSE):
attr_name = attr.group('attribute_name')
attr_value = attr.group('attribute_value')
if attr_name in _allowed_tags[tag]:
output += ' ' + attr_name
if attr_value:
output += '=' + _allowed_tags[tag][attr_name](attr_value)
if is_self_closing:
output += '/>'
else:
if tag not in _self_closing_tags:
tag_stack.append(tag)
output += '>'
while tag_stack:
output += '</%s>' % tag_stack.pop()
return output
</code></pre>
<p>The regex and some poorly formatted sample text are pre-loaded into <a href="https://regex101.com/r/vuhnKS/1/" rel="nofollow noreferrer">https://regex101.com/r/vuhnKS/1/</a> for playing with.</p>
<p>The regex should allow fairly ugly HTML, but I think it does a fairly good job of cleaning it up. There's a whitelist of allowed tags in there, and <code><style></code> and <code><script></code> aren't allowed. My guess is that the greatest weakness is in <code>_check_href</code> and something slipping through there.</p>
<p>Are there any identifiable flaws in this though? Are there any other tags that are low-risk that I should allow?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:25:00.170",
"Id": "507393",
"Score": "6",
"body": "Not intended as a criticism of your approach. Just remembering the glory days of StackOverflow: https://stackoverflow.com/a/1732454/55857"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T21:22:12.587",
"Id": "525125",
"Score": "0",
"body": "Who's asking you to do this? School, coding challenge, interview?"
}
] |
[
{
"body": "<p>It is generally thought that html parsing with regular-expressions is complex and difficult to maintain over time.</p>\n<p>Python's standard library includes a basic html parser, <code>html.parser</code>, so it shouldn't be part of the 3rd-party exclusion set. You might try re-implementing your solution with it and then compare the two solutions.</p>\n<p>Html.parser information:<br />\n<a href=\"https://docs.python.org/3/library/html.parser.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/html.parser.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:15:12.537",
"Id": "257038",
"ParentId": "256938",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T19:05:39.570",
"Id": "256938",
"Score": "2",
"Tags": [
"python",
"html",
"regex"
],
"Title": "Sanitize user-supplied HTML with Python and Regular Expressions"
}
|
256938
|
<h1>Introduction & Test</h1>
<p>I would like to create an object which associates employees to X/Y coordinates. Multiple employees can be associated to each coordinate, but each employee can only be associated with one coordinate.</p>
<p>Also critically: employees must be able to have identical externally-configurable attributes, for example, three employees with the name "Mary".</p>
<p>Here's my test (<code>AssociatorTest.java</code>) that I would like to implement a solution to:</p>
<pre><code>package com.example;
import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import static junit.framework.TestCase.*;
public class AssociatorTest {
final Employee marySmith = new Employee("Mary");
final Employee maryJohnson = new Employee("Mary");
final Employee maryWilliams = new Employee("Mary");
final Employee maryJones = new Employee("Mary");
final Coordinates coords1 = new Coordinates(1,2);
final Coordinates coords2 = new Coordinates(3,4);
@Test
public void basicAssociatorValidAssociations() throws EmployeeInTwoSpacesError {
// valid associations
Associator associator = new Associator()
.associate(marySmith, coords1)
.associate(maryJohnson, coords2)
.associate(maryWilliams, coords2);
// lookup coords per employee
assertEquals(coords1, associator.getLocation(marySmith).get());
assertEquals(coords2, associator.getLocation(maryJohnson).get());
assertEquals(coords2, associator.getLocation(maryWilliams).get());
// Unaffiliated employee has no location
assertTrue(associator.getLocation(maryJones).isEmpty());
// lookup employees at coords
assertEquals(ImmutableSet.of(marySmith), associator.getEmployees(coords1));
assertEquals(ImmutableSet.of(maryJohnson, maryWilliams), associator.getEmployees(coords2));
assertEquals(ImmutableSet.of(), associator.getEmployees(new Coordinates(5,6)));
}
@Test (expected = EmployeeInTwoSpacesError.class)
public void tryToAssociateAnEmployeeWithTwoCoords() throws EmployeeInTwoSpacesError {
// Employees shouldn't be able to exist in two places at the same time
new Associator()
.associate(marySmith, coords1)
.associate(marySmith, coords2);
}
}
</code></pre>
<h1>Implementation</h1>
<p>My solution depends on using <a href="https://mvnrepository.com/artifact/com.google.guava/guava/30.1-jre" rel="nofollow noreferrer">Guava</a></p>
<p>Here's my <code>Associator.java</code>:</p>
<pre><code>package com.example;
import com.google.common.collect.*;
import java.util.*;
public class Associator {
private final ImmutableSetMultimap<Coordinates, Employee> associations;
public Associator() {
associations = ImmutableSetMultimap.of();
}
private Associator(final Multimap<Coordinates, Employee> associations) {
this.associations = ImmutableSetMultimap.copyOf(associations);
}
public Associator associate(final Employee employee, final Coordinates coordinate)
throws EmployeeInTwoSpacesError {
if (associations.containsValue(employee)) {
throw new EmployeeInTwoSpacesError();
} else {
Multimap<Coordinates, Employee> mutableMap = HashMultimap.create(associations);
mutableMap.put(coordinate, employee);
return new Associator(mutableMap);
}
}
public Optional<Coordinates> getLocation(final Employee employee) throws EmployeeInTwoSpacesError {
final Set<Coordinates> found = new HashSet<>();
for (Map.Entry<Coordinates, Employee> entry : associations.entries()) {
if (entry.getValue().equals(employee)) {
found.add(entry.getKey());
}
}
int numLocations = found.size();
if (numLocations == 1) {
return Optional.of(found.iterator().next());
} else if (numLocations > 1) {
// This should be unnecessary, but I'm being paranoid
throw new EmployeeInTwoSpacesError();
} else {
return Optional.empty();
}
}
public ImmutableSet<Employee> getEmployees(final Coordinates location) {
return associations.get(location);
}
}
</code></pre>
<p>Here's my <code>Employee.java</code>:</p>
<pre><code>package com.example;
import java.util.Objects;
import java.util.UUID;
public class Employee {
private final String name;
private final UUID uuid;
public Employee(String name) {
this.name = name;
this.uuid = UUID.randomUUID();
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Employee)) {
return false;
}
Employee other = (Employee) o;
return name.equals(other.name) && uuid.equals(other.uuid);
}
@Override
public int hashCode() {
return Objects.hash(name, uuid);
}
}
</code></pre>
<p>Here's my <code>Coordinates.java</code></p>
<pre><code>package com.example;
import java.util.Objects;
public class Coordinates {
private final int x;
private final int y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Coordinates)) {
return false;
}
Coordinates other = (Coordinates) o;
return x == other.x && y == other.y;
}
@Override
public int hashCode() {
return Objects.hash(x,y);
}
}
</code></pre>
<p>And for completeness, here's my <code>EmployeeInTwoSpacesError.java</code>:</p>
<pre><code>package com.example;
public class EmployeeInTwoSpacesError extends Exception { }
</code></pre>
<h1>Main Questions:</h1>
<p>Any feedback would be appreciated, but here's some specific questions:</p>
<ul>
<li>Is the Employee's UUID the best course of action here to avoid the case where you have similar objects? I never hear people discuss UUIDs</li>
<li>Is the use of <code>Optional</code>s appropriate?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T23:09:44.333",
"Id": "507404",
"Score": "1",
"body": "I'm not sure I understand why you need the associator class instead of having each employee have their location as a class member..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T00:49:49.183",
"Id": "507409",
"Score": "0",
"body": "Wouldn't that be a violation of the Single Responsibility Principle?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T08:58:38.080",
"Id": "507565",
"Score": "1",
"body": "It's not a violation of the SRP. The employee class has one responsibility, to represent an employee (data and operations), the location is a property of an employee in the same way as name is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T09:02:01.427",
"Id": "507566",
"Score": "1",
"body": "The goal of SRP, DRY, SOLID etc is to create correct, simple and maintainable code. By creating an associator like this you're increasing complexity and adding more risk for bugs compared to just considering the location to be a property of the employee (like name and title), which is counter to the overall goal of all of these principles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T14:54:32.187",
"Id": "507599",
"Score": "0",
"body": "I disagree about the SRP violation. To me, having an Employee keep its location is akin to keeping its own index in a list it is contained in. How coordinates are represented has a high likelihood for change (say I want to extend X/Y to X/Y/Z or support representing coordinates with different coordinate spaces); and if I have a setPosition, I might want to add constraints on what is a valid Position to set, but this would have nothing to do with an employee's attributes really. Another reason is that having an employee track its location invites mutability into the Employee class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T20:36:24.567",
"Id": "507643",
"Score": "4",
"body": "So your employees are not allowed to change their name if they get married or have a sex change or whatever? Loss of immutability seems moot as humans are mutable whether you like it or not. If you want to extend location information by adding another dimension, you're looking at it from the wrong direction. A location **is a** coordinate tuple and should be encapsulated in a class. An employee **has a** location, and should then have an instance of a location object. You break cohesion of the class by externalising the **has a** relation and this makes code less readable."
}
] |
[
{
"body": "<blockquote>\n<p>Is the Employee's UUID the best course of action here to avoid the case where you have similar objects? I never hear people discuss UUIDs</p>\n</blockquote>\n<p>Since your Associator relies on comparing Employees, using <code>UUID</code> seems better than using mutatable fields that do not clearly identify one and the same Employee. But let's keep in mind, that your Associator, which manages your Employee-Location relationship depends on <code>Employee#equals</code>.</p>\n<blockquote>\n<p>Is the use of Optionals appropriate?</p>\n</blockquote>\n<p>Yes, there is no coding reason to not use Optionals by providing a non-arbitrary way for <code>null</code> checks. As such, you could add <code>@Test</code> cases with an Employee having no Coordinates, so you can estimate if e.g. <code>if(associator.getLocation(employee).isPresent())</code> is doing what it's supposed to do.</p>\n<blockquote>\n<p>How to associate any number of employees with a location, but only one location per employee?</p>\n</blockquote>\n<p>There seem to be two major drawbacks with your approach:</p>\n<ol>\n<li><p>Adding a Employee-Location pair to your <code>Associator</code> means you a) copy your immutable collection to a new immutable collection + the new value and b) returning a <code>new Associator(...)</code> as the return value, just to create another <code>ImmutableMap</code> of the newly created <code>MutableMap</code>.</p>\n</li>\n<li><p>Checking, if one Employee occupies two Locations means the Associator traversing <strong>all values</strong> of <strong>all Coordinates</strong> in your map, regardless of a key. This seems to defeat the whole purpose of having a <code>Map</code> key in the first place.</p>\n</li>\n</ol>\n<p>Instead, having a Location field in your employee class, and forcing the setLocation() method to just be callable once handles your "One Location per Employee" nicely.</p>\n<pre><code>public class Employee {\n Location location = null;\n\n public Optional<Location> getLocation() {\n return Optional.ofNullable(this.location);\n }\n\n public void setLocation(Location loc) {\n if(this.location != null) throw AppropriateRuntimeException();\n this.location = loc;\n }\n}\n</code></pre>\n<p>Everything else, like transition operations, depends on your design of <code>Moveable</code> objects in a designated <code>Area</code>. But now, you can now use a normal Multimap to store your "Many Employees per Location" relationship.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T14:37:54.140",
"Id": "508426",
"Score": "0",
"body": "Thanks very much for this feedback. I'm curious about what you consider drawback #2. You say that retrieving the Location of an Employee is inefficient, which I agree with. But, using your suggested mutable Location field, wouldn't retrieving all Employees at a given location be just as inefficient because you'd have to iterate through all Employees? To me, this is another reason to use my Associator scheme, because you could further develop the Associator so that it includes two maps, one Location->Employee, and the other Employee UUID->Location."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T16:14:59.327",
"Id": "508441",
"Score": "0",
"body": "Sorry for the poor wording (edited drawback #2). The difference is iterating over all Employees of *one* Coordinate (proposal) vs iterating over all Employees of *all* Coordinates, effectively ignoring the chosen data structure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T08:27:47.100",
"Id": "257388",
"ParentId": "256940",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257388",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:11:20.673",
"Id": "256940",
"Score": "1",
"Tags": [
"java",
"guava"
],
"Title": "Java: How to associate any number of employees with a location, but only one location per employee?"
}
|
256940
|
<p>I'm making some small board game and wanted to code a very simple greed AI with this algorithm. It turns out it doesn't play the most greedy moves, it is simply not working. I'd appreciate any comments around this code.</p>
<p>First, the position evaluation functions are:</p>
<pre><code>uint8_t get_piece_value(PKind kind)
{
switch (kind) {
case PKind::FIRST:
return 10;
case PKind::SECOND:
return 30;
case PKind::THIRD:
return 35;
case PKind::FORTH:
return 100;
}
int get_position_value(const Position& position)
{
int value;
for (auto var : position.pieces) {
if (var.id.color == position.turnToPlay) {
value += get_piece_value(var.id.kind);
continue;
}
value -= get_piece_value(var.id.kind);
}
return value;
}
</code></pre>
<p>Now this is the function I use to get the valid moves:</p>
<pre><code>std::vector<PMove> get_ALL_valid_moves(const Position& position)
{
std::vector<PMove> allMoves;
for (auto piece : position.pieces)
{
if (piece.id.color == position.turnToPlay) {
auto validMoves = get_valid_moves(piece);
if (validMoves.size() == 0) {
continue;
}
for (auto var : validMoves) {
allMoves.push_back(var);
}
} else {
assert(("Wrong color passed to get ALL valid moves!!\n"));
}
}
return allMoves;
}
</code></pre>
<p>Next, here are the minmax functions:</p>
<pre><code>constexpr int MAX_EVAL = 9999;
constexpr int MIN_EVAL = -MAX_EVAL;
///Minmax evaluation with alpha beta pruning
int minmax_ab(const Position newposition, int depth, int alpha, int beta, bool isMaximizer)
{
if (depth == 0) {
return get_position_value(newposition);
}
std::vector<PMove> validMoves;
validMoves = get_ALL_valid_moves(newposition);
if (validMoves.size() == 0) {
return get_position_value(newposition);
}
if (isMaximizer) {
for (auto move : validMoves) {
alpha = std::max(alpha, minmax_ab(make_position(newposition, move), depth - 1, alpha, beta, false) );
if (alpha >= beta) {
return beta;
}
}
return alpha;
} else {
for (auto move : validMoves) {
beta = std::min(beta, minmax_ab(make_position(newposition, move), depth - 1, alpha, beta, true) );
if (beta <= alpha) {
return alpha;
}
}
return beta;
}
}
PMove minmax_root(const Position& position, const int depth)
{
std::vector<PMove> validMoves = get_ALL_valid_moves(position);
/// assume the starting value of the last valid move for best move
PMove bestmove = validMoves.front();
int besteval = get_position_value(make_position(position, bestmove));
int eval = MIN_EVAL;
for (auto move : validMoves) {
eval = minmax_ab(make_position(position, move), depth - 1, MIN_EVAL, MAX_EVAL, false);
if (eval > besteval) {
besteval = eval;
bestmove = move;
}
}
return bestmove;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:56:30.160",
"Id": "507397",
"Score": "0",
"body": "I’m very much looking forward to reviews of this - I developed an alpha-beta-pruning too, and have been debugging it for months… can’t find my errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T00:59:33.287",
"Id": "507410",
"Score": "2",
"body": "I am sorry, but the code which _is simply not working_ is strictly off-topic here."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:39:18.620",
"Id": "256941",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"ai",
"chess"
],
"Title": "minmax evaluation with alpha beta pruning"
}
|
256941
|
<p>I've been assigned a tast to implement an SMTP client-server protocol providing limited functionality and the Solution for this is to execute a typical execution simiilar to this transcription:</p>
<pre><code>S: 220 [ip]
C: HELLO [email]
S: 250 Hello [email], pleased to meet you
C: MAIL FROM: <email1@email.com>
S: 250 ok
C: RCPT TO: <email2@email2.com>
S: 250 ok
C: DATA
S: 354 End data with <CR><LF>.<CR><LF>
C: Hello,
C: Test Email
C: .
S: 250 ok Message accepted for delivery
C: QUIT
S: 221 [ip] closing connection
</code></pre>
<p>Essentially, it's not supposed to send any emails or anything but more simulate the process of sending an email through an SMTP.</p>
<p>I've taken the easy route of using Cases and Switches so when it reads the data, it prints out exactly what i want, but i want to know if there's a way i can get the Client's input and read it in the server to produce an ouptut similar to the trasncript i've written. And also how can i code it any better?</p>
<p>Here's the Server code:</p>
<pre><code> package TCPSocket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer{
private ServerSocket server;
/**
* The TCPServer constructor initiate the socket
* @param ipAddress
* @param port
* @throws Exception
*/
public TCPServer(String ipAddress, int port) throws Exception {
if (ipAddress != null && !ipAddress.isEmpty())
this.server = new ServerSocket(port, 1, InetAddress.getByName(ipAddress));
else
this.server = new ServerSocket(0, 1, InetAddress.getLocalHost());
}
/**
* The listen method listen to incoming client's datagrams and requests
* @throws Exception
*/
private void listen() throws Exception {
// listen to incoming client's requests via the ServerSocket
//add your code here
String data = null;
Socket client = this.server.accept();
String clientAddress = client.getInetAddress().getHostAddress();
System.out.println("\r\nNew client connection from " + clientAddress);
// print received datagrams from client
//add your code here
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ( (data = in.readLine()) != null ) {
//System.out.println("\r\nMessage from " + clientAddress + ": " + data);
switch (data){
case("HELLO 192.168.56.1"):
System.out.println("\r\n250 Hello " + clientAddress + ", pleased to meet you");
break;
case("MAIL FROM: <test1@gmail.com>"):
System.out.println("\r\n250 ok");
break;
case("RCPT TO: <test@email.com>"):
System.out.println("\r\n250 ok");
break;
case("DATA"):
System.out.println("\r\n354 End data with <CR><LF>.<CR><LF>");
break;
case("."):
System.out.println("\r\nok Message accepted for delivery");
break;
case("QUIT"):
System.out.println("\r\n221 " + clientAddress + " closing connection");
in.close();
break;
}
client.sendUrgentData(1);
}
}
public InetAddress getSocketAddress() {
return this.server.getInetAddress();
}
public int getPort() {
return this.server.getLocalPort();
}
public static void main(String[] args) throws Exception {
// set the server address (IP) and port number
//add your code here
String serverIP = "192.168.56.1"; // local IP address
int port = 7077;
if (args.length > 0) {
serverIP = args[0];
port = Integer.parseInt(args[1]);
}
// call the constructor and pass the IP and port
//add your code here
TCPServer server = new TCPServer(serverIP, port);
System.out.println("\r\nRunning Server: " +
"Host=" + server.getSocketAddress().getHostAddress() +
" Port=" + server.getPort());
System.out.println("220 " + serverIP);
server.listen();
}
}
</code></pre>
<p>And here's the Client code:</p>
<pre><code>package TCPSocket;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class TCPClient{
private Socket tcpSocket;
private InetAddress serverAddress;
private int serverPort;
private Scanner scanner;
/**
* @param serverAddress
* @param serverPort
* @throws Exception
*/
private TCPClient(InetAddress serverAddress, int serverPort) throws Exception {
this.serverAddress = serverAddress;
this.serverPort = serverPort;
//Initiate the connection with the server using Socket.
//For this, creates a stream socket and connects it to the specified port number at the specified IP address.
//add your code here
this.tcpSocket = new Socket(this.serverAddress, this.serverPort);
this.scanner = new Scanner(System.in);
}
/**
* The start method connect to the server and datagrams
* @throws IOException
*/
private void start() throws IOException {
String input;
//create a new PrintWriter from an existing OutputStream (i.e., tcpSocket).
//This convenience constructor creates the necessary intermediateOutputStreamWriter, which will convert characters into bytes using the default character encoding
//You may add your code in a loop so that client can keep send datagrams to server
//add your code here
while (true) {
input = scanner.nextLine();
PrintWriter output = new PrintWriter(this.tcpSocket.getOutputStream(), true);
//output.println("hello " + serverAddress);
output.println(input);
output.flush();
}
}
public static void main(String[] args) throws Exception {
// set the server address (IP) and port number
//add your code here
InetAddress serverIP = InetAddress.getByName("192.168.56.1"); // local IP address
int port = 7077;
if (args.length > 0) {
serverIP = InetAddress.getByName(args[0]);
port = Integer.parseInt(args[1]);
}
// call the constructor and pass the IP and port
//add your code here
TCPClient client = new TCPClient(serverIP, port);
System.out.println("\r\n Connected to Server: " + client.tcpSocket.getInetAddress());
client.start();
}
}
</code></pre>
<p>Hopefully what i've written made sense and i appreciate any feedback and help provided</p>
|
[] |
[
{
"body": "<p>This is a side issue really, but if your client and server are running on the same machine you may want to consider using the loop back address "127.0.0.1" when connecting from the client, or having it as a command line parameter. It'll mean that you don't need to recompile the application every time you move machines / your DNS decides to reallocate your address.</p>\n<h1>Responsibilities</h1>\n<p>Aim to have your classes responsible for one main thing. Typically, I would expect the job of a <code>TCPServer</code> to be to listen on a given port for connection requests, which are then accepted and passed onto another class (possibly something like <code>EmailClient</code>) to manage the connection. The server can then go back to waiting for the next connection request. The way you've coded it up at the moment, the server can't start dealing with the next request until after it's received all of the messages from the first connection. This means that a faulty/malicious client could block your server by simply never closing its connection.</p>\n<h1>Commands</h1>\n<p>There are several commands that your server is able to handle. Some of them (<code>QUIT</code>, <code>.</code>) consist of the entire message. Other commands start with a particular message (<code>HELLO</code>, <code>MAIL FROM:</code>), which then have parameters consisting of the rest of the line. Splitting the message between the command and the parameters would allow you to capture relevant information, such as the email address to echo back to the client.</p>\n<h1>Data</h1>\n<p>At the moment, although you recognise that you've received a <code>DATA</code> command, you don't do anything about it. Similarly, you always respond to <code>.</code>, as if you'd been processing <code>DATA</code>. Consider using some kind of state in your client class to track what the client is currently doing. If they send <code>DATA</code>, then you start building up the message to send (or ignoring it if you don't care at present), until they send an end message <code>.</code>. While you're processing the message data you don't want to be checking for commands other than end of data. At the moment, if the message contained "MAIL FROM: test1@gmail.com", you'd respond as if it was a command.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T22:05:21.250",
"Id": "257419",
"ParentId": "256942",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T20:51:11.823",
"Id": "256942",
"Score": "3",
"Tags": [
"java",
"email"
],
"Title": "How can I implement the SMTP protocol better in my Server and Client “SMTP” code?"
}
|
256942
|
<p>I have some code here that basically takes in a list of IDs (sequencing read names) using STDIN, and then filters <code>fin</code> (a gzipped FASTQ file) to just those reads with a read name which matches one of the IDs, and then writes the name and sequence to <code>fout</code> (a gzipped FASTA file). Fairly standard data processing problem in bioinformatics.</p>
<p>The code below can run through about 100k/sec lines of <code>fin</code>, however <code>fin</code> is about 500M lines, so it still takes over an hour.</p>
<p>Can this be sped up significantly? I'm hoping for a 10x or better improvement in performance. I may be taking a performance hit running <code>line.decode('utf-8')</code>, however it's necessary for matching since gzip files are read as bytestring. I'm willing to drop down and rewrite this in C if this will substantially increase speed.</p>
<pre><code>import sys
import gzip
import re
id_array = []
for line in sys.stdin:
id_array.append(line.rstrip())
ids = set(id_array)
with gzip.open(sys.argv[1], "r") as fin:
with gzip.open(sys.argv[2], "w") as fout:
take_next_line = False
for line in fin.readlines():
seq_search = re.search('[@+]([^\s]+)', line.decode('utf-8'))
if take_next_line:
fout.write(line)
take_next_line = False
elif seq_search and seq_search.group(1) in ids:
take_next_line = True
fout.write('>' + line[1:])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T02:54:01.050",
"Id": "507413",
"Score": "0",
"body": "How many IDs are there? How big is the uncompressed FASTQ file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T03:29:47.557",
"Id": "507414",
"Score": "0",
"body": "@RootTwo The number of IDs can vary quite a lot, from zero to millions. The uncompressed FASTQ file is likely around 30GB."
}
] |
[
{
"body": "<p>Opened Python file objects are directly iterable, so you almost never need to\nuse <code>readlines()</code>, which reads the entire file and creates a list storing the\nwhole thing. Usually one avoids <code>readlines()</code> to prevent out-of-memory errors,\nbut the change might help with speed, so it's worth trying. Just iterate\ndirectly:</p>\n<pre><code>for line in fin:\n ...\n</code></pre>\n<p>A couple regex issues, not related to speed: (1) it's\na good habit to create all regexes with <code>r'...'</code> strings to avoid unwanted\ninterpretation of escape characters; and (2) you don't need <code>[^\\s]</code>,\nwhich does the same thing as <code>\\S</code></p>\n<pre><code>rgx = re.compile(r'[@+](\\S+)')\n</code></pre>\n<p>I haven't used the <code>gzip</code> library very many times, but the documentation\nimplies that it will perform the decoding for you. The library might be\nfaster at decoding than your code, because it performs fewer decoding\noperations (entire blocks at a time, rather than\nline-by-line). Anyway, all of this speculative, but it might be worth reversing\nthings as an experiment: let <code>gzip</code> decode, and you encode whatever you need to write.</p>\n<p>That said, your regular expression isn't very complex and Python does support\nregex searches on <code>bytes</code>, provided that the regex and the target string are\nboth <code>bytes</code>. That might eliminate the need for large-scale decoding; maybe you\njust need to decode <code>seq_search.group(1)</code> when you get a match. Or just\npre-convert <code>ids</code> to be <code>bytes</code> as well, and live in the land of bytes!</p>\n<pre><code>rgx = re.compile(rb'[@+](\\S+)')\nfor line in fin:\n seq_search = rgx.search(line)\n ...\n</code></pre>\n<p>Beyond that, you could try parallelism: partitioning the work into\nblocks within the file and handing those partitions off to different\nPython processes. These heavy file reading/writing\nscripts sometimes benefit from that kind of approach, but not always.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T01:30:46.373",
"Id": "256947",
"ParentId": "256943",
"Score": "2"
}
},
{
"body": "<p>Do not reinvent the wheel. There are bioinformatics tools that accomplish this task.</p>\n<p>To extract reads from fastq files by IDs, use <a href=\"https://github.com/lh3/seqtk\" rel=\"nofollow noreferrer\"><code>seqtk subseq</code></a>.</p>\n<blockquote>\n<p>Extract sequences with names in file name.lst, one sequence name per line:<br />\n<code>seqtk subseq in.fq name.lst > out.fq</code></p>\n</blockquote>\n<p>It works with <code>fasta</code> files as well.</p>\n<p>Use <code>conda install seqtk</code> or <code>conda create --name seqtk seqtk</code> to install the <code>seqtk</code> package, which has other useful functionalities as well, and is very fast.</p>\n<p>Alternatively, use <a href=\"https://sourceforge.net/projects/bbmap/\" rel=\"nofollow noreferrer\"><code>BBMap filterbyname.sh</code></a>, see <a href=\"http://seqanswers.com/forums/showthread.php?t=58221\" rel=\"nofollow noreferrer\">docs</a>:</p>\n<blockquote>\n<p>By default, "filterbyname" discards reads with names in your name list, and keeps the rest. To include them and discard the others, do this:<br />\n<code>filterbyname.sh in=003.fastq out=filter003.fq names=names003.txt include=t</code></p>\n</blockquote>\n<p><strong>SEE ALSO:</strong><br />\n<a href=\"https://www.biostars.org/p/342043/\" rel=\"nofollow noreferrer\">Extracting specific sequences from FASTQ using Seqtk</a><br />\n<a href=\"https://www.biostars.org/p/74243/\" rel=\"nofollow noreferrer\">How To Extracting Fastq Sequence For Given Fastq Ids And Fastq File</a><br />\n<a href=\"https://www.biostars.org/p/45816/\" rel=\"nofollow noreferrer\">How To Extract A Subset Of Reads In Fastq Using An Id List?</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:51:53.593",
"Id": "256985",
"ParentId": "256943",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "256985",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-09T22:09:54.280",
"Id": "256943",
"Score": "2",
"Tags": [
"python",
"performance",
"io",
"bioinformatics"
],
"Title": "Filtering FASTQ file based on read names from other file (how to increase performance) Python"
}
|
256943
|
<p>This is what I implemented in Rust to get the maximum number of consecutive 1s in list of binary numbers.</p>
<pre><code>impl Solution {
pub fn print_values(nums: Vec<i32>) -> i32{
let mut result = 0;
let mut count = 0;
// let mut end = 0;
// NotE: Change the if so that it check
// if 0 else have body for 1 condition
if nums.len() < 10000 {
for (index,num) in nums.iter().enumerate() {
// println!("{}:{}", index, num);
if *num == 1 && index != nums.len() {
count+=1;
// println!("count updated to {}", count);
}else{
if count > result {
result = count;
}
count = 0;
// println!("count reset to {} from {}", count, result);
}
if index == nums.len()-1 && count > 0 {
// println!("Last if checked count {} result {}", count, result);
if count > result{
result = count;
count =0;
}
}
}
// println!("afeter leaving for loop ending result :{} ", result);
result
}else{
// what's the difference if we put semicolon here at end or what if not
panic!("List is too much larger!! Kindly reduce your list.")
}
}
}
</code></pre>
<p>Though I've accomplished the desired resutl, I guess as long I tested. Kindly review strictly.
How can I improve the speed and memory usage here?</p>
|
[] |
[
{
"body": "<p>I will mainly focus on style and design, instead of speed and memory usage, as I think that is where you have the most room for improvement. :)</p>\n<ul>\n<li><p><strong>Formatting:</strong> Always run <code>cargo fmt</code> (aka <code>rustfmt</code>) before posting your code online! It enforces standard formatting to improve readability.</p>\n</li>\n<li><p><strong>Function arguments:</strong> This is a function that does not need ownership over its argument; you can count the ones in a purely read-only way. So it should take <code>&[i32]</code> instead of <code>Vec<i32></code>. The idea is that this will be much faster and more memory-efficient if the user has a <code>Vec<i32></code> but needs to retain ownership over it.</p>\n</li>\n<li><p><strong>Naming:</strong> The name, <code>print_values</code>, is nondescriptive. A good name for this function would be <code>count_consecutive_ones</code> or <code>max_consecutive_ones</code>.\nOther than this, the names for your variables look good to me.</p>\n</li>\n<li><p><strong>Program logic:</strong> The implementation is a bit convoluted. A few specifics:</p>\n<ul>\n<li><p><code>&& index != nums.len()</code> is not necessary, here you know <code>index</code> is used to index <code>nums</code> so it is less than the length.</p>\n</li>\n<li><p>The logic in the block <code>if index == nums.len() - 1</code> does not belong inside the loop, but outside. In particular, this fails if the vector is empty, but it is also just clearer to include "final" code at the end.</p>\n</li>\n<li><p>With this fixed, you shouldn't need <code>index</code> at all.</p>\n</li>\n<li><p>Local variables (<code>result</code> and <code>count</code>): don't initialize variables at the top of the function, but rather initialize as late as possible, when you need a particular variable.</p>\n</li>\n</ul>\n<p>Here's a better implementation of the main part of the body:</p>\n<pre><code> let mut result = 0;\n let mut count = 0;\n for num in nums.iter() {\n if *num == 1 {\n count += 1;\n if count > result {\n result = count;\n }\n } else {\n count = 0;\n }\n }\n result\n</code></pre>\n</li>\n<li><p><strong>Length cap:</strong> Regarding the cap you put on the function (<code>panic!</code>ing if <code>nums.len() >= 10000</code>), I like the idea, but I think that you want to be more thoughtful about the way this is designed. Presently, if a user has a vector longer than <code>10000</code> to count, they will (1) not be able to use your function, and (2) even worse, probably run into an unexpected crash at runtime that they did not realize would occur.</p>\n<p>The rule in Rust is to always make the possibility of errors -- especially <code>panic!</code> runtime errors -- explicit. I would consider the following design:</p>\n<ul>\n<li><p>First, make the magic number <code>10000</code> configurable: <code>const LIST_TOO_LARGE: usize = 10000</code>.</p>\n</li>\n<li><p>Second, provide a version that does not fail -- e.g. <code>max_consecutive_ones(nums: &[i32]) -> i32</code>. If you like, you can print a warning: <code>if nums.len() >= LIST_TOO_LARGE { eprintln!("Warning: list too large! Function may be a bit slow.") }</code></p>\n</li>\n<li><p>Third, if you like, provide a version which fails by wrapping around your non-failing version. Basically <code>if nums.len() >= LIST_TOO_LARGE { /* fail */ } else { max_consecutive_ones(nums) }</code>\nI would return <code>Result<i32, String></code> (expose the error explicitly) in this version instead of using <code>panic!()</code>.</p>\n</li>\n</ul>\n<p>Another design you could consider: you could define\n<code>max_consecutive_ones_throttled(nums, throttle: Option<usize>)</code>, where if <code>throttle</code> is specified then you <em>only</em> check the first <code>throttle</code> values. That seems to go along with the idea of providing a cap for efficiency, but now you have the advantage that (1) users of your code can choose a throttle specific to their use case; (2) you don't just fail if the list is too long, but you still at least check the first <code>throttle</code> values.</p>\n</li>\n<li><p><strong>Answering your question about semicolons after <code>panic</code>:</strong> whether you have a semicolon or not doesn't make any difference. It is up to you what style you prefer.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T02:01:45.087",
"Id": "257046",
"ParentId": "256949",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T04:33:30.627",
"Id": "256949",
"Score": "2",
"Tags": [
"algorithm",
"programming-challenge",
"rust"
],
"Title": "Returning maximum number of consecutive 1s in list of binary numbers"
}
|
256949
|
<p>I'm trying to write a Python program to predict the most likely substitution for a Caesar cipher. I managed to get it working, but it just seems very clunky and slow, especially because I need to preserve cases and non-alphabetical characters.</p>
<ul>
<li>Would it be cleaner / more pythonic to use the <code>chr()</code> and <code>ord()</code> functions instead of the <code>ALPHABET</code> list?</li>
<li>Any suggestions on how I could improve it overall (while also maintaining relative readability)?</li>
</ul>
<p>Thank you so much!</p>
<pre><code>ALPHABET = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
FREQUENCIES = [.0817, .0149, .0278, .0425, .1270, .0223, .0202, .0609, .0697, .0015, .0077, .0402, .0241, .0675, .0751, .0193, .0009, .0599, .0633, .0906, .0276, .0098, .0236, .0015, .0197, .0007]
def getGoodness(msg):
msg_length = sum([1 for i in msg if i.isalpha()])
msg_frqs = [round(msg.count(a) / msg_length, 4) for a in ALPHABET]
diffs = [abs(a - b) for a, b in zip(msg_frqs, FREQUENCIES)]
avg_diff = round(sum(diffs) / len(diffs), 4)
return avg_diff
def shift(string, n):
shifted = [i for i in string]
for char in range(len(shifted)):
if shifted[char].isalpha():
new_char = ALPHABET[(ALPHABET.index(shifted[char].lower()) + n) % len(ALPHABET)]
if shifted[char].isupper():
new_char = new_char.upper()
shifted[char] = new_char
return ''.join(shifted)
#########################################
msg = "Oqqcfrwbu hc ozz ybckb zokg ct ojwohwcb, hvsfs wg bc kom o pss gvcizr ps opzs hc tzm. Whg kwbug ofs hcc gaozz hc ush whg toh zwhhzs pcrm ctt hvs ufcibr. Hvs pss, ct qcifgs, tzwsg obmkom psqoigs pssg rcb'h qofs kvoh viaobg hvwby wg wadcggwpzs. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Ccv, pzoqy obr mszzck! Zsh'g gvoys wh id o zwhhzs. Poffm! Pfsoytogh wg fsorm!"
goodness = []
shifted = []
for i in range(26):
goodness.append(getGoodness(shift(msg, i)))
shifted.append(shift(msg, i))
gdict = dict(zip(goodness, shifted))
print(gdict.get(min(gdict.keys())))
</code></pre>
|
[] |
[
{
"body": "<p>The <code>shift()</code> function was fairly easy to understand, in no small part because\nyou've chosen reasonable and clear variable names. Here are a few relatively\nminor suggestions regarding the function. (1) Strings are iterable, so you can\nconvert to characters directly. (2) Python makes iteration so easy that looping\nover data via an index is usually not needed. Instead, just iterate directly.\nAnd for those cases when an index is needed, <code>enumerate()</code> is often the best\noption, because it provides both index and value -- which helps your code by\nreducing its visual weight and thus aiding readability. (3) The assignment to\n<code>new_char</code> is a moderately complex expression. One way to improve code\nreadability is to such computations apart. (4) A <code>dict</code> to lookup a letter's\nindex would eliminate the need to scan <code>ALPHABET</code> repeatedly.</p>\n<pre><code># 4\nALPHA_IDXS = {a:i for i, a in enumerate(ALPHABET)}\n\ndef shift(string, n):\n # 1\n shifted = list(string)\n # 2\n for i, char in enumerate(shifted):\n if char.isalpha():\n # 3 and 4\n j = (ALPHA_IDXS[char.lower()] + n) % len(ALPHABET)\n new_char = ALPHABET[j]\n if char.isupper():\n new_char = new_char.upper()\n shifted[i] = new_char # The only place we use index.\n return ''.join(shifted)\n</code></pre>\n<p>Another technique to consider is converting <code>shift()</code> into a generator function.\nThis simplifies the code even more because the function no longer has to\nassemble a return data collection -- although at a small cost to the caller,\nwhich must do the assembling. Here's what that might look like.</p>\n<pre><code>def shift(string, n):\n for i, char in enumerate(string):\n if char.isalpha():\n j = (ALPHA_IDXS[char.lower()] + n) % len(ALPHABET)\n new = ALPHABET[j]\n char = new if char.islower() else new.upper()\n yield char\n</code></pre>\n<p>You did a nice job in <code>getGoodness()</code> with keeping the steps of the algorithm\nvery clear. Here are a few suggestions: (1) Because <code>bool</code> is a subclass of\n<code>int</code>, you can treat <code>True</code> and <code>False</code> as integers -- just add up the <code>True</code>s.\nAlso, functions like <code>sum()</code> take any iterable, so you don't need an\nintermediate list. (2) <code>msg_length</code> seems a bit misleading: it is not the\nlength of <code>msg</code>; it is the number of alpha characters. (3) A <code>Counter</code> can\ncompute letter frequencies for you. (4)\nShouldn't this calculation be done on a lowercase version of the text?</p>\n<pre><code>from collections import Counter\n\ndef getGoodness(msg):\n # 1 and 2\n n_alphas = sum(i.isalpha() for i in msg)\n # 3 and 4\n freqs = Counter(msg.lower())\n msg_frqs = [round(freqs[a] / n_alphas, 4) for a in ALPHABET]\n diffs = [abs(a - b) for a, b in zip(msg_frqs, FREQUENCIES)]\n avg_diff = round(sum(diffs) / len(diffs), 4)\n return avg_diff\n</code></pre>\n<p>Finally, some comments about the orchestration code. (1) Put your code in\nfunctions. (2) Set yourself up for testing. It helps a lot during the\ndevelopment and debugging lifecycle. (3) In the loop to compute goodnesses for\nthe shifted strings, a <code>tuple</code> seems like a handier data structure than a\n<code>dict</code>. It simplifies the code and is better suited for <code>min()</code>. (4) I\nrecommend the habit of setting up all scripts so they can take arguments --\nagain, useful during development and sometimes usage.</p>\n<pre><code># 1\ndef main(args):\n # 2\n TESTS = (\n (\n "Oqqcfrwbu hc ozz ybckb zokg ct ojwohwcb, hvsfs wg bc kom o pss gvcizr ps opzs hc tzm. Whg kwbug ofs hcc gaozz hc ush whg toh zwhhzs pcrm ctt hvs ufcibr. Hvs pss, ct qcifgs, tzwsg obmkom psqoigs pssg rcb'h qofs kvoh viaobg hvwby wg wadcggwpzs. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Mszzck, pzoqy. Ccv, pzoqy obr mszzck! Zsh'g gvoys wh id o zwhhzs. Poffm! Pfsoytogh wg fsorm!",\n "According to all known laws of aviation, there is no way a bee should be able to fly. Its wings are too small to get its fat little body off the ground. The bee, of course, flies anyway because bees don't care what humans think is impossible. Yellow, black. Yellow, black. Yellow, black. Yellow, black. Ooh, black and yellow! Let's shake it up a little. Barry! Breakfast is ready!",\n ),\n (\n "Ebiil, tloia!",\n "Hello, world!",\n ),\n )\n for msg, exp in TESTS:\n # 3\n scores = []\n for i in range(26):\n txt = ''.join(shift(msg, i))\n g = (getGoodness(txt), txt)\n scores.append(g)\n got = min(scores)[1]\n # 2 Always be testing.\n print(exp == got, '=>', got[0:30])\n\n# 4\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:41:00.990",
"Id": "507495",
"Score": "1",
"body": "thank you so much for your help! I have a question though - is a `Counter` necessarily faster or better in some way than the `.count()` function? thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:29:48.360",
"Id": "507502",
"Score": "0",
"body": "@tommy2111111111 No, not faster (often slower). But it can simplify code in a variety of situations. It's not clear how much simplicity it provides in this case -- not a lot -- but it is a useful data structure to know about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:42:17.407",
"Id": "507508",
"Score": "0",
"body": "ah got it, thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:57:01.337",
"Id": "256956",
"ParentId": "256950",
"Score": "3"
}
},
{
"body": "<p>You're diffing <code>msg_frqs</code> with <code>FREQUENCIES</code>. The latter's sum is 1, the former's isn't, because you're counting the upper case letters in <code>msg_length</code> but not in <code>msg_frqs</code>. That seems inappropriate. So better start <code>getGoodness</code> with <code>msg = msg.lower()</code>.</p>\n<p>And I wouldn't <code>round</code>. Why throw away information? Especially using extra code and time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:41:41.007",
"Id": "507496",
"Score": "0",
"body": "thank you! this was helpful. totally forgot about the `msg = msg.lower()`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T08:00:17.267",
"Id": "256957",
"ParentId": "256950",
"Score": "3"
}
},
{
"body": "<p>Your part</p>\n<pre><code>goodness = []\nshifted = []\nfor i in range(26):\n goodness.append(getGoodness(shift(msg, i)))\n shifted.append(shift(msg, i))\ngdict = dict(zip(goodness, shifted))\nprint(gdict.get(min(gdict.keys())))\n</code></pre>\n<p>is rather complicated. You could just use min-by-goodness:</p>\n<pre><code>shifts = (shift(msg, i) for i in range(26))\nprint(min(shifts, key=getGoodness))\n</code></pre>\n<p>Also takes less memory, as it just keeps the best shift so far, doesn't build a list+dict containing all of them like yours.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:02:00.680",
"Id": "507497",
"Score": "0",
"body": "wow, that's super smart. thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:34:43.097",
"Id": "507504",
"Score": "0",
"body": "oh got it, yeah just figured it out when I tested out the code lol. how would we get the corresponding number of shifts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:37:21.420",
"Id": "507506",
"Score": "0",
"body": "Not sure what you mean with that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:39:57.683",
"Id": "507507",
"Score": "0",
"body": "like the second line `print(min(shifts, key=getGoodness))` outputs the most likely plaintext, right? how would I get the number of places the ciphertext was shifted to the right to produce that most likely output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:44:19.230",
"Id": "507509",
"Score": "0",
"body": "Ah, so something your original doesn't do? You could compute it separately with `min(range(26), key=lambda i: getGoodness(shift(msg, i)))` (didn't test this) or you could take the input message and the output message and find the first difference."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:47:47.290",
"Id": "256983",
"ParentId": "256950",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256956",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T04:34:25.717",
"Id": "256950",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"cryptography"
],
"Title": "Caesar Cipher Encryption / Decryption in Python"
}
|
256950
|
<p>I tried to get the all unique pair combinations from a list.</p>
<p>Here is what I have done so far,</p>
<pre><code>import itertools
# Unique Combination Pairs for list of elements
def uniqueCombinations(list_elements):
l = list(itertools.combinations(list_elements, 2))
s = set(l)
# print('actual', len(l), l)
return list(s)
</code></pre>
<p><strong>Test Case</strong></p>
<pre><code>sample = ["apple", "orange", "banana", "grapes", "mango"]
uniqueCombinations(sample)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[('apple', 'banana'),
('orange', 'mango'),
('orange', 'grapes'),
('apple', 'grapes'),
('orange', 'banana'),
('apple', 'mango'),
('grapes', 'mango'),
('apple', 'orange'),
('banana', 'mango'),
('banana', 'grapes')]
</code></pre>
<p><strong>The input will be unique strings of list</strong>. Assume that duplicate elements will not be passed.</p>
<p>Is there a better / more elegant / more accurate way to do this??</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:53:38.730",
"Id": "507426",
"Score": "0",
"body": "`uniqueCombinations(['apple', 'orange', 'apple'])` returns `[('orange', 'apple'), ('apple', 'apple'), ('apple', 'orange')]`. Is this the output you are expecting for this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T08:00:40.303",
"Id": "507428",
"Score": "1",
"body": "yes, the original `list_elements` can contains duplicates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T08:26:45.993",
"Id": "507432",
"Score": "0",
"body": "When I run your code it does not produce that output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T08:34:48.537",
"Id": "507433",
"Score": "0",
"body": "The code in the question or in the answer??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:22:08.080",
"Id": "507444",
"Score": "0",
"body": "Is the order of the tuple important? If you sort `list_elements` you get `('banana', 'orange')` but lose `('orange', 'banana')`. The challenge is poorly defined. If so why are you duplicating output with `['apple', 'orange', 'apple']`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:41:24.420",
"Id": "507445",
"Score": "0",
"body": "Assume that the list of elements is the column names of a dataframe. I'm trying to plot column vs column using matplotlib. I want unique pairs to plot that. Ex: 'apple' vs 'banana' or 'banana' vs 'apple' it gives me the same or similar results which I don't need. Here I want only unique pairs to get my work done"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:43:36.787",
"Id": "507446",
"Score": "0",
"body": "I specifically need unique pairs from the list of elements, either as a list of lists or list of tuples or in any other way... in an efficient, accurate, and faster form"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:50:52.620",
"Id": "507448",
"Score": "0",
"body": "@Pluviophile Double-checking here, so in your Test Case 2 where the function returns `[('apple', 'orange'), ('apple', 'apple'), ('orange', 'apple')]`, isn't this a bad result for your use case? Since it would give you both `('apple', 'orange')` and `('orange', 'apple')`, and it sounds like you actually only want one of these, not both. This comment is in response to `Ex: 'apple' vs 'banana' or 'banana' vs 'apple' it gives me the same or similar results which I don't need.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:55:07.723",
"Id": "507449",
"Score": "0",
"body": "Well, I don't pass the duplicate strings as input. I think I need to update this..."
}
] |
[
{
"body": "<p>From <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\"><code>itertools.combinations</code></a>, emphasis mine:</p>\n<blockquote>\n<p>Return r length subsequences of elements from the input iterable.</p>\n<p>The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.</p>\n<p>Elements are treated as unique based on their position, not on their value. <strong>So if the input elements are unique, there will be no repeat values in each combination.</strong></p>\n</blockquote>\n<p>Which means as long as we pass in a collection of unique elements to <code>itertools.combinations</code>, there will be no duplicate values in the combinations it returns. And if we can assume that the input list will not contain any duplicate elements, we can rewrite the function like so:</p>\n<pre class=\"lang-python prettyprint-override\"><code>import itertools\n\ndef unique_combinations(elements: list[str]) -> list[tuple[str, str]]:\n """\n Precondition: `elements` does not contain duplicates.\n Postcondition: Returns unique combinations of length 2 from `elements`.\n\n >>> unique_combinations(["apple", "orange", "banana"])\n [("apple", "orange"), ("apple", "banana"), ("orange", "banana")]\n """\n return list(itertools.combinations(elements, 2))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T07:47:38.190",
"Id": "507424",
"Score": "0",
"body": "@superbrain True, then in that case we'd need clarification from @Pluviophile on what assumptions can be made about `list_elements`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:15:02.247",
"Id": "507439",
"Score": "0",
"body": "Trying the above code, I'm getting `TypeError: 'type' object is not subscriptable`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:16:09.457",
"Id": "507440",
"Score": "0",
"body": "Is that becoz of this part `: list[str] -> list[tuple[str, str]]`??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:17:32.010",
"Id": "507442",
"Score": "0",
"body": "@Pluviophile sounds like you're not running Python 3.9, you can either omit those type hints or use `from typing import List, Tuple` -> `List[str]` `List[Tuple[str, str]]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:21:12.423",
"Id": "507443",
"Score": "0",
"body": "Yes, I'm not using 3.9+, using 3.7. Thank you for the Fix"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:45:52.867",
"Id": "507447",
"Score": "1",
"body": "@superbrain I think the output for `['apple', 'orange', 'apple']` is actually a bug not a feature, with the OP's code. [Check here](https://codereview.stackexchange.com/q/256952#comment507445_256952), what do you think?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:58:41.483",
"Id": "507450",
"Score": "0",
"body": "Sounds like I can revert back to my original answer then, admittedly I should have asked for more clarification in the beginning to clarify the problem statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T17:26:18.453",
"Id": "507486",
"Score": "0",
"body": "@Peilonrayz Well, initially the OP's usage of `set` suggested the input *can* have duplicates (they wouldn't do that otherwise), then they edited the question to make it *clear* that it can have duplicates, then they edited it *again* to *rule them out*. So I guess this answer is fine until the next question edit :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:12:21.103",
"Id": "507492",
"Score": "0",
"body": "@superbrain Yeah been quite the roller-coaster ;)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T06:11:38.663",
"Id": "256954",
"ParentId": "256952",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "256954",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T05:33:04.263",
"Id": "256952",
"Score": "-1",
"Tags": [
"python"
],
"Title": "Python get all Unique Pair combinations from list of elements"
}
|
256952
|
<p><a href="https://i.stack.imgur.com/lLoIo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lLoIo.png" alt="enter image description here" /></a></p>
<p>I have already addressed this issue and corrected something .really..now the graph looks different</p>
<p>Please tell me if the program works correctly?You can see the results in the picture above.I will be grateful if you find any mistakes (if there are any, of course..)
/I'm just not sure if the average number of swaps and comps is calculated correctly.I thought that with this sort there should be fewer of them, but the data obtained from the classic Insertion sort is not much different.Maybe that's how it should be, which is why I'm asking./</p>
<p>Thank you all in advance</p>
<pre><code> #include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
FILE *f=fopen("stat18.csv","w");
int n=100;
int i,s;
while (n<=10000){
int st=0;
for (s=0;s<5;s++)
{
int *a;
a=(int *)malloc(n*sizeof(int));
srand(time(NULL));
int k;
for (k=0;k<n;k++)
{
*(a+k)=rand()%50;
}
int j,comps,swaps;
swaps=0;
comps=0;
int rem = a[0];
a[0] = -1;
for( i = 2, j; i < n; i++)
{
int x = a[i];
j = i;
while(j > 1 && a[j-1] > x)
{
comps += 2;
swaps++;
a[j] = a[j-1];
j--;
}
comps += 2;
a[j] = x;
}
a[0] = rem;
for(i = 0; i < n-1; i++)
{
if(a[i] > a[i+1])
{
comps++;
swaps++;
int temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
comps++;
i++;
}
st+=swaps + comps;
free(a);
}
st=st/5;
fprintf(f,"%d ; %d\n", n , st);
if (n<1000){
n+=100;}
else {n+=1000;}
}
fclose(f);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:19:06.087",
"Id": "507462",
"Score": "0",
"body": "Welcome to the Code Review Community. Please be aware that the `Code must be working to the best of knowledge of the author. We aren't supposed to check for correctness. The point of the Code Review Community is to help you improve your coding skills."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:27:42.147",
"Id": "507465",
"Score": "0",
"body": "@pacmaninbw, part of reviewing code is to spot mistakes, isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:31:25.767",
"Id": "507467",
"Score": "0",
"body": "I don't understand what your first paragraph and the chart are for - could you give some explanation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T14:18:58.927",
"Id": "507475",
"Score": "2",
"body": "@TobySpeight I didn't down vote or VTC, the problem I see is the lack of confidence in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T07:20:54.233",
"Id": "507551",
"Score": "0",
"body": "The lack of documentation, lucid comments and structure in the code presented is amplified by non-helpful code layout/indentation. This puts an uncalled for burden on readers of this code just to identify the parts you state interest in. For all I can tell, the first loop, checking `j` to stay \"inside array `a`\", orders `a` initialised to pseudo-random values; the second starts with that pre-ordered array. Array size and *accumulated* (averaged?!) operation totals get printed - what results *do* you expect, and why?"
}
] |
[
{
"body": "<h3>Random seeding</h3>\n<blockquote>\n<pre><code> srand(time(NULL));\n</code></pre>\n</blockquote>\n<p>You call this inside a loop (or two loops actually). But here's the problem, <code>time</code> returns the current number of seconds since an arbitrary historical point of time (1970 January 1st at midnight). Most of the time in your loop, that will be the same number. So you are seeding the number the same. But occasionally you will tick over to the next second.</p>\n<p>You should either create a variable</p>\n<pre><code> time_t invocation_time = time(NULL);\n</code></pre>\n<p>that you can then use</p>\n<pre><code> srand(invocation_time);\n</code></pre>\n<p>Or just move that seeding call outside the loops.</p>\n<p>You would create the variable if you want to always seed with the same number so you get the same "random" sequence each time. You could even set the value to something fixed rather than the current time. I just used the current time because that's what you had been using and I have no particular reason to prefer a different value. By creating the variable, you ensure that you will be seeding with the same value each time and will get the same sequence of numbers. You won't sometimes repeat and sometimes not, as you do now.</p>\n<p>If you want a different sequence each time, then just seed the randomness once per invocation of your program. Repeated calls to <code>srand</code> make things less random rather than more. You would only do this if you wanted to repeat the original results. And frankly, if that's what you wanted, it would probably be easier to just generate the data once and make a copy for each iteration.</p>\n<p>Calling <code>srand</code> once at the beginning of the program is the more typical approach. Calling it multiple times with the same value is an option if you want to make the values repeatable in some way. The way that you are doing it now is neither of those things. It is neither random nor repeatable. Sometimes it repeats and sometimes it is from a pseudorandom sequence. Which is somewhat unpredictable, although there likely would be patterns.</p>\n<p>I think that what you want in this situation is to seed once at the beginning of the program, so you get different values in <code>a</code> each time. But it really depends on exactly what you are trying to test.</p>\n<h3>Readability</h3>\n<blockquote>\n<pre><code> *(a+k)=rand()%50;\n</code></pre>\n</blockquote>\n<p>It would be more common to write this</p>\n<pre><code> a[k] = rand() % 50;\n</code></pre>\n<p>Now we can easily see that you are doing an array dereference. It's also conceivable that this might have performance impact. Because iterating over an array is something that would be done frequently and might be optimized. Whereas pointer addition is rarer and might not be, even if identical in effect. But I still think that the primary reason to write it this way is that it is easier for people reading your code to see what's happening.</p>\n<p>You will also notice that I added whitespace. This also makes it easier to see what things go together and what are different. The compiler will remove this during tokenization, so it has impact on the executable. But for the source code, it makes it easier for the person reading the code to figure out what it is doing.</p>\n<strong>Consistent indentation</strong>\n<p>Similarly, it will be easier to read your code if you always indent inside a block and reduce the indentation when the block ends. This makes it easier to see where your code starts and ends.</p>\n<h3>Counting</h3>\n<p>Now to get to the question that you were actually asking.</p>\n<blockquote>\n<pre><code> for( i = 2, j; i < n; i++)\n {\n int x = a[i];\n j = i;\n while(j > 1 && a[j-1] > x)\n {\n comps += 2;\n swaps++;\n a[j] = a[j-1];\n j--;\n }\n comps += 2;\n a[j] = x;\n }\n</code></pre>\n</blockquote>\n<p>Whether this is counting the comparisons correctly or not depends on exactly what you want to count.</p>\n<p>You are not counting a comparison <code>i < n</code> that you are doing on each iteration of the outer loop. I would usually think of this as something that you should measure.</p>\n<p>You are counting two comparisons on the failure of the inner loop even when only one is done. I.e. when <code>j</code> is equal to 1, you count two comparisons even though short circuiting will only do the <code>j > 1</code> and not the <code>a[j-1] > x</code>. Perhaps you want to count as if short circuiting does not occur.</p>\n<p>In terms of swaps, you aren't counting either</p>\n<blockquote>\n<pre><code> int x = a[i];\n</code></pre>\n</blockquote>\n<p>or</p>\n<blockquote>\n<pre><code> a[j] = x;\n</code></pre>\n</blockquote>\n<p>but you are counting each</p>\n<blockquote>\n<pre><code> a[j] = a[j-1];\n</code></pre>\n</blockquote>\n<p>What's a swap? If it is an assignment, then you should count the first two. If it is an exchange, you should not count the last one, as it is not a swap. You are doing no "swaps" in that loop. You are moving a block of memory.</p>\n<p>Note that what I'd actually call a swap involves three assignments (although it's quite possible that only two of them hit memory, as one can be held in a register). So if your improvement to insertion sort is that you are doing fewer assignments, you are counting the wrong thing. You should be counting assignments, not swaps.</p>\n<blockquote>\n<pre><code> for(i = 0; i < n-1; i++)\n {\n if(a[i] > a[i+1])\n {\n comps++;\n swaps++;\n int temp = a[i];\n a[i] = a[i+1];\n a[i+1] = temp;\n }\n comps++;\n i++;\n }\n</code></pre>\n</blockquote>\n<h3>Comparing</h3>\n<p>I'm having trouble understanding what you consider to be "classic" insertion sort and what your revision is. This would be easier to understand if you used functions. Then you could call each with the same data and compare those results. And for those of us reading your code, we could see what was different between the two functions.</p>\n<p>That would also create more of a separation between your test setup and the sorting. As is, those things are pretty much run together. There isn't a clear demarcation between what is setup and what is sorting. If your sorting were entirely in functions, then it would be clearer. The stuff outside the functions is setup. The stuff inside is sorting.</p>\n<p>It would also be easier if we could see the results from both the classic and revised versions. Perhaps they are showing data as expected. Perhaps not. Without the classic version, it's hard for me to see what you are trying to compare. So it's difficult to critique it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T08:53:30.710",
"Id": "256958",
"ParentId": "256953",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T05:49:42.643",
"Id": "256953",
"Score": "0",
"Tags": [
"c",
"sorting",
"insertion-sort"
],
"Title": "C.Insertion sort with guard"
}
|
256953
|
<p>I started programming in Python after learning the basics of C, which is why I like the user-defined functions to be described after the main() function's job is over. Also, I like to specify the sep and end parameters of every print() function in my programs.</p>
<p>After some research, I came to know that the majority of programmers stick to a characters-per-line limit (80, 120, etc.), while others don't bother with such a limit. I have decided to limit my lines to 80 characters (if there are no in-line comments), or to 120 characters (including in-line comments). Using this style makes codes look very neat and easy to understand, in my opinion.</p>
<pre><code>def main():
get_the_number_of_students_from_user()
if (NUMBER_OF_STUDENTS > 0):
get_the_list_of_names_from_user()
get_the_list_of_marks_obtained_from_user()
print_the_names_after_sorting()
print_the_marks_obtained_after_sorting()
else:
print("The number of students should be greater than 0!\n",
sep = "", end = "")
def get_the_number_of_students_from_user():
global NUMBER_OF_STUDENTS
NUMBER_OF_STUDENTS = int(input("Enter the number of students enrolled in "
"this course: "))
print("\n", sep = "", end = "")
def get_the_list_of_names_from_user():
global LIST_OF_NAMES
LIST_OF_NAMES = []
for x in range(NUMBER_OF_STUDENTS):
print("Enter the name of student no. ", x+1, ": ", sep = "", end = "")
dummyVariable1 = input()
LIST_OF_NAMES.append(dummyVariable1)
print("\n", sep = "", end = "")
def get_the_list_of_marks_obtained_from_user():
global MARKS_OBTAINED
MARKS_OBTAINED = []
for y in LIST_OF_NAMES:
print("Enter the marks obtained by ", y, ": ", sep = "", end = "")
dummyVariable2 = int(input())
MARKS_OBTAINED.append(dummyVariable2)
print("\n", sep = "", end = "")
def print_the_names_after_sorting():
listOfNames = LIST_OF_NAMES # To let LIST_OF_NAMES stay
# constant.
print("The name(s) of the student(s) enrolled in this course is(are) :-\n",
sep = "", end = "")
listOfNames.sort()
for z in range(NUMBER_OF_STUDENTS): # To print listOfNames like
if (z+1 == NUMBER_OF_STUDENTS): # a, b, c, d & e instead of like
print(listOfNames[z], sep = "", end = " ") # ['a', 'b', 'c', 'd', 'e'].
elif (z+2 == NUMBER_OF_STUDENTS):
print(listOfNames[z], sep = "", end = " & ")
else:
print(listOfNames[z], sep = "", end = ", ")
print("(in ascending alphabetical order).\n", sep = "", end = "")
listOfNames.reverse()
for w in range(NUMBER_OF_STUDENTS): # To print listOfNames like
if (w+1 == NUMBER_OF_STUDENTS): # a, b, c, d & e instead of like
print(listOfNames[w], sep = "", end = " ") # ['a', 'b', 'c', 'd', 'e'].
elif (w+2 == NUMBER_OF_STUDENTS):
print(listOfNames[w], sep = "", end = " & ")
else:
print(listOfNames[w], sep = "", end = ", ")
print("(in descending alphabetical order).\n\n", sep = "", end = "")
def print_the_marks_obtained_after_sorting():
marksObtained = MARKS_OBTAINED # To let MARKS_OBTAINED stay
# constant.
print("The marks obtained by the student(s) enrolled in this course ",
"is(are) :-\n", sep = "", end = "")
marksObtained.sort()
for u in range(NUMBER_OF_STUDENTS): # To print marksObtained like
if (u+1 == NUMBER_OF_STUDENTS): # 1, 2, 3, 4 & 5 instead of like
print(marksObtained[u], sep = "", end = " ") # [1, 2, 3, 4, 5].
elif (u+2 == NUMBER_OF_STUDENTS):
print(marksObtained[u], sep = "", end = " & ")
else:
print(marksObtained[u], sep = "", end = ", ")
print("(in ascending order).\n", sep = "", end = "")
marksObtained.reverse()
for v in range(NUMBER_OF_STUDENTS): # To print marksObtained like
if (v+1 == NUMBER_OF_STUDENTS): # 1, 2, 3, 4 & 5 instead of like
print(marksObtained[v], sep = "", end = " ") # [1, 2, 3, 4, 5].
elif (v+2 == NUMBER_OF_STUDENTS):
print(marksObtained[v], sep = "", end = " & ")
else:
print(marksObtained[v], sep = "", end = ", ")
print("(in descending order).\n", sep = "", end = "")
main()
</code></pre>
|
[] |
[
{
"body": "<p>Global variables in a module or script are a bad idea, except for constants\nor under rare circumstances (you don't have one of those).\nInstead pass the necessary data from one function to another.</p>\n<p>It's great that you are using functions. However, you have only taken advantage\nof one of their purposes -- namely, to break a sequence of steps into\nmeaningful groups. Functions can also be used to perform repetitive operations.\nThis is their greatest value: it prevents the need to repeat yourself too often\nin the code.</p>\n<p>I encourage you to abandon the style of placing comments globally\naligned on the far right side. It might have an aesthetic appeal, but it's\nharder to maintain (and read, I would argue). The problems magnify if you ever\nintend to work on projects where you are writing code with other people.\nThe commenting style in the code below is easy to edit, easy to move around\nin a text file, and flexible to use with a variety of types of comments.</p>\n<p>Similarly, give up your style regarding <code>print()</code>. A key issue with software is\nhow easily one can type and read it -- sometimes precisely and often via quick\nvisual scanning. Adding unnecessary stuff hinders those goals.</p>\n<p>Python allows you to iterate directly over collections rather than having to\niterate over indexes. And if you need indexes, use <code>enumerate()</code>.</p>\n<pre><code># Do this in almost all situations.\nfor x in xs:\n ...\n\n# Not this.\nfor i in range(len(xs)):\n x = xs[i]\n ...\n</code></pre>\n<p>Here's a short illustration of some of those ideas:</p>\n<pre><code>def main():\n # No global variables. Pass data back and forth among functions.\n n = get_the_number_of_students_from_user()\n if n > 0:\n names = get_the_list_of_names_from_user(n)\n ...\n print_the_names_after_sorting(names)\n ...\n\ndef print_the_names_after_sorting(names):\n # Be practical: no unnecessary arguments for print() and\n # no unnecessary text in messages to users.\n print('Students enrolled:')\n\n # Use loops, functions, and data to reduce code repetition.\n # Here a tuple of data drives the process.\n for rev in (False, True):\n\n # We use data to control sorting direction.\n #\n # Be practical: join the names on a consistent\n # basis (comma-space) so you don't need special tricks\n # to insert '&' before the last items.\n names_txt = ', '.join(sorted(names, reverse = rev))\n\n # Data is also used to modify the message.\n direction = 'descending' if rev else 'ascending'\n\n # Python has powerful ways to build strings.\n msg = f'{names_txt} (in {direction} alphabetical order).'\n print(msg)\n</code></pre>\n<p>You could take this even farther by noticing that\n<code>print_the_names_after_sorting()</code> and\n<code>print_the_marks_obtained_after_sorting()</code> are almost identical. They differ\nonly in their initial message. You could generalize the function\nand use it for both <code>names</code> and <code>marks</code>:</p>\n<pre><code>def print_items_after_sorting(items, init_msg):\n print(init_msg)\n for rev in (False, True):\n vals_txt = ', '.join(sorted(items, reverse = rev))\n direction = 'Descending' if rev else 'Ascending'\n msg = f'{direction}: {vals_txt}'\n print(msg)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T11:46:23.987",
"Id": "507453",
"Score": "0",
"body": "I agree that using global variables is a bad idea. But, I've used them as constants. Is that bad as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:39:16.737",
"Id": "507494",
"Score": "2",
"body": "@KushagrJaiswal They are not constants: they are set via user input and data conversion (eg `int()`) -- which can fail. Constants are just set directly: `DOZEN = 12`, `DEFAULT_MSG = 'Hello'`, etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:58:13.573",
"Id": "256964",
"ParentId": "256961",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "256964",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T09:36:24.667",
"Id": "256961",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Sort and reverse lists"
}
|
256961
|
<p>The task that I have to perform is to take an array of a specific length, and figure out which sub-list has the closest sum to another given number. Then, I need to print the index of that sub-array.</p>
<p>For anyone that doesn't understand this problem, we add up indexes of the given list and the moment their sum exceeds or is equal to the required amount of power (the second number in the second line of the input), we append it to another list and then we append the index of the number we started to count from and the index of the number we stopped adding up to a third list. Afterwards, we start from the next index. For example, in this input, if we start counting from the list index 0, we will see that if we keep adding up until index 6, the sum will be 28. We keep repeating this, but this time from the index 1, then 2, 3, 4 etc. When we finish, we will realise that the number with the closest sum to 23 are the numbers 7, 8, 9 which range from 6 to 8 and have a sum of 24. So, we print: 6 8.</p>
<p>And if anyone is wondering, if we end up with multiple ranges that meet the criteria, we will choose, according to the problem statement, the nearest to the entrance, the one with the
lowest starting index and the lowest ending index. In our case we have looked out for it, because every time time we append the indexes sum in <code>server_lst</code> we append their indexes too at the same time in <code>index_lst</code>. So, the indexes that are printed are the first ones that have the best sum.</p>
<pre class="lang-py prettyprint-override"><code>num_of_cases = int(input())
for case in range(num_of_cases):
num_of_servers, c_power = map(int, input().split())
server_lst = list(map(int, input().split()))
server_total = []
server_index = []
j = 0
total = 0
k = 0
def servers(lst, k):
global total
global j
for i in range(k, len(lst)):
if total < c_power:
total += lst[i]
j += 1
else:
server_total.append(total)
j += k
server_index.append([k, j-1])
j = 0
total = 0
break
def execute(server_lst, k):
for i in range(len(server_lst)):
k = i
servers(server_lst, k)
min_pow = min(server_total)
winner = server_total.index(min_pow)
mf = server_index[winner]
print('Case #{}:'.format(case+1), *mf )
execute(server_lst, k)
</code></pre>
<p>The problem that I am currently encountering is that, although it works, it takes around 10 minutes to run 10MB inputs. Is there anyway that I can improve it so it runs faster?</p>
<p>Here is a very simple input:</p>
<pre><code>1
10 23
1 2 3 4 5 6 7 8 9 10
</code></pre>
<p>and the output to this is:</p>
<pre><code>Case #1: 6 8
</code></pre>
<p>The constraints are:</p>
<ul>
<li>1 ≤ num_of_cases ≤ 20.</li>
<li>1 ≤ servers ≤ 100 000.</li>
<li>1 ≤ amount of power required(c_power) ≤ 1 000 000 000.</li>
<li>1 ≤ power of every server(every index in server_lst) ≤ 1 000 000, for i = 0 … N − 1</li>
</ul>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T11:12:17.737",
"Id": "507451",
"Score": "2",
"body": "Please link to the page you got the programming challenge from."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T11:16:18.710",
"Id": "507452",
"Score": "0",
"body": "of course. here is the [link](https://challenges.reply.com/tamtamy/challenge/2021-train-win-3/detail) and [here](https://challenges.reply.com/tamtamy/file/download-362689.action) if you want to download the problem statement without going through the link first (it's the cloud server problem)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T22:33:13.350",
"Id": "507523",
"Score": "2",
"body": "A login is required to view the problem statement. Please [edit](https://codereview.stackexchange.com/posts/256963/edit) your question to directly embed the problem, instead of requiring reviewers to jump through hurdles just to understand the task. Important details like the range of inputs: what is the limit of number of servers? What is the range of individual server numerical values? You say you're looking for the closest sum to the target value, but ignore values that exceed it? That isn't the closest, then. Please clarify the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T19:02:42.087",
"Id": "507630",
"Score": "0",
"body": "Just edited the post. I dont think that i haven't explained now everything in detail but still tell me if you need any more clarifications."
}
] |
[
{
"body": "<p>Ah ha! Your example output showed the result <code>6 8</code>. Using 1-based indexes (common in certain programming challenges), <code>server_lst</code> had in that sub-list the values <code>[6, 7, 8]</code> whose sum is <code>21</code>, which is close to the target value of <code>23</code>. I was looking at <code>total < c_power</code>, and thought I was looking at a bug since it would be ignoring a sub-list that totalled exactly <code>23</code> as too large.</p>\n<p>Your "very simple input" is actually confusing, since server powers and indices are not distinct values. Similarly, the sorted order gives no clear indication of whether 0-based or 1-based indices are returned.</p>\n<p>The lack of good comments, an inaccessible problem statement, and confusing code made it hard to tell what the code was intended to do, which made "reviewing the code" a difficult and error-prone task.</p>\n<p>Now that I understand what is going on, let's do both: review the code and optimize it.</p>\n<hr />\n<h1>Code Review</h1>\n<h2>Naming</h2>\n<p>Your functions and variables are a mix of understandable names (<code>num_of_cases</code>, and <code>num_of_servers</code>) and completely opaque names that don't convey any meaning (<code>execute</code>, and <code>mf</code>).</p>\n<h2>Globals</h2>\n<p>Global variables have their place. This isn't it.</p>\n<p>The function <code>servers</code> returns nothing, but calls out <code>total</code> and <code>j</code> as global variables it will be reading and writing. It turns out that it is actually modifying <code>server_total</code> and <code>server_index</code> as well.</p>\n<p>More likely that not, the <code>total</code> and <code>j</code> variables need not have been global, and could simply have been initialized to zero at the start of the function. Except that if the loop inside servers reaches the end of the loop without exceeding <code>c_power</code>, then <code>j</code> and <code>total</code> are not cleared, and the next call to servers will continue where they left off. Was this intentional? Some kind of wrap-around? It doesn't seem likely, since the starting point <code>k</code> on the next call is not the start of the list, so odds are this is actually a bug.</p>\n<h2>Unnecessary parameters and variables</h2>\n<pre class=\"lang-py prettyprint-override\"><code> def execute(server_lst, k):\n for i in range(len(server_lst)):\n k = i\n servers(server_lst, k)\n</code></pre>\n<p>What is the point of <code>k</code>? Both of them.</p>\n<p>The <code>execute</code> function requires a <code>k</code> argument, but whatever value is given will be ignored, overwritten by <code>k = i</code> before it is ever used.</p>\n<p>Inside the for loop, the value of <code>i</code> is stored in <code>k</code>. Then, neither <code>I</code> nor <code>k</code> is modified inside the body of the loop, nor used outside of the loop. <code>i == k</code> remains true as long as both variables are in scope. Which begs the question of: why use <code>k</code> instead of <code>i</code>?</p>\n<h2>Don't define functions inside of loops</h2>\n<p>This one can really result in strange behaviour.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(2):\n try:\n f()\n except NameError:\n print("f() didn't exist")\n\n def f():\n print("Hello world")\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>f() didn't exist\nHello world\n</code></pre>\n<h2>Write for testing</h2>\n<p>If you structured your code as a function which solved the problem, and used a main guard to run the code when submitted to the programming challenge site ...</p>\n<pre class=\"lang-py prettyprint-override\"><code>\ndef find_minimum_power_sublist(server_powers, required_power):\n # ... implementation omitted ...\n return start, end\n\ndef main():\n num_cases = int(input())\n\n for case in range(1, num_cases+1):\n num_servers, required_power = map(int, input().split())\n server_powers = list(map(int, input().split()))\n\n start, end = find_minimum_power_sublist(server_powers, required_power)\n print('Case #{}:'.format(case), start, end)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>... then you could write a test program which runs sample cases, something like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from solution import find_minimum_power_sublist\n\ndef test(test_name, powers, required_power, expected):\n actual = find_minimum_power_sublist(powers, required_power)\n if expected == actual:\n print(test_name, "passed.")\n else:\n print(test_name, "failed! Expected:", expected, actual)\n\ndef run_tests():\n test("1-10", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 23, (6, 8))\n # ... more test cases here ...\n\nif __name__ == '__main__':\n run_tests()\n</code></pre>\n<p>There are test frameworks which make testing easier. Look into <a href=\"https://docs.pytest.org/en/stable/index.html\" rel=\"nofollow noreferrer\">pytest</a>, <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"nofollow noreferrer\">unittest</a>, and <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctest</a>. Those will get you started, but there are many others you can try.</p>\n<h1>Optimization</h1>\n<h2>Partial Sums</h2>\n<p>Whenever you see a problem where you are adding up a sequence of numbers, starting and ending at different points, you should stop and ask if there is a better way.</p>\n<p>In your example, you have the numbers <code>1 2 3 4 5 6 7 8 9 10</code>, and you first start with <code>1</code>, then <code>1+2</code>, then <code>1+2+3</code>, and so on, until you arrive at the total of <code>1+2+3+4+5+6+7</code> or <code>28</code>. Then you reset and start <code>2</code>, <code>2+3</code>, <code>2+3+4</code>, and so on until you reach <code>2+3+4+5+6+7</code> or <code>27</code>. Then you reset and start at <code>3</code> and compute <code>3+4</code>, <code>3+4+5</code>, <code>3+4+5+6</code>, <code>3+4+5+6+7</code> or <code>25</code>. Then you reset and start <code>4</code>, <code>4+5</code>, <code>4+5+6</code>, <code>4+5+6+7</code>, <code>4+5+6+7+8</code> or <code>30</code>.</p>\n<p>How many times have you added 4 and 5 together? Or phrased a better way, how many times have you added 5 to a previous sum that included the four term? Only four times. Not a lot. But this is an example with only 10 servers. You could have one hundred thousand servers and a fairly high power threshold to exceed. You could be repeatedly add a specific server value to a previous total thousands of times, and since you can have thousands of individual server values, you've got an <span class=\"math-container\">\\$O(N^2)\\$</span> algorithm.</p>\n<p>Instead, consider a running total of the values: <code>1 3 6 10 15 21 28 36 45 55</code>. We've added the server value to the previous total exactly once. From that list, you can get the sum of any sublist of servers. For instance the sum of server values from index 6 to index 8 would be the sum of server values up to index 8, <code>45</code>, less the sum of server values up to index 5, <code>21</code>. <code>45-21=24</code>. After processing the list of N servers, doing a total of N additions, you can get the sum of any sublist with at most one subtraction!</p>\n<p>As exciting as this sounds, this hasn't actually improved anything. Using the same steps above, algorithm would still start with <code>1-0</code>, <code>3-0</code>, <code>6-0</code>, <code>10-0</code>, <code>15-0</code>, <code>21-0</code>, <code>28-0</code>, then reset to <code>3-1</code>, <code>6-1</code>, <code>10-1</code>, <code>15-1</code>, <code>21-1</code>, <code>28-1</code>, and then reset to <code>6-3</code>, up to <code>28-3</code>, then reset to <code>10-6</code> up to <code>36-6</code>, and so on. Instead of doing one addition per loop step, we're doing one subtraction per loop step.</p>\n<h2>Why reset to the beginning?</h2>\n<p>After adding the server power values until you exceeded the requirement, why reset the sequence and walk up to the threshold again? Why not simply advance the starting point of the sublist until the threshold is no longer reached?</p>\n<ul>\n<li>We move the end-point forward until the difference is greater than or equal to the requirement: <code>1-0</code>, <code>3-0</code>, <code>6-0</code>, <code>10-0</code>, <code>15-0</code>, <code>21-0</code>, <code>28-0</code>.</li>\n<li>Then we walk the start-point forward until we dip below the requirement: <code>28-1</code>, <code>28-3</code>, <code>28-6</code>.</li>\n<li>Then we return to walking the end-point forward until the requirement is met again: <code>36-6</code>.</li>\n<li>Then we return to walking the start-point forward: <code>36-10</code>, <code>36-15</code>.</li>\n<li>Walk end-point forward: <code>45-15</code>.</li>\n<li>Walk start-point forward: <code>45-21</code>, <code>45-28</code>.</li>\n<li>Walk end-point forward: <code>55-28</code>.</li>\n<li>Walk start-point forward: <code>55-36</code></li>\n<li>Walk end-point forward: <strong>end-of-list</strong></li>\n</ul>\n<p>More concisely,</p>\n<ul>\n<li>While the total power requirement is not satisfied,\n<ul>\n<li>walk the end-point forward</li>\n</ul>\n</li>\n<li>While the total power requirement is satisfied,\n<ul>\n<li>If total power is smaller than the smallest found so far:\n<ul>\n<li>update the smallest found so far, and memorize the start and end points.</li>\n</ul>\n</li>\n<li>walk the start-point forward</li>\n</ul>\n</li>\n</ul>\n<p>Note we're only walking the start-point and end-point forward through the list once. This is <span class=\"math-container\">\\$O(N)\\$</span>.</p>\n<h2>Running totals</h2>\n<p>You don't have to precompute and store the running totals. You could just keep two running totals as you move the starting point and ending point forward.</p>\n<p>You don't even need two totals. Just add or subtract from a single running total. Or consider the total a <code>surplus</code>, and initialize it with the negative of the power requirement. When <code>surplus >= 0</code>, the power requirement is satisfied; when <code>surplus < 0</code>, the power requirement is not satisfied.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T18:29:21.117",
"Id": "257076",
"ParentId": "256963",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T10:51:09.343",
"Id": "256963",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "Find sub-list index with the closest to a given number sum"
}
|
256963
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.