body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have put together this f# code in an attempt to solve the following problem</p>
<ul>
<li>Given a mapping operation that may not be able to return a value</li>
<li>Cease mapping over the remaining items of a sequence if the mapping operation fails</li>
<li>Append the error to items already mapped and return early</li>
</ul>
<p>This cannot be achieved with the inbuilt <code>Seq.map</code> and I could not locate any other existing implementations</p>
<pre><code>type OptionFunction<'a, 'b> = 'a -> 'b option
type ResultFunction<'a, 'b, 'c> = 'a -> Result<'b, 'c>
type MaybeProjection<'a,'b,'c> =
| OptionProjection of OptionFunction<'a,'b>
| ResultProjection of ResultFunction<'a,'b,'c>
type OptionResultBuilder<'e>() =
member _.Return(x) = Result.Ok x
member _.Bind(m,f) =
let r = match m with
| Some a -> Ok a
| None -> Error Unchecked.defaultof<'e>
Result.bind f r
member _.Bind(m,f) = Result.bind f m
let orb = OptionResultBuilder()
let mapTillFail mapper s =
let rec inner sq =
seq {
let mapped = orb {
let! head = Seq.tryHead sq
match mapper with
| OptionProjection a ->
let! m = a head
return m
| ResultProjection a ->
let! m = a head
return m
}
match mapped with
| Error _ as err-> yield err
| Ok _ ->
yield mapped
yield! sq |> Seq.skip 1 |> inner
}
inner s
//code to test it, not part of the implementation
let r = Seq.empty
let s = seq{1..10}
let op = OptionProjection (fun x -> if x < 5 then Some x else None)
let rp = ResultProjection (fun x -> if x < 5 then Ok x else Error "if >= 5")
r|> mapTillFail op
s|> mapTillFail op
r|> mapTillFail rp
s|> mapTillFail rp
</code></pre>
<p>The inbuilt <code>Option</code> and <code>Result</code> types are a natural fit, and I wanted to be able to use a mapping function that returned either of these types.</p>
<p>Despite several attempts to refactor the duplicate statements inside the <code>match mapper with</code>, I just could not not work out how to satisfy the compiler. Every attempt results in the compiler complaining that it can't find a suitable overload for Bind. Suggestions ?</p>
<p>Beyond that I'm largely happy with it for my purposes. But I welcome any other improvements, or comments on issues like performance (at this stage I've not stress tested it).</p>
|
[] |
[
{
"body": "<p>I can't say, I have the full understanding of computation expressions, so here are some comments that may go in another direction than your purpose with the post:</p>\n<blockquote>\n<p><code>sq |> Seq.skip 1</code></p>\n</blockquote>\n<p>can be replaced with</p>\n<pre><code>sq |> Seq.tail\n</code></pre>\n<hr />\n<p>I'm not sure, I like that the function returns <code>[ Error null ]</code> for an empty sequence, but that again may be needed in the context? I would expect an empty sequence to return - an empty sequence.</p>\n<hr />\n<p>I don't understand the <code>Projection</code> layer, but that may be dictated by the original context.</p>\n<p>You could define the type at the function level:</p>\n<pre><code>type MaybeFunction<'a, 'b, 'c> = \n | OptionFunction of ('a -> 'b option)\n | ResultFunction of ('a -> Result<'b, 'c>)\n</code></pre>\n<p>and then create the functions as:</p>\n<pre><code>let mbopFunction = OptionFunction (fun x -> if x < 5 then Some x else None)\nlet mbrsFunction = ResultFunction (fun x -> if x < 5 then Ok x else Error "if >= 5")\n</code></pre>\n<p>Your main function will then looks like:</p>\n<pre><code>let mapTillFail mapper s = \n let rec inner sq =\n seq {\n let mapped = orb {\n let! head = Seq.tryHead sq\n match mapper with\n | OptionFunction a -> \n let! m = a head\n return m\n | ResultFunction a -> \n let! m = a head\n return m\n } \n \n match mapped with\n | Error _ as err-> yield err\n | Ok _ -> \n yield mapped\n yield! sq |> Seq.tail |> inner\n }\n inner s\n</code></pre>\n<p>which tells that your monad can handle that level without modifications.</p>\n<p>Maybe it would be fair to call these function <code>Projections</code> as well as that is what they do?</p>\n<hr />\n<p>That said, you can go without the computation expression:</p>\n<pre><code>let mapTillFail projection data = \n\n let test x =\n let result = \n match projection with\n | OptionProjection a -> \n match a x with\n | Some d -> Ok d\n | None -> Error Unchecked.defaultof<'c>\n | ResultProjection a -> a x\n result\n\n let rec inner lst =\n seq {\n match lst |> Seq.isEmpty with\n | true -> yield Error Unchecked.defaultof<'c>\n | _ ->\n match test (lst |> Seq.head) with\n | Error e -> yield Error e\n | Ok o ->\n yield Ok o\n yield! inner (lst |> Seq.tail)\n }\n\n inner data\n</code></pre>\n<hr />\n<p>Another alternative is to extent the <code>MaybeProjection</code> or <code>MaybeFunction</code> with a member called calculate:</p>\n<pre><code>type MaybeFunction<'a, 'b, 'c> = \n | OptionFunction of ('a -> 'b option)\n | ResultFunction of ('a -> Result<'b, 'c>)\nwith\nmember this.Calculate (a) =\n match this with\n | OptionFunction f -> \n match f a with\n | Some d -> Ok d\n | None -> Error Unchecked.defaultof<'c>\n | ResultFunction f -> f a\n</code></pre>\n<p>used as:</p>\n<pre><code>module Seq = \n let mapTillFail (func: MaybeFunction<'a, 'b, 'c>) data = \n \n let rec inner lst =\n seq {\n match lst |> Seq.isEmpty with\n | true -> ()\n | _ ->\n match func.Calculate (lst |> Seq.head) with\n | Error e -> yield Error e\n | Ok o ->\n yield Ok o\n yield! inner (lst |> Seq.tail)\n }\n\n inner data\n</code></pre>\n<p>Here I've made an extension to <code>Seq</code> so you can call it like any other <code>Seq</code> functions:</p>\n<pre><code>printfn "%A" ((r |> Seq.mapTillFail mbopFunction) |> Seq.toList)\nprintfn "%A" ((s |> Seq.mapTillFail mbopFunction) |> Seq.toList)\nprintfn "%A" ((r |> Seq.mapTillFail mbrsFunction) |> Seq.toList)\nprintfn "%A" ((s |> Seq.mapTillFail mbrsFunction) |> Seq.toList)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T23:06:08.423",
"Id": "479600",
"Score": "0",
"body": "Wow you review of my code is fantastic, I'm really grateful for your efforts. I've learnt quite a few things already. You were right about returning an empty list that is what should be expected, did not think that through from my end. Impressed that that it could be done without the computation expression too. I had a hammer and all I was seeing was nails...did not think outside the box. I like Calculate member approach very clever, I would never have thought of that. I've updated my version to yours and added it to my lib. Again a huge thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T17:01:34.363",
"Id": "479890",
"Score": "0",
"body": "@OrdinaryOrange: My pleasure - I'm glad it's useful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T10:54:23.290",
"Id": "244256",
"ParentId": "244085",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T01:33:58.057",
"Id": "244085",
"Score": "4",
"Tags": [
"f#"
],
"Title": "Return early with Error from Sequence mapping"
}
|
244085
|
<p>I have the code below, which works successfully, and is used to parse, clean log files (very large in size) and output into smaller sized files. Output filename is the first 2 characters of each line. However, if there is a special character in these 2 characters, then it needs to be replaced with a '_'. This will help ensure there is no illegal character in the filename.</p>
<p>This would take about 12-14 mins to process 1 GB worth of logs (on my laptop). Can this be made faster?</p>
<p>For example, would it help to run this parallel? I am aware I could do <code>}' "$FILE" &</code>. However, I tested and that does not help much. Perhaps AWK itself could run in parallel (the equivalent of <code>print $0 >> Fpath & </code>)?</p>
<p><strong>Sample log file</strong></p>
<pre><code>email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com datahere2
email5@foo.com;dtat'ah'ere2
wrongemailfoo.com
nonascii@row.com;data.is.junk-Œœ
email3@foo.com:datahere2
</code></pre>
<p><strong>Expected Output</strong></p>
<pre><code># cat em
email1@foo.com:datahere2
email2@foo.com:datahere2
email3@foo.com:datahere2
email5@foo.com:dtat'ah'ere2
email3@foo.com:datahere2
# cat errorfile
wrongemailfoo.com
nonascii@row.com;data.is.junk-Œœ
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>#/bin/sh
pushd "_test2" > /dev/null
for FILE in *
do
awk '
BEGIN {
FS=":"
}
{
gsub(/^[ \t"'\'']+|[ \t"'\'']+$/, "")
$0=gensub("[,|;: \t]+",":",1,$0)
if (NF>1 && $1 ~ /^[[:alnum:]_.+-]+@[[:alnum:]_.-]+\.[[:alnum:]]+$/ && $0 ~ /^[\x00-\x7F]*$/)
{
Fpath=tolower(substr($1,1,2))
Fpath=gensub("[^[:alnum:]]","_","g",Fpath)
print $0 >> Fpath
}
else
print $0 >> "errorfile"
}' "$FILE"
done
popd > /dev/null
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T06:07:29.083",
"Id": "480887",
"Score": "0",
"body": "To the reviewers: I think this question has been edited into shape good enough that it's within the scope of the site. Please leave a comment if you disagree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T13:56:42.770",
"Id": "480925",
"Score": "0",
"body": "Mast: i disagree. your edits wont make the code run any faster. in future pls post your answer separately, and not edit the original ques"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T11:45:26.777",
"Id": "481107",
"Score": "0",
"body": "@rogerwhite You may find this blog post helpful: http://aosabook.org/en/posa/working-with-big-data-in-bioinformatics.html .."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-25T14:17:39.553",
"Id": "483322",
"Score": "0",
"body": "@akki - sorry for the slow revert. all good, but i need help with the code !!"
}
] |
[
{
"body": "<p>Perhaps switching the outputfile for each line can be avoided by sorting the inputfiles first or with some changes in your script:</p>\n<pre><code># Store the 2-letter filenames\noutfile[Fpath];\n# Store the highest index for given outputfile\ni[Fpath]++;\n# Store current line in output array for that file\na[Fpath][i[Fpath]]=$0\n# And in the END block print for array per output file\n for (out in outfile) {\n for (j=1;j<=i[out]; j++) {\n print a[out][j] >> out;\n }\n }\n</code></pre>\n<p>This results in</p>\n<pre><code>awk '\n BEGIN {\n FS=":"\n }\n {\n gsub(/^[ \\t"'\\'']+|[ \\t"'\\'']+$/, "")\n $0=gensub("[,|;: \\t]+",":",1,$0)\n if (NF>1 && $1 ~ /^[[:alnum:]_.+-]+@[[:alnum:]_.-]+\\.[[:alnum:]]+$/ && $0 ~ /^[\\x00-\\x7F]*$/)\n {\n Fpath=tolower(substr($1,1,2))\n Fpath=gensub("[^[:alnum:]]","_","g",Fpath);\n outfile[Fpath];\n i[Fpath]++;\n a[Fpath][i[Fpath]]=$0\n }\n else\n print $0 >> "errorfile"\n }\n END {\n for (out in outfile) {\n for (j=1;j<=i[out]; j++) {\n print a[out][j] >> out;\n }\n }\n } ' "$FILE"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T18:13:14.470",
"Id": "259700",
"ParentId": "244088",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T02:48:00.487",
"Id": "244088",
"Score": "1",
"Tags": [
"performance",
"bash",
"awk"
],
"Title": "Parse and clean large log files"
}
|
244088
|
<p>Below is a constexpr circular queue whose size is fixed. From what I tested the code seems to work exactly as expected of a queue. One advantage is how there's no dynamic allocations, so ignoring the hopefully low chance that there are errors in the logic, are there any suggestions to improve this code's performance?</p>
<p>Code taken from: <a href="https://github.com/SteveZhang1999-SZ/CircularQueue/blob/master/circularQueue.hpp" rel="nofollow noreferrer">https://github.com/SteveZhang1999-SZ/CircularQueue/blob/master/circularQueue.hpp</a></p>
<pre><code>#ifndef CIRCULARQUEUEHPP
#define CIRCULARQUEUEHPP
#include <cstddef>
#include <type_traits>
template<class T ,std::size_t N /*Max capacity*/,
typename Idxtype = std::size_t /*Integral type to store indices. May change,
like to uint_least16_t, to lower space usage*/,
typename = typename std::enable_if<std::is_integral<Idxtype>::value>::type>
class circularQueue{
union myUnion{
bool forConstexprCtor;
T value;
constexpr myUnion() : forConstexprCtor{true} {}
template<class PossibleUnion,typename = typename std::enable_if<std::is_same<PossibleUnion, myUnion>::value >::type>
constexpr myUnion(PossibleUnion&& other) : value{other.value} {}
template<typename... Args,typename = typename std::enable_if<std::is_constructible_v<T,Args>...>::type>
constexpr myUnion(Args&&... args) : value(std::forward<Args>(args)...) {}
template<typename AnotherUnion>
constexpr void operator=(const AnotherUnion&& other){
value = other.value;
}
};
struct myStruct{
myUnion theArray[N];
template<typename... t>
constexpr myStruct(t&&... theList) : theArray{(theList)...} {}
} mS;
//Head == idx of element at the front. Tail == idx of last element + 1. theSize == queue's size
Idxtype head, tail, theSize;
public:
constexpr circularQueue() : head{0}, tail{0}, theSize{0} {}
explicit constexpr circularQueue(const circularQueue<T,N>& other) : mS{other.mS}, head{other.head},
tail{other.tail}, theSize{other.theSize} {}
explicit constexpr circularQueue(circularQueue<T,N>& other) :
circularQueue{const_cast<circularQueue<T,N> const&>(other)} {}
template<typename... Args>
explicit constexpr circularQueue(Args&&... theList) : mS{(theList)...}, head{0},
tail{sizeof...(theList)}, theSize{sizeof...(theList)}{}
constexpr bool push(const T theObj){
if(theSize == N){
return false;//queue is full
}
mS.theArray[(tail == N ? (tail = 0)++ : tail++)] = myUnion(std::move(theObj));
return ++theSize; //++theSize always > 0. Return true
}
template<typename ...Args>
constexpr bool emplace(Args&&... args){
if(theSize == N){
return false;//queue is full
}
mS.theArray[(tail == N ? (tail = 0)++ : tail++)] = myUnion(std::forward<Args>(args)...);
return ++theSize;
}
constexpr const T& front() const noexcept{
return mS.theArray[head].value;
}
constexpr bool pop() noexcept{
if(!theSize) return false; //If it's empty, pop fails
(head == N ? head = 0 : head++);
return theSize--;//Even if theSize == 1, theSize-- will > 0 so this returns true.
}
constexpr bool empty() const noexcept{
return !theSize;
}
constexpr Idxtype size() const noexcept{
return theSize;
}
constexpr std::size_t maxCapacity() const noexcept{
return N;
}
//Assignment
constexpr circularQueue& operator=(const circularQueue<T,N>& other){
std::size_t first{head = other.head};
tail = other.tail;
theSize = other.theSize;
if(other.tail < other.head){ //Only need to copy elements from other.head to other.tail
for(; first < N; ++first){
mS.theArray[first] = other.mS.theArray[first];
}
for(first = 0; first < tail; ++first){
mS.theArray[first] = other.mS.theArray[first];
}
}
else{
for(; first < other.tail; ++first) mS.theArray[first] = other.mS.theArray[first];
}
return *this;
}
constexpr circularQueue& operator=(const circularQueue<T,N>&& other){
std::size_t first{head = std::move(other.head)};
tail = std::move(other.tail);
theSize = std::move(other.theSize);
if(other.tail < other.head){ //Only need to copy elements from other.head to other.tail
for(; first < N; ++first){
mS.theArray[first] = std::move(other.mS.theArray[first]);
}
for(first = 0; first < tail; ++first){
mS.theArray[first] = std::move(other.mS.theArray[first]);
}
}
else{
for(; first < other.tail; ++first) mS.theArray[first] = std::move(other.mS.theArray[first]);
}
return *this;
}
};
#endif //CIRCULARQUEUEHPP
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T21:45:04.647",
"Id": "480633",
"Score": "0",
"body": "Follow up here: https://codereview.stackexchange.com/questions/244813/constexpr-circular-queue-follow-up-1"
}
] |
[
{
"body": "<p>I’m afraid you have some very serious, game-breaking bugs in this class, mostly to do with your use of a union. But I’ll do the review from top to bottom to keep everything in order.</p>\n<p>Before I begin: In my opinion, the biggest problem with this code—the problem that would first make me reject it out of hand before even bothering to try reading it—is the near-complete lack of useful comments. There are one or two comments that are useful, but there are many more things in the code that just make no sense at all at first glance, and with no comments to explain your thinking, I have no idea whether I’m looking at the most ingenious piece of software engineering ever committed, or an incoherent mess. Why are you using a union? Why is the array inside a <code>struct</code>? Why are some special member functions defined while others are not? All mysteries. Some I can (somewhat) guess at. Others are just ciphers.</p>\n<p>One major thing that isn’t explained anywhere (that comes up as an issue over and over in the review) is whether this queue is intended to be used with non-trivial types (like <code>std::string</code>). That makes a huge difference in the complexity of the problem. If I saw a comment explaining that only trivial types should be used (or even better, a <code>static_assert</code>), then fine. But without that, I have to assume the intention is to use non-trivial types. And that’s going to make things a lot more complicated, and the review a lot more brutal.</p>\n<pre><code>template<class T ,std::size_t N /*Max capacity*/, \ntypename Idxtype = std::size_t /*Integral type to store indices. May change,\nlike to uint_least16_t, to lower space usage*/,\ntypename = typename std::enable_if<std::is_integral<Idxtype>::value>::type>\n</code></pre>\n<p>I’m not sure <code>enable_if</code> is what you want to use here.</p>\n<p><code>enable_if</code>/SFINAE is the mechanism to use when you want to disable particular template instantiations <em>while leaving other options available</em>. In other words, if your intention was that the class you’ve written will only work for integral indexes… <em>but there is another class that will work for non-integral indexes</em>… then SFINAE would be the way go.</p>\n<p>But I don’t think that’s your intention. I think you just want to ban non-integral indexes, and that’s that. For that, it’s simpler just to use <code>static_assert</code>:</p>\n<pre><code>template<class T ,std::size_t N /*Max capacity*/, \ntypename Idxtype = std::size_t /*Integral type to store indices. May change,\nlike to uint_least16_t, to lower space usage*/>\nclass circularQueue\n{\n static_assert(std::is_integral_v<Idxtype>);\n</code></pre>\n<p>(Also, you’re using <code>enable_if</code> wrong. What you want is to have an undefined (or <code>static_assert</code>-ed) primary template with the selection parameter defaulted, and then use <code>enable_if</code> in the real template, like so:</p>\n<pre><code>// Primary template is undefined so it will trigger a compile error.\n// You could also define it with a static_assert to get a clearer\n// error message.\ntemplate <\n class T,\n std::size_t N,\n typename Idxtype = std::size_t,\n typename = void>\nclass circularQueue;\n\ntemplate <\n class T,\n std::size_t N,\n typename Idxtype>\nclass circularQueue<T, N, Idxtype, typename std::enable_if<std::is_integral<Idxtype>::value>::type>\n{\n // ...\n</code></pre>\n<p>The way you’re using <code>enable_if</code>, I could use a non-integral type as the index by doing this:</p>\n<pre><code>// A std::string index!\ncircularQueue<T, std::size_t, std::string, void>\n</code></pre>\n<p>The two-step dance shown above—with the empty primary template—is how you prevent such abuses.)</p>\n<pre><code>union myUnion{\n bool forConstexprCtor;\n T value;\n constexpr myUnion() : forConstexprCtor{true} {}\n\n template<class PossibleUnion,typename = typename std::enable_if<std::is_same<PossibleUnion, myUnion>::value >::type>\n constexpr myUnion(PossibleUnion&& other) : value{other.value} {}\n\n template<typename... Args,typename = typename std::enable_if<std::is_constructible_v<T,Args>...>::type> \n constexpr myUnion(Args&&... args) : value(std::forward<Args>(args)...) {}\n\n template<typename AnotherUnion>\n constexpr void operator=(const AnotherUnion&& other){\n value = other.value;\n }\n};\n</code></pre>\n<p>This is a clever way to have correctly sized and aligned storage for an uninitialized <code>T</code> while still being <code>constexpr</code>, but there are lot of problems… so many, in fact, that I don’t know if you could reasonably fix them in C++17.</p>\n<p>First, you shouldn’t use <code>bool</code> for the “alternate” object. <code>bool</code> is not necessarily 1 byte, nor is its alignment necessarily 1. It’s entirely possible and legal for <code>bool</code> to be 4 bytes (and that actually was the case in older versions of Visual C++). You could end up with a situation where you’ve created a circular buffer for 10 <code>char</code>s, and it turns out to be 40 bytes in size.</p>\n<p>You can use any flavour of <code>char</code> (<code>signed</code>, <code>unsigned</code>, or not), or <code>std::byte</code>. But a better solution is to use an empty class. Why? Because:</p>\n<pre><code> bool forConstexprCtor; // or use char\n constexpr myUnion() : forConstexprCtor{true /* or '\\0' for char */} {}\n</code></pre>\n<p>is not a no-op default construction, because it has to set <code>forConstexprCtor</code> to <code>true</code> (or zero). But this is a no-op:</p>\n<pre><code> // struct empty_t {};\n empty_t forConstexprCtor;\n constexpr myUnion() : forConstexprCtor{} {}\n</code></pre>\n<p>If you made a circular buffer with 100 elements, the constructor has to initializer 100 <code>bool</code>s to <code>true</code>. With an empty type, it has to theoretically initialize those 100 objects… but since initialization is zero-cost, that means nothing actually needs to be done in practice.</p>\n<pre><code>template<class PossibleUnion,typename = typename std::enable_if<std::is_same<PossibleUnion, myUnion>::value >::type>\nconstexpr myUnion(PossibleUnion&& other) : value{other.value} {}\n</code></pre>\n<p>Okay, so what I think you’re trying to do here is write both your move and copy constructors in a single function. That’s… not a great idea on any given day. But it’s especially bad here because of the surrounding context.</p>\n<p>Let’s start with asking why you even <em>need</em> to define the move and copy constructors. I can think of two reasons:</p>\n<ol>\n<li>You want to use non-trivial <code>T</code>s. A non-trivial <code>T</code> will probably cause the move and copy constructors to be deleted.</li>\n<li>The following constructor template “swallows” the move/copy operations, so you need to reclaim them.</li>\n</ol>\n<p>So let’s assume you need to rewrite the move and copy constructors. What’s wrong with doing it this way? Well, a lot of things.</p>\n<p>To start with, the code above turns the copy and move constructors into two copy constructors. You lose move ops: <code>myUnion</code>’s move constructor invokes <code>value</code>’s copy constructor… not its move constructor. You can “fix” this problem by using <code>std::forward()</code>, I suppose.</p>\n<p>But there’s other problems. Move ops should always be <code>noexcept</code> whenever possible. And most types are <code>noexcept</code> moveable. But if we put one of those types in this union, then it won’t be anymore. You could probably fix this with type traits.</p>\n<p>But you also lose triviality. This, too, might be able to be “fixed”… but certainly not easily.</p>\n<p>My advice is to forget trying to be clever. You’re only shooting yourself in the foot, not to mention making it more difficult for others to understand and maintain the class. You want copy and move constructors? Write copy and move constructors. Individually, as the good Bjarne intended.</p>\n<p>But that brings us to the biggest problem here: you impement the copy/move by assuming that <code>value</code> is the active object in the union. Why would you assume that? It certainly won’t be true for a default-constructed circular queue:</p>\n<pre><code>auto cq1 = circularQueue<std::string, 32>{};\n// cq1 internally has an array of 32 myUnion objects, all with active\n// object set to "forConstexprCtor"... not "value".\n\nauto cq2 = cq1;\n// This calls the copy constructor of myUnion 32 times, which copies 32\n// nonexistent "value" objects, triggering UB (and, likely, a\n// spectacular crash the first time you try to do anything with any of\n// those strings).\n</code></pre>\n<p>You can’t fix this within the union. You need an external discriminator of some sort, to keep track of which <code>myUnion</code> objects have <code>forConstexprCtor</code> active, and which have <code>value</code> active. And then you need to write the copy constructor <em>in <code>circularQueue</code></em>… <em>not</em> <code>myUnion</code>… to properly move/copy each <code>myUnion</code> object according to its active member.</p>\n<p>What a complicated mess, eh?</p>\n<pre><code>template<typename... Args,typename = typename std::enable_if<std::is_constructible_v<T,Args>...>::type> \nconstexpr myUnion(Args&&... args) : value(std::forward<Args>(args)...) {}\n</code></pre>\n<p>This seems like a simple and obvious implementation, but… consider what happens if <code>T</code> is a <code>vector<int></code>, and you do this:</p>\n<pre><code>auto v1 = std::vector<int>{4, 4};\nstd::cout << v1.size(); // prints 2\n\nauto v2 = circularQueue<std::vector<int>, N>::myUnion{4, 4};\nstd::cout << v2.value.size(); // what do you think this prints?\n</code></pre>\n<p>The problem here is that you don’t support initializer lists with <code>myUnion</code>. Perhaps that’s not a problem. Perhaps you’re okay with preventing in-place construction with initializer lists. But it’s something you should think about.</p>\n<p>Aside from that, I think implementing a direct-construction constructor for <code>value</code> like this is a terrible idea. Of the many headaches it introduces, the fact that it “swallows” the copy and move constructors is just the tip of the iceberg.</p>\n<p>If you really want a function like this (and, I can’t imagine why you think you need it), you really should use a tagged constructor instead:</p>\n<pre><code>struct value_construct_tag_t {} value_construct_tag;\n\ntemplate<typename... Args,typename = typename std::enable_if<std::is_constructible_v<T,Args>...>::type> \nconstexpr myUnion(value_construct_tag_t, Args&&... args) : value(std::forward<Args>(args)...) {}\n\n// used as:\nmyUnion(value_construct_tag, args...);\n</code></pre>\n<p>Next up is the copy/move assignment dual-purpose function, which basically has all the same problems as the copy/move constructor chimera.</p>\n<p>Okay, so <code>myUnion</code> is just <em>riddled</em> with problems. In my opinion, all of them are due to you trying to be too clever, and trying to make <code>myUnion</code> a “perfect”, self-contained, self-aware type. My advice? Throw it all out. <code>myUnion</code> should be nothing more than a union of <code>T</code> and some dummy, empty type (along with dummy operations if necessary to make it work with non-trivial <code>T</code>s). Don’t try to make <code>myUnion</code> a container in its own right. It’s nothing more than an internal storage type; an implementation detail. All the <em>real</em> work should be done by <code>circularQueue</code>.</p>\n<pre><code>struct myStruct{\n myUnion theArray[N];\n template<typename... t>\n constexpr myStruct(t&&... theList) : theArray{(theList)...} {}\n} mS;\n</code></pre>\n<p>I honestly don’t see the purpose of this internal <code>struct</code>. Am I missing something? It looks it all you need it for is that constructor, but that constructor is trivial to write in place where you need it (and you only need it in one place).</p>\n<pre><code>Idxtype head, tail, theSize;\n</code></pre>\n<p>Declaring all your variables on one line like this is terrible practice in general. You should never do it.</p>\n<p>And in this case, it’s actually self-defeating. If you gave <code>myUnion</code> a default constructor that activated <code>forConstexprCtor</code>, and defined your member variables like this:</p>\n<pre><code>myUnion theArray[N] = {};\nIdxtype head = {};\nIdxtype tail = {};\nIdxtype theSize = {};\n</code></pre>\n<p>then your default constructor could be defaulted:</p>\n<pre><code>constexpr circularQueue() noexcept = default;\n</code></pre>\n<p>Next up is the copy constructor, and this (along with the move constructor, which you don’t have but should) is where the rubber really hits the road.</p>\n<p>When you are coping a <code>circularQueue</code>, none, some, or all of the elements in <code>other</code> will be present. You need to correctly handle all cases. You need to do <code>this->theArray[i].value = other.theArray[i].value;</code> for all elements that are present, and <code>this->theArray[i].forConstexprCtor = {};</code> for all elements that are not.</p>\n<p>Figuring out how to do that correctly is the real trick of writing this type.</p>\n<p>As an aside… why is your copy constructor <code>explicit</code>? What do you think that is accomplishing?</p>\n<p>And I am completely baffled as to why you have a constructor that copies from a non-<code>const</code> <code>circularQueue</code>. Is this because the following template constructor swallowed the copy/move ops? If so, there is an easier fix.</p>\n<pre><code>template<typename... Args>\nexplicit constexpr circularQueue(Args&&... theList) : mS{(theList)...}, head{0},\ntail{sizeof...(theList)}, theSize{sizeof...(theList)}{}\n</code></pre>\n<p>I’m guessing the intention here is to be able to write code like:</p>\n<pre><code>auto c = circularQueue<int, 4>{1, 2, 3, 4};\n// c is a queue with 1,2,3,4 in it.\n</code></pre>\n<p>That’s cool, but as you may or may not have noticed, this function swallows your default constructor, and your copy and move constructors. I’m blindly guessing that’s why you implemented a non-<code>const</code> lvalue reference copy constructor. If that’s the case, there’s a better way.</p>\n<p>First, note that it doesn’t make sense to have zero args. That would be the default constructor. So you only need to consider cases with one or more args. So you can do this:</p>\n<pre><code>template <typename T, typename... Args>\ncircularQueue(T&& t, Args&&... theList)\n</code></pre>\n<p>Now the default constructor is safe. (It was anyway, but bear with me.)</p>\n<p>Next up you want to rescue the copy and move constructors. That’s easy: that’s the case where <code>T&&</code> is <code>circularQueue</code> with or without <code>const</code> and either an lvalue or rvalue reference, and <code>args</code> is empty. No problem (using concepts… to do this with <code>enable_if</code>, you’re on your own—perhaps use a non-type template parameter?):</p>\n<pre><code>template <typename T, typename... Args>\nrequires requires(sizeof...(Args) > 0 or not std::is_same_v<circularQueue, std::remove_cv_ref_t<T>>)\ncircularQueue(T&& t, Args&&... theList)\n</code></pre>\n<p>Now this constructor will not step on the toes of either the default constructor, or the copy or move constructor.</p>\n<pre><code>constexpr bool push(const T theObj)\n</code></pre>\n<p>I’m not a fan of interfaces that let you just ignore errors. If you fail you push an object to the queue, that’s not just an “oh, well, doesn’t matter” kind of thing. That’s a <em>critical</em> error! You’ve lost data. You really want to know when that happens.</p>\n<p>At the very <em>least</em>, you should mark the return value here as <code>[[nodiscard]]</code>. But honestly, this seems like something that warrants an exception.</p>\n<p>Also… why is <code>theObj</code> <code>const</code>? There doesn’t seem to be any point. Worse, making it <code>const</code> means it’s impossible to move it. So this line:</p>\n<pre><code>mS.theArray[(tail == N ? (tail = 0)++ : tail++)] = myUnion(std::move(theObj));\n</code></pre>\n<p>doesn’t do what you apparently think it does. The <code>std::move()</code> in there does absolutely nothing.</p>\n<p>(And I’m not even talking about the gastly ternary op going on in there. That indexing operation is one of the most important parts of your whole class! It’s what makes your circular queue circular! It even gets repeated in both <code>push()</code> and <code>emplace()</code>! It shouldn’t be buried in a mess of operations like that! That should be its own function.)</p>\n<pre><code>constexpr const T& front() const noexcept\n</code></pre>\n<p>This shouldn’t be a <code>noexcept</code> function, because <code>noexcept</code> means a function cannot fail. But this function <em>can</em> fail; it can fail if the queue is empty. You don’t <em>necessarily</em> need to throw an exception here (or you could throw one in debug mode, and just do UB in release mode). But you do need to not give the impression the function can’t fail.</p>\n<pre><code>constexpr std::size_t maxCapacity() const noexcept\n</code></pre>\n<p>Unless you have a reason not to, you should follow the conventions of the standard library. In the standard library, this function would be called <code>capacity()</code>. (Plus “max capacity” is redundant. A thing’s “capacity” is the maximum it can hold, by definition.)</p>\n<pre><code>constexpr circularQueue& operator=(const circularQueue<T,N>& other)\n</code></pre>\n<p>The copy/move assignment operations have all the complexity of the copy/move constructors… and then some, because you <em>also</em> have to handle the existing elements in <code>this</code>, all while giving the strong exception guarantee (if possible).</p>\n<p>As it stands, you have the same serious bugs in the assignment ops as in the constructors, plus more. The comment in the function says “[o]nly need to copy elements from <code>other.head</code> to <code>other.tail</code>”… except that’s wrong. Yes, you do only need to copy the active elements and not the inactive ones… but you also need to <em>de</em>activate the inactive ones in <code>this</code>.</p>\n<pre><code>constexpr circularQueue& operator=(const circularQueue<T,N>&& other)\n</code></pre>\n<p>Why is this taking a <code>const</code> rvalue reference? That breaks moving; it’s no long a move assignment, and all the <code>std::move()</code>s in there do nothing.</p>\n<p>Finally, this class doesn’t have a destructor, but it needs one, because you need to manually call the <code>T</code> destructors for active elements, and the dummy destructors for the inactive ones.</p>\n<p>Overall, I think the biggest source of bugs here is the fact that you’re not keeping track of which elements are active in your unions. Even when you’re dealing with trivial types, you can’t do that. It is UB to access the non-active member of a union (though it is usually <em>silent</em> UB, meaning your program is broken, but you’ll never know because everything <em>appears</em> to “work”). And when it’s a non-trivial type, you’re pretty much cruising for a crash.</p>\n<p>Normally you’d use a flag to keep track of which part of the union is active—that’s what <code>std::variant</code> does. But you can actually get away without a flag, because you can tell which elements are active and which aren’t by whether they’re in the live part of the queue or not.</p>\n<p>But there’s still the complexity of handling non-trivial types. It may be necessary to have two different union types: one for trivial types, and one for non-trivial types—that’s how I’ve seen it done for implementations of <code>variant</code> anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:40:39.780",
"Id": "244181",
"ParentId": "244089",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244181",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T03:11:24.500",
"Id": "244089",
"Score": "4",
"Tags": [
"c++",
"performance",
"c++17",
"queue"
],
"Title": "Constexpr circular queue"
}
|
244089
|
<p>I often copy things from my terminal to other places (like Discord), and to make my workflow even easier I decided to use the IPython API to make an extension that has two magic functions <code>pickle</code> and <code>clip</code>.</p>
<p><code>clip</code> can copy the contents of a line (or cell). It can copy both, the input line or the output line.<br />
<code>pickle</code> takes in a variable as an argument and pickles its contents and copies it to your clipboard, it can also unpickle your clipboard's content and load it into a variable or print it.</p>
<p>I've heard that unpickling unknown data can be dangerous but I'm not sure if there is anything I can do about that, other than assume that the user trusts the data he or she is unpickling. (If there are other alternatives please let me know).</p>
<p>Are there any improvements that I could apply to my code? Like making the docstrings/error messages more understandable or patching a bug that I have not spotted, or rewriting something specific.</p>
<p>I'm kind of concerned about the user trying to unpickle a large object, such as a pandas data frame (I was helping someone with a pandas question and told him to pickle the data frame and send it, I didn't feel any noticeable delay as I unpickled the file, but the data frame <em>was</em> small anyways).</p>
<p>I also don't know how I could create tests for magic functions in case I add any extra features or patches in the future.</p>
<p>Any recommendations and constructive feedback are welcome. Thank you for taking the time to read this.</p>
<pre class="lang-py prettyprint-override"><code>import sys
from argparse import ArgumentTypeError
from ast import literal_eval
from keyword import iskeyword
from pickle import dumps as p_dumps
from pickle import loads as p_loads
import IPython.core.magic_arguments as magic_args
from IPython.core.magic import line_magic, Magics, magics_class
from pyperclip import copy as pycopy
from pyperclip import paste as pypaste
def valid_identifier(s: str):
if not s.isidentifier() or iskeyword(s):
raise ArgumentTypeError(f'{s} is not a valid identifier.')
return s
def valid_line_num(s: str):
valid_conditions = (
s.isdigit(),
s in '_ __ ___ _i _ii _iii'.split(),
s.startswith('_') and s[1:].isdigit(),
s.startswith('_i') and s[1:].isdigit()
)
if not any(valid_conditions):
raise ArgumentTypeError(f'{s} is not a valid line number or a valid ipython cache variable (eg. `_` or `_i3`)')
return s
@magics_class
class IPythonClipboard(Magics):
@line_magic
@magic_args.magic_arguments()
@magic_args.argument('line_number',
default='_',
type=valid_line_num,
nargs='?',
help='The line number to copy the contents from'
)
def clip(self, line: str = ''):
"""Copies an input or output line to the clipboard.
`_i7` copies the input from line 7
`_7` copies the output from line 7
`7` copies the output from line 7"""
args = magic_args.parse_argstring(self.clip, line)
line_num: str = args.line_number
if line_num.isdigit():
line_num = f'_{line_num}'
ip = self.shell
content: str = str(ip.user_ns.get(line_num, ''))
pycopy(content)
@line_magic
@magic_args.magic_arguments()
@magic_args.argument('--output', '-o',
type=valid_identifier,
nargs=1,
help='The variable to store the output to.')
@magic_args.argument('var',
type=valid_identifier,
nargs='?',
help='The variable to pickle.')
def pickle(self, line: str = ''):
"""
Pickles a variable and copies it to the clipboard or un-pickles clipboard contents and prints or stores it.
`%pickle` unpickle clipboard and print
`%pickle v` pickle variable `v` and store in clipboard
`%pickle _` pickle last line's output and store in clipboard
`%pickle -o my_var` unpickle clipboard contents and store in `my_var`"""
ip = self.shell
args = magic_args.parse_argstring(self.pickle, line)
if bool(args.output) and bool(args.var):
msg = (
'Incorrect usage, you can either pickle a variable, or unpickle, but not both at the same time.' '\n'
'\n' f'`%pickle {args.var}` to pickle the contents of `{args.var}` and send them to your clipboard'
'\n' f'`%pickle -o {args.output[0]}` to unpickle clipboard contents and send them to `{args.output[0]}`'
'\n' f'`%pickle` to unpickle your clipboard contents and print'
)
ip.write_err(msg)
return None
if not line or args.output: # user wants to unpickle from clipboard
content: str = pypaste()
possible_errors = (not content.startswith('b') and content[1] != content[-1], # must be like b'...'
not content # clipboard is empty
)
if any(possible_errors): # clipboard doesn't have a valid pickle string
sys.stderr.write(r"Your clipboard doesn't have a bytes-like string (ie. b'\x80\x03N.')")
return None
if args.output: # user wants to unpickle into a variable
ip.user_ns[args.output[0]] = p_loads(literal_eval(content))
else: # user wants to unpickle and print
sys.stdout.write(str(p_loads(literal_eval(content))))
else: # user wants to pickle a var
pycopy(str(p_dumps(ip.user_ns.get(args.var))))
def load_ipython_extension(ipython):
ipython.register_magics(IPythonClipboard)
</code></pre>
|
[] |
[
{
"body": "<h2>Valid line numbers</h2>\n<p>This is a mix of too-clever, not-very-efficient and not-informative-enough:</p>\n<pre><code>valid_conditions = (\n s.isdigit(),\n s in '_ __ ___ _i _ii _iii'.split(),\n s.startswith('_') and s[1:].isdigit(),\n s.startswith('_i') and s[1:].isdigit()\n)\nif not any(valid_conditions):\n raise ArgumentTypeError(f'{s} is not a valid line number or a valid ipython cache variable (eg. `_` or `_i3`)')\nreturn s\n</code></pre>\n<p>It really needs to be exploded out to the various error conditions. Also, the fourth condition is likely incorrect because it will never be true; you probably meant <code>[2:]</code>. An example:</p>\n<pre><code>if s in {'_', '__', '___', '_i', '_ii', '_iii'} or s.isdigit():\n return s\n\nmatch = re.match(r'_i?(.*)$', s)\nif match is None:\n raise ArgumentTypeError(f'{s} is not a valid line number or a valid ipython cache variable (eg. `_` or `_i3`)')\n\nif match[1].isdigit():\n return s\n\nraise ArgumentTypeError(f'{s} has a valid prefix but {match[1]} is not a valid integer')\n</code></pre>\n<p>Similarly, this:</p>\n<pre><code> possible_errors = (not content.startswith('b') and content[1] != content[-1], # must be like b'...'\n not content # clipboard is empty\n )\n if any(possible_errors):\n</code></pre>\n<p>should actually care that a single or double quote is used, and have separated error messages for mismatched quotes vs. missing 'b'. Don't handwave at your users - tell them exactly what went wrong.</p>\n<h2>Separated newlines</h2>\n<p>This:</p>\n<pre><code> msg = (\n 'Incorrect...time.' '\\n'\n '\\n' f'...\n</code></pre>\n<p>is odd. Why not just include the newlines in the same string?</p>\n<pre><code> msg = (\n 'Incorrect...time.\\n\\n'\n f'...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T06:45:38.767",
"Id": "479432",
"Score": "0",
"body": "I would also like to know why you chose to use a set in your example, instead of a tuple or a list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:30:34.870",
"Id": "244201",
"ParentId": "244091",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244201",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T06:27:03.267",
"Id": "244091",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"api",
"configuration"
],
"Title": "IPython - Clipboard Extension"
}
|
244091
|
<p>I've started learning Lisp one more time (I seem to do this every couple years); <em>my experience is with C, basically</em>. I attempted to solve the <a href="https://projecteuler.net/problem=1" rel="nofollow noreferrer">Project Euler problem 1</a>:</p>
<blockquote>
<p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</p>
</blockquote>
<p>My solution to the problem is below.</p>
<p>Please suggest improvements, style changes, indentation, commenting, naming of "objects", ...</p>
<pre><code>(defun multiple-of-3-or-5p (n)
"predicate for multiple of 3 or 5"
(cond ((= 0 (rem n 3)) t)
((= 0 (rem n 5)) t)
(t nil)))
(defun sum35 (n)
"sum all multiples of 3 or 5 up to n (including n)"
(cond ((= n 0) 0)
(t (+ (if (multiple-of-3-or-5p n) n 0) (sum35 (- n 1))))))
;; in the repl use
;; (sum35 999)
(defun predicate-sum (predicate n)
"sum integers up to n (including n) that match the predicate"
(cond ((= n 0) 0) ; stop recursion
(t (+
(if (funcall predicate n) n 0) ; add n or 0 and
(predicate-sum predicate (- n 1)))))) ; the recursed sum to (n - 1)
;; in the repl use
;; (predicate-sum 'multiple-of-3-or-5p 999)
</code></pre>
<p>Other than "stuff" relevant to the code above, I came across a few question while working on this problem.</p>
<ol>
<li>What is the natural Lispy way to define upper boundaries? Include or exclude the specific value? Ie, if you see <code>(summation 3 6)</code> you think <code>3+4+5</code> or <code>3+4+5+6</code>?</li>
<li>Is there a standard way to make a list of numbers <code>0</code> to <code>1000</code> (<code>999</code>)? Something like <code>(make-list 0 1000)</code>?</li>
</ol>
<p>Thanks in advance</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T09:55:20.483",
"Id": "479186",
"Score": "1",
"body": "This can be done in constant time, by multiplying formula for sum of arithmetic series by 3 or 5."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T09:56:55.070",
"Id": "479187",
"Score": "0",
"body": "Assuming negative multiples are ignored otherwise the result Is always negative infinity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T10:11:22.627",
"Id": "479188",
"Score": "0",
"body": "3 * arsum(1, 1000/3) + 5 * arsum (1, 1000/5) - 15 * arsum(1, 1000/15)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T09:53:28.520",
"Id": "479335",
"Score": "0",
"body": "@slepic Unsigned infinity if you don't count zero; undefined otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T11:54:31.107",
"Id": "479345",
"Score": "0",
"body": "@bipll you are wrong, adding any Infinite set of negative numbers together Is Always defined And Always negative Infinity. Even if you also add any finite set of nonnegative numbers (including zeroes)."
}
] |
[
{
"body": "<p><strong>Conditions</strong></p>\n<p>In general something like "if a then true else false" can be simplified as "a". So your first function could be simplified as:</p>\n<pre><code>(defun multiple-of-3-or-5p (n)\n "predicate for multiple of 3 or 5"\n (or (= 0 (rem n 3)) (= 0 (rem n 5))))\n</code></pre>\n<p><strong>Cond with only two cases</strong></p>\n<p>A <code>cond</code> with only two cases is written preferibly as an <code>if</code>. For instance:</p>\n<pre><code>(defun sum35 (n)\n "sum all multiples of 3 or 5 up to n (including n)"\n (if (= n 0)\n 0\n (+ (if (multiple-of-3-or-5p n) n 0) (sum35 (- n 1)))))\n</code></pre>\n<p><strong>Use the operators 1+ and 1- instead of adding or subtracting 1</strong></p>\n<p>The usual way of writing <code>(- n 1)</code> is <code>(1- n)</code>.</p>\n<p><strong>Recursion and Iteration</strong></p>\n<p>Common Lisp has a very powerful iteration construct, <code>loop</code> (see for instance <a href=\"http://www.gigamonkeys.com/book/loop-for-black-belts.html\" rel=\"nofollow noreferrer\">here</a> for a detailed\ndiscussion), that can make\nsimpler to write cases like in the last two functions. For instance:</p>\n<pre><code>(defun sum35 (n)\n "sum all multiples of 3 or 5 below n"\n (loop for i below n\n when (multiple-of-3-or-5p i) sum i))\n\n; (sum35 1000)\n</code></pre>\n<p>Analogously,</p>\n<pre><code>(defun predicate-sum35 (predicate n)\n "sum integers up to n (including n) that match the predicate"\n (loop for i below n\n when (funcall predicate i) sum i))\n\n; (predicate-sum35 #'multiple-of-3-or-5p 1000)\n</code></pre>\n<p>(note the use of <code>#'</code> to get a function).</p>\n<p>Finally, to answer your last two questions:</p>\n<ol>\n<li><p>The “natural” way in Common Lisp is to exclude the last value, as in all predefined functions that specify a range (for instance to get a substring with the first two characters of <code>"foo"</code>, you can write <code>(subseq "foo" 0 2)</code>, that returns <code>"fo"</code>,\nwith the index starting from 0).</p>\n</li>\n<li><p>A primitive function does not exists. You can obtain a list of this kind very easily by using <code>loop</code>, for instance: <code>(loop for i below 1000 collect i)</code>.</p>\n</li>\n</ol>\n<p><strong>Edited</strong></p>\n<p>As suggested in a comment by @slepic, the algorithm is not the best one, since it checks for all the numbers from 0 to <em>n</em>, while one could simply sum directly all the multiples. Here is a possible solution:</p>\n<pre><code>(defun sum35 (n)\n (flet ((sum-m (k)\n (loop for i from k below n by k sum i)))\n (+ (sum-m 3) (sum-m 5) (- (sum-m 15)))))\n</code></pre>\n<p>Or you can use a direct formula, like that in another comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:41:23.907",
"Id": "479221",
"Score": "0",
"body": "Good suggestions. Unfortunately they are only cosmetic changes to the OP's brute force solution. You both missed the point of project Euler. It's more about thinking then it is about coding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T13:26:09.390",
"Id": "479348",
"Score": "0",
"body": "You don't even have to loop to get the sum of arithmetic series, there is a simple formula for this: `n * (a_1 + a_n) / 2`, where `a_1`, is the first element of the series, `a_n` is the last element of the series and `n` is number of elements of the series. In our case `a_1=1`, `n=round_down((1000-1)/(3 resp. 5 resp, 15))`, `a_n=n (that is 333 resp. 199 resp. 66)`. So it is `3 * (334 / 2 * 333) + 5 * (200 / 2 * 199) - 15 * (66 / 2 * 67)`. Sure you can generalize to any upper limit, not just 1000."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T07:52:05.777",
"Id": "244094",
"ParentId": "244092",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244094",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T06:57:28.950",
"Id": "244092",
"Score": "3",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "Lispy code? Sum multiples of 3 or 5 up to 1000"
}
|
244092
|
<p>Just would like to ask if these custom web API naming follow best practice? Below are some of the web API methods I have created for my pet project using ASP.NET .NET Framework 4.7.</p>
<p>I understand that the standard CRUD naming convention especially when I use the scaffolding option. For example, this <code>Cart</code> controller web API, the scaffolded code are.</p>
<pre><code> // GET: api/Carts
public IQueryable<Cart> GetCarts()
{
return db.Carts;
}
// GET: api/Carts/5
[ResponseType(typeof(Cart))]
public async Task<IHttpActionResult> GetCart(int id)
{
Cart cart = await db.Carts.FindAsync(id);
if (cart == null)
{
return NotFound();
}
return Ok(cart);
}
// PUT: api/Carts/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutCart(int id, Cart cart)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != cart.Id)
{
return BadRequest();
}
db.Entry(cart).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!CartExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Carts
[ResponseType(typeof(Cart))]
public async Task<IHttpActionResult> PostCart(Cart cart)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Carts.Add(cart);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = cart.Id }, cart);
}
// DELETE: api/Carts/5
[ResponseType(typeof(Cart))]
public async Task<IHttpActionResult> DeleteCart(int id)
{
Cart cart = await db.Carts.FindAsync(id);
if (cart == null)
{
return NotFound();
}
db.Carts.Remove(cart);
await db.SaveChangesAsync();
return Ok(cart);
}
</code></pre>
<p>But, I don't use much of those CRUD method above. So, I added my own like below:</p>
<pre><code> [Route("api/Carts/GetClearAllCart/{id:int}")]
public async Task<IHttpActionResult> GetClearAllCart(int id)
{
var carts = db.Carts.Where(c => c.UsersId == id);
if (carts == null)
{
return NotFound();
}
db.Carts.RemoveRange(carts);
await db.SaveChangesAsync();
return Ok(carts);
}
[Route("api/Carts/GetClearOne/{id:int}")]
public async Task<IHttpActionResult> GetClearOneItemFromCart(int id)
{
var cart = db.Carts.SingleOrDefault(c => c.SeatId == id);
if (cart == null)
{
return NotFound();
}
db.Carts.Remove(cart);
await db.SaveChangesAsync();
return Ok();
}
[Route("api/Carts/GetClearAllByUserId/{id:int}")]
public async Task<IHttpActionResult> GetClearAllByUserId(int id)
{
var cart = db.Carts.Where(c => c.UsersId == id);
if (cart == null)
{
return NotFound();
}
db.Carts.RemoveRange(cart);
await db.SaveChangesAsync();
return Ok();
}
[Route("api/Carts/GetCartsByUserId/{id:int}")]
public IQueryable<CartVM> GetCartsByUserId(int id)
{
var cartVMList = new List<CartVM>();
var selectedCart = db.Carts.Where(c => c.UsersId == id);
foreach (var item in selectedCart)
{
var cartVM = new CartVM();
cartVM.MovieTitle = item.MovieTitle;
cartVM.HallNo = item.HallNo;
cartVM.MovieDateTime = item.MovieDateTime;
cartVM.Seats = item.Seats;
cartVM.SeatId = item.SeatId;
cartVMList.Add(cartVM);
}
return cartVMList.AsQueryable();
}
// GET: api/Movies
public IQueryable<MovieVM> GetMovies()
{
var movieVMList = new List<MovieVM>();
foreach (var item in db.Movies)
{
var movieVM = new MovieVM();
movieVM.MovieTitle = item.MovieTitle;
movieVM.Id = item.Id;
movieVM.PhotoFile = item.PhotoFile;
movieVMList.Add(movieVM);
}
return movieVMList.AsQueryable();
}
// GET: api/Movies/5
[ResponseType(typeof(Movie))]
public async Task<IHttpActionResult> GetMovie(int id)
{
Movie movie = await db.Movies.FindAsync(id);
if (movie == null)
{
return NotFound();
}
return Ok(movie);
}
</code></pre>
<p>I read that we should focus on the <code>noun</code> for RESTful API instead of <code>verbs</code> which is SOAP. How can we create a custom web API only with <code>noun</code> and without <code>verbs</code>? Any comment on my <code>custom</code> web API methods?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:00:41.027",
"Id": "479225",
"Score": "3",
"body": "This looks on-topic to me IDK why people are saying it's not (They don't have 3k yet so there's no close votes either). Your question (description) seems somewhat high level, but your code looks fairly solid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T16:24:49.713",
"Id": "479248",
"Score": "3",
"body": "@Peilonrayz alright, there https://codereview.meta.stackexchange.com/questions/10500/is-it-on-topic-to-provide-working-code-snippets-but-ask-only-questions-unrelated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:46:42.827",
"Id": "479263",
"Score": "1",
"body": "Can you tell us more about the goal of your API? What prompted you to write this code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:04:02.760",
"Id": "479291",
"Score": "0",
"body": "@Mast it is for my pet project for self-learning purpose. Yeah, my api works but not sure if my web api naming meet best practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T04:30:39.803",
"Id": "479309",
"Score": "3",
"body": "@SteveNgai I don't know if you've been watching the comments and the following discussion on meta. It seems your question is indeed ontopic. I've already retracted my close vote. Nevertheless, chances are that your question is more suitable for Software Engineering Stack Exchange, if you are interested in design review rather then code review, which seems to be the case, at least to me. If you decide to go ask there, please delete the post here, so that the answers are not fragmented over multiple sites. That is something I wanted to make clear, because I did not when mentioned it first time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T04:55:21.970",
"Id": "479310",
"Score": "0",
"body": "Okay sure. Thanks for the info."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T07:50:26.103",
"Id": "479321",
"Score": "2",
"body": "\"GetClearAllCart\", \"GetClearOne\" etc. are not proper English and kinda break my brain."
}
] |
[
{
"body": "<p>The only thing that stands out to me is these blocks:</p>\n<pre><code> var cartVM = new CartVM();\n cartVM.MovieTitle = item.MovieTitle;\n cartVM.HallNo = item.HallNo;\n cartVM.MovieDateTime = item.MovieDateTime;\n cartVM.Seats = item.Seats;\n cartVM.SeatId = item.SeatId;\n\n var movieVM = new MovieVM();\n movieVM.MovieTitle = item.MovieTitle;\n movieVM.Id = item.Id;\n movieVM.PhotoFile = item.PhotoFile;\n</code></pre>\n<p>which should use inline property assignment, i.e.</p>\n<pre><code> var cartVM = new CartVM() {\n MovieTitle = item.MovieTitle,\n HallNo = item.HallNo,\n MovieDateTime = item.MovieDateTime,\n Seats = item.Seats,\n SeatId = item.SeatId\n };\n\n var movieVM = new MovieVM() {\n MovieTitle = item.MovieTitle,\n Id = item.Id,\n PhotoFile = item.PhotoFile\n };\n</code></pre>\n<p>Better yet would be a constructor on each of those VM classes that accepts your <code>item</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:48:30.863",
"Id": "244447",
"ParentId": "244097",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T08:49:23.450",
"Id": "244097",
"Score": "2",
"Tags": [
"c#"
],
"Title": "RESTful movie shop"
}
|
244097
|
<p>I created a function that takes a dictionary as parameter. This dictionary is expected to have lists as value pair. <em>(i.e. <code>{1: [1, 2, 3], 'a': [4, 'b', 5, 'c']}</code> )</em></p>
<p>This function has to return the key associated to the biggest list in the dictionary, or <code>None</code> if the dictionary is empty. <em>(considering the above example, it would return <code>'a'</code> )</em></p>
<p>I came up with this code:</p>
<pre class="lang-py prettyprint-override"><code>def biggest(aDict):
return None if not aDict else [x for x in aDict if len(aDict[x]) == max(len(x) for x in aDict.values())][0]
</code></pre>
<p>Can I have some review on this and any ideas on how to further simplify without using external libraries?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:15:36.277",
"Id": "479213",
"Score": "1",
"body": "1 LOC doesn't equate to good code. At the very least this shouldn't use a turnery or nested comprehensions."
}
] |
[
{
"body": "<p>Your code is difficult to read:</p>\n<ul>\n<li>The line is too long (according to the <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"noreferrer\">Python style guide</a> all lines should be limited to 79 characters).</li>\n<li>The same iterator variable <code>x</code> is used for the outer iteration and also inside the <code>max()</code> function.</li>\n</ul>\n<p>It is also inefficient because the maximal list length is determined in each iteration.</p>\n<p>Using the <code>key</code> and <code>default</code> argument of the <a href=\"https://docs.python.org/3/library/functions.html#max\" rel=\"noreferrer\"><code>max()</code></a> function the same can be concisely and efficiently be implemented as</p>\n<pre><code>def biggest(aDict):\n return max(aDict, key=lambda k: len(aDict[k]), default=None)\n</code></pre>\n<p>More suggestions:</p>\n<ul>\n<li>Have a look at the <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"noreferrer\">Python naming conventions</a> (<code>snake_case</code>, not <code>camelCase</code>).</li>\n<li>Choose a more descriptive function name.</li>\n<li>Use <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">docstrings</a> to describe the function.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:25:39.253",
"Id": "479199",
"Score": "1",
"body": "This is the kind of answer that I was needing! I have just started to learn python. I come from Java, so camelCase is the way to go, for me. Hehe. Also, I realize the line was big enough,but I just wanted to exploit python capabilities of one-lining all the logic, to get a better understanding of the language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:38:06.690",
"Id": "479200",
"Score": "0",
"body": "Also, would you care to explain, what the param key exactly does? Does it only accept a lambda?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:46:12.387",
"Id": "479203",
"Score": "0",
"body": "@msmilkshake: It can be any function taking a single argument: a “named” function or an “anonymous” function (lambda). See also https://docs.python.org/3/library/functions.html#max and https://docs.python.org/3/library/stdtypes.html#list.sort: “key specifies a function of one argument that is used to extract a comparison key from each list element”"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:09:17.583",
"Id": "244103",
"ParentId": "244101",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "244103",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T10:42:44.667",
"Id": "244101",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"hash-map"
],
"Title": "Function takes a dictionary with list as value, returns the key of the biggest list"
}
|
244101
|
<p>I would like some advice on efficiency and ways to further remove redundant code.</p>
<p>Regex Text File Search:</p>
<ol>
<li><p>enter a valid directory path, and a string to search for</p>
</li>
<li><p>makes a list containing all the matched paths, and a dictionary with the matches of the matched paths</p>
</li>
<li><p>get a list of all the text files and go through them</p>
</li>
<li><p>for each text file, search for a match, line by line</p>
</li>
<li><p>if a match is found, then the path is appended to the matched_paths list</p>
</li>
<li><p>update the matched_dict to include the lines and the start index and end index for each match in the matched path</p>
</li>
<li><p>format the output into an appropriate form and display the results of the find</p>
</li>
</ol>
<pre class="lang-py prettyprint-override"><code>from pathlib import Path
from pyinputplus import inputCustom, inputStr
import re
# 2)
def check_path(path):
"""
returns the directory if the path is a directory, and it exists otherwise asks to input again
"""
directory = Path(path)
if directory.is_dir():
return directory
else:
raise Exception('Path is not a valid directory')
def format_output(matched_paths, matched_dict):
"""
- outputs the directories and matches for the string to be searched, only outputs the matched text files
Formats the output into this template:
file1.txt
>>> --------------------------- <<<
------ Line 280 ------
(start_index, end_index) # match 1
(start_index, end_index) # match 2 if it exists
<<< --------------------------- >>>
file2.txt
...
"""
for path in matched_paths:
print()
print(path.name)
print('>>> --------------------------- <<<')
for line, matches in matched_dict[path].items():
print(f' ------ Line {line} ------')
for match in matched_dict[path][line]:
print(' ', match)
print()
print('<<< --------------------------- >>>')
def search_for_string(path, string):
"""
1) opens the string
2) makes a check on if a match exists in the file
3) if it does, goes line by line
4) appending all the matches (start_index, end_index) to the line number in the dict of path
returns True if match was found, so it will be appended to the matched_paths list
matched_paths = [path1, path2, path3]
matched_dict = {path1: {line1: [(s1, e1), (s2, e2)] }, path2: ... }
"""
global matched_dict
with open(path, 'r') as text_file:
if re.search(string, path.read_text()):
matched_dict[path] = dict()
for i, line in enumerate(text_file.readlines()): # i refers to line number
matches = list(re.finditer(string, line))
if matches:
matched_dict[path][i] = []
for m in matches:
matched_dict[path][i].append(m.span())
return True
return False
# 1)
path = inputCustom(check_path, prompt='Enter Path: ')
string = inputStr(prompt='Enter string: ')
# 2)
matched_paths = []
matched_dict = dict()
# 3)
for text_file in path.glob('*.txt'):
# 4) and 6)
if search_for_string(text_file, string):
# 5)
matched_paths.append(text_file)
# 7)
format_output(matched_paths, matched_dict)
</code></pre>
|
[] |
[
{
"body": "<h2>Documentation</h2>\n<pre><code>"""\nreturns the directory if the path is a directory, and it exists otherwise asks to input again\n"""\n</code></pre>\n<p>OK; but that's not what this function does at all. The "asking to input again" is done elsewhere.</p>\n<h2>Type hints</h2>\n<p>Guessing for this signature; type hints would remove the guesswork:</p>\n<pre><code>def format_output(matched_paths, matched_dict):\n</code></pre>\n<p>could become</p>\n<pre><code>def format_output(\n matched_paths: Iterable[str],\n matched_dict: Dict[\n str,\n Dict[str, str]\n ],\n):\n</code></pre>\n<p>If this is true, the second type is complex enough that it could benefit from external declaration, i.e.</p>\n<pre><code>MatchesDict = Dict[\n str,\n Dict[str, str]\n]\n</code></pre>\n<h2>Dictionary iteration</h2>\n<pre><code>for path in matched_paths:\n for line, matches in matched_dict[path].items():\n for match in matched_dict[path][line]:\n</code></pre>\n<p>should be</p>\n<pre><code>for path in matched_paths:\n for line, matches in matched_dict[path].items():\n for match in matches:\n</code></pre>\n<p>In other words, <code>items</code> gets you a key and a value; when you have the value, use it.</p>\n<h2>Logic inversion</h2>\n<p>I find that this:</p>\n<pre><code> if re.search(string, path.read_text()):\n matched_dict[path] = dict()\n for i, line in enumerate(text_file.readlines()): # i refers to line number\n matches = list(re.finditer(string, line))\n if matches:\n matched_dict[path][i] = []\n\n for m in matches:\n matched_dict[path][i].append(m.span())\n return True\n return False\n</code></pre>\n<p>is more legible as</p>\n<pre><code> if not re.search(string, path.read_text()):\n return False\n\n matched_dict[path] = dict()\n for i, line in enumerate(text_file.readlines()): # i refers to line number\n matches = list(re.finditer(string, line))\n if matches:\n matched_dict[path][i] = []\n for m in matches:\n matched_dict[path][i].append(m.span())\n return True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:35:23.717",
"Id": "479404",
"Score": "0",
"body": "On your point about dictionary iteration, matched paths isn't a dictionary but a list of paths to the matched text files, so how am I supposed to iterate through its items() method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:08:35.630",
"Id": "479413",
"Score": "1",
"body": "My mistake; edited."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:17:48.380",
"Id": "244193",
"ParentId": "244104",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244193",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T12:21:23.053",
"Id": "244104",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"regex",
"file"
],
"Title": "Python - A Regex Text File Searcher by Content Project"
}
|
244104
|
<p>I've been trying to build an ORM. I started with the connector layer, which is responsible for the database server connections and executes raw SQL as the code below shows.</p>
<p>I have built the <code>_dbconnect</code> decorator to separate database connection procedures from the CRUD functions. This will be responsible for SQL conversions only, maintaining the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle" rel="nofollow noreferrer">single responsibility principle</a>.</p>
<p>Is the idea of this decorator good or not since it doesn't return any thing?<br />
In the future the <code>create_record()</code>, <code>delete_record()</code> or <code>read_record()</code> functions will need some sort of values to be returned. The result is also going to be different for all of them because when creating a record you will need to return the id only which is supposed to be an <code>int</code>, but selecting record will be a list of records in predefined data structure.</p>
<p>So is it OK for the decorator to be returning different types like mentioned above, and what are the better ways to handle it ?</p>
<pre><code>from abstract_connector import AbstractConnector
import psycopg2
class PsqlConnector(AbstractConnector):
def __init__(self, username: str, password: str, dbname: str):
self.username = username
self.password = password
self.dbname = dbname
def _dbconnect(func):
def wrapper(self, *args, **kwargs):
query = func(self, *args, **kwargs)
conn = psycopg2.connect("dbname=%s user=%s, password=%s" % (self.dbname, self.username, self.password))
cur = conn.cursor()
cur.execute(query)
conn.commit()
cur.close()
conn.close()
return wrapper
@_dbconnect
def create_table(self, name: str):
return "CREATE TABLE %s(id serial PRIMARY KEY, name VARCHAR(100));" % name
@_dbconnect
def drop_table(self, name: str):
return "DROP TABLE IF EXISTS %s" % name
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T18:54:24.567",
"Id": "479387",
"Score": "0",
"body": "_I've been trying to build an ORM_ - perhaps there's been a curse placed on you, or perhaps someone is secretly drugging you, but for a personal project this is biting off a lot more than most people could chew. Is there any reason you aren't using SQLAlchemy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T13:26:30.087",
"Id": "479454",
"Score": "0",
"body": "Actually it's a side project where I am trying to practice system design, applying best practices and writing clean code. Regarding the curse stuff, I started to doubt it :) ."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T13:57:07.700",
"Id": "244110",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"design-patterns",
"database",
"orm"
],
"Title": "Database connector in Python"
}
|
244110
|
<p>What are some ideas or ways that I can increase the efficiency of this gravity script because it is way to depending for what i want it for.</p>
<p>The game has a target at the center and there are objects far away all around the target and when gravity script is enabled I create an overlap sphere check which objects have a rigidbody and collision and pull them to target at a constant speed, but my FPS drops to the floor.</p>
<p>Would it be more efficient to have a script in each of these objects with a AddForce and direction towards target? Or any other ideas? Maybe something to change in this current script?</p>
<p>Am I right on the gravity script being too demanding because of the distance the gravity script is checking?</p>
<pre><code>[RequireComponent(typeof(Rigidbody))]
public class Gravity : MonoBehaviour
{
private Rigidbody ownBody;
[HideInInspector]
public float maxVelocityOfInfluence;
private float rangeOfInfluence = 7000.0f;
private void OnEnable()
{
if (ownBody == null)
{
ownBody = GetComponent<Rigidbody>();
}
}
private void FixedUpdate()
{
Collider[] cols = Physics.OverlapSphere(transform.position, rangeOfInfluence);
List<Rigidbody> rbs = new List<Rigidbody>();
foreach (Collider c in cols)
{
Rigidbody otherBody = c.attachedRigidbody;
if (otherBody != null && otherBody != ownBody && !rbs.Contains(otherBody) &&
HasTagDownHierarchy(otherBody.transform, "Boat"))
{
rbs.Add(otherBody);
Vector3 offset = transform.position - c.transform.position;
otherBody.velocity = (offset.normalized * maxVelocityOfInfluence);
}
}
}
private static bool HasTagDownHierarchy(Transform transform, string tag)
{
if (!transform)
{
return false;
}
if (transform.CompareTag(tag))
{
return true;
}
foreach (Transform child in transform)
{
if (HasTagDownHierarchy(child, tag))
{
return true;
}
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>You are allocating like crazy use <code>Physics.OverlapSphereNonAlloc</code></p>\n<p>dont do <code>List<Rigidbody> rbs = new List<Rigidbody>();</code></p>\n<p>Replace with o(1) lookup <code>HasTagDownHierarchy(otherBody.transform, "Boat")</code> also avoid tags. Use markup classes.</p>\n<p>edit: With look up I mean, in <em>Boat</em> <code>Awake</code> method cache the Colliders in a look up <code>Dictionary<Collider, Boat></code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:36:31.210",
"Id": "479239",
"Score": "0",
"body": "I will do what you say thank you! The thing is once objects reach target, new objects get spawned again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:37:25.363",
"Id": "479240",
"Score": "0",
"body": "What do I do instead of List<Rigidbody> ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:40:51.987",
"Id": "479241",
"Score": "0",
"body": "You should probably use a pool then. Use a hashmap instead of the List its o(1). clear it each iteration"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T18:53:29.973",
"Id": "479270",
"Score": "0",
"body": "okay so I created the `HashSet`, I added an `Add()` and `Remove()` on `Enable()` and `Disable()`, now how do I incorporate `Physics.OverlapSphereNonAlloc` and `Time.fixedDeltaTime`? Mind helping me out?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T19:10:39.887",
"Id": "479275",
"Score": "0",
"body": "Physics.OverlapSphereNonAlloc takes an array that it fills with the overlapping colliers. Make sure to make it big enough so that it can always contain all collders that you can overlap. But not too big for memory. The integer returned from it is the actual number of found colliders"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T20:38:21.940",
"Id": "479282",
"Score": "0",
"body": "Okay so I have completed this, I have returned the actual number of found colliders but the problem is I have other objects in this scene that should not be collected by overlap"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T20:42:48.983",
"Id": "479283",
"Score": "0",
"body": "isn't it best to get all the colliders from the HashSet because that is only filled with the \"boats\" that I am looking for, how would I do this. This will terminate the need to use overlapsphere"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T09:17:43.813",
"Id": "479330",
"Score": "0",
"body": "wait what? I thought a boat was a spaceship and 7k meters radius was to capture all spaceships within this radius (like a black hole or something)? Or are 7k radius a way of making sure all boats in scene are captured? If you want all boats in scene just put them in a List<Boat> at wake/destroy or enable/disable if pooled. Iterate over this list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T11:08:51.180",
"Id": "479342",
"Score": "0",
"body": "its like a blackhole but only for boats as they are the only enemies, i just realized I should just used your hashset/list idea to be faster not the overlapSphere. Performance should improve correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T10:02:19.757",
"Id": "479436",
"Score": "0",
"body": "Yeah, but then it will affect all boats in scene. Not just the ones inside the sphere. So different result."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:32:00.927",
"Id": "244118",
"ParentId": "244112",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244118",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:54:53.867",
"Id": "244112",
"Score": "1",
"Tags": [
"unity3d"
],
"Title": "Unity Gravity script lowering FPS because of overlap sphere checking collision"
}
|
244112
|
<p>I am building an Android quiz app. I want to display a progress bar showing how many questions a user has answered correctly and how many they have left. Questions are split by difficulty level; easy, medium and hard.</p>
<p>All my questions are stored in an SQLite database. The questions table is made up of three columns:</p>
<pre><code>level question guessed
</code></pre>
<p>The <code>guessed</code> column is a flag (<code>1</code> or <code>null</code>) to let me know if the user has guessed the question correctly or not.</p>
<p>To build my progress bar, I'm currently running two pieces of SQL code, for each level, to pull out the total number of questions and the total number of questions guessed correctly. This gives me the numbers I need to build the progress bar. However I am doing it by running 6 individual Java functions, one after the other.</p>
<p>Here is my code:</p>
<pre><code>public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static DatabaseAccess instance;
public static String player_name;
Cursor c = null;
// private constructor so that object creation from outside the class is avoided
public DatabaseAccess(Context context) {
this.openHelper = new DatabaseOpenHelper(context);
}
// to return the single instance of database
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
//to open the database
public void open() {
this.db = openHelper.getWritableDatabase();
}
//closing the database connection
public void close() {
if (db != null) {
this.db.close();
}
}
public String getEasyMax(String string) {
c = db.rawQuery("select count(*) FROM player_clues where level = 'easy'", new String[]{});
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
String diff = c.getString(0);
buffer.append("" + diff);
}
return buffer.toString();
}
public String getEasyGuessed(String string) {
c = db.rawQuery("select count(*) FROM player_clues where level = 'easy' and guessed = 1", new String[]{});
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
String diff = c.getString(0);
buffer.append("" + diff);
}
return buffer.toString();
}
public String getMedGuessed(String string) {
c = db.rawQuery("select count(*) FROM player_clues where level = 'medium' and guessed = 1", new String[]{});
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
String diff = c.getString(0);
buffer.append("" + diff);
}
return buffer.toString();
}
public String getHardGuessed(String string) {
c = db.rawQuery("select count(*) FROM player_clues where level = 'hard' and guessed = 1", new String[]{});
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
String diff = c.getString(0);
buffer.append("" + diff);
}
return buffer.toString();
}
public String getMedMax(String string) {
c = db.rawQuery("select count(*) FROM player_clues where level = 'medium'", new String[]{});
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
String diff = c.getString(0);
buffer.append("" + diff);
}
return buffer.toString();
}
public String getHardMax(String string) {
c = db.rawQuery("select count(*) FROM player_clues where level = 'hard'", new String[]{});
StringBuffer buffer = new StringBuffer();
while (c.moveToNext()) {
String diff = c.getString(0);
buffer.append("" + diff);
}
return buffer.toString();
}
}
</code></pre>
<p>In another class, I call on these functions individually and assign the outputs to variables and use them there.</p>
<p>How can I make this more efficient and better?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T14:58:08.353",
"Id": "244113",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "Multiple functions to run SQLite queries and save the output to a variable"
}
|
244113
|
<p>I've implemented Many-To-Many relationship and wonder if this is the optimal way for it. Since I do not have extensive EF Core experience I would love if someone with more experience could check it out.</p>
<p>Scenario:</p>
<ul>
<li>Many users</li>
<li>Many organizations</li>
<li>User can belong to multiple organizations</li>
<li>Organization can hold multiple users</li>
</ul>
<pre><code>// Organization.cs
public class Organization
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual IEnumerable<OrganizationUser> OrganizationUsers { get; set; }
}
</code></pre>
<pre><code>// OrganizationUser.cs
public class OrganizationUser
{
public Guid OrganizationId { get; set; }
public virtual Organization Organization { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
public Role Role { get; set; }
}
public enum Role
{
Owner,
Admin,
User
}
</code></pre>
<pre><code>// User.cs
public class User
{
public Guid Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public virtual IEnumerable<OrganizationUser> OrganizationUsers { get; set; }
[NotMapped]
public virtual IEnumerable<UserOrganizationOutputDto> Organizations
{
get
{
return OrganizationUsers.Select(x => new UserOrganizationOutputDto
{
Id = x.OrganizationId.ToString(),
Name = x.Organization.Name,
Role = x.Role
});
}
}
}
</code></pre>
<pre><code>// Database Context code that is related
modelBuilder.Entity<Organization>()
.HasMany<OrganizationUser>()
.WithOne(x => x.Organization);
modelBuilder.Entity<User>()
.HasMany<OrganizationUser>()
.WithOne(x => x.User);
modelBuilder.Entity<OrganizationUser>()
.HasKey(x => new {x.OrganizationId, x.UserId});
modelBuilder.Entity<OrganizationUser>()
.HasOne(x => x.User)
.WithMany(x => x.OrganizationUsers)
.HasForeignKey(x => x.UserId);
modelBuilder.Entity<OrganizationUser>()
.HasOne(x => x.Organization)
.WithMany(x => x.OrganizationUsers)
.HasForeignKey(x => x.OrganizationId);
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Couple of pointers. You are mixing data notation and fluent mapping.</p>\n<p>replace <code>NotMapped</code> attribute with <code>.Ignore</code> fluent mapping.</p>\n<p>Also I think its cleaner to move each entity into its own mapping config class using <code>IEntityTypeConfiguration<T></code></p>\n<p>Dont mix DTO and entities like that. Best practice is to project your entities to DTOs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:30:30.227",
"Id": "479235",
"Score": "0",
"body": "Good point about `.Ignore`, will do that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:44:11.313",
"Id": "479244",
"Score": "0",
"body": "You know, the reason I mix this DTO is that I need to get list of users and their respective role so this was the cleanest way I could imagine doing that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:45:11.960",
"Id": "479245",
"Score": "0",
"body": "I would project to a UserDto with a UserOrganizationOutputDto"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:45:51.890",
"Id": "479246",
"Score": "0",
"body": "x.Organization.Name forces you to use include otherwise you will get null reference error. with projection its not needed. Alot cleaner. Best practice too"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:25:51.113",
"Id": "244117",
"ParentId": "244116",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244117",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T15:15:00.053",
"Id": "244116",
"Score": "1",
"Tags": [
"c#",
"entity-framework",
"entity-framework-core"
],
"Title": "Many to Many Relationship using EF Core"
}
|
244116
|
<p>I want to create a very big gigantic PNG image. The image pixel are generated randomly, being</p>
<p>How can I improve the below code to create a fast random pixel image in java?</p>
<pre><code>import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class RandomImage
{
public static void main(String args[])throws IOException
{
// Image file dimensions
int width = 30000, height = 24000;
// Create buffered image object
BufferedImage img = null;
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
// file object
File f = null;
// create random values pixel by pixel
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int a = (int)(Math.random()*256); //generating
int r = (int)(Math.random()*256); //values
int g = (int)(Math.random()*256); //less than
int b = (int)(Math.random()*256); //256
int p = (a<<24) | (r<<16) | (g<<8) | b; //pixel
img.setRGB(x, y, p);
}
}
// write image
try
{
f = new File("G:\\Out.png");
ImageIO.write(img, "png", f);
}
catch(IOException e)
{
System.out.println("Error: " + e);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T06:56:02.710",
"Id": "480564",
"Score": "0",
"body": "This question contains an unfinished"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T07:04:17.393",
"Id": "480566",
"Score": "0",
"body": "The question leaves unanswered what you want to do with the random image, after you generated it. That's much more interesting than generating it fast, and there may even be completely different approaches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T12:37:47.970",
"Id": "480668",
"Score": "0",
"body": "@RolandIllig I want to save the image to disk."
}
] |
[
{
"body": "<p>In regards to speed, I'm not seeing a whole lot you could improve. One thing that comes to mind is the use of lower level APIs -- i.e. don't use File and BufferedImage. You could, for example, use a <code>DataOutputStream</code> (<a href=\"https://docs.oracle.com/javase/10/docs/api/java/io/DataOutputStream.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/10/docs/api/java/io/DataOutputStream.html</a>) which, from my understanding, is one of Java's lowest level APIs for writing data to a file. You could do something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>DataOutputStream stream = new DataOutputStream(new FileOutputStream("path/to/file"));\n</code></pre>\n<p>Then with this, you can use methods like <code>writeByte</code> to continuously populate the image file, rather than doing it in one whole buffer. I don't know if in the end this produces a faster result, but it produces a result such that the user could stop the program partway through and still end up with an image.</p>\n<p>The caveat here is that you need to research what the proper metadata for a PNG file looks like and output that manually.</p>\n<hr>\n<p>Something you could also try is using one loop as opposed to two.</p>\n<p>To do that, you would do something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for(int i = 0; i < width * height; i++) {\n //row=floor(n / width)\n //col=n-(row*width)\n}\n</code></pre>\n<p>(I think I did the math right on those row and col numbers but you might want to check me).</p>\n<p>This might be faster -- I don't know if the extra computations will slow things down, but it'd be worthy to try out.</p>\n<hr>\n<p>Finally, unrelated to speed: a lot of things in your code are hardcoded right now (i.e. the width, height, and file name).</p>\n<p>I would instead export everything to a separate function for generating random images, and that function could take parameters width, height, and file name. Then, in your main function, you use some sort of user input to determine what to pass to that function (e.g. command-line arguments or STDIN).</p>\n<p>Additionally, having a separate function makes it unit-testable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T21:07:30.380",
"Id": "479285",
"Score": "0",
"body": "There is no need to go quite that low level, you can use the fact that `BufferedImage` exposes it's underlying `WritableRaster` via `BufferedImage.getRaster`, see my answer for a full explanation.\n\nAlso I doubt unfolding the inner loop will yield any measurable performance benefit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T03:24:51.913",
"Id": "479308",
"Score": "0",
"body": "@Marv Thank you for the info!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T07:02:22.957",
"Id": "480565",
"Score": "0",
"body": "The unfolded inner loop will be slower if you really put two integer divisions in it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T00:22:13.500",
"Id": "480639",
"Score": "0",
"body": "@RolandIllig Hmm yeah, I wasn't sure about that. I don't know how Java optimizes it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T19:52:30.233",
"Id": "244135",
"ParentId": "244123",
"Score": "-1"
}
},
{
"body": "<p>You can write arrays of Integers directly on the <code>WritableRaster</code> of the <code>BufferedImage</code>:</p>\n<pre><code>public static BufferedImage createRandomImage(final int width, final int height) {\n final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n\n final long bytesPerPixel = 4L;\n\n final int[] pixelData = new SplittableRandom().ints(bytesPerPixel * width * height, 0, 256).toArray();\n\n result.getRaster().setPixels(0, 0, width, height, pixelData);\n\n return result;\n}\n</code></pre>\n<p>This performs more than three times faster on my machine in a very crude benchmark (3.92S vs 1.26S), with the caveat that for very big images like the one you desire, you have a lot of data duplication, because you basically have to allocate twice the amount of memory, since you're writing the random data to a buffer first.</p>\n<p>This can easily be solved by writing arrays of random Integers line by line though, which nets comparable performance:</p>\n<pre><code>public static BufferedImage createRandomImage(final int width, final int height) {\n final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);\n\n final long bytesPerPixel = 4L;\n\n for (int y = 0; y < height; y++) {\n final int[] pixelData = new SplittableRandom().ints(bytesPerPixel * width, 0, 256)\n .toArray();\n\n result.getRaster().setPixels(0, y, width, 1, pixelData);\n }\n\n return result;\n}\n</code></pre>\n<p><code>BufferedImage.setRGB</code> is very slow, because for every pixel you set, it has to go fetch the corresponding data element:</p>\n<pre><code>public void setRGB(int x, int y, int rgb) {\n raster.setDataElements(x, y, colorModel.getDataElements(rgb, null));\n}\n</code></pre>\n<p>which is a comparatively heavy operation.</p>\n<hr />\n<h2>Parallelization</h2>\n<p>Crude parallelization improves performance slightly, but it does not scale linearly with number of cores. On my 24 thread machine, the following yields a 30-40% improvement compared to the loop <code>WritableRaster</code> variant:</p>\n<pre><code>public static BufferedImage createRandomImage(final int width, final int height) {\n final BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n\n final long bytesPerPixel = 4L;\n\n IntStream.range(0, height).parallel().forEach(y -> {\n final int[] pixelData = new SplittableRandom().ints(bytesPerPixel * width, 0, 256)\n .toArray();\n result.getRaster().setPixels(0, y, width, 1, pixelData);\n });\n\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:00:28.533",
"Id": "479323",
"Score": "2",
"body": "Really nice answer, I didn't know the `SplittableRandom` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T11:42:19.287",
"Id": "480413",
"Score": "0",
"body": "Did you copy-paste the same snippet twice? I can't spot the difference in the parallelized example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T13:03:16.740",
"Id": "480420",
"Score": "0",
"body": "@TorbenPutkonen thank you, indeed a copy paste error. Fixed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T21:06:32.377",
"Id": "244139",
"ParentId": "244123",
"Score": "5"
}
},
{
"body": "<p>Since you are constructing a full, 32-bit word from random bits, you could skip the niceties and simply generate a 32-bit random number as your p. What is unclear is how the edge cases would behave. For instance, I would have used an unsigned int instead of an int to hold your four values (0-255), as the leftmost one (R) might mess with the sign of p. etc. That should go roughly 4x faster than using 4 calls and multiplies for each pixel.</p>\n<p>Also, do you really need 720 million <em>different</em> random values? or does it just need to look real random? You could have an array of say 1,000,000 pixels, instead of p, have p[1000000]. That's a pretty fast gen, 1M v 720M. Then, simply generate random values between 0 and 999999, do your img.setRGB() with random selections from that pallette. And yes, that is no faster than the above code. But consider NOT generating random values from 0-999999. Consider, instead, taking these already-random pixels in a loop, from first to last, and then repeating that loop, over and over, as you progress through your image. Sure it will "repeat" but visually, it will be kind of hard to see a pattern.</p>\n<p>As a further alternative, having very quickly generated a million random pixels, fill your image array by doing the following:</p>\n<ol>\n<li>generate a random number, X, from 0-970000</li>\n<li>fill the first 30000 image pixels with 30000 values from the million pixels, starting at X</li>\n<li>repeat for the next 30000 image pixels (a total of 24000 times. 24000 add'l calls to Math.random()).</li>\n</ol>\n<p>This should have a decided speed advantage over calling Math.random() 720,000,000 times and still should be uber random <em>looking</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T02:34:19.890",
"Id": "479307",
"Score": "0",
"body": "Using `WritableRaster` instead of `setRGB` like I suggested in my answer yields a greater improvement, but this suggestion yields about another speed doubling when using `WritableRaster`, depending on how many values you generate. It definitely doesn't scale linearly with the amount of pixels."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T11:43:59.223",
"Id": "479441",
"Score": "0",
"body": "I have to confess that I did not read your original answer very carefully! If Java actually allows direct access to video raster space, then the part where random BLocks are Transferred from the million pixel source might be handled by BLiT routines. This is all new to me (in Java)! Thank you @Marv; very nice low-level info!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:14:13.010",
"Id": "244143",
"ParentId": "244123",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T16:51:25.143",
"Id": "244123",
"Score": "0",
"Tags": [
"java",
"performance",
"multithreading",
"file",
"image"
],
"Title": "Fastest way to create random pixel image"
}
|
244123
|
<p>I am wondering, how can I improve this simple <code>MissingResource</code> exception class? I am using it in my simple game.</p>
<pre><code>template <typename Resource>
class MissingResource : public std::exception {
std::string_view fileName{};
std::string_view msg{};
public:
MissingResource() = default;
MissingResource(std::string_view fileName)
: fileName{fileName}
{
initMsg<Resource>();
}
template <typename T>
void initMsg() {
msg = "Failed loading resource: "
"{ Type: " + std::string(typeid(Resource).name()) + ", "
"File name: " + fileName.data() + " }";
}
virtual const char* what() const noexcept override {
return msg.data();
}
};
</code></pre>
<p>Throw usage:</p>
<pre><code>template <typename Key, typename Resource>
#if (__cplusplus == 202002L)
requires Mappable<Key>
#endif
class ResourceHolder {
std::unordered_map<Key, std::unique_ptr<Resource>> resources;
std::string resourcesDir;
public:
explicit ResourceHolder(std::string_view resourcesDir = "../resources/")
: resourcesDir{std::move(resourcesDir)}
{}
template <typename... Args>
void insert(const Key& key, std::string_view fileName, Args&&... args) {
auto resPtr = std::make_unique<Resource>();
bool loaded{};
if constexpr (std::is_same<Resource, sf::Music>()) {
loaded = resPtr->openFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);
} else {
loaded = resPtr->loadFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);
}
/** Called here */
if (!loaded) {
throw MissingResource<Resource>(fileName);
}
resources.emplace(key, std::move(resPtr));
}
</code></pre>
<p>Try-Catch usage:</p>
<pre><code>ResourceManager::ResourceManager() {
try {
loadResources();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
std::exit(EXIT_FAILURE);
}
}
</code></pre>
<p>Exemplary error message:</p>
<pre><code>what(): Failed loading resource: { Type: N2sf11SoundBufferE, File name: Death.wav }
</code></pre>
<p>P.S: If you see some smelly code or have doubts or found any kind of other mistakes, I would be looking forward to knowing them. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T09:17:37.270",
"Id": "479329",
"Score": "0",
"body": "I'm surprised that none of the answers mention that you shouldn't derive from std::exception directly, but rather from std::runtime_error or similar. But maybe I'm just wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T10:29:00.193",
"Id": "479339",
"Score": "0",
"body": "@sbecker, I don't see the benefit of deriving from `std::runtime_error` in this case. `std::exception` is an abstract class, and he wants to override `what` basically. Maybe he can remove some code if inheriting from `std::runtime_error` (removing string member), but I think the class is clear enough as it is. Inheritance chains don't need to be unnecessarily long."
}
] |
[
{
"body": "<p><strong><code>std::string_view</code></strong></p>\n<p>Firstly, there seems to be some <em>misusages</em> of <code>string_view</code>. <code>string_view</code> is non-owning, and is a view to an allocated char array (such as <code>string</code>).</p>\n<p>The usage</p>\n<pre><code>template <typename Resource>\nclass MissingResource : public std::exception {\n std::string_view fileName{};\n std::string_view msg{};\n \npublic:\n [...]\n template <typename T>\n void initMsg() {\n msg = "Failed loading resource: "\n "{ Type: " + std::string(typeid(Resource).name()) + ", "\n "File name: " + fileName.data() + " }";\n }\n [...]\n};\n</code></pre>\n<p>Is dangerous, since after calling <code>initMsg()</code>, msg will point to an destroyed object (the right hand string is temporary).</p>\n<p>Better change it to be an owning string in this case: <code>std::string_view msg</code> => <code>std::string msg</code>. I assume you already have it like this, otherwise it would provide the output which you gave in the description.</p>\n<p>Secondly, the other member variable <code>std::string_view fileName</code> does not seem <em>necessary</em>. Since you create the error message for <code>msg</code> with <code>fileName</code> and do not use alone, we can skip it, right?</p>\n<p><strong>General design of <code>MissingResource</code></strong></p>\n<p>Applying the changes above, we have:</p>\n<pre><code>template <typename Resource>\nclass MissingResource : public std::exception {\n std::string msg{};\n \npublic:\n MissingResource() = default;\n MissingResource(std::string_view fileName)\n {\n initMsg<Resource>();\n }\n\n template <typename T>\n void initMsg(std::string_view fileName) {\n msg = "Failed loading resource: "\n "{ Type: " + std::string(typeid(Resource).name()) + ", "\n "File name: " + fileName.data() + " }";\n }\n\n virtual const char* what() const noexcept override {\n return msg.data();\n }\n};\n</code></pre>\n<p><code>initMsg</code> is currently a <em>public method</em>, but from what I see, it's only used locally in the constructor. If this is the case, it should rather be a <em>private method</em> - you want to keep the public API for the class as simple and small as possible.</p>\n<p>Another improvement would be to be able to create <code>msg</code> in the constructor list - so that it does not have to be created twice. We can do this by making the initMsg a static method.</p>\n<p>Let's remove the extra unnecessary template for initMsg as well - the entire class already holds the template argument.</p>\n<p>And note that virtual + override is <em>unnecessary</em>. If you mark a method as overrided, it is implicitly virtual. Remove virtual for unnecessary noise.</p>\n<p>We now have something like this:</p>\n<pre><code>template <typename Resource>\nclass MissingResource : public std::exception {\n std::string msg{};\n\n static std::string initMsg(std::string_view fileName) {\n return "Failed loading resource: "\n "{ Type: " + std::string(typeid(Resource).name()) + ", "\n "File name: " + fileName.data() + " }";\n }\n \npublic:\n MissingResource() = default;\n MissingResource(std::string_view fileName) : msg{initMsg<Resource>()}\n {}\n\n const char* what() const noexcept override {\n return msg.data();\n }\n};\n</code></pre>\n<p><strong><code>ResourceHolder</code></strong></p>\n<p>Since this review is already long, I will just point out one thing in <code>ResourceHolder</code>, namely in <code>insert</code>. We can avoid separating declaration from initialization for bool loaded (and make it const!) by encapsulating the logic into a separate method. This might be a bit preferential, but it is good practice to avoid separating declaration and initialization.</p>\n<p>Something like this:</p>\n<pre><code>private:\n bool fromFile(std::string_view fileName, Args&&... args) \n {\n if constexpr (std::is_same<Resource, sf::Music>()) {\n return resPtr->openFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);\n } \n else {\n return resPtr->loadFromFile(resourcesDir + fileName.data(), std::forward<Args>(args)...);\n }\n\npublic:\n template <typename... Args>\n void insert(const Key& key, std::string_view fileName, Args&&... args) {\n auto resPtr = std::make_unique<Resource>();\n \n const bool loaded = fromFile(fileName, std::forward<Args>(args)...)\n \n /** Called here */\n if (!loaded) {\n throw MissingResource<Resource>(fileName);\n }\n resources.emplace(key, std::move(resPtr));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T01:54:59.637",
"Id": "479305",
"Score": "1",
"body": "Came to say this. An easy rule of thumb is: use `std::string` to store and `std::string_view` to look/pass around."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T19:38:37.253",
"Id": "244132",
"ParentId": "244124",
"Score": "5"
}
},
{
"body": "<p>One problem I can see with your code is, that you can't catch <code>MissingResource</code> unless you know the specific <code>Resource</code> type used when that exception was thrown.<br />\nAll you can do in the <code>catch</code> is to capture the generic <code>std::exception</code>, which is also the base for many other kinds of failure, including the stuff that's used from the c++ standard library.</p>\n<p>A better way would be to introduce a specific base class for the whole category of <code>MissingResource</code> exceptions. E.g. like this:</p>\n<pre><code>class MissingResourceCategory : public std::exception {\nprotected:\n std::string_view fileName{};\n std::string_view msg{};\n\n MissingResourceCategory() = default;\n};\n\ntemplate <typename Resource>\nclass MissingResource : public MissingResourceCategory {\n \npublic:\n MissingResource() = default;\n MissingResource(std::string_view fileName) : fileName{fileName} {\n initMsg<Resource>();\n }\n\n template <typename T>\n void initMsg() {\n msg = "Failed loading resource: "\n "{ Type: " + std::string(typeid(Resource).name()) + ", "\n "File name: " + fileName.data() + " }";\n }\n\n virtual const char* what() const noexcept override {\n return msg.data();\n }\n};\n</code></pre>\n<p>This would allow you to distinguish <code>MissingResource</code> exceptions from others in your <code>catch</code> blocks:</p>\n<pre><code>ResourceManager::ResourceManager() {\n try {\n loadResources();\n } catch (const MissingResourceCategory& e) {\n std::cerr << e.what() << std::endl;\n std::exit(EXIT_RESOURCE_FAILURE);\n }\n } catch (const std::exception& e) {\n std::cerr << e.what() << std::endl;\n std::exit(EXIT_FAILURE);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T19:43:44.377",
"Id": "244133",
"ParentId": "244124",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244132",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T16:59:46.827",
"Id": "244124",
"Score": "5",
"Tags": [
"c++",
"error-handling",
"exception",
"c++20"
],
"Title": "C++ custom exception class"
}
|
244124
|
<p>My answer to <a href="https://projecteuler.net/problem=3" rel="nofollow noreferrer">Project Euler problem 3</a> <em>(largest prime factor of 600851475143)</em> is below.</p>
<p>Please suggest improvements, style changes, indentation, commenting, naming of "objects", ...</p>
<pre><code>(defun factors (n)
"return a list with prime factors of n"
(let ((result))
(loop while (zerop (rem n 2)) ; do 2
do (loop while (zerop (rem n 2))
do (setf n (/ n 2))
do (setf result (cons 2 result))))
(loop for i from 3 by 2 ; do 3, 5, 7, 9, ...
while (>= n (* i i)) ; until square root of what's left of n
do (loop while (zerop (rem n i))
do (setf n (/ n i))
do (setf result (cons i result))))
(if (= n 1) result (cons n result)))) ; if n is not 1 it is also a factor
</code></pre>
<p>Questions:</p>
<ol>
<li>Is the <code>(let ((result)) #| ... (setf result ...) ... |# result)</code> construction acceptable?</li>
<li>I like the result as it is, <em>in reverse</em>; but, other than <code>(reverse result)</code> is there a way to <code>collect</code> factors <strong>into</strong> result? My attempts with <code>collect i</code> (or <code>collect i into result</code>) would not compile.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:05:04.017",
"Id": "479324",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>Your code is perfectly fine, except for a few nitpicks.</p>\n<ol>\n<li><p>Use <a href=\"http://clhs.lisp.se/Body/m_push.htm\" rel=\"nofollow noreferrer\"><code>push</code></a> instead of <code>(setf x (conx y x))</code> for readability.</p>\n</li>\n<li><p>Use <a href=\"http://clhs.lisp.se/Body/f_floorc.htm\" rel=\"nofollow noreferrer\"><code>floor</code></a> instead of <code>rem</code> + <code>/</code> for efficiency.</p>\n</li>\n<li><p>1st and 3rd <code>loop</code>s are identical, so they should be abstracted into a local <a href=\"http://clhs.lisp.se/Body/s_flet_.htm\" rel=\"nofollow noreferrer\"><code>flet</code></a> function.</p>\n</li>\n<li><p>Use <a href=\"http://clhs.lisp.se/Body/f_revers.htm\" rel=\"nofollow noreferrer\"><code>nreverse</code></a> instead of <code>reverse</code> for the return value. Yes, you can avoid that by using <code>collect</code> combined with <a href=\"http://clhs.lisp.se/Body/f_nconc.htm\" rel=\"nofollow noreferrer\"><code>nconc</code></a> but it makes little sense in your specific case.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T18:42:27.650",
"Id": "479269",
"Score": "0",
"body": "Thank you. I still gotta learn how to use functions that return two values. Now working on that `flet` suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T18:57:25.147",
"Id": "479271",
"Score": "0",
"body": "see https://stackoverflow.com/q/22795608/850781 for multi-valued functions"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:26:49.393",
"Id": "244128",
"ParentId": "244125",
"Score": "3"
}
},
{
"body": "<p>After direct feedback on <a href=\"https://codereview.stackexchange.com/a/244128/2842\">sds's answer</a> my code is now</p>\n<pre><code>(defun factors (n)\n "return a list with prime factors of n"\n (let ((result))\n (flet ((transfer-factor (fac)\n "transfer available fac from number `n` to list `result`"\n (loop with quotient and remainder\n do (setf (values quotient remainder)\n (floor n fac))\n while (zerop remainder)\n do (setf n quotient)\n do (push fac result))))\n (transfer-factor 2) ; do 2\n (loop for i from 3 by 2 ; do 3, 5, 7, 9, ...\n while (>= n (* i i)) ; until sqrt of what's left of n\n do (transfer-factor i)))\n (when (> n 1) (push n result)) ; n may still be a factor\n result)) ; return complete list\n\n;; in the repl use\n;; (first (factors 600851475143))\n</code></pre>\n<p>Incorporated using <code>floor</code> to get quotient and remainder in one operation, incorporated the <code>flet</code> <em>inner function</em>.</p>\n<p>I learned to use <code>values</code> and a lot more about the <code>loop</code> construct.<br />\nThanks @sds</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:58:52.043",
"Id": "244156",
"ParentId": "244125",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244128",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:08:15.547",
"Id": "244125",
"Score": "2",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "Lispy code? Prime factors of a number"
}
|
244125
|
<p>I'm posting my C++ code for LeetCode's <a href="https://leetcode.com/problems/expressive-words/" rel="nofollow noreferrer">Expressive Words</a>. If you have time and would like to review, please do so. Thank you!</p>
<blockquote>
<p>Sometimes people repeat letters to represent extra feeling, such as
"hello" -> "heeellooo", "hi" -> "hiiii". In these strings like
"heeellooo", we have groups of adjacent letters that are all the same:
"h", "eee", "ll", "ooo".</p>
<p>For some given string S, a query word is stretchy if it can be made to
be equal to S by any number of applications of the following extension
operation: choose a group consisting of characters c, and add some
number of characters c to the group so that the size of the group is 3
or more.</p>
<p>For example, starting with "hello", we could do an extension on the
group "o" to get "hellooo", but we cannot get "helloo" since the group
"oo" has size less than 3. Also, we could do another extension like
"ll" -> "lllll" to get "helllllooo". If S = "helllllooo", then the
query word "hello" would be stretchy because of these two extension
operations: query = "hello" -> "hellooo" -> "helllllooo" = S.</p>
<p>Given a list of query words, return the number of words that are
stretchy.</p>
<p>Example: Input: S = "heeellooo" words = ["hello", "hi", "helo"]<br />
Output: 1 Explanation: We can extend "e" and "o" in the word "hello"<br />
to get "heeellooo". We can't extend "helo" to get "heeellooo" because
the group "ll" is not size 3 or more.</p>
<p>Notes:</p>
<p>0 <= len(S) <= 100.<br />
0 <= len(words) <= 100.<br />
0 <= len(words[i]) <= 100.
S and all words in words consist only of lowercase letters</p>
</blockquote>
<h3>Accepted C++</h3>
<pre><code>class Solution {
public:
int expressiveWords(std::string base_string, std::vector<string> &words) {
int count = 0;
for (auto &word : words)
if (is_stretchable(base_string, word))
count++;
return count;
}
protected:
bool is_stretchable(std::string base_string, std::string words) { // 4 pointers
int base_length = base_string.size();
int words_length = words.size();
int left_a = 0, right_a = 0;
for (int left_b = 0, right_b = 0; left_a < base_length && right_a < words_length; left_a = left_b, right_a = right_b) {
if (base_string[left_a] != words[right_a])
return false;
while (left_b < base_length && base_string[left_b] == base_string[left_a])
left_b++;
while (right_b < words_length && words[right_b] == words[right_a])
right_b++;
if (left_b - left_a != right_b - right_a && left_b - left_a < std::max(3, right_b - right_a))
return false;
}
return left_a == base_length && right_a == words_length;
}
};
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is an instance usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename those.</p>
<ul>
<li><a href="https://leetcode.com/problems/expressive-words/solution/" rel="nofollow noreferrer">Solution</a></li>
<li><a href="https://leetcode.com/problems/expressive-words/discuss/" rel="nofollow noreferrer">Discussion</a></li>
<li><a href="https://leetcode.com/problems/expressive-words/" rel="nofollow noreferrer">Question</a></li>
</ul>
|
[] |
[
{
"body": "<p>Pass by const reference to prevent copying and modification:</p>\n<pre><code>int expressiveWords(std::string const& base_string, std::vector<string> const& words)\n ^^^^^^ ^^^^^^\n\nbool is_stretchable(std::string const& base_string, std::string const& words)\n ^^^^^^ ^^^^^^\n\n\n for (auto const& word : words)\n ^^^^^^\n</code></pre>\n<p>This prevents the strings being copied into the function. It will also catch situations were you accidentally try and modify the string.</p>\n<hr />\n<p>Please add braces <code>{}</code> around sub blocks.<br />\nIt will save you one day without you even knowing. Issues caused by missing braces are notoriously hard to find because they are caused when sombody else does something nasty that affects your code (multi line macros come to mind).</p>\n<hr />\n<p>One variable per line:</p>\n<pre><code> int left_a = 0, right_a = 0;\n</code></pre>\n<p>Its not going to hurt you to add an extra line and it makes the job easier for the next person.</p>\n<hr />\n<p>Not sure it is worth it.<br />\nBut just to be complete you could use a standard algorithm to count.</p>\n<pre><code> int count = 0;\n\n for (auto &word : words)\n if (is_stretchable(base_string, word))\n count++;\n\n return count;\n\n // ---\n\n return std::count(std::begin(words), std::end(words),\n [&base_string, this](auto const& word){return is_stretchable(base_string, word);});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T20:05:30.900",
"Id": "479279",
"Score": "0",
"body": "Is it still true that \"issues caused by missing braces are notoriously hard to find\", now that GCC has `-Wmisleading-indentation`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T20:31:53.977",
"Id": "479280",
"Score": "0",
"body": "@RolandIllig: `warning: unknown warning option '-Wmisleading-indentation'; did you mean '-Wbinding-in-condition'?`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T19:01:43.957",
"Id": "479483",
"Score": "0",
"body": "Are you saying that pass by reference without the const does copy?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T19:04:45.967",
"Id": "244131",
"ParentId": "244127",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T17:20:10.673",
"Id": "244127",
"Score": "1",
"Tags": [
"c++",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "LeetCode 809: Expressive Words"
}
|
244127
|
<p>Here's what I trying to do:</p>
<p>Given a paginated API, get all the resources using parallel requests.</p>
<p>The API returns a limited number of resources per call. So, you need to use an offset parameter to get to the next set of data until all data is extracted.</p>
<p>Here's my idea (but getting some warning because I'm using flat on the response), so maybe there's a better way to do this.</p>
<ol>
<li>Get the total count of items.</li>
<li>Given the count and the limit, calculate how many requests are needed to get all data.</li>
<li>Trigger all requests in parallel and combine all data into a flattened array.</li>
</ol>
<p>Here's an example:</p>
<p><a href="https://stackblitz.com/edit/paginated-api?embed=1&file=index.ts&hideExplorer=1&devtoolsheight=100" rel="nofollow noreferrer">https://stackblitz.com/edit/paginated-api?embed=1&file=index.ts&hideExplorer=1&devtoolsheight=100</a></p>
<pre class="lang-js prettyprint-override"><code>getCount().pipe(
mergeMap(count => range(0, Math.ceil(count / limit))),
map(offset => getDevices(offset, limit)),
combineAll(),
).subscribe(res => {
const a = res.flat(); // <--- warning: Property 'flat' does not exist on type '{ name: string; }[][]'.
console.log(JSON.stringify(a));
});
</code></pre>
<p>I feel this solution is a little hacky. It's flattening the response in the subscription. I'd like to know if there's an RXJS operator that I can use on the pipe to flatten the response, so I don't have to in the subscription?</p>
<p>How to merge the multiple observables responses into a single array?</p>
|
[] |
[
{
"body": "<p>Use <code>mergeMap</code> on the call to getDevices, then <a href=\"https://www.learnrxjs.io/learn-rxjs/operators/combination/mergeall\" rel=\"nofollow noreferrer\">mergeAll</a> to flatten the results, and <a href=\"https://www.learnrxjs.io/learn-rxjs/operators/transformation/toarray\" rel=\"nofollow noreferrer\">toArray</a> to convert back to an array:</p>\n<pre><code>getCount().pipe(\n mergeMap(count => range(0, Math.ceil(count / pageSize))),\n mergeMap(offset => getDevices(offset, pageSize)),\n mergeAll(),\n toArray()\n).subscribe(res => {\n console.log(JSON.stringify(res));\n});\n</code></pre>\n<p>See here: <a href=\"https://stackblitz.com/edit/so-rxjs-merge-results?file=index.ts\" rel=\"nofollow noreferrer\">https://stackblitz.com/edit/so-rxjs-merge-results?file=index.ts</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T11:46:17.717",
"Id": "244990",
"ParentId": "244134",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T19:52:14.013",
"Id": "244134",
"Score": "1",
"Tags": [
"javascript",
"typescript",
"rxjs"
],
"Title": "Merge the multiple observables responses into a single array"
}
|
244134
|
<p>I recently have been ̶w̶a̶s̶t̶i̶n̶g̶ spending my time on making a web scraper specifically designed for FanFictions from <a href="https://www.fanfiction.net" rel="nofollow noreferrer">fanfiction.net</a> (Okay, I'll admit, I like reading them in my spare time that I should spend with coding) I wrote it so I could read FanFictions offline. (For a Raspberry Pi E-Paper reader, but that's offtopic for this question)</p>
<p>I even spent more time making a GUI for it.</p>
<p>Here is the code:</p>
<pre><code>import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
from tkinter import messagebox
import requests # pip install requests
import bs4 # pip install beautifulsoup4
import pathlib
from time import sleep
import re
# import logging
# Set logging level
# logging.basicConfig(level=logging.DEBUG)
# Define functions that takes care of the ID and URL entries
# https://bit.ly/tkinterautofillonso
after_ids = {}
def get_url(id_):
"""returns url from id."""
url = "https://www.fanfiction.net/s/{}/"
return url.format(id_.replace(" ", ""))
def get_id(url):
"""returns id from the url."""
l = url.split("/")
return l[4] if len(l) > 4 else ""
def autofill_entry(mode, delay=50):
"""Auto-fills Url/ID."""
for v in after_ids.values():
root.after_cancel(v)
if mode == "url":
id_ = get_id(fanfic_url.get())
after_ids[0] = root.after(delay, lambda: fanfic_id.set(id_))
elif mode == "id":
url = get_url(fanfic_id.get())
after_ids[1] = root.after(delay, lambda: fanfic_url.set(url))
# Thanks @Saad at SO
# Define a function to have the user choose a directory and set the path accordingly
def get_directory():
global path
# Ask for directory
selected_directory = filedialog.askdirectory()
# Set selected directory if user did not cancel
if selected_directory:
path = pathlib.Path(selected_directory)
directory.set(path)
# Define a function to set the status
def set_status(string):
status.config(text = string + 100 * " ")
# Allows GUI to process and display events
root.update_idletasks()
# Define the function to download the fanfic
def download_fanfic():
num_chapter = 1
chapter = 0
base_url = fanfic_url.get()
progress_bar["value"] = 0
while not chapter == num_chapter:
# Set progress barmax value
progress_bar["maximum"] = 10 * num_chapter
chapter += 1
url = base_url + f"{chapter}/"
set_status(f"Downloading {url}...")
progress_bar["value"] = 1 * chapter
try:
response = requests.get(url)
except requests.exceptions.MissingSchema:
set_status(f"Error downloading {url}...")
messagebox.showerror("FanFiction Downloader: ERROR",
"Uh oh, an error has occurred!\n"
"That does not seem to a be a valid URL!")
except requests.exceptions.InvalidSchema:
set_status(f"Error downloading {url}...")
messagebox.showerror("FanFiction Downloader: ERROR",
"Uh oh, an error has occurred!\n"
"That does not seem to a be a valid URL!")
else:
set_status(f"Status code is {response.status_code}")
if response.status_code == 200:
set_status("Parsing FanFiction...")
# Parse HTML with html5lib
soup = bs4.BeautifulSoup(response.content, "html5lib")
progress_bar["value"] = 2 * chapter
# Check if we actually got a real chapter not an error message
if response.text.find("FanFiction.Net Message Type ") == -1 and \
response.text.find("Story Not Found") == -1:
# Count the number of chapters we need to download
set_status("Counting chapters...")
# This gets the number between the words "Chapters: " and " - Words: ")
num_chapter = int(
soup.find("span", class_="xgray xcontrast_txt").text[
soup.find(
"span", class_="xgray xcontrast_txt"
).text.find("Chapters: ") + 10:soup.find(
"span", class_="xgray xcontrast_txt"
).text.find(" - Words: ")
]
)
progress_bar["value"] = 3 * chapter
# Add title
set_status("Finding title...")
text = soup.find("b", class_="xcontrast_txt").string + "\n"
progress_bar["value"] = 4 * chapter
# Find first link that looks like the author's name
set_status("Finding author...")
for author in soup.findAll("a", class_="xcontrast_txt"):
if author.parent.name == "div":
text += f"By: {author.string}\n\n"
# Break because we only want the first one
break
progress_bar["value"] = 5 * chapter
# Add the synopsis
set_status("Finding synopsis...")
text += f"Synopsis: {soup.find('div', class_='xcontrast_txt').string}\n\n"
progress_bar["value"] = 6 * chapter
# Add more information about fanfiction
set_status("Finding FanFiction information...")
text += soup.find("span", class_="xgray xcontrast_txt").text + "\n\n"
progress_bar["value"] = 7 * chapter
# Add fanfic iteself
set_status("Finding FanFiction content...")
for paragraph in soup.find_all("p"):
text += paragraph.text + "\n"
progress_bar["value"] = 8 * chapter
set_status("Signing FanFiction...")
# Add signature
text += "\n\nThis fanfiction was downloaded with the fanfiction downloader v3\n"
text += "See the source code at https://bit.ly/fanficdownloaderv3code\n"
# Add link to original fanfiction
text += f"Link to fanfiction (To read online): {url}\n"
progress_bar["value"] = 9 * chapter
# Make path to fanfiction
file_path = path / (
re.sub("[^\w\-_\. ]", "_", soup.title.string).replace(" ", "_") + ".txt"
)
set_status("Writing FanFiction to "
f"{str(file_path)[:80] + '...' if len(str(file_path)) > 80 else str(file_path)}")
# If a file with that name already exists
if file_path.exists():
if messagebox.askokcancel("FanFiction Downloader v3: Confirmation",
"It looks like this file already exists! Overwrite?"):
with file_path.open("wt") as file:
file.write(text)
set_status("Sucessfully written FanFiction to "
f"{str(file_path)[:68] + '...' if len(str(file_path)) > 68 else str(file_path)}")
else:
set_status("Canceled writting FanFiction to "
f"{str(file_path)[:70] + '...' if len(str(file_path)) > 70 else str(file_path)}")
else:
with file_path.open("wt") as file:
file.write(text)
set_status("Sucessfully written FanFiction to "
f"{str(file_path)[:68] + '...' if len(str(file_path)) > 68 else str(file_path)}")
progress_bar["value"] = 10 * chapter
else:
# Chapter does not exist
if response.text.find("FanFiction.Net Message Type ") == -1:
messagebox.showerror("FanFiction Downloader: ERROR",
"Uh oh, an error has occurred!\n"
"Story Not Found\n"
"Story is unavailable for reading. (A)")
# Story does not exist
elif response.text.find("Story Not Found") == -1:
messagebox.showerror("FanFiction Downloader v3: ERROR",
"Uh oh, an error has occurred!\n"
"Chapter not found. Please check to see you are not using an outdated url.\n"
"New chapter/story can take up to 15 minutes to show up.")
else:
# Raise an error
messagebox.showerror("FanFiction Downloader v3: ERROR",
"Uh oh, an error has occurred!\n"
f"Unexpected status code: {response.status_code}\n"
"No files have been written.")
# Define the path where to download the fanfics
path = pathlib.Path.cwd()
# Root window
root = tk.Tk()
# Set title of root window
root.title("FanFiction Downloader v3")
# Define the labeled frame where we input stuff
input_frame = tk.LabelFrame(master=root, text="Input")
input_frame.grid(row=0, column=0, padx=1, pady=1, rowspan=2, sticky=tk.NS)
# Label for entering URL
ttk.Label(master=input_frame, text="URL of FanFiction:").grid(row=0, column=0, padx=1, pady=1)
# Entry field for URL
fanfic_url = tk.StringVar()
fanfic_url.trace_variable("w", lambda *a: autofill_entry("url"))
url_entry = ttk.Entry(master=input_frame, textvariable=fanfic_url)
url_entry.grid(row=0, column=1, padx=1, pady=1)
# Label for entering fanfic ID
ttk.Label(master=input_frame, text="ID of FanFiction:").grid(row=1, column=0, padx=1, pady=1)
# Entry field for fanfic ID
fanfic_id = tk.StringVar()
fanfic_id.trace_variable("w", lambda *a: autofill_entry("id"))
id_entry = ttk.Entry(master=input_frame, textvariable=fanfic_id)
id_entry.grid(row=1, column=1, padx=1, pady=1)
# Define the labeled frame where we output stuff
output_frame = tk.LabelFrame(master=root, text="Output")
output_frame.grid(row=0, column=1, padx=1, pady=1, sticky=tk.NW)
# Label for entering directory of downloaded files
ttk.Label(
master=output_frame, text="Directory path of downloaded FanFictions:"
).grid(row=0, column=0, padx=1, pady=1)
# Entry field for directory of downloaded files
directory = tk.StringVar()
directory.set(path)
directory_entry = ttk.Entry(master=output_frame, textvariable=directory)
directory_entry.grid(row=0, column=1, padx=1, pady=1)
# Button to browse for directory of downloaded files
ttk.Button(master=output_frame, text="Browse", command=get_directory).grid(row=0, column=2, padx=1, pady=1)
# Button to start downloading fanfic
ttk.Button(master=root, text="Start", command=download_fanfic).grid(row=1, column=1, padx=1, pady=1, sticky=tk.NSEW)
# Define the labeled frame where we output status stuff
status_frame = tk.LabelFrame(master=root, text="Status")
status_frame.grid(row=2, column=0, padx=1, pady=1, columnspan=2, sticky=tk.NSEW)
# Progress bar for, well, progress
progress_bar = ttk.Progressbar(master=status_frame, orient=tk.HORIZONTAL, length=670, mode="determinate")
progress_bar.grid(row=0, column=0, padx=1, pady=1)
# Status bar for showing current operation
status = ttk.Label(master=status_frame, text="Idle", width=100)
status.grid(row=1, column=0, padx=1, pady=1, sticky=tk.NW)
# Start GUI event loop
root.mainloop()
</code></pre>
<p><a href="https://gist.github.com/UnsignedArduino/afa05f44b2480a68a28b56cbf3552a16" rel="nofollow noreferrer">Here is the Gist link too</a></p>
<p>When I implemented the progress bar, I did some stuff that doesn't look pretty and the progress bar likes to jump back to the beginning for like 0.1 seconds. The thing works, but that detail is driving me up the wall. I'd appreciate help in that department. I'd also appreciate general code optimizations/cleanups.</p>
<p>EDIT: After playing with it a bit more, I realized that Windows likes to mark the program as not responding if there are a lot of FanFictions to download. Is there a way to get rid of that too?</p>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:44:01.863",
"Id": "479371",
"Score": "2",
"body": "+1 for side-project candidness. I know that feel."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:05:16.853",
"Id": "479372",
"Score": "0",
"body": "Yes. I was supposed to keep working on my RPi, but I wanted some more stories than the Bible on it. (I will admit the Bible can get boring - and I did mention that I made an E-paper reader with RPi) So you turn to Python to get FanFictions for you, because I am too lazy to look up a program to do it on code review stack exchange but I will work 4+ hours into making a program to do it for me. Perfectly sensible..."
}
] |
[
{
"body": "<h2>Requirements</h2>\n<p>Move these:</p>\n<pre><code># pip install requests\n# pip install beautifulsoup4\n</code></pre>\n<p>into a pip-compatible <code>requirements.txt</code>:</p>\n<pre><code>requests\nbeautifulsoup4\n</code></pre>\n<h2>Type hints</h2>\n<p>They will help. I don't know if <code>id_</code> is an <code>int</code> or <code>str</code> here, but:</p>\n<pre><code>def get_url(id_: int) -> str:\n</code></pre>\n<h2>Path parsing</h2>\n<p>This:</p>\n<pre><code>l = url.split("/")\nreturn l[4] if len(l) > 4 else ""\n</code></pre>\n<p>is a little risky. You're probably better off writing a regular expression that is explicit in where the ID is situated with respect to the element above it:</p>\n<pre><code>re.search(r'/s/(\\d+)')\n</code></pre>\n<p>assuming that the ID is integral. Also, avoid using an empty string as the default if no ID is found; either return <code>None</code> or maybe raise an exception, depending on how much of a problem it is.</p>\n<h2>Mode variables</h2>\n<p>Since <code>mode</code> only has two states, use a <code>bool</code>, maybe named <code>get_url</code>. If it had more than two states, or if you feel that the use of <code>bool</code> is too confusing, use an <code>Enum</code> - but avoid using strings for this purpose.</p>\n<h2>Globals</h2>\n<pre><code>def get_directory():\n global path\n</code></pre>\n<p>should not declare a global. Simply return <code>path</code>.</p>\n<h2>Separation of UI and logic</h2>\n<p><code>download_fanfic</code> is a big old ball of yarn. You have calls to <code>requests</code> beside calls to <code>messagebox</code>. Separate out the actual downloading logic and parsing logic into their own separate functions that do not have any <code>tk</code> code in them at all. Errors can be signalled via exceptions, and progress can be signalled via a generic callback function.</p>\n<h2>Logging</h2>\n<p>Try converting this:</p>\n<pre><code>set_status("Writing FanFiction to " ...\n</code></pre>\n<p>into a call to the standard logging framework, and adding your own logging handler to do what <code>set_status</code> currently does. It will make your application much more flexible - you could fairly easily flip one switch to have the entire thing run in console-only mode.</p>\n<h2>Requests check</h2>\n<pre><code> if response.status_code == 200:\n</code></pre>\n<p>should be replaced with:</p>\n<pre><code>if response.ok:\n</code></pre>\n<p>or better yet</p>\n<pre><code>response.raise_for_status()\n</code></pre>\n<h2>Threading</h2>\n<blockquote>\n<p>I realized that Windows likes to mark the program as not responding if there are a lot of FanFictions to download. Is there a way to get rid of that too?</p>\n</blockquote>\n<p>Put the downloading code in a worker thread, so that no single tk ui function is long-lived.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:10:39.997",
"Id": "479373",
"Score": "0",
"body": "Thank you so much for your answer. I will now go w̶a̶s̶t̶e spend time on fixing it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:53:02.237",
"Id": "479378",
"Score": "0",
"body": "Sorry if I'm bothering you, but I'm having trouble with trying not to use `global`, because I can't figure out how to assign the result of `get_directory()` in a `lambda` if the result is not `None`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:54:28.670",
"Id": "479380",
"Score": "0",
"body": "Not a bother. Let us continue this discussion in chat - https://chat.stackexchange.com/rooms/109586/fanfiction-downloader-in-python-with-gui"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:07:03.183",
"Id": "244184",
"ParentId": "244138",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244184",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T20:56:22.323",
"Id": "244138",
"Score": "5",
"Tags": [
"python",
"web-scraping",
"tkinter",
"beautifulsoup"
],
"Title": "FanFiction Downloader in Python, with GUI"
}
|
244138
|
<p>I am building a social network with PHP, HTML and CSS and a bit of JS. I want to know how secure my login and register code is.</p>
<p>Register html:</p>
<pre><code> <input id="uname" type="text" onblur="this.value=removeSpaces(this.value);" name="username" required placeholder="Username..."><p/>
<br>
<input id="pww" type="password" onblur="this.value=removeSpaces(this.value);" name="pw" required placeholder="Password..."><p />
<br>
<input id="cpw" type="password" onblur="this.value=removeSpaces(this.value);" name="pw2" required placeholder="Confirm Password..."><p />
<br>
<button type="submit" id="bt1" name="Register">Register</button>
</form>
</code></pre>
<p>Login html:</p>
<pre><code> <input type="text" id="luname" onblur="this.value=removeSpaces(this.value);" required name="username" placeholder="Username...">
<input type="password" id="lpw" onblur="this.value=removeSpaces(this.value);" required name="pw" placeholder="Password..." >
<button id="bt2" type="submit" name="signin">Login</button>
</form>
</code></pre>
<p>Register code:</p>
<pre><code><?php
error_reporting(-1); // reports errors
// check if form is submitted
if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) {
// looks like a hack, send to index.php
header('Location: index.php');
die();
}
require 'config/connect.php';
//Initializing variable. "" When you want to append stuff later. 0 When you want to add numbers later
$username = '';
$pw = '';
$pw2 = '';
$_SESSION['username'] = $username; // stores username in session variable
$success = array(); // holds success messages
$errors = []; // holds error messages
if ($pw !== $pw2) {
//$errors[] = "The passwords do not match.";
}
if (!$errors) {
//An SQL statement template is created and sent to the database
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
// This function binds the parameters to the SQL query and tells the database what the parameters are.
$stmt->bind_param("s", $_POST['username']);
// the database executes the statement.
$stmt->execute();
// Associative arrays are arrays that use named keys that you assign to them.
$row = $stmt->get_result()->fetch_assoc();
if ($row && $row['username'] == $_POST['username']) {
//$errors[] = "<p id='exists'>Username exists</p>";
$_SESSION['error'] = '<b><p style="color: #000000; font-size: 25px; top: 34%;right: 30%;position: absolute;">Username exists</p></b>';
header('Location: index.php');
}
}
if (!$errors) {
$pw = password_hash($pw, PASSWORD_BCRYPT, array('cost' => 14));
$stmt = $conn->prepare("INSERT INTO users (username, pw) VALUES(?, ?)");
$stmt->bind_param("ss", $_POST['username'], $pw );
$stmt->execute();
$_SESSION["username"] = $_POST['username'];
header('Location: profile.php');
die();
} else {
// The foreach construct provides an easy way to iterate over arrays.
foreach ($errors as $error) {
echo "$error <br /> \n";
}
echo '<a href="index.php" id="exists">Try again</a><br />';
}
?>
</code></pre>
<p>Login code:</p>
<pre><code><?php
error_reporting(-1); // reports errors
require 'config/connect.php';
$username = '';
$_SESSION['username'] = $username;
//check if form is submitted
//if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['signin'])) {
// looks like a hack, send to index.php
//header('Location: index.php');
//die();
//}
if (empty($_POST["username"])) {
//echo 'Fill in username to sign in. <a href= index.php>Try again</a><br />';
//die();
$_SESSION['error'] = '<b><p style="color: #000000; font-size: 25px; top: 15%;right: 38%;position: absolute;">Username cannot be empty</p></b>';
header('Location: index.php');
}
if (empty($_POST["pw"])) {
// echo 'Fill in password to sign in. <a href= index.php>Try again</a><br />';
// die();
$_SESSION['error'] = '<b><p style="color: #000000; font-size: 25px; top: 15%;right: 38%;position: absolute;">Password cannot be empty</p></b>';
header('Location: index.php');
}
$sql = "SELECT pw FROM users WHERE username = ?";
$stmt = mysqli_prepare($conn, $sql);
if ( !$stmt ) {
echo mysqli_error($conn);
die();
}
$stmt->bind_param('s', $_POST['username']);
if ( !$stmt->execute() ) {
echo mysqli_error($conn);
die();
}
// we found a row with that username,
// now we need to check the password is correct
// get the password from the row
$stmt->bind_result($hashed_pwd); // Binds variables to a prepared statement for result storage
$stmt->fetch(); // Fetch results from a prepared statement into the bound variables
if ( password_verify($_POST['pw'], $hashed_pwd) ) {
// password verified
$_SESSION["username"] = $_POST['username'];
header('Location: profile.php');
} else {
//echo 'Incorrect username or Password. <a href= index.php>Try again</a><br />';
$_SESSION['error'] = '<b><p style="color: #fff; font-size: 25px; top: 15%;right: 30%;position: absolute;">Incorrect username or Password.</p></b>';
header('Location: index.php');
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T22:24:07.120",
"Id": "479288",
"Score": "0",
"body": "Welcome to code review, you can improve the question by making the title more about what the code does and leave the actual question about security in the body of the question. There are many questions that start off with `How secure is my ...`. A better title would be Social network login and registration forms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T22:53:14.077",
"Id": "479289",
"Score": "0",
"body": "Please tell us why you are disallowing spaces in the password fields? Mutating the user's password (silently) will lead to user frustration when they try to login with spaces in the future. Why do you unconditionally save a blank username to the SESSION array? Why is `$errors` an array if can only have a max size of 1? Showing `mysqli_error()` messages to the end user is never secure practice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T00:51:42.963",
"Id": "479301",
"Score": "0",
"body": "@mickmackusa ok I fixed all the other problems but is this good ? `$errors = '';` instead of holding it as an array ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T00:53:37.430",
"Id": "479302",
"Score": "0",
"body": "I suppose so. (I guess my questions were actually a review.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T00:56:53.183",
"Id": "479303",
"Score": "0",
"body": "@mickmackusa Lol I guess so. I allowed user's to add spaces to their passwords. I removed the session at the start of the file. And I fixed the $errors. Is there a security problem with allowing users to add spaces to passwords or usernames ?"
}
] |
[
{
"body": "<ul>\n<li><p>Allowing spaces in usernames and passwords represents absolutely no security risk -- so let your users do it if they like. Well, if you don't want usernames to have spaces, that's a personal choice. In fact, by silently removing spaces, you stand the chance of irritating your users because they will struggle to log in if the saved username or password doesn't match what they [thought they] typed.</p>\n</li>\n<li><p>I don't see any reason to save a blank username string to the <code>$_SESSION</code> array. If you are going to save the username to the SESSION, then only added it after it is validated.</p>\n</li>\n<li><p>Because your script can only produce a single error message, then it could be argued that employing an array to contain this data is an overly complex data structure. Unless you plan on extending the volume of error messages to be displayed to the user, just save the variable as a string.</p>\n</li>\n<li><p>Never display <code>mysqli_error()</code> messages in production code. You never want to give bad-actors any "useful" information.</p>\n</li>\n<li><p>I don't recommend saving html in your SESSION array. Save the lean text and maybe save meta data on the text (was it a successful or failed outcome). If html markup & styling is necessary, that should be generated by the view/template and css should be in an external style sheet.</p>\n</li>\n<li><p><code>if ( $_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) {</code> is more simply written as <code>if (!isset($_POST['Register'])) {</code>.</p>\n</li>\n<li><p>The check if <code>$row['username'] == $_POST['username']</code> is silly. Of course, the two values will be identical -- you just pulled the qualifying match from the database! Instead, just return the <code>COUNT()</code> from your query, this way you will always have a result set and you can just check if the result set's lone column value is truthy/falsey to determine if the username is already taken.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T01:21:49.937",
"Id": "244148",
"ParentId": "244140",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244148",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T22:04:50.737",
"Id": "244140",
"Score": "4",
"Tags": [
"php",
"html",
"html5"
],
"Title": "Social network login and registration forms"
}
|
244140
|
<pre><code>import random
# Variables, lists, tuples, and dictionaries.
nucleotides = ("A", "C", "G", "T")
rev_compliment = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
seq = ""
description = ""
frames = []
proteins = []
RNA_codon_table = {"UUU": "F", "CUU": "L", "AUU": "I", "GUU": "V",
"UUC": "F", "CUC": "L", "AUC": "I", "GUC": "V",
"UUA": "L", "CUA": "L", "AUA": "I", "GUA": "V",
"UUG": "L", "CUG": "L", "AUG": "M", "UCU": "S",
"GUG": "V", "CCU": "P", "ACU": "T", "GCU": "A",
"UCC": "S", "CCC": "P", "ACC": "T", "GCC": "A",
"UCA": "S", "CCA": "P", "ACA": "T", "GCA": "A",
"UCG": "S", "CCG": "P", "ACG": "T", "GCG": "A",
"UAU": "Y", "CAU": "H", "AAU": "N", "GAU": "D",
"UAC": "Y", "CAC": "H", "AAC": "N", "GAC": "D",
"UAA": "_", "CAA": "Q", "AAA": "K", "GAA": "E",
"UAG": "_", "CAG": "Q", "AAG": "K", "GAG": "E",
"UGU": "C", "CGU": "R", "AGU": "S", "GGU": "G",
"UGC": "C", "CGC": "R", "AGC": "S", "GGC": "G",
"UGA": "_", "CGA": "R", "AGA": "R", "GGA": "G",
"UGG": "W", "CGG": "R", "AGG": "R", "GGG": "G"
}
amino_acid_weights = {
"A": 71.03711,
"C": 103.00919,
"D": 115.02694,
"E": 129.04259,
"F": 147.06841,
"G": 57.02146,
"H": 137.05891,
"I": 113.08406,
"K": 128.09496,
"L": 113.08406,
"M": 131.04049,
"N": 114.04293,
"P": 97.05276,
"Q": 128.05858,
"R": 156.10111,
"S": 87.03203,
"T": 101.04768,
"V": 99.06841,
"W": 186.07931,
"Y": 163.06333,
"_": 0,
}
# Just for aesthetics.
def title_screen():
print("""-. .-. .-. .-. .-. .-. .
||\|||\ /|||\|||\ /|||\|||\ /|
|/ \|||\|||/ \|||\|||/ \|||\||
~ `-~ `-` `-~ `-` `-~ `-""")
print("DNA SEQUENCE ANALYZER by Ethan Hetrick\n")
# Lets user choose a custom sequence, generate a random one, or import a FASTA file.
def randomvschoice(retry = 1):
global seq
global description
while retry:
response = input("What would you like to do?\n"
"1. Input your own DNA sequence.\n"
"2. Generate a random DNA sequence.\n"
"3. Import a FASTA file.\n")
if response == '1':
seq = input("Paste your sequence here: \n").upper().replace(' ', '').replace('\n', '')
return seq
elif response == '2':
try:
x = int(input("How many nucleotides long do you want your sequence? Enter an integer.\n"))
seq = ''.join([random.choice(nucleotides) for nuc in range(x)])
return seq
except ValueError:
print("\nInvalid response.\n")
retry += 1
elif response == '3':
try:
seq, description = open_fasta()
return seq, description
except FileNotFoundError:
print("\nFile not found. Please input a valid file path.\n")
retry += 1
else:
print("You must answer 1, 2, or 3.\n")
retry += 1
# Converts the FASTA file into a readable sequence.
def open_fasta():
path = input(r'Input path to the fasta file: ')
with open(path, 'r') as file:
fasta = file.readlines()
seq = fasta[1:]
description = fasta[0]
seq = "".join(seq).replace("\n", "")
return seq, description
# Validates the sequence to make sure it only contains A, C, G, or T.
def validate_seq(dnaseq):
try:
1/len(dnaseq)
for nuc in dnaseq:
if nuc not in nucleotides:
print("Invalid sequence. Only A, C, T, and G are accepted characters.\n")
randomvschoice()
except ZeroDivisionError:
print("Invalid sequence. Only A, C, T, and G are accepted characters.\n")
randomvschoice()
# Counts nucleotides (A, T, G, and C) and gives percentages + total nucleotides.
def nuc_count(dnaseq):
print("\n================================================")
print(f'THE ANALYSIS: {description}\n')
print(f'Total: {len(dnaseq)} nucleotides\n')
print("Nucleotide frequency:")
for letter in nucleotides:
letter_total = dnaseq.count(letter)
letter_per = round(letter_total / len(dnaseq) * 100, 1)
print(letter + ": " + str(letter_total) + " : " + str(letter_per) + "%")
# Converts DNA to cDNA by using the rev_compliment dictionary.
def DNA_to_cDNA1(dnaseq):
dnaseq = "".join([rev_compliment[nuc] for nuc in dnaseq])[::1]
print("\nDNA: " + "5' " + seq + " 3'")
# This is to show the base pairing for shorter sequences as if you run it in a .exe, over 150 nucleotides
# and it looks like a mess if the sequence is more than one line.
if len(seq) <= 150:
print(" " + "|" * len(dnaseq))
print("cDNA: " + "3' " + dnaseq + " 5'")
return ''.join([rev_compliment[nuc] for nuc in dnaseq])[::-1]
# I would like both of these to be one function since this code is redundant. Was not sure how to only access the
# return and not the print statement of DNA_to_cDNA1.
def DNA_to_cDNA(dnaseq):
dnaseq = "".join([rev_compliment[nuc] for nuc in dnaseq])[::1]
return ''.join([rev_compliment[nuc] for nuc in dnaseq])[::-1]
# Converts cDNA to RNA by replacing T with U.
def transcription(dnaseq):
dnaseq = dnaseq.replace("T", "U")
print("RNA: 5' " + str(dnaseq) + " 3'")
return dnaseq
# GC content calculator. Calculates percentages of G+C in the sequence.
def GC_content(dnaseq):
content = round(((dnaseq.count("C") + dnaseq.count("G")) / len(dnaseq)) * 100, 3)
print("GC content: " + str(content) + "%")
# Converts mRNA to protein using the RNA_codon_table.
def translation(dnaseq, init_pos=0):
dnaseq = dnaseq.replace("T", "U")
return [RNA_codon_table[dnaseq[pos:pos + 3]] for pos in range(init_pos, len(dnaseq) - 2, 3)]
# Generates all 6 reading frames from nucleotide positions 0, 1, and 2 from both the DNA and cDNA sequences.
def gen_reading_frames(dnaseq):
global frames
frames.append(translation(dnaseq, 0))
frames.append(translation(dnaseq, 1))
frames.append(translation(dnaseq, 2))
frames.append(translation(DNA_to_cDNA(dnaseq), 0))
frames.append(translation(DNA_to_cDNA(dnaseq), 1))
frames.append(translation(DNA_to_cDNA(dnaseq), 2))
return frames
# Generates a protein from the reading frames.
def prot_from_rf(aa_seq):
prot1 = []
for aa in aa_seq:
if aa == "_":
proteins.extend(prot1)
prot1 = []
else:
if aa == "M":
prot1.append("")
for i in range(len(prot1)):
prot1[i] += aa
return proteins
# This code I took inspiration from a video but seems like too much. It runs the gen_reading_frames function
# and generates all proteins from the 6 reading frames generated. The first statement is to make sure the
# dnaseq is not 0.
def all_proteins_from_rfs(dnaseq, startReadPos=0, endReadPos=0):
if endReadPos > startReadPos:
rfs = gen_reading_frames(dnaseq[startReadPos: endReadPos])
else:
rfs = gen_reading_frames(dnaseq)
all_proteins = []
for rf in rfs:
prots = prot_from_rf(rf)
for p in prots:
all_proteins.append(p)
return all_proteins
# Protein weight calculator. Uses the amino_acid_weights dictionary to calculate the mass of each protein in Daltons.
def protein_weight(protein):
for aa in protein:
weights = (([amino_acid_weights[protein[pos: pos + 1]] for pos in range(0, len(protein))]))
weight = round(sum(weights), 3)
return weight
# This was all the extra code I had to write to make the program present the data in a user-friendly fashion.
# This is the main function I would like to do away with or change.
def stupid():
print("\nThe 6 possible reading frames:")
x = 0
# Numbers and prints the reading frames in a string.
for frame in frames:
x += 1
print(f'{x}. {"".join(frame)}')
print("\nAll possible proteins:")
list = []
# Even more code to get the proteins to print numbered and sorted by length.
for prot in all_proteins_from_rfs(seq):
if prot not in list:
list.append(prot)
list.sort(key=len, reverse=True)
y = 0
for prot in list:
y += 1
print(f'{y}. {prot}: {protein_weight(prot)} Da')
print("================================================\n")
# This is how I run the program. Also probably not optimal.
def run():
randomvschoice()
validate_seq(seq)
nuc_count(seq)
DNA_to_cDNA1(seq)
transcription(seq)
translation(seq)
GC_content(seq)
all_proteins_from_rfs(seq, startReadPos=0, endReadPos=0)
stupid()
run()
title_screen()
run()
</code></pre>
<p>I am a biologist that decided to learn coding and apply it to my field. This is my first project and I would love some feedback. I noticed by my last post that I have some bad coding habits. I was told the mutable global variables was not the most appropriate in this context and I was able to remove some. I have a lot of redundant code and readability issues. Even when I go back through it is hard for me to understand exactly what I wrote. I would like to condense it and clarify it as much as possible as I am planning to add more functions to it and possibly turning it into an application in the future. I simply hate the current structure of my code and it makes it hard for me to keep adding to it in its current state. Any advice will be much appreciated!</p>
|
[] |
[
{
"body": "<h2>Data domain restriction</h2>\n<p>Your <code>nucleotides</code> should be represented as an <code>Enum</code>, given that there are only four possible values. The values of the enum can be strings, but usage in the rest of the program should be through the enum to get more confidence in correctness.</p>\n<h2>External data</h2>\n<p>Your codon table should be externalized, to a CSV or JSON file.</p>\n<h2>Globals</h2>\n<blockquote>\n<p>the mutable global variables was not the most appropriate in this context</p>\n</blockquote>\n<p>Indeed. Constants (nucleotides, rev_compliment, the codon table and the amino acids) are fine as global constants, but the others are problematic. Pull them out of global scope and pass them around as parameters and return values for your various methods.</p>\n<h2>Docstrings</h2>\n<pre><code># Validates the sequence to make sure it only contains A, C, G, or T.\ndef validate_seq(dnaseq):\n</code></pre>\n<p>should actually look more like</p>\n<pre><code>def validate_seq(dnaseq):\n """\n Validates the sequence to make sure it only contains A, C, G, or T.\n """\n</code></pre>\n<p>for a few reasons, including that Python can reflect on that string.</p>\n<h2>Length checking</h2>\n<p>This:</p>\n<pre><code>1/len(dnaseq)\n...\nexcept ZeroDivisionError:\n</code></pre>\n<p>is a nasty way to do a length check. Your error message string is also wrong in that case, because it isn't a matter of invalid characters - the sequence is empty. Instead, spell it out:</p>\n<pre><code>if len(dnaseq) == 0:\n raise ValueError('Empty DNA sequence')\n</code></pre>\n<p>Further, attempt to keep console printing and scanning at the top, so that methods like this can use exceptions, which should consistently be the internal error-signalling mechanism of the application.</p>\n<h2>String interpolation</h2>\n<pre><code> print(letter + ": " + str(letter_total) + " : " + str(letter_per) + "%")\n</code></pre>\n<p>can be</p>\n<pre><code> print(f'{letter}: {letter_total} : {letter_per:%}')\n</code></pre>\n<p>Note that the use of <code>%</code> in this way obviates a multiplication by 100.</p>\n<h2>String formation</h2>\n<p>This:</p>\n<pre><code> dnaseq = "".join([rev_compliment[nuc] for nuc in dnaseq])[::1]\n</code></pre>\n<p>has a few issues:</p>\n<ul>\n<li>Don't make an inner <code>[]</code> list; pass the generator directly to <code>join</code></li>\n<li>The step size of 1 for a slice is the default, so you can omit it and write <code>[:]</code></li>\n<li>But why do a slice at all? Just omit the slice.</li>\n</ul>\n<h2>Console lines</h2>\n<blockquote>\n<p>it looks like a mess if the sequence is more than one line.</p>\n</blockquote>\n<p>Sure, but 150 will be far above the width of some consoles and far below the width of others. Getting the exact width is platform-dependent and can be tricky. Most console applications simply assume that the user is an adult and will be able to pipe through a scrolling frame buffer if they want, and do not do anything special with long lines.</p>\n<h2>Counting</h2>\n<p>This:</p>\n<pre><code>dnaseq.count("C") + dnaseq.count("G")\n</code></pre>\n<p>is not as efficient as making a <code>Counter</code> instance. It's a built-in and will do the counting for both symbols in one pass.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T05:38:23.207",
"Id": "479316",
"Score": "0",
"body": "Thank you! @Reinderien"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T04:03:49.203",
"Id": "244149",
"ParentId": "244141",
"Score": "8"
}
},
{
"body": "<p>The answer from @Reinderien covers a lot of things well. I want to particularly pick up on the Global Variables aspect as I think it's the single part that will help you to improve your code the most.</p>\n<p>You seem to have down the idea that functions take an input and that you can get an output from them using <code>return</code>, but you don't seem to use that output in the <code>run</code> function. Giving the intermediate variables name would also make it easier to work out what stage you were at.\ne.g.</p>\n<pre><code>def run(): \n ...\n c_dna_seq = DNA_to_cDNA(seq)\n rna_seq = transcription(c_dna_seq)\n ...\n</code></pre>\n<p>Another thing that I would recommend for readability is using verbs for function names rather than nouns. e.g. <code>convert_dna_to_cdna()</code> or <code>transcribe(seq)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:35:42.943",
"Id": "244180",
"ParentId": "244141",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244149",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:06:10.780",
"Id": "244141",
"Score": "9",
"Tags": [
"python"
],
"Title": "Looking for feedback on my DNA analyzer program that reads FASTA and generates cDNA, RNA, reading frames, and codons"
}
|
244141
|
<p>I've made a very simple tile editor. I'd like for someone to review my code and tell me what I could improve on. For example I'm bad at input management and creating systems that work nicely. Say I want to add a way to pick what file it saves to by typing in the file path after a keypress. How do I stop my program from doing other stuff currently associated with those key presses. Right now my code just seems like a mess and the more features I add the more messy it becomes.
<a href="https://github.com/MonkeyToiletLadder/tile/tree/master/game" rel="nofollow noreferrer">https://github.com/MonkeyToiletLadder/tile/tree/master/game</a></p>
<pre><code>require "player"
require "map"
require "view"
windowWidth, windowHeight, flags = love.window.getMode()
windowWidthHalf = windowWidth / 2
windowHeightHalf = windowHeight / 2
atlas = love.graphics.newImage("dungeon_sheet.png")
quad = love.graphics.newQuad(0,0,16,16,atlas:getDimensions())
map = Map(atlas,16,16,20,20)
player = Player(0,0,100,0)
camera = Camera(0,0,player)
view = View(atlas,0,0,200,200)
updatable = {}
table.insert(updatable,player)
table.insert(updatable,camera)
table.insert(updatable,view)
drawable = {}
-- table.insert(drawable,player
table.insert(drawable,map)
currentTile = 54
function love.update(dt)
if love.keyboard.isDown("s") then
map:save("save.txt")
end
if love.keyboard.isDown("l") then
map:load("save.txt")
end
if love.keyboard.isDown("k") then
atlas = love.graphics.newImage("dungeon_sheet.png")
view.image = atlas
end
if love.keyboard.isDown("c") then
map:clear()
end
-- Place tile
if love.mouse.isDown(1) then
mx,my = love.mouse.getPosition()
wx = math.floor((camera.x + mx - windowWidthHalf) / map.tw) + 1
wy = math.floor((camera.y + my - windowHeightHalf) / map.th) + 1
if wx >= 1 and wx < map.width + 1 and wy >= 1 and wy < map.height + 1 then
map:add(wx,wy,currentTile)
end
-- Remove tile
elseif love.mouse.isDown(2) then
mx,my = love.mouse.getPosition()
wx = math.floor((camera.x + mx - windowWidthHalf) / map.tw) + 1
wy = math.floor((camera.y + my - windowHeightHalf) / map.th) + 1
if wx >= 1 and wx < map.width + 1 and wy >= 1 and wy < map.height + 1 then
map:remove(wx,wy,currentTile)
end
end
-- Pick tile
if view.selected then
if love.mouse.isDown(1) then
mx, my = love.mouse.getPosition()
if mx > view.x and mx < view.x + view.image:getWidth() and my > view.y and my < view.y + view.image:getHeight() then
tx = math.floor((mx + view.grip.x) / map.tw)
ty = math.floor((my + view.grip.y) / map.th)
id = tx + ty * map.sw
currentTile = id
end
end
end
for _,v in ipairs(updatable) do
v:update(dt)
end
end
function love.draw()
-- Canvas Draws
love.graphics.push()
love.graphics.translate(windowWidthHalf,windowHeightHalf)
for _,v in ipairs(drawable) do
v:draw(camera)
end
love.graphics.pop()
view:draw()
-- Tile selection
local x = currentTile % map.sw * map.tw - view.grip.x
local y = math.floor(currentTile / map.sw) * map.th - view.grip.y
if x < view.x + view.width and y < view.y + view.height then
love.graphics.rectangle("line",x,y,map.tw,map.th)
end
end
function love.wheelmoved(x,y)
currentTile = currentTile + y
if currentTile < 0 then currentTile = 0 end
if currentTile > map.sw * map.sh - 1 then currentTile = map.sw * map.sh - 1 end
end
</code></pre>
<p>Map</p>
<pre><code>class = require "clasp"
Map = class {
init = function(self,atlas,tw,th,mw,mh)
self.atlas = atlas
self.data = {}
self.width = mw
self.height = mh
self.size = self.width * self.height
self.tw = tw
self.th = th
local sw,sh = self.atlas:getDimensions()
self.sw = sw / self.tw
self.sh = sh / self.th
for i=1,self.height do
self.data[i] = {}
for j=1,self.width do
self.data[i][j] = -1
end
end
self.quad = love.graphics.newQuad(0,0,self.tw,self.th,self.sw,self.sh)
end,
draw = function(self,camera)
love.graphics.rectangle("line",0-camera.x,0-camera.y,self.width*self.tw,self.height*self.th)
for i=1,#self.data do
for j=1,#self.data[i] do
local id = self.data[i][j]
if id ~= -1 then
local x = id % self.sw * self.tw
local y = math.floor(id/self.sw) * self.th
self.quad:setViewport(x,y,self.tw,self.th,self.atlas:getDimensions())
love.graphics.draw(atlas,self.quad,math.floor((j-1)*self.tw - camera.x),math.floor((i-1)*self.th - camera.y))
end
end
end
end,
add = function(self,x,y,id)
self.data[y][x] = id
end,
remove = function(self,x,y)
self.data[y][x] = -1
end,
save = function(self,path)
local file = assert(io.open(path,"w"))
io.output(file)
io.write("return {")
for i=1,#self.data do
io.write("{")
for j=1,#self.data[i] do
local id = self.data[i][j]
io.write(id..",")
end
io.write("},")
end
io.write("}")
io.close(file)
end,
load = function(self,path)
if file_exists(path) then
self.data = dofile(path)
end
end,
clear = function(self)
for i=1,self.height do
self.data[i] = {}
for j=1,self.width do
self.data[i][j] = -1
end
end
end
}
</code></pre>
<p>view</p>
<pre><code>class = require "clasp"
require "scrollbar"
require "utils"
View = class {
init = function(self,image,x,y,width,height)
self.image = image
self.x = x
self.y = y
self.width = width
self.height = height
self.quad = love.graphics.newQuad(0,0,self.width,self.height,self.image:getDimensions())
self.selected = false
self.grip = {}
self.grip.x = 0
self.grip.y = 0
-- self.scrollbar = Scrollbar()
end,
draw = function(self)
self.quad:setViewport(self.grip.x,self.grip.y,self.width,self.height,self.image:getDimensions())
love.graphics.draw(self.image,self.quad,self.x,self.y)
love.graphics.rectangle("line",self.x,self.y,self.width,self.height)
end,
update = function(self,dt)
if love.mouse.isDown(1) then
mx, my = love.mouse:getPosition()
if isPointInRect(mx,my,self.x,self.y,self.width,self.height) then
self.selected = true
else
self.selected = false
end
end
if self.selected then
if love.keyboard.isDown("up") then
self.grip.y = self.grip.y - 64 * dt
elseif love.keyboard.isDown("left") then
self.grip.x = self.grip.x - 64 * dt
elseif love.keyboard.isDown("down") then
self.grip.y = self.grip.y + 64 * dt
elseif love.keyboard.isDown("right") then
self.grip.x = self.grip.x + 64 * dt
end
if self.grip.x < 0 then self.grip.x = 0 end
if self.grip.x + self.width > self.image:getWidth() then
if self.image:getWidth() - self.width < 0 then
self.grip.x = 0
else
self.grip.x = self.image:getWidth() - self.width
end
end
if self.grip.y < 0 then self.grip.y = 0 end
if self.grip.y + self.height > self.image:getHeight() then
if self.image:getHeight() - self.height < 0 then
self.grip.y = 0
else
self.grip.y = self.image:getHeight() - self.height
end
end
end
end
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:32:15.923",
"Id": "479297",
"Score": "0",
"body": "Maybe you missed the text on the right side when asking: \"_Your question must contain code that is already working correctly, and **the relevant code sections must be embedded in the question**._\" Questions must [include the code to be reviewed](https://codereview.meta.stackexchange.com/a/3653/120114). Links to code hosted on third-party sites are permissible, but the most relevant excerpts must be embedded in the question itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T07:12:55.050",
"Id": "479318",
"Score": "0",
"body": "(Looks like a plan was needed: 1) pin down what to achieve 2) how to test you succeeded 3) code the tests 4) start the code with just the comments and heads of what to achieve 5) run the tests 6) code until the tests pass 7) resist featurism)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:09:01.953",
"Id": "244142",
"Score": "2",
"Tags": [
"lua"
],
"Title": "Tile editor with increasing number of features"
}
|
244142
|
<p>I'm posting my C++ code for LeetCode's <a href="https://leetcode.com/problems/evaluate-division/" rel="nofollow noreferrer">Evaluate Division</a>. If you have time and would like to review, please do so. Thank you!</p>
<h3>Problem</h3>
<blockquote>
<p>Equations are given in the format A / B = k, where A and B are
variables represented as strings, and k is a real number (floating
point number). Given some queries, return the answers. If the answer
does not exist, return -1.0.</p>
<p>Example: Given a / b = 2.0, b / c = 3.0. queries are: a / c = ?, b / a
= ?, a / e = ?, a / a = ?, x / x = ? . return [6.0, 0.5, -1.0, 1.0, -1.0 ].</p>
<p>The input is: vector<pair<string, string>> equations, vector&
values, vector<pair<string, string>> queries , where equations.size()
== values.size(), and the values are positive. This represents the equations. Return vector.</p>
<p>According to the example above:</p>
<p>equations = [ ["a", "b"], ["b", "c"] ], values = [2.0, 3.0], queries =
[ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].</p>
<p>The input is always valid. You may assume that evaluating the queries
will result in no division by zero and there is no contradiction.</p>
</blockquote>
<h3>Accepted C++</h3>
<pre><code>class Solution {
public:
std::vector<double> calcEquation(std::vector<vector<string>> equations, std::vector<double> values, std::vector<vector<string>> const& queries) {
generate_graph(equations, values);
std::vector<double> evaluates;
for (auto& query : queries) {
std::set<string> visited;
double accumulated = 1.0;
bool evaluate = solve_equation(query[0], query[1], accumulated, visited);
if (evaluate) {
evaluates.push_back(accumulated);
} else {
evaluates.push_back(-1);
}
}
return evaluates;
}
protected:
struct Node {
Node(std::string const parameter, double const evaluate) {
this -> parameter = parameter;
this -> evaluate = evaluate;
}
std::string parameter;
double evaluate;
};
map<string, vector<Node>> graph;
void generate_graph(std::vector<vector<string>>& equations, std::vector<double>& values) {
for (auto const& equation : equations) {
vector<Node> children;
graph[equation[0]] = children;
}
for (int equation = 0; equation < equations.size(); equation++) {
Node node(equations[equation][1], values[equation]);
graph[equations[equation][0]].push_back(node);
Node node_reverse(equations[equation][0], 1 / values[equation]);
graph[equations[equation][1]].push_back(node_reverse);
}
}
bool solve_equation(std::string const nominator, std::string const denominator, double& accumulated, std::set<string>& visited) {
if (nominator == denominator && graph.find(nominator) != graph.end()) {
return true;
}
if (graph.find(nominator) == graph.end() || graph.find(denominator) == graph.end()) {
return false;
}
visited.insert(nominator);
for (auto& child : graph[nominator]) {
if (visited.find(child.parameter) == visited.end()) {
accumulated *= child.evaluate;
if (child.parameter == denominator) {
return true;
}
if (solve_equation(child.parameter, denominator, accumulated, visited)) {
return true;
} else {
accumulated /= child.evaluate;
}
}
}
return false;
}
};
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is an instance usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename those.</p>
<ul>
<li><a href="https://leetcode.com/problems/evaluate-division/" rel="nofollow noreferrer">Question</a></li>
<li><a href="https://leetcode.com/problems/evaluate-division/discuss/" rel="nofollow noreferrer">Discussion</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T11:48:17.633",
"Id": "479344",
"Score": "1",
"body": "Could you maybe put comments on some places in the code? It's not so obvious why it works, at least to me. Especially the different if-cases in the for-loop in solve_equation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:14:45.973",
"Id": "479374",
"Score": "1",
"body": "@Emma: I agree somewhat with Mikael, assuming that the tricky part he's talking about is the rewriting of the problem from \"solve these math equations\" to \"do a depth-first search on a graph.\" Your _implementation_ of the graph algorithm seems appropriate to me, but it's \"not obvious why it works\" to solve the original problem about solving a collection of simultaneous equations. (Related: Hypothetically, if you had accidentally omitted the bit about `node_reverse`, would the bug have been \"obvious\"?)"
}
] |
[
{
"body": "<p>Seems basically reasonable. Some English nits: You said "nominator and denominator," when the English terms are "<strong>numerator</strong> and denominator." You also seem to be using the word "evaluate(s)" as a noun (something like "precipitate" in chemistry), when I think the word you meant was more like "value(s)."</p>\n<hr />\n<pre><code>struct Node {\n Node(std::string const parameter, double const evaluate) {\n this -> parameter = parameter;\n this -> evaluate = evaluate;\n }\n\n std::string parameter;\n double evaluate;\n};\n</code></pre>\n<p>Write <code>this->x</code>, not <code>this -> x</code>, for the same reason you write <code>st.x</code> and not <code>st . x</code>. But in fact, this constructor would be better written as either</p>\n<pre><code>struct Node {\n explicit Node(const std::string& p, double v) : parameter(p), value(v) {}\n std::string parameter;\n double value;\n};\n</code></pre>\n<p>or simply</p>\n<pre><code>struct Node {\n std::string parameter;\n double value;\n};\n</code></pre>\n<p>since simple aggregates can already be initialized with e.g. <code>Node{"a", 2}</code>. Notice that I'm passing <code>std::string</code> by const reference, because it is expensive to copy.</p>\n<p>You <em>could</em> actually rewrite all of the helper functions and data structures to use C++17 <code>std::string_view</code> instead of <code>std::string</code>, as long as all the stringviews referred to the original long-lived strings from <code>equations</code> and <code>queries</code> which you are appropriately careful not to modify. This would be an "advanced" idea, though, and probably wouldn't even buy you any speed in this case where all your strings seem to be 1 character long.</p>\n<hr />\n<p><code>for (auto& query : queries)</code> — Use <code>for (const auto& query : queries)</code> to indicate that the const-qualification is on purpose; or <a href=\"https://quuxplusone.github.io/blog/2018/12/15/autorefref-always-works/\" rel=\"nofollow noreferrer\">use <code>auto&&</code> in generic code if you just want something that always works</a>. I don't see any reason to use specifically <code>auto&</code> to get a specifically const-qualified result.</p>\n<hr />\n<pre><code> if (visited.find(child.parameter) == visited.end()) {\n accumulated *= child.evaluate;\n\n if (child.parameter == denominator) {\n return true;\n }\n\n if (solve_equation(child.parameter, denominator, accumulated, visited)) {\n return true;\n\n } else {\n accumulated /= child.evaluate;\n }\n }\n</code></pre>\n<p>This if-else ladder is indeed confusing. I would write it like this:</p>\n<pre><code> if (visited.find(child.parameter) != visited.end()) {\n // we have already visited this node; skip it\n } else if (child.parameter == denominator) {\n // we've reached our destination node and resolved the query\n accumulated *= child.value;\n return true;\n } else if (solve_equation(child.parameter, denominator, accumulated, visited)) {\n // this node is on a path that resolves the query\n accumulated *= child.value;\n return true;\n } else {\n // this node is not involved in the solution; do nothing\n }\n</code></pre>\n<p>The most confusing part of the original ladder was</p>\n<pre><code> } else {\n accumulated /= child.evaluate;\n }\n</code></pre>\n<p>That line is really just undoing the multiplication hidden at the top of the loop. But the multiplication is <em>done</em> one scope higher than it is <em>undone</em>, which violates most programmers' intuition. It would have been a simple fix to write</p>\n<pre><code> if (visited.find(child.parameter) == visited.end()) {\n accumulated *= child.evaluate;\n if (child.parameter == denominator) {\n return true;\n }\n if (solve_equation(child.parameter, denominator, accumulated, visited)) {\n return true;\n }\n accumulated /= child.evaluate;\n }\n</code></pre>\n<p>thus visually indicating the symmetry between <code>*=</code> and <code>/=</code>.</p>\n<hr />\n<pre><code>bool solve_equation(std::string const nominator,\n std::string const denominator, double& accumulated,\n std::set<string>& visited)\n</code></pre>\n<p>Consider whether <code>visited</code> should be a data member of <code>class Solution</code>.</p>\n<p>Passing by const value is always a bug; you left off the <code>&</code>. If you used west const style, you could use these <code>git grep</code> lines to find such bugs: <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\">https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/</a></p>\n<p>Consider whether the return type of this function should be <code>std::pair<bool, double></code>; or, in C++17, <code>std::optional<double></code>.</p>\n<p>Put it all together and you get a C++14 signature like</p>\n<pre><code>std::pair<bool, double> solve_equation(const std::string& numerator,\n const std::string& denominator);\n</code></pre>\n<p>or a C++17 signature like</p>\n<pre><code>std::optional<double> solve_equation(std::string_view numerator,\n std::string_view denominator);\n</code></pre>\n<hr />\n<p>You have methods named both <code>calcEquation</code> and <code>solve_equation</code>. Admittedly, the name <code>calcEquation</code> is just flat wrong; it should be something like <code>solve_equations</code> (plural). But, given that you aren't allowed to change the public name, personally I would go with <code>calcEquation</code> and <code>calcSingleEquation</code> — reusing the same verb instead of a near-synonym, and emphasizing that this function calculates for a <em>single</em> equation, since I don't have the option of adding an <code>s</code> to pluralize the public name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T15:03:54.043",
"Id": "244173",
"ParentId": "244145",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244173",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-18T23:49:23.000",
"Id": "244145",
"Score": "1",
"Tags": [
"performance",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 399: Evaluate Division"
}
|
244145
|
<p>I'm really new to OpenCV. :) I have been working on this for almost an entire day. After hours of sleepless work I would like to know if I can further improve my code.</p>
<p>I have written some code to <strong>select only the black markings</strong> on <a href="https://drive.google.com/drive/folders/1WCLpx7HbmzR5zmVocIvWAbaCVl16v9P1?usp=sharing" rel="nofollow noreferrer">the images</a>. These black markings are child contours. Whilst my code is able to select some contours, it isn't accurate. You can see the code <em>draws contours around the shadows</em> along with black markings.</p>
<p><strong>Code 1</strong></p>
<p>At first I tried to use canny edge detection. But I was unable to overlay with the original image correctly.</p>
<pre><code>import cv2
import numpy as np
image = cv2.imread('3.jpg')
image = cv2.resize(image, (500, 500))
image2 = image
cv2.waitKey(0)
# Grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find Canny edges
edged = cv2.Canny(gray, 30, 200)
cv2.waitKey(0)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.imshow('Canny', edged)
cv2.waitKey(0)
# print("Number of Contours found = " + str(len(contours)))
cv2.drawContours(image2, contours, -1, (0, 255, 0), 3)
cv2.imshow('Contours', image2)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p><a href="https://i.stack.imgur.com/y74oO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y74oO.png" alt="The original image and contours" /></a></p>
<p><strong>Code 2</strong></p>
<p>I was able to improve on Code 1 to be far more accurate. You should be able to see that it now only selects half of the thumb, none of the other fingers and it doesn't select the indent on the background.<br />
Additionally changing the background of the image also increases the accuracy of the result.</p>
<pre><code>import cv2
import numpy as np
image = cv2.imread('3.jpg', 0)
image2 = cv2.imread('3.jpg')
image = cv2.resize(image, (500, 500))
image2 = cv2.resize(image2, (500, 500))
cv2.waitKey(0)
ret, thresh_basic = cv2.threshold(image, 100, 255, cv2.THRESH_BINARY)
cv2.imshow("Thresh basic", thresh_basic)
# Taking a matrix of size 5 as the kernel
kernel = np.ones((5, 5), np.uint8)
img_erosion = cv2.erode(thresh_basic, kernel, iterations=1)
#####################
ret, thresh_inv = cv2.threshold(img_erosion, 100, 255, cv2.THRESH_BINARY_INV)
cv2.imshow("INV", thresh_inv)
#####################
# Find Canny edges
edged = cv2.Canny(img_erosion, 30, 200)
cv2.waitKey(0)
contours, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.imshow('Canny', edged)
cv2.waitKey(0)
# print("Number of Contours found = " + str(len(contours)))
cv2.imshow('Original', image2)
cv2.drawContours(image2, contours, -1, (0, 255, 0), 3)
cv2.imshow('Contours', image2)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code></pre>
<p><a href="https://i.stack.imgur.com/fEMth.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fEMth.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/DMP3a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DMP3a.png" alt="enter image description here" /></a></p>
<p>Can I improve my code further?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T04:56:26.317",
"Id": "479311",
"Score": "0",
"body": "That's not an easy picture to work with. Have you tried making a hogh-contrast version of it to assist in the contour detection? Check for contours in both, see the differences."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T05:31:05.443",
"Id": "479314",
"Score": "0",
"body": "@Mast, I've decided to change the background color."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T15:56:44.310",
"Id": "479361",
"Score": "0",
"body": "Keep in mind that general review is on-topic here, but issues of accuracy improvement will not be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:49:30.370",
"Id": "479395",
"Score": "0",
"body": "@Reinderien Whilst you would normally be correct. [We have long classed ML accuracy to be similar to performance, TLE or memory optimization](https://codereview.meta.stackexchange.com/q/2331)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:51:44.223",
"Id": "479396",
"Score": "0",
"body": "I see. Framing this as \"algorithmic performance\" makes the distinction easier for me to understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:44:58.827",
"Id": "479405",
"Score": "1",
"body": "@Reinderien No problem. This section of our rules can be rather confusing. :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T04:28:50.167",
"Id": "244151",
"Score": "5",
"Tags": [
"python",
"algorithm",
"python-3.x",
"opencv",
"object-detection"
],
"Title": "Selecting child contours in OpenCV"
}
|
244151
|
<p>Here are my class library code which create credit card.</p>
<pre><code>public abstract class CreditCard
{
public CardType CardType { get; protected set; }
public decimal CreditLimit { get; protected set; }
public decimal AnnualCharge { get; protected set; }
}
public class GoldCreditCard : CreditCard
{
private GoldCreditCard(decimal creditLimit, decimal annualCharge)
{
CardType = CardType.Gold;
CreditLimit = creditLimit;
AnnualCharge = annualCharge;
}
/// <summary>
/// Factory pattern
/// </summary>
/// <returns></returns>
public static CreditCard Create()
{
return new GoldCreditCard(creditLimit: 15000, annualCharge: 100);
}
}
public class TitaniumCreditCard : CreditCard
{
private TitaniumCreditCard(decimal creditLimit, decimal annualCharge)
{
CardType = CardType.Titanium;
CreditLimit = creditLimit;
AnnualCharge = annualCharge;
}
/// <summary>
/// Factory pattern
/// </summary>
/// <returns></returns>
public static CreditCard Create()
{
return new TitaniumCreditCard(creditLimit: 30000, annualCharge: 250);
}
}
</code></pre>
<p>and the ui will be:</p>
<pre><code> static void Main(string[] args)
{
CreditCard card;
System.Console.WriteLine("Select your card type");
System.Console.WriteLine("1. Gold Credit Card");
System.Console.WriteLine("2. Titanium Credit Card");
var option = System.Console.ReadLine();
switch (option)
{
case "1":
card = GoldCreditCard.Create();
PrintCard(card);
break;
case "2":
card = TitaniumCreditCard.Create();
PrintCard(card);
break;
default:
break;
}
}
static void PrintCard(CreditCard card)
{
System.Console.WriteLine($"Your credit card has been successfully created.");
System.Console.WriteLine($"The credit card type is {card.CardType}.");
System.Console.WriteLine($"The credit card limit is {card.CreditLimit:C}.");
System.Console.WriteLine($"The credit card annual fee is {card.AnnualCharge:C}.");
}
</code></pre>
<p>Is this implementation of factory design pattern in C#?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T09:22:23.493",
"Id": "479331",
"Score": "1",
"body": "Subclasses are not ment to be used like this. In your example both implemnetations are identical with only the data being different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T09:24:33.650",
"Id": "479332",
"Score": "2",
"body": "In a normal usecase these are stored in a credit card type table or nosql data type. Than you set which credit card type a instance has. Thats the naive way, you probably need to make that data periodic since mulrtiple versions of the card can exists at the same time with different bonuses, fees etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:34:05.650",
"Id": "479415",
"Score": "1",
"body": "\"State what your code does in your title, not your main concerns about it.\" https://codereview.stackexchange.com/help/how-to-ask"
}
] |
[
{
"body": "<p>In your implementation you have smashed together two separate roles: <strong>Product</strong> and <strong>Creator</strong>.</p>\n<p>Your implementation is equivalent with the following:</p>\n<pre><code>public class GoldCreditCard : CreditCard\n{\n private GoldCreditCard(decimal creditLimit, decimal annualCharge)\n {\n CardType = CardType.Gold;\n CreditLimit = creditLimit;\n AnnualCharge = annualCharge;\n }\n\n public GoldCreditCard()\n {\n CardType = CardType.Gold;\n CreditLimit = 15000; \n AnnualCharge = 100;\n }\n}\n</code></pre>\n<p>Or almost with this one (this provides more flexibility):</p>\n<pre><code>public class GoldCreditCard : CreditCard\n{\n public GoldCreditCard(decimal creditLimit = 15000, decimal annualCharge = 100)\n {\n CardType = CardType.Gold;\n CreditLimit = creditLimit;\n AnnualCharge = annualCharge;\n }\n}\n</code></pre>\n<p>The whole point of the pattern is that only the Creator (Factory) knows how to setup a concrete product. In your case your class knows how to initialize itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T13:46:06.857",
"Id": "244166",
"ParentId": "244153",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:06:36.947",
"Id": "244153",
"Score": "0",
"Tags": [
"c#",
"design-patterns",
"factory-method"
],
"Title": "Is this implementation of factory design pattern in C#?"
}
|
244153
|
<p>I have an api end point which returns the paginated result, the corresponding code for that is as below:</p>
<pre><code>public Task<PaginatedDataResult<ProductSearchResult>> GetPaginatedSearchAsync(int currentPage,
int perPage,
string nameFilter,
string sortBy,
bool sortDesc,
CancellationToken cancellationToken = default)
{
IEnumerable<Expression<Func<Product, bool>>> GetFilters()
{
if (!string.IsNullOrEmpty(nameFilter))
{
var normalizedNameFilter = nameFilter.NormalizeUpper();
yield return p => p.NormalizedName.Contains(normalizedNameFilter);
}
}
Expression<Func<Product, ProductSearchResult>> projectionExpression =
p => new ProductSearchResult
{
Id = p.Id,
Name = p.Name,
EndDate = p.EndDate,
IsActive = p.IsActive,
ServicesCount = p.ProductServices.Count
};
return PaginatedFilterWithProjectionAsync(currentPage, perPage, sortBy, sortDesc, cancellationToken, projectionExpression, GetFilters().ToArray());
}
protected async Task<PaginatedDataResult<TProjectedEntity>>
PaginatedFilterWithProjectionAsync<TProjectedEntity>(int currentPage,
int perPage,
string sortBy,
bool sortDesc,
CancellationToken cancellationToken,
Expression<Func<TEntity, TProjectedEntity>> projectionExpression,
params Expression<Func<TEntity, bool>>[] filters
) where TProjectedEntity : class
{
var query = filters.Aggregate(DbSet.AsQueryable(), (q, f) => q.Where(f));
var queryWithProjection = query.Select(projectionExpression);
if (!string.IsNullOrEmpty(sortBy))
{
queryWithProjection = sortDesc
? queryWithProjection.OrderByDescending(sortBy)
: queryWithProjection.OrderBy(sortBy);
}
var filteredQueryOfProjectedEntity = queryWithProjection
.Skip((currentPage - 1) * perPage)
.Take(perPage);
var filteredListOfProjectedEntity = await filteredQueryOfProjectedEntity.ToListAsync(cancellationToken);
var count = await queryWithProjection.CountAsync(cancellationToken);
return new PaginatedDataResult<TProjectedEntity>
{
PerPage = perPage,
CurrentPage = currentPage,
TotalCount = count,
Data = filteredListOfProjectedEntity
};
}
</code></pre>
<p>Now, I have another end point which is returning a complete collection as below</p>
<pre><code> public async Task<ICollection<ProductRelationship>> GetAllByRelationshipDataAsync(
bool includeDetail,
bool filterActiveProduct = false,
DateTime? filterActiveRelationshipDate = null,
CancellationToken cancellationToken = default)
{
var set = includeDetail ? IncludeDetail(DbSet) : DbSet;
//I have removed few parameters from the method and also few if conditions for brevity
if (filterActiveProduct)
{
set = set.Where(x => x.Product != null && x.Product.IsActive);
}
if (filterActiveRelationshipDate.HasValue)
{
var filterDate = filterActiveRelationshipDate.Value.Date;
set = set.Where(x => x.StartDate <= filterDate && (!x.EndDate.HasValue || x.EndDate.Value >= filterDate));
}
return await set.ToListAsync(cancellationToken);
}
</code></pre>
<p>The requirement is to change the above method to return a paginated result, so the changes I did are as below:</p>
<ol>
<li><p>change the method signature to add four additional parameters (currentPage, perPage, sortBy, sortDesc)</p>
</li>
<li><p>Rather than returning a collection, calling a PaginatedAsync method to return paginated result</p>
<pre><code> public async Task<PaginatedDataResult<ProductRelationship>> GetAllByRelationshipDataAsyncTest(
bool includeDetail,
int currentPage,
int perPage,
string sortBy,
bool sortDesc,
bool filterActiveProduct = false,
DateTime? filterActiveRelationshipDate = null,
CancellationToken cancellationToken = default)
{
var set = includeDetail ? IncludeDetail(DbSet) : DbSet;
//I have removed few parameters from the method and also few if conditions for brevity
if (filterActiveProduct)
{
set = set.Where(x => x.Product != null && x.Product.IsActive);
}
if (filterActiveRelationshipDate.HasValue)
{
var filterDate = filterActiveRelationshipDate.Value.Date;
set = set.Where(x => x.StartDate <= filterDate && (!x.EndDate.HasValue || x.EndDate.Value >= filterDate));
}
return await PaginatedAsync(set, currentPage, perPage, sortBy, sortDesc, cancellationToken);
}
</code></pre>
<ol start="3">
<li><p>PaginatedAsync method is the same copy of PaginatedFilterWithProjectionAsync method above but without the variables query and queryWithProjection, since I have got the queryWithProjection value in the variable set above.<br />
I could also refactor the PaginatedFilterWithProjectionAsync method to include PaginatedAsync as most of the code is same, but that was already in use, that adds more testing effort. May be I am breaking open closed principle</p>
<pre><code>protected async Task<PaginatedDataResult<TProjectedEntity>> PaginatedAsync<TProjectedEntity>(IQueryable<TProjectedEntity> queryWithProjection, int currentPage,
int perPage,
string sortBy,
bool sortDesc,
CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(sortBy))
{
queryWithProjection = sortDesc
? queryWithProjection.OrderByDescending(sortBy)
: queryWithProjection.OrderBy(sortBy);
}
var filteredQueryOfProjectedEntity = queryWithProjection
.Skip((currentPage - 1) * perPage)
.Take(perPage);
var filteredListOfProjectedEntity = await filteredQueryOfProjectedEntity.ToListAsync(cancellationToken);
var count = await queryWithProjection.CountAsync(cancellationToken);
return new PaginatedDataResult<TProjectedEntity>
{
PerPage = perPage,
CurrentPage = currentPage,
TotalCount = count,
Data = filteredListOfProjectedEntity
};
}
</code></pre>
</li>
</ol>
</li>
</ol>
<p>Please can anyone review and provide me with suggestions for better approach and point me the mistakes in the above code.</p>
|
[] |
[
{
"body": "<p>Some quick remarks:</p>\n<ul>\n<li><p>There are almost 90 white-space characters before I can see the arguments to <code>GetPaginatedSearchAsync</code>. In such cases, move the parameters to the next line.</p>\n</li>\n<li><p>Consider renaming <code>PaginatedDataResult</code> and <code>ProductSearchResult</code> (is the "Result" part of the name necessary?), and even <code>GetPaginatedSearchAsync</code> (is there a non-async method? if not, then why add this to the method name?).</p>\n</li>\n<li><p><code>GetPaginatedSearchAsync</code> has six parameters: that is bordering on the limit, and I'd advise you to pass a custom class instead. You could at least group the pagination-related parameters into their own class.</p>\n</li>\n<li><p>Do not pointlessly abbreviate names. I get what <code>sortDesc</code> means but it still is jarring to read.</p>\n</li>\n<li><p>Judging by <code>//I have removed few parameters from the method and also few if conditions for brevity</code> it seems you realized the amount of parameters grew too large and impacted readability. Consider moving all of the filter-related parameters into a class of their own and pass that class instead of an ever-growing and thus hard to maintain list.</p>\n</li>\n<li><p>IMHO you should avoid pointlessly detailed variable names like <code>filteredQueryOfProjectedEntity</code> and <code>filteredListOfProjectedEntity</code>, and even <code>queryWithProjection</code> (why assign <code>query</code> only to immediately apply <code>Select</code> to it on the next line and then never use it again? why not combine these two lines and simply use <code>query</code> instead of <code>queryWithProjection</code>?). These make your code hard to read. Instead, I'd expect these names to convey more of a concept.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T23:00:35.033",
"Id": "244204",
"ParentId": "244157",
"Score": "1"
}
},
{
"body": "<p>One main remark: the paging method is too busy. The number of arguments is a tell-tale. The parts that don't belong there are filtering and sorting.</p>\n<p>In general, a method returning any paged result, should only receive an <code>IQueryable</code> and the paging instructions page number and page size. Your second method is almost there. After removing the superfluous responsibilities, what's left is:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>protected async Task<PaginatedDataResult<TEntity>> PaginateAsync<TEntity>(\n IQueryable<TEntity> query, int pageNumber, int pageSize,\n CancellationToken cancellationToken)\n{\n var pageQuery = query\n .Skip((pageNumber - 1) * pageSize)\n .Take(pageSize);\n\n var page = await pageQuery.ToListAsync(cancellationToken);\n\n var count = await query.CountAsync(cancellationToken);\n\n return new PaginatedDataResult<TEntity>\n {\n PerPage = pageSize,\n CurrentPage = pageNumber,\n TotalCount = count,\n Data = page\n };\n}\n</code></pre>\n<p>Now you have a method that you can offer any <code>IQueryable</code>. It doesn't need to know if it's a <code>DbSet</code> or a projection, or filtered, or ordered. The count of the query is independent of all these details. [In fact, when using Entity Framework, you won't even see the projection in the generated SQL count query)].</p>\n<p>This makes each method that calls <code>PaginateAsync</code> responsible for composing the <code>IQueryable</code> they want to have paged. And —the main point— now it's possible to have a method that just returns the <code>IQueryable</code> and another method that takes this <code>IQueryable</code> and returns a page.</p>\n<p>So, you'll just keep <code>GetAllByRelationshipDataAsync</code>, which I would at least shorten to <code>GetAllByRelationshipAsync</code>, and add a method <code>GetAllByRelationshipPagedAsync</code> that looks like your <code>GetAllByRelationshipDataAsyncTest</code> method, but now internally just executes\n<code>GetAllByRelationshipAsync</code> and <code>PaginateAsync</code>.</p>\n<p>Likewise, <code>GetPaginatedSearchAsync</code> should be changed to contain the filtering and ordering parts, so it will be able to call <code>PaginateAsync</code> as well.</p>\n<p>Of course, if you want, you can create separate methods that execute filtering and/or ordering.</p>\n<p>Now it's even possible to have a service layer that's just bothered with composing queries and doesn't even contain any paging logic. The paging method could be part of the controller layer only.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T19:52:25.790",
"Id": "244239",
"ParentId": "244157",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T09:25:20.927",
"Id": "244157",
"Score": "4",
"Tags": [
"c#",
"entity-framework",
"asp.net-core",
"asp.net-core-webapi"
],
"Title": "pagination in entity framework and refactoring"
}
|
244157
|
<p>I made this random password script. It works, but i think it is kind of bloated. The part where random characters are being added is the area where I think it needs work. I don't want to declare if and else statement for every combination of lowercase list, uppercase list and digits list(I am taking input from user whether they want uppercase,lowercase,digits or any possible combination of these three). Is there any possible way in which I can just check which of these three values are yes and then just use only those.
<br><br/> Also what is more efficient using <strong>lower()</strong> to turn the list called using string module into lower case or just calling the lowercase list itself.</p>
<pre><code>import random
from string import ascii_letters ,digits
while True:
userchoice_size = int(input("Enter the length of the password : ")) # Asks for length of password
userchoice_syntax_lower = input("Do you want lower case letter?(y or n) ")
userchoice_syntax_upper = input("Do you want upper case letter?(y or n) ")
userchoice_syntax_number = input("Do you want numbers?(y or n) ")
counter=0
password='' # String which stores the password
choice_list=[1,2,3]
while counter <= userchoice_size:
choice_number = random.choice(choice_list)
if choice_number == 1:
if userchoice_syntax_upper == 'y': # Uppercase list
password = password + str(random.choice(ascii_letters.upper()))
counter += 1
if choice_number == 2:
if userchoice_syntax_number=='y': # Digits list
password = password + str(random.choice(digits))
counter += 1
if choice_number == 3:
if userchoice_syntax_lower == 'y': # Lower case list
password= password + str(random.choice(ascii_letters.lower())) # Converts all letters into lowercase then randomly select and store in list
counter += 1
print (password)
</code></pre>
|
[] |
[
{
"body": "<h2>Character distribution</h2>\n<p>You randomly choose between uppercase, lowercase and digit characters with an equal probability, but there are more letters than digit characters. That means characters will be under-represented in your password's probability distribution. Easier and more accurate is to make one string of all eligible characters and choose from it randomly.</p>\n<h2>Redundant str</h2>\n<p>No need for <code>str</code> here:</p>\n<pre><code>str(random.choice(ascii_letters.upper())) \n</code></pre>\n<h2>Move your increment</h2>\n<pre><code>counter += 1\n</code></pre>\n<p>should not be repeated three times in <code>if</code> statements. You can do it once at the end of the loop. Better yet,</p>\n<pre><code>for _ in range(userchoice_size):\n</code></pre>\n<h2>Choice list</h2>\n<p>This:</p>\n<pre><code>choice_list=[1,2,3]\nchoice_number = random.choice(choice_list)\n</code></pre>\n<p>should not use a list, and should be replaced with a call to <code>randrange</code>.</p>\n<h2>Secure entropy</h2>\n<p>For password generation it's crucially important to use a secure source of entropy. Read this quote carefully:</p>\n<blockquote>\n<p>Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is <strong>completely unsuitable for cryptographic purposes</strong>.</p>\n</blockquote>\n<p>Emphasis mine. A better built-in option is <a href=\"https://docs.python.org/3/library/secrets.html#module-secrets\" rel=\"nofollow noreferrer\">secrets</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T16:44:22.160",
"Id": "479477",
"Score": "1",
"body": "There's the reference for the quote: https://docs.python.org/3/library/random.html"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T15:40:45.287",
"Id": "244176",
"ParentId": "244159",
"Score": "3"
}
},
{
"body": "<h1>About your code</h1>\n<h2>Style</h2>\n<p>Your style is mostly fine, except lacking a bit of white space, especially after the imports, and having mostly useless comments that break the 80 character barrier.</p>\n<h2>Input validation</h2>\n<p>You don't check if the user input can be parsed as an integer in the first input. The <code>int()</code> methods validates its input, however a bad input will crash your program. It would be preferable to reject the input, and ask again.</p>\n<p>You don't validate the input for the yes/no question either, and it is much worse. Typing anything other than a lowercase <code>y</code> will be treated as a no. At the very least, add a <code>.lower()</code> to handle inputs like <code>Y</code>. It would be high priority to check for <code>n</code>/<code>N</code>, instead of silently treating anything else than <code>y</code> as meaning no.</p>\n<p>Since you ask 3 yes/no questions (and possibly more if you'd like to add stuff like special characters), you should delegate the input and its validation to a separate method.</p>\n<h2>Bug</h2>\n<p>If the user says "no" (more precisely: not "y") to all 3 questions, the program will hang indefinitely, as <code>counter</code> will never increase and the inner <code>while</code> loop will never end.</p>\n<h2>Security</h2>\n<p><code>random</code> is not a cryptographically secure random number generator. Use <a href=\"https://docs.python.org/3/library/secrets.html\" rel=\"nofollow noreferrer\"><code>secrets</code></a> instead, which is very similar to use.</p>\n<p>Also, ideally you'd want the probability for any character to be chosen to be the same. By separating the character categories as you did, digits are over-represented if they appear alongside letters.</p>\n<h2>Outer while loop</h2>\n<p>You put the entire code in an infinite loop. How many passwords do you think a user would want to generate?</p>\n<h1>My take on the problem</h1>\n<pre><code>def generate_password():\n password_length = ask_for_int('Enter the length of the password')\n \n choices = ''\n if ask_for_bool('Use lowercase letters? [y/n]'):\n choices += string.ascii_lowercase\n if ask_for_bool('Use uppercase letters? [y/n]'):\n choices += string.ascii_uppercase\n if ask_for_bool('Use digits? [y/n]'):\n choices += string.digits\n \n password = ''\n for _ in range(password_length):\n password += secrets.choice(choices)\n \n return password\n\n\ndef ask_for_int(msg):\n while True:\n print(msg)\n try:\n return int(input('> '))\n except ValueError:\n print('Unable to parse number. Please try again.')\n\n\ndef ask_for_bool(msg):\n while True:\n print(msg)\n user_in = input('> ').lower()\n if user_in =='y':\n return True\n if user_in =='n':\n return False\n print('Unable to parse answer. Please try again.')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:23:11.993",
"Id": "479364",
"Score": "0",
"body": "`password +=` should be replaced with `''.join` - `secrets` even shows an example doing so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:31:03.750",
"Id": "479366",
"Score": "0",
"body": "@Reinderien Is there a reason - besides performance - for doing so? I don't like list comprehensions, as they are rather hard to read. I assume that arsh is quite new to python, and I feel that code readability is more valuable than a clever one-liner, especially at a beginner level."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:33:15.420",
"Id": "479369",
"Score": "0",
"body": "The use of `''.join` in this case is already well-understood, and is more \"standard\" than \"clever\". Terseness and performance are both factors, and for some it's more legible than a loop. For the scale of password generation performance will not matter, but in other applications your loop will be O(n²) where `join` is O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:36:30.350",
"Id": "479370",
"Score": "0",
"body": "More generally: I try to give submissions on this site the best code possible and not necessarily code that they're guaranteed to understand, since presumably they came here to learn. People that come here are aspiring."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:13:40.103",
"Id": "244177",
"ParentId": "244159",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244177",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T11:02:53.077",
"Id": "244159",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"reinventing-the-wheel"
],
"Title": "Script to generate random password"
}
|
244159
|
<p>I just finished writing an implementation of the "singly linked list data structure",and i wanna know if there are some bugs or memory leaks or any bad code to make the code better!
i'm so sorry because there is no comment(But the code is simple , you can understand it)</p>
<pre><code>#include <iostream>
template<typename T>
struct Node
{
T Data;
Node* NextPtr = nullptr;
Node() {
NextPtr = nullptr;
}
Node(T Filler, Node* NextPtrAr) {
Data = Filler;
NextPtr = NextPtrAr;
}
void operator =(Node NAr) {
Data = NAr.Data;
NextPtr = NAr.NextPtr;
}
};
template<typename T>
class LinkedList
{
protected:
unsigned int Size = 0;
void SetSize(unsigned int SizeAr);
public:
Node<T> Head;
Node<T> Tail;
LinkedList();
LinkedList(T Filler, unsigned int NbrOfElem = 1);
LinkedList(std::initializer_list<T> List);
unsigned int GetSize();
void Push(T Filler, unsigned int Index = Size);
void Pop(unsigned int Index = 0);
void operator=(LinkedList<T> List);
void operator=(std::initializer_list<T> List);
Node<T>& operator[](unsigned int Index);
Node<T>& NodeAt(unsigned int Index);
};
template<typename T>
void LinkedList<T>::SetSize(unsigned int SizeAr) {
Size = SizeAr;
}
template<typename T>
unsigned int LinkedList<T>::GetSize() {
return Size;
}
template<typename T>
LinkedList<T>::LinkedList() {
}
template<typename T>
LinkedList<T>::LinkedList(T Filler, unsigned int NbrOfElem) {
if (NbrOfElem==1)
{
Head.Data = Filler;
SetSize(1);
}
else if(NbrOfElem==2)
{
Head.Data = Filler;
Tail.Data = Filler;
Head.NextPtr = &Tail;
SetSize(2);
}
else
{
Node<T>* TempNextPtr=new Node<T>;
Head.Data = Filler;
Head.NextPtr = TempNextPtr;
for (int i = 0; i < NbrOfElem - 1; i++)
{
Node<T>* NewNode = TempNextPtr;
TempNextPtr = new Node<T>;
NewNode->Data = Filler;
NewNode->NextPtr = TempNextPtr;
}
Tail.Data = Filler;
SetSize(NbrOfElem);
}
}
template<typename T>
Node<T>& LinkedList<T>::operator[](unsigned int Index) {
if (Index >= Size - 1)
{
return Tail;
}
Node<T>* ReturnNode = &Head;
for (int i=0;i<Index;i++)
{
ReturnNode = ReturnNode->NextPtr;
}
return *ReturnNode;
}
template<typename T>
void LinkedList<T>::operator=(LinkedList<T> List) {
//Clear
for (int i=1;i<Size-1;i++)
{
delete& NodeAt(i);
}
//Fill
Head.Data = List.Head.Data;
Head.NextPtr = new Node<T>;
Tail.Data = List.Tail.Data;
for (int i = 1; i < List.GetSize() - 1; i++)
{
Node<T>* NewNode = NodeAt(i - 1).NextPtr;
NewNode->Data = List[i].Data;
NewNode->NextPtr = new Node<T>;
}
SetSize(List.GetSize());
}
template<typename T>
void LinkedList<T>::operator=(std::initializer_list<T> List) {
//Clear
for (int i = 1; i < Size - 1; i++)
{
delete& NodeAt(i);
}
//Fill
Head.Data = *List.begin();
Head.NextPtr = new Node<T>;
Tail.Data = *(List.end()-1);
for (int i = 1; i < List.size() - 1; i++)
{
Node<T>* NewNode = NodeAt(i - 1).NextPtr;
NewNode->Data = *(List.begin()+i);
NewNode->NextPtr = new Node<T>;
}
SetSize(List.size());
}
template<typename T>
LinkedList<T>::LinkedList(std::initializer_list<T> List) {
Head.Data =*List.begin() ;
Head.NextPtr = new Node<T>;
Tail.Data = *(List.end()-1);
Tail.NextPtr = nullptr;
for (int i=1;i<List.size()-1;i++)
{
Node<T>* NewNode = NodeAt(i-1).NextPtr;
NewNode->Data = *(List.begin()+i);
NewNode->NextPtr = new Node<T>;
}
SetSize(List.size());
}
template<typename T>
Node<T>& LinkedList<T>::NodeAt(unsigned int Index) {
if (Index>=Size-1)
{
return Tail;
}
Node<T>* ReturnNode = &Head;
for (int i = 0; i < Index; i++)
{
ReturnNode = ReturnNode->NextPtr;
}
return *ReturnNode;
}
template<typename T>
void LinkedList<T>::Push(T Filler, unsigned int Index) {
Node<T>* NewNode = new Node<T>;
if (Index==0)
{
NewNode->Data = Head.Data;
NewNode->NextPtr = Head.NextPtr;
Head.Data = Filler;
Head.NextPtr = NewNode;
}
else if(Index>=Size) {
NewNode->Data = Tail.Data;
NewNode->NextPtr = &Tail;
NodeAt(Size - 2).NextPtr = NewNode;
Tail.Data = Filler;
}
else
{
NewNode->Data = Filler;
NewNode->NextPtr = NodeAt(Index - 1).NextPtr;
NodeAt(Index - 1).NextPtr = NewNode;
}
SetSize(Size + 1);
}
template<typename T>
void LinkedList<T>::Pop(unsigned int Index) {
if (Size < 2)
{
*Head.Data = nullptr;
Head.NextPtr = nullptr;
SetSize(0);
break;
}
if (Index==0)
{
Head = NodeAt(1);
delete& NodeAt(1);
}
else if(Index>=Size-1)
{
Tail.Data = NodeAt(Size - 2).Data;
NodeAt(Size - 3).NextPtr = &Tail;
delete& NodeAt(Size-2);
}
else
{
NodeAt(Index - 1).NextPtr = &NodeAt(Index + 1);
delete& NodeAt(Index);
}
SetSize(Index - 1);
}
int main()
{
LinkedList <int> L1 = { 10, 20, 30 };
LinkedList<int>L2(175, 100);
L2 = L1;
std::cout << L2[99].Data;
}
</code></pre>
|
[] |
[
{
"body": "<p>Firstly, the code is not compiling:</p>\n<blockquote>\n:36:46: error: invalid use of non-static data member 'Size'\n void Push(T Filler, unsigned int Index = Size);\n ^~~~ \n</blockquote>\n<p>=> Size is a member variable of the class, you cannot have it as a default argument. If you want to have <code>Push</code> with only one method, you'd have to create a separate overload for that one:</p>\n<p>void Push(T Filler)\n{\nPush(Filler,Size); // now possible, since we are in class-scope.\n}</p>\n<blockquote>\n:206:9: error: 'break' statement not in loop or switch statement\n break;\n</blockquote>\n<p>=> change <code>break</code> to <code>return</code>, since I guess you want to exit the method.</p>\n<hr />\n<p>Ignoring that and before digging in to the code, I would like to say something about <em>naming</em>.</p>\n<p>I will take <code>Node</code> as an example:</p>\n<pre><code>template<typename T>\nstruct Node\n{\n T Data;\n Node* NextPtr = nullptr;\n Node() {\n NextPtr = nullptr;\n }\n Node(T Filler, Node* NextPtrAr) {\n Data = Filler;\n NextPtr = NextPtrAr;\n }\n void operator =(Node NAr) {\n Data = NAr.Data;\n NextPtr = NAr.NextPtr;\n }\n};\n</code></pre>\n<p>The type <code>Node</code> has the same naming convention as <code>NodePtr</code>, a variable. Thus, reading code without context, I would not know whether, for example, Data is a <em>type</em> or a <em>variable</em>. It's good practice to separate them. You can, for example, have <strong>CamelCase</strong> for types, and <strong>camelCase</strong> for variables. It's usually also good to note private variables with some notation, this can be prefixing with <em>m_</em> or suffixing with <em>_</em>.</p>\n<p>Updated naming gives:</p>\n<pre><code>template<typename T>\nstruct Node\n{\n T data;\n Node* nextPtr = nullptr;\n Node() {\n nextPtr = nullptr;\n }\n Node(T filler, Node* nextPtrAr) {\n data = filler;\n nextPtr = nextPtrAr;\n }\n void operator =(Node nAr) {\n Data = nAr.data;\n nextPtr = NAr.nextPtr;\n }\n};\n</code></pre>\n<p>Look how even the syntax highlighter works better - now not everything has the color of a type.</p>\n<hr />\n<p>Since we already are looking at <code>Node</code>, we can tweak the constructors a bit. <code>nextPtr</code> is already (correctly) default member initialized to <code>nullptr</code>, so we do not need an explicit default constructor doing the same. Actually, you do not need <em>any</em> of your constructors in this case - the compiler will create all of them for you.</p>\n<pre><code>template<typename T>\nstruct Node\n{\n T data;\n Node* nextPtr = nullptr;\n}\n</code></pre>\n<p>is thus <em>fine</em>.</p>\n<p>Letting the compiler do it's job is usually better. Now we don't have to deal with <code>operator=</code> having wrong return type (it should return <code>Node&</code> and not <code>void</code>), and construction should be done in the <em>initializer list</em> to avoid double initialization. <code>Node(T filler, Node* nextPtrAr) : data(filler), nextPtr(nextPtrAr) {}</code>, for example. The problem is that once you are in the body of the constructor, the object is already constructed - so changing the variables there <em>reinitializes</em> them.</p>\n<hr />\n<p>Now to the singly linked list.</p>\n<p>There is already a singly linked list in the STL: <a href=\"https://de.cppreference.com/w/cpp/container/forward_list\" rel=\"nofollow noreferrer\">https://de.cppreference.com/w/cpp/container/forward_list</a></p>\n<p>Not to put you off writing your own, but it can be instructive to read the API. Interestingly, the list only has one access operator <code>front</code>, that gives you the first element. If you want to get the rest of the element, you have to iterate over them (by using the <code>std::forward_list::iterator</code>). Linked lists are usually used for the cases, where we only want to know the head (priority queues, stacks) or iterate over them blindly.</p>\n<p>The <code>LinkedList</code>, as you have it, has a <em>random access</em> operator <code>Node<T>& operator[](unsigned int Index);</code>. But a random access operator is usually provided to containers that actually support random access. If I used operator[], I would assume that it has a constant complexity (O(1)), but for a linked list, it is linear (O(N)), since we have to iterate through the list to get the element. <code>NodeAt</code> is a better name for the method, although even better would be to provide an iterator.\n=> remove <em>operator[]</em>.</p>\n<p>You are using <em>NodeAt</em> yourself in a for-loop:</p>\n<pre><code>for (int i = 1; i < Size - 1; i++)\n{\n delete& NodeAt(i);\n}\n</code></pre>\n<p>This essentially gives you a complexity of O(N^2), which is unnecessary. And actually, I have to admit I do not understand why it is working. When you delete the Node, how you you in the next iteration iterate to the node that the destructed object was pointing to? Better would probably be to <code>pop</code> and delete until list is empty.</p>\n<p>I will stop with the review here. Hopefully you have some points you can take with you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T13:14:14.680",
"Id": "479852",
"Score": "0",
"body": "Appreciate that!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T18:41:23.953",
"Id": "244276",
"ParentId": "244163",
"Score": "1"
}
},
{
"body": "<h2>Overview</h2>\n<p>Your code definitely leaks nodes. You should fix this in the destructor of <code>LinkedList</code>.</p>\n<p>You don't implement move semantics. Which means that you can only copy and this will be less efficient in most cases.</p>\n<p>You return access to your internal structures of your class. This means you have not protected the structure from external interference and thus have not protected your class (why are you using C++ may as well use PERL).</p>\n<p>You have a copy assignment operator but not a copy constructor. Sure this is possible but normally these are symmetric operations.</p>\n<p>You are creating a singly linked list. It is not that much harder to crate a doubly linked list. Also using a doubly linked list makes inserting and removal of items from the list much easier to write.</p>\n<h2>Code Review</h2>\n<p>The struct <code>Node</code> is part of the <code>LinkedList</code> class. There is no need to expose it (this exposes users to implementation details they don't need to know).</p>\n<p>You add a constructor and assignment operator. But these operations don't do anything special and the default versions do exactly the same. So you may as well not explicitly write them.</p>\n<pre><code>Example:\n\n template<typename T>\n struct LokiNode\n {\n Node* next;\n Node* prev;\n int value;\n };\n\n LokiNode x{nullptr, nullptr, 10}; // Works as expected.\n LokiNode y{x}; // Works as expected.\n LokiNode z; // Uninitialized value.\n z = y; // Works as expected;\n</code></pre>\n<hr />\n<p>I don't like this:</p>\n<pre><code> Node() {\n NextPtr = nullptr;\n }\n</code></pre>\n<p>It allows you to create a Node that can be partially initialized. This means that you can potentially fall into UB if code reads the <code>Data</code> value.</p>\n<hr />\n<p>Naming: It is traditional in C++. That object/method names begin with a lowercase letter and user defined types begin with an uppercase letter.</p>\n<pre><code>T Data; // I would make this data\nNode* NextPtr = nullptr; // I would make this next (I would drop Ptr)\n</code></pre>\n<p>This allows you to quickly and easily deferential types from objects which in C++ is an important distiction.</p>\n<hr />\n<p>Prefer to use the initializer list:</p>\n<pre><code> Node(T Filler, Node* NextPtrAr) {\n Data = Filler;\n NextPtr = NextPtrAr;\n }\n</code></pre>\n<p>In this case it makes no different. But if you do it like this all the time you may get into this bad habbit. This will cause issues if one of the members is expensive to initialize and re-initialization may double that code.</p>\n<pre><code> Node(T Filler, Node* NextPtrAr)\n : Data{Filler}\n , NextPtr{NextPtrAr}\n {}\n</code></pre>\n<hr />\n<p>It is traditional for the assignment operator to return a reference to self.</p>\n<pre><code> void operator =(Node NAr) {\n }\n\n Node& operator=(Node n)\n {\n // STUFF\n return *this;\n }\n</code></pre>\n<p>Not essential but people will wonder why you are doing it funny. By returning a reference to self you allow assignment chaining which makes the usage to similar to built in types (and thus easier to use).</p>\n<hr />\n<p>Protected is a terrible thing stop using it.</p>\n<pre><code>protected:\n unsigned int Size = 0;\n void SetSize(unsigned int SizeAr);\n</code></pre>\n<p>Member variables should definitely be private (unless you have a very good and documentable reason not to make it private).</p>\n<p>Member methods can by protected, but simply subverts the protection mechanism. This is only really useful where this is a non concreate base class where other people would never use it. i.e. this class provides some basic functionality but is not the final class. A derived class may inherit from this and provides the real class that a user would have.</p>\n<hr />\n<p>This look like a bug.</p>\n<pre><code> Node<T> Head;\n Node<T> Tail;\n</code></pre>\n<p>This means your list always has two members (a head and tail that are different). Your list is never empty? What I think you want are two pointers to the head and tail of the list.</p>\n<pre><code> Node<T>* Head;\n Node<T>* Tail;\n</code></pre>\n<p>Now a head and tail can be nullptr to represent the empty list.</p>\n<hr />\n<p>Fine set of constructors:</p>\n<pre><code> LinkedList();\n LinkedList(T Filler, unsigned int NbrOfElem = 1);\n LinkedList(std::initializer_list<T> List);\n</code></pre>\n<p>But I don't see a destructor. This is a bug. In a list you must dynamically allocate the elements in the list. I don't see a destructor in the <code>Node</code> so this destructor must do some work to tidy up that dynamic allocation.</p>\n<hr />\n<p>Const correctness:</p>\n<p>This function does not change the state of the object.</p>\n<pre><code> unsigned int GetSize();\n</code></pre>\n<p>As a result you should probably mark it as <code>const</code> so it can be called from a const context (ie passed by const reference to a method). Also size type functions we usually specify this in terms of <code>std::size_t</code> to indicate this is a size. This also applies to index operations.</p>\n<pre><code> std::size_t GetSize() const;\n</code></pre>\n<hr />\n<p>That's interesting:</p>\n<pre><code> void operator=(std::initializer_list<T> List);\n</code></pre>\n<p>Sure. You can do this. But can you not achieve the same affect by using constructor and assignment operator:</p>\n<pre><code> LinkedList<int> x;\n\n x = {1,2,3,4}; // This calls your assignment operator.\n</code></pre>\n<p>But if you did not have this assignment operator what would it do?</p>\n<pre><code> x = {1,2,3,4}; // Different types in assignment.\n // but there is a one parameter constructor that will\n // convert an initializer list into a LinkedList. So\n // the compiler will call this constructor to convert\n // the initializer list into a LinkedList<int> type.\n //\n // We can then apply the normal assignment operator to \n // copy (or move) the new object to the original `x`.\n //\n // Note: Because of copy elision optimization\n // We can optimize away the copy if needed or\n // simply use the move assignment operator.\n</code></pre>\n<hr />\n<p>Sure I don't mind the use of <code>NodeAt()</code>. Though if you look in the standard library functions like this are simply called <code>at()</code></p>\n<pre><code> Node<T>& operator[](unsigned int Index);\n Node<T>& NodeAt(unsigned int Index);\n</code></pre>\n<hr />\n<p>You can simply set the size!</p>\n<pre><code>template<typename T>\nvoid LinkedList<T>::SetSize(unsigned int SizeAr) {\n Size = SizeAr;\n}\n</code></pre>\n<p>I would expect you have to add the appropriate number of elements into the list.</p>\n<hr />\n<p>This is overly complex because you are not using pointers for head and tail.</p>\n<pre><code>template<typename T>\nLinkedList<T>::LinkedList(T Filler, unsigned int NbrOfElem) {\n if (NbrOfElem==1)\n {\n Head.Data = Filler;\n SetSize(1);\n }\n else if(NbrOfElem==2)\n {\n Head.Data = Filler;\n Tail.Data = Filler;\n Head.NextPtr = &Tail;\n SetSize(2);\n }\n else\n {\n Node<T>* TempNextPtr=new Node<T>;\n Head.Data = Filler;\n Head.NextPtr = TempNextPtr;\n for (int i = 0; i < NbrOfElem - 1; i++)\n {\n Node<T>* NewNode = TempNextPtr;\n TempNextPtr = new Node<T>;\n NewNode->Data = Filler;\n NewNode->NextPtr = TempNextPtr;\n }\n Tail.Data = Filler;\n SetSize(NbrOfElem);\n }\n}\n</code></pre>\n<p>I would simply write this (assuming head/tail are pointers).</p>\n<pre><code>template<typename T>\nLinkedList<T>::LinkedList(T Filler, unsigned int NbrOfElem)\n : Head(nullptr)\n , Tail(nullptr)\n{\n for(int loop = 0; loop < NbrOfElem; ++loop) {\n Head = new Node<T>{Filler, Head};\n if (Tail == nullptr) {\n Tail = Head;\n }\n }\n}\n</code></pre>\n<hr />\n<p>Normally in C++ <code>operator[]</code> is unchecked accesses into the container. While <code>at()</code> is the checked accesses into the container. You use them both as checked. Personally I would not bother but you can.</p>\n<p>If you want both to be checked then one of these two should call the other.</p>\n<pre><code>template<typename T>\nNode<T>& LinkedList<T>::operator[](unsigned int Index) {\n if (Index >= Size - 1)\n {\n return Tail;\n }\n</code></pre>\n<hr />\n<p>Why are you returning a <code>Node</code>!!!</p>\n<pre><code>template<typename T>\nNode<T>& LinkedList<T>::operator[](unsigned int Index) {\n</code></pre>\n<p>You are giving people access to the internal types of your class. This will allow them (actually encourage) them to modify your internal structures. You should be returning the element stored at that location.</p>\n<pre><code>template<typename T>\nT& LinkedList<T>::operator[](unsigned int Index);\ntemplate<typename T>\nT const& LinkedList<T>::operator[](unsigned int Index) const;\n</code></pre>\n<hr />\n<p>You have marked this as a functionality</p>\n<pre><code> //Clear\n for (int i=1;i<Size-1;i++)\n {\n delete& NodeAt(i);\n }\n</code></pre>\n<p>Why not make that explicit and make it a new method?</p>\n<hr />\n<p>You have marked this as a functionality</p>\n<pre><code> //Fill\n Head.Data = List.Head.Data;\n Head.NextPtr = new Node<T>;\n Tail.Data = List.Tail.Data;\n for (int i = 1; i < List.GetSize() - 1; i++)\n {\n Node<T>* NewNode = NodeAt(i - 1).NextPtr;\n NewNode->Data = List[i].Data;\n NewNode->NextPtr = new Node<T>;\n }\n</code></pre>\n<p>Why not make that explicit and make it a new method?</p>\n<hr />\n<p>In this question <a href=\"https://codereview.stackexchange.com/a/126007/507\">My first implementation of a linked list in C++</a> I have provided a review of another linked list. Scroll to the bottom of my answer and there is a reference implementation. Please have a look.</p>\n<h2>Simplified List</h2>\n<pre><code>template<typename T>\nclass LinkedList\n{\n struct Node\n {\n T data;\n Node* prev;\n Node* next;\n };\n\n Node* head;\n Node* tail;\n std::size_t length;\n\n public:\n LinkedList() // Default Constructor\n : head(nullptr)\n , tail(nullptr)\n , length(0)\n {}\n // Have to release all the nodes in a destructor\n ~LinkedList()\n {\n for (Node* loop = head; loop != nullptr;) {\n Node* old = loop;\n loop = loop->next;\n delete old;\n }\n }\n // Copy Constructor and Assignment.\n LinkedList(LinkedList const& copy)\n : head(nullptr)\n , tail(nullptr)\n , length(0)\n {\n // Loop over the other list.\n // Simply push each element into this list.\n for (Node* loop = copy.head; loop != nullptr; loop = loop->next) {\n push_back(loop->data);\n }\n }\n LinkedList& operator=(LinkedList const& rhs)\n {\n // Use the copy and swap idiom to do assignment.\n\n // 1. Copy the list using the copy constructor.\n LinkedList copy(rhs);\n\n // 2. Swap the copy with the current object.\n swap(copy);\n\n // 3. When we go out of scope the `copy` object is\n // destroyed. This releases the old object list\n return *this;\n }\n // Move Constructor and Assignment\n // For now we delete these. But we will␣\n // come back to this later.\n LinkedList(LinkedList&&) noexcept = delete;\n LinkedList& operator=(LinkedList&&) noexcept = delete;\n\n // Swap\n // We want to swap two objects of type Linked List.\n void swap(LinkedList const& rhs) noexcept\n {\n std::swap(head, rhs.head);\n std::swap(tail, rhs.tail);\n }\n void push_back(T const& value)\n {\n if (tail) {\n // If the list is not empty add it to the back.\n // Simply create the node linked to the tail and\n // then move the tail to the new tail node.\n tail->next = new Node{value, tail, nullptr};\n tail = tail->next;\n }\n else {\n // If the list is empty.\n // Then the new node is both the head and tail\n head = tail = new Node{value, nullptr, nullptr};\n }\n ++length;\n }\n void pop_back()\n {\n if (tail) {\n // Keep track of the old value.\n Node* old = tail;\n\n // Remove the last element from the list\n tail = tail->prev;\n tail->next = nullptr;\n --length;\n\n // Tidy up. Delete the old element.\n delete old;\n }\n }\n std::size_t size() const {return length;}\n T const& back() const {return tail->data;}\n T& back() {return tail->data;}\n\n // I leave the following easy to implement methods for you.\n\n // Front version equivalent of the back methods.\n void push_front(T&);\n void pop_front();\n T const& front() const;\n T& front();\n\n // Unchecked accesses.\n T const& operator[](std::size_t index) const;\n T& operator[](std::size_t index);\n\n // Checked accesses.\n T const& at(std::size_t index) const;\n T& at(std::size_t index);\n};\n\nint main()\n{\n LinkedList<int> list;\n list.push_back(1);\n list.push_back(2);\n list.push_back(3);\n list.push_back(4);\n list.push_back(5);\n\n LinkedList<int> second(list);\n std::cout << second.back();\n second.pop_back();\n second.pop_back();\n std::cout << second.back();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:05:52.657",
"Id": "479865",
"Score": "0",
"body": "Thanks! but you're code so much harder for me (20 days in c++)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T15:48:43.720",
"Id": "479881",
"Score": "0",
"body": "@BadrEddine Sure we can write something simplified. Hold on."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T20:16:36.730",
"Id": "244406",
"ParentId": "244163",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T12:17:50.033",
"Id": "244163",
"Score": "3",
"Tags": [
"c++",
"linked-list"
],
"Title": "Singly linked list implementation in c++ (Data Structure)"
}
|
244163
|
<p>Can I improve on this any further. Is there a prettier way of passing the array sizes?</p>
<pre><code>#include <stdio.h>
void matrix_addition(size_t n, int A[n][n], int B[n][n], int C[2*n][2*n], size_t c_start, size_t c_end) {
for(size_t i = 0; i < n; ++i) {
for(size_t j = 0; j < n; ++j) {
C[i+c_start][j+c_end] = A[i][j] + B[i][j];
}
}
}
void recursive_matrix_multiply(
size_t l, size_t n, int A[l][l], int B[l][l], int C[n][n],
size_t a_r_start, size_t a_r_end, size_t a_c_start, size_t a_c_end,
size_t b_r_start, size_t b_r_end, size_t b_c_start, size_t b_c_end
) {
if(n == 1) {
C[0][0] = A[a_r_start][a_c_start]*B[b_r_start][b_c_start];
} else {
int m = n/2;
int C1[m][m];
int C2[m][m];
recursive_matrix_multiply(l, m, A, B, C1, a_r_start, a_r_end-m, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start, b_c_end-m);
recursive_matrix_multiply(l, m, A, B, C2, a_r_start, a_r_end-m, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start, b_c_end-m);
matrix_addition(m, C1, C2, C, 0, 0);
recursive_matrix_multiply(l, m, A, B, C1, a_r_start, a_r_end-m, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start+m, b_c_end);
recursive_matrix_multiply(l, m, A, B, C2, a_r_start, a_r_end-m, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start+m, b_c_end);
matrix_addition(m, C1, C2, C, 0, m);
recursive_matrix_multiply(l, m, A, B, C1, a_r_start+m, a_r_end, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start, b_c_end-m);
recursive_matrix_multiply(l, m, A, B, C2, a_r_start+m, a_r_end, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start, b_c_end-m);
matrix_addition(m, C1, C2, C, m, 0);
recursive_matrix_multiply(l, m, A, B, C1, a_r_start+m, a_r_end, a_c_start, a_c_end-m, b_r_start, b_r_end-m, b_c_start+m, b_c_end);
recursive_matrix_multiply(l, m, A, B, C2, a_r_start+m, a_r_end, a_c_start+m, a_c_end, b_r_start+m, b_r_end, b_c_start+m, b_c_end);
matrix_addition(m, C1, C2, C, m, m);
}
}
int main()
{
int A[4][4] = {{1, 2, 3, 4}, {4, 3, 2, 1}, { 0, 0, 1, 1 }, {1, 1, 0, 0}};
int B[4][4] = {{2, 2, 4, 4}, {4, 1, 1, 4}, {1, 0, 1, 0}, {1, 0, 1, 0}};
int C[4][4];
recursive_matrix_multiply(4, 4, A, B, C, 0, 3, 0, 3, 0, 3, 0, 3);
for(size_t i = 0; i < 4; ++i) {
for(size_t j = 0; j < 4; ++j) {
printf("C[%i][%i] = %i, ", i, j, C[i][j]);
}
printf("\n");
}
return 0;
}
</code></pre>
<p>It currently works as intended but I'm looking to beautify this a bit. Even an improvement on variable naming would be appreciated. I'm trying to build up a portfolio so if you saw this from a professional standpoint what would you think?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T14:07:01.433",
"Id": "479349",
"Score": "0",
"body": "Is necessary to implement the multiplication in a recursive way ? If not, your matrix multiplication algorithm would take 10 lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T14:15:57.940",
"Id": "479350",
"Score": "0",
"body": "@MiguelAvila Yes, I'm avoiding for loops and practicing divide and conquer algorithms. This is really a warm up for Strassens algorithm."
}
] |
[
{
"body": "<p>All of the endpoints are redundant. If anyone can add anything else I'd still appreciate it.</p>\n<pre><code>#include <stdio.h>\n\nvoid matrix_addition_partition(size_t n, size_t m, int A[m][m], int B[m][m], int C[n][n], size_t start, size_t end) {\n for(size_t i = 0; i < m; ++i) {\n for(size_t j = 0; j < m; ++j) {\n C[i+start][j+end] = A[i][j] + B[i][j];\n }\n }\n}\n\nvoid recursive_matrix_multiply(\n size_t l, size_t n, int A[l][l], int B[l][l], int C[n][n],\n size_t ar, size_t ac, size_t br, size_t cb\n ) {\n if(n == 1) {\n C[0][0] = A[ar][ac]*B[br][cb];\n } else {\n int m = n>>1;\n int C1[m][m], C2[m][m];\n\n recursive_matrix_multiply(l, m, A, B, C1, ar, ac, br, cb);\n recursive_matrix_multiply(l, m, A, B, C2, ar, ac+m, br+m, cb);\n\n matrix_addition_partition(n, m, C1, C2, C, 0, 0);\n \n recursive_matrix_multiply(l, m, A, B, C1, ar, ac, br, cb+m);\n recursive_matrix_multiply(l, m, A, B, C2, ar, ac+m, br+m, cb+m);\n\n matrix_addition_partition(n, m, C1, C2, C, 0, m);\n\n recursive_matrix_multiply(l, m, A, B, C1, ar+m, ac, br, cb);\n recursive_matrix_multiply(l, m, A, B, C2, ar+m, ac+m, br+m, cb);\n\n matrix_addition_partition(n, m, C1, C2, C, m, 0);\n\n recursive_matrix_multiply(l, m, A, B, C1, ar+m, ac, br, cb+m);\n recursive_matrix_multiply(l, m, A, B, C2, ar+m, ac+m, br+m, cb+m);\n \n matrix_addition_partition(n, m, C1, C2, C, m, m);\n\n }\n}\n\nvoid matrix_multiply(size_t n, int A[n][n], int B[n][n], int C[n][n]) {\n recursive_matrix_multiply(n, n, A, B, C, 0, 0, 0, 0);\n}\n\n\nint main()\n{\n int A[4][4] = {{1, 2, 3, 4}, {4, 3, 2, 1}, {0, 0, 1, 1}, {1, 1, 0, 0}};\n int B[4][4] = {{2, 2, 4, 4}, {4, 1, 1, 4}, {1, 0, 1, 0}, {1, 0, 1, 0}};\n int C[4][4];\n \n matrix_multiply(4, A, B, C);\n\n for(size_t i = 0; i < 4; ++i) {\n for(size_t j = 0; j < 4; ++j) {\n printf("C[%i][%i] = %i, ", i, j, C[i][j]);\n }\n printf("\\n");\n }\n \n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T14:47:40.257",
"Id": "480217",
"Score": "0",
"body": "this is hard to parallelize. you can't spawn any threads inside of the recursion as it will create a fork bomb."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-12T08:11:57.210",
"Id": "532957",
"Score": "0",
"body": "(There was a \"finger rot\" changing `bc` to `cb`.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:48:19.353",
"Id": "244182",
"ParentId": "244164",
"Score": "0"
}
},
{
"body": "<p>Caution: Assessment of <em>advanced matrix multiplication</em> is non-trivial. See <a href=\"https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-172-performance-engineering-of-software-systems-fall-2018/lecture-slides/MIT6_172F18_lec1.pdf\" rel=\"nofollow noreferrer\">Introduction to Performance Engineering &\nMatrix Multiplication</a> for starters, in particular the part about cache access patterns and similarities therein between tiling and recursive decomposition on one hand and Strassen&Cie․ on the other.</p>\n<hr />\n<p>Public/main items of a program should be self-explanatory, or come with a description.<br />\nI'm under the impression that as presented <code>recursive_matrix_multiply()</code> (and consequently <code>matrix_multiply()</code> in the self-answer) only work for square matrices sized the same power of 2.</p>\n<p><code>improvement on variable naming</code><br />\nI can see that telling names aren't short, and only short names keep the length of calls with many parameters and expressions with many primaries from getting out of hand.<br />\nI'd much prefer terse names to be introduced with a comment.<br />\nI take the names <em>A</em>, <em>B</em>, and <em>C</em> to be conventional for binary operations.<br />\nIn <code>matrix_addition()</code>, <code>c_start</code> looks plausible, but is it <em>c_</em> for <em>column</em> or <em>referring to matrix/parameter C</em>?<br />\n<code>c_end</code> is worse - I don't see any <em>end</em> it refers to, just the <em>offset for second dimension index in C</em>.<br />\nI can live with (I guess I'm still with <a href=\"https://www.doxygen.nl/manual/faq.html\" rel=\"nofollow noreferrer\">doxygen</a>)</p>\n<pre><code>/// suitable to hold one matrix dimension\ntypedef size_t md;\n\nvoid matrix_addition( ///< Let part of C = A + B.\n md n, int A[][n], int B[][n], int C[][2*n],\n md fo, ///< first dimension offset into C\n md so ///< second dimension offset into C\n ) {\n</code></pre>\n<p><code>I'm avoiding for loops</code> beyond reason -<br />\nrecursion inside a one nested loop sure is shorter and, in my eyes, more readable.<br />\nTaking names from <a href=\"https://codereview.stackexchange.com/a/244182/93149\">Ivor Denham-Dyson's answer</a>:</p>\n<pre><code> for (md ro = 0 ; ro <= m ; ro += m)\n for (md co = 0 ; co <= m ; co += m) {\n recursive_matrix_multiply(l, m, A, B, C1, ar+ro, ac, br, bc+co);\n recursive_matrix_multiply(l, m, A, B, C2, ar+ro, ac+m, br+m, bc+co);\n\n matrix_addition_partition(n, m, C1, C2, C, ro, co);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-12T10:25:10.157",
"Id": "270007",
"ParentId": "244164",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T12:41:06.037",
"Id": "244164",
"Score": "1",
"Tags": [
"algorithm",
"c",
"recursion",
"matrix"
],
"Title": "Recursive Matrix Multiplication Algorithm"
}
|
244164
|
<p>The code works as intended but I believe it is very inefficient. The calculation of weights is simple, but I imagine this would be silly, for example, a 100 asset portfolio. The first problem is that my code returns to the beginning of the loop if the weight for y is entered incorrectly. Help with this would be amazing.</p>
<p>Secondly, as alluded to above, this is an inefficient approach. Someone entering 100 weights would not repeat this process. Any ideas where I could find some help for this approach would be great.</p>
<pre><code>r_x=0.15
r_y=0.21
while True:
try: w_x=float(input("Enter the weight of stock x in your portfolio: "))
except ValueError:
print("Please enter the weight using numbers")
continue
else:
if w_x<0 or w_x>1: #seperating it instead of doing it altogether corrected this error for me
print("Please enter the number as a decimal. Remember, your maximum investment is 100%.")
continue
try: w_y=float(input("Enter the weight of stock y in your portoflio: "))
except ValueError:
print("Please enter the weight using numbers")
else:
if w_y<0 or w_y>1:
print("Please enter the numbers as a decimal. Remember, your maximum investment is 100%.")
continue
else:
if w_x+w_y<0 or w_x+w_y>1:
print("Remember, the total weight of the portfolio is 100%. The weights should add to 1.")
continue
else:
r_p=r_x*w_x+r_y*w_y
r_p=r_p*100
print("The total return on your portoflio is %.2f"%r_p +"%")
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:27:07.200",
"Id": "479390",
"Score": "0",
"body": "If you have more than a few stocks, then store the stock and weights in a data file of some kind. For example, a simple text file with each line containing a stock symbol and it's weight would be easy to process. A CSV file can be processed using the `csv` module in the standard library. A CSV file can be created using a text editor or saved from Excel. Excel files can also be read directly, but it is a bit more involved and requires a 3rd-party library."
}
] |
[
{
"body": "<p>You should write a function that takes care of asking the user for input. It should be able to assign a type and validate the input. This way you can continue asking for a valid input for each of the variables independently. It also allows you to validate the second variable using the value of the first.</p>\n<pre><code>def ask_user(message, type_=str, valid=lambda x: True, wrong_type="Wrong type!", invalid="Invalid!"):\n while True:\n try:\n x = type_(input(message))\n except (TypeError, ValueError):\n print(wrong_type)\n continue\n if valid(x):\n return x\n else:\n print(invalid)\n</code></pre>\n<p>Which you can use like this:</p>\n<pre><code>if __name__ == "__main__":\n r_x = 0.15\n r_y = 0.21\n w_x = ask_user("Enter the weight of stock x in your portfolio: ",\n type_=float,\n wrong_type="Please enter the weight using numbers",\n valid=lambda w_x: 0 <= w_x <= 1,\n invalid="Please enter the number as a decimal. Remember, your maximum investment is 100%.")\n w_y = ask_user("Enter the weight of stock y in your portoflio: ",\n type_=float,\n wrong_type="Please enter the weight using numbers",\n valid=lambda w_y: 0 <= w_x + w_y <= 1,\n invalid="Remember, the total weight of the portfolio is 100%. The weights should add to 1.")\n r_p = r_x * w_x + r_y * w_y\n print(f"The total return on your portoflio is {r_p:.2%}")\n</code></pre>\n<p>I also used the newer <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings</a> for string formatting, with the <code>%</code> format code, which takes care of that multiplication by one hundred. I also added a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == "__main__":</code> guard</a> to allow importing from this script without the code being run.</p>\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using spaces around <code>=</code> when using it for assignment, but not when using it for keyword arguments. Similarly, operators like <code>+</code> and <code>*</code> should generally also be surrounded by spaces.</p>\n<hr />\n<p>If you want to be able to input <code>n</code> weights, I would add another function:</p>\n<pre><code>def ask_n_weights(message, n, type_=str, wrong_type="Wrong type!", invalid="Invalid!"):\n weights = []\n for i in range(1, n + 1):\n weights.append(ask_user(message.format(i),\n type_=type_,\n wrong_type=wrong_type,\n valid=lambda w: 0 <= w + sum(weights) <= 1,\n invalid=invalid))\n return weights\n</code></pre>\n<p>This uses the fact that <code>sum([]) = 0</code> to also be correct for the first variable. In order not to loose the ability to know which weight you are entering I made it so that <code>message</code> should have one placeholder:</p>\n<pre><code>ask_n_weights("Enter weight {}: ", 4, type_=float)\n# Enter weight 1: 0.25\n# Enter weight 2: 0.25\n# Enter weight 3: 0.25\n# Enter weight 4: 0.25\n# [0.25, 0.25, 0.25, 0.25]\n</code></pre>\n<p>You could also take an iterable of variable names instead of <code>n</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T13:43:29.957",
"Id": "479459",
"Score": "2",
"body": "Thank you! I have a lot of learning to do... The valid/invalid approach seems much more appropriate. Still not there with defining functions so a bit of learning and building on what you have given me will be great. thanks for your time :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T14:25:29.067",
"Id": "244170",
"ParentId": "244168",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T13:58:38.287",
"Id": "244168",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"console",
"user-interface"
],
"Title": "Validating initial inputs then a joint validation test"
}
|
244168
|
<p>I am solving the following Hackerrank problem: <a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="nofollow noreferrer">Climbing the Leaderboard</a>.</p>
<h2>The problem statement:</h2>
<p>Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses Dense Ranking, so its leaderboard works like this:</p>
<ul>
<li>The player with the highest score is ranked number 1 on the leaderboard.</li>
<li>Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.</li>
</ul>
<p>For example, the four players on the leaderboard have high scores of 100, 90, 90, and 80. Those players will have ranks 1, 2, 2, and 3, respectively. If Alice's scores are 70, 80 and 105, her rankings after each game are 4th, 3rd and 1st.</p>
<h3>Function Description</h3>
<p>Complete the climbingLeaderboard function in the editor below. It should return an integer array where each element <code>res[j]</code> represents Alice's rank after the <em>jth</em> game.</p>
<p><code>climbingLeaderboard</code> has the following parameter(s):</p>
<p><code>scores</code>: an array of integers that represent leaderboard scores
<code>alice</code>: an array of integers that represent Alice's scores</p>
<h3>Input Format</h3>
<p>The first line contains an integer n, the number of players on the leaderboard.
The next line contains n space-separated integers scores[i], the leaderboard scores in decreasing order.
The next line contains an integer, m, denoting the number games Alice plays.
The last line contains m space-separated integers alice[j], the game scores.</p>
<h3>Constraints</h3>
<ul>
<li>1 <= n <= 2 * 10^5</li>
<li>1 <= m <= 2 * 10^5</li>
<li>0 <= scores[i] <= 10^9 for 0 <= i < n</li>
<li>0 <= alice[j] <= 10^9 for 0 <= j < m</li>
</ul>
<p>The existing leaderboard, scores, is in descending order.
Alice's scores, alice, are in ascending order.</p>
<h3>Subtask</h3>
<p>For 60% of the maximum score:</p>
<ul>
<li>1 <= n <= 200</li>
<li>1 <= m <= 200</li>
</ul>
<p>Output Format</p>
<p>Print m integers. The jth integer should indicate Alice's rank after playing the <em>jth</em> game.</p>
<hr />
<p>My solution is failing to pass 4 test cases due to <em>timeout</em>. The code is as follows:</p>
<pre><code> import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int totalPlayers = scanner.nextInt();
ArrayList<Integer> playerScores = new ArrayList<>();
for(int i = 0; i < totalPlayers; i++) {
playerScores.add(scanner.nextInt());
}
int aliceTotalScores = scanner.nextInt();
ArrayList<Integer> aliceScores = new ArrayList<>();
for(int i = 0; i < aliceTotalScores; i++) {
aliceScores.add(scanner.nextInt());
}
List<Integer> finalScores = new ArrayList<>(playerScores);
for(int i = 0; i < aliceTotalScores; i++) {
finalScores.add(aliceScores.get(i));
finalScores.sort(Collections.reverseOrder());
Set<Integer> set = new LinkedHashSet<>(finalScores);
finalScores.clear();
finalScores.addAll(set);
System.out.println(finalScores.indexOf(aliceScores.get(i)) + 1);
}
}
}
</code></pre>
<p>Any suggestions on how to improve the solution or some general direction as to where I am making a mistake would be appreciated. Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:40:24.887",
"Id": "479377",
"Score": "1",
"body": "Use a binary search to determine where on the leader board Alice's score belongs. With up to 10 to the ninth scores on the leader board, any other search method is too slow."
}
] |
[
{
"body": "<p>I have some suggestions to make the code cleaner, not faster.</p>\n<h2>Always try to pass the size of the maximum size to the Collection / Map when known</h2>\n<p>The <code>ArrayList</code> has a default size of 10 elements, if you have more elements, the list will have to resize its internal pool. By setting the size, you can prevent the resize and make your code faster.</p>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nint totalPlayers = scanner.nextInt();\nArrayList<Integer> playerScores = new ArrayList<>(totalPlayers);\n//[...]\nint aliceTotalScores = scanner.nextInt();\nArrayList<Integer> aliceScores = new ArrayList<>(aliceTotalScores);\n//[...]\n</code></pre>\n<h2>Always use the base class / interface in the left part of the variable when possible</h2>\n<p>By setting the <code>java.util.List</code> interface in the variable part, this could make the code more refactorable in the future, since you could easily change the list type without changing everything (inheritance).</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> ArrayList<Integer> playerScores = new ArrayList<>(totalPlayers);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> List<Integer> playerScores = new ArrayList<>(totalPlayers);\n</code></pre>\n<h2>Replace the <code>for</code> loop with an enhanced 'for' loop</h2>\n<p>In your code, you don’t actually need the index provided by the loop, you can the enhanced version.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i < aliceTotalScores; i++) {\n finalScores.add(aliceScores.get(i));\n finalScores.sort(Collections.reverseOrder());\n Set<Integer> set = new LinkedHashSet<>(finalScores);\n finalScores.clear();\n finalScores.addAll(set);\n System.out.println(finalScores.indexOf(aliceScores.get(i)) + 1);\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (Integer aliceScore : aliceScores) {\n finalScores.add(aliceScore);\n finalScores.sort(Collections.reverseOrder());\n Set<Integer> set = new LinkedHashSet<>(finalScores);\n finalScores.clear();\n finalScores.addAll(set);\n System.out.println(finalScores.indexOf(aliceScore) + 1);\n}\n</code></pre>\n<h2>Extract some of the logic to methods.</h2>\n<p>To remove some of the code of the main method, you could move both list instantiation (playerScores & aliceScores) to methods. Since the logic is similar, you could make only one method to read the inputs to a list and reuse the same for both cases.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n List<Integer> playerScores = getPlayerScores(scanner);\n List<Integer> aliceScores = getAliceScores(scanner);\n}\n\nprivate static List<Integer> getAliceScores(Scanner scanner) {\n return getIntegers(scanner);\n}\n\nprivate static List<Integer> getPlayerScores(Scanner scanner) {\n return getIntegers(scanner);\n}\n\n\nprivate static List<Integer> getIntegers(Scanner scanner) {\n int size = scanner.nextInt();\n List<Integer> integers = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n integers.add(scanner.nextInt());\n }\n return integers;\n}\n\n</code></pre>\n<p><strong>or</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n List<Integer> playerScores = getIntegers(scanner);\n List<Integer> aliceScores = getIntegers(scanner);\n}\n\nprivate static List<Integer> getIntegers(Scanner scanner) {\n int size = scanner.nextInt();\n List<Integer> integers = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n integers.add(scanner.nextInt());\n }\n return integers;\n}\n\n</code></pre>\n<h1>Refactored code</h1>\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n List<Integer> playerScores = getPlayerScores(scanner);\n List<Integer> aliceScores = getAliceScores(scanner);\n List<Integer> finalScores = new ArrayList<>(playerScores);\n\n for (Integer aliceScore : aliceScores) {\n finalScores.add(aliceScore);\n finalScores.sort(Collections.reverseOrder());\n Set<Integer> set = new LinkedHashSet<>(finalScores);\n finalScores.clear();\n finalScores.addAll(set);\n System.out.println(finalScores.indexOf(aliceScore) + 1);\n }\n}\n\nprivate static List<Integer> getAliceScores(Scanner scanner) {\n return getIntegers(scanner);\n}\n\nprivate static List<Integer> getPlayerScores(Scanner scanner) {\n return getIntegers(scanner);\n}\n\n\nprivate static List<Integer> getIntegers(Scanner scanner) {\n int size = scanner.nextInt();\n List<Integer> integers = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n integers.add(scanner.nextInt());\n }\n return integers;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:20:23.870",
"Id": "244261",
"ParentId": "244171",
"Score": "1"
}
},
{
"body": "<p>The below solution is simpler and it should pass all the test cases. You don't need the sorting techniques to solve this. Your code is quite complicated as you did a sort in each loop which is not needed at all. Here what we can do instead:</p>\n<p>1- Use Set to remove duplicate scores</p>\n<p>2- Use LinkedHashSet to keep the set in order state</p>\n<p>3- Save the Set again to a List which helps us to get the index of each score</p>\n<p><em><strong>Refactor code</strong></em></p>\n<pre><code>public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n List<Integer> playerScores = getPlayerScores(scanner);\n List<Integer> aliceScores = getAliceScores(scanner);\n\n Set<Integer> uniqueScores = new LinkedHashSet<>(playerScores);\n playerScores = new ArrayList<>(uniqueScores);\n\n int i = playerScores.size() - 1;\n for (Integer oneScore : aliceScores) {\n while (i >= 0) {\n if (oneScore < playerScores.get(i)) {\n System.out.println(i + 2);\n break;\n }\n i--;\n }\n if (i < 0) {\n System.out.println(1);\n }\n }\n}\n\nprivate static List<Integer> getAliceScores(Scanner scanner) {\n return getIntegers(scanner);\n}\n\nprivate static List<Integer> getPlayerScores(Scanner scanner) {\n return getIntegers(scanner);\n}\n\n\nprivate static List<Integer> getIntegers(Scanner scanner) {\n int size = scanner.nextInt();\n List<Integer> integers = new ArrayList<>(size);\n for (int i = 0; i < size; i++) {\n integers.add(scanner.nextInt());\n }\n return integers;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T13:01:44.060",
"Id": "506780",
"Score": "5",
"body": "Welcome! This is code-review, not post-your-solution. Please explain why this works and the main take-away for the OP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T13:22:13.040",
"Id": "506782",
"Score": "4",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T16:56:18.483",
"Id": "506805",
"Score": "0",
"body": "Much better for the edit, but what about the parameters to `climbingLeaderboard()` does (supposedly) make it work? Don't write, never publish/commit undocumented/uncommented code!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-03T12:49:02.640",
"Id": "256680",
"ParentId": "244171",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "244261",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T14:27:44.467",
"Id": "244171",
"Score": "3",
"Tags": [
"java",
"algorithm",
"functional-programming",
"memory-optimization"
],
"Title": "Hackerrank problem: Climbing the Leaderboard (Java)"
}
|
244171
|
<p>I use TinyMCE with responsivefilemanager and I wanted to know that is my code well-written maintainable and readable, Sorry If this sounds like a stupid and basic question because this is such a basic thing to do, and I have also been in web dev for a long time but I am new at WYSIWYG editors and TinyMCE.</p>
<p>Here is my file structure</p>
<pre><code>Website's main parent folder/public_html
myapp folder for the whole app
my HTML & some PHP files which use TinyMCE and responsivefilemanager
my tinyMCE's init.js file
plugins folder for all my 3rd party plugins
TinyMCE folder which contains TinyMCE itself
other folders you find inside TinyMCE
a plugins folder inside TinyMCE used for plugins related to it
filemanager folder for the responsivefilemanager plugin
</code></pre>
<p>Here is my necessary code of config.php file which is inside the filemanager's config folder</p>
<pre><code><?php
/*
|--------------------------------------------------------------------------
| DON'T TOUCH (base url (only domain) of site).
|--------------------------------------------------------------------------
|
| without final / (DON'T TOUCH)
|
*/
'base_url' => ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http"). "://". @$_SERVER['HTTP_HOST'],
/*
|--------------------------------------------------------------------------
| path from base_url to base of upload folder
|--------------------------------------------------------------------------
|
| with start and final /
|
*/
'upload_dir' => '/myapp/uploads/',
/*
|--------------------------------------------------------------------------
| relative path from filemanager folder to upload folder
|--------------------------------------------------------------------------
|
| with final /
|
*/
'current_path' => '../../uploads/',
/*
|--------------------------------------------------------------------------
| relative path from filemanager folder to thumbs folder
|--------------------------------------------------------------------------
|
| with final /
| DO NOT put inside upload folder
|
*/
'thumbs_base_path' => '../../thumb/',
?>
</code></pre>
<p>My init.js file so I can initialize TinyMCE for my textarea</p>
<pre><code> tinymce.init({
selector: "textarea",
plugins: [
"advlist autolink link image lists charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
"table contextmenu directionality emoticons paste textcolor responsivefilemanager code codesample"
],
toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
toolbar2: "| responsivefilemanager | link unlink anchor | image media | codesample | forecolor backcolor | print preview code ",
image_advtab: true,
branding: false,
external_filemanager_path: "plugins/filemanager/",
filemanager_title: "Scintilla Filemanager for Lessons",
external_plugins: {
"filemanager": "plugins/filemanager/plugin.min.js"
}
});
tinymce.init(demoBaseConfig);
</code></pre>
|
[] |
[
{
"body": "<p>How you want to arrange your JS files depends also on your build processes too, and whether you want to utilise the cloud version of TinyMCE, or a self-hosted one.</p>\n<p>If you're sticking with self-hosted, I find it easier to move external plugins out of the TinyMCE folder - this just makes updating the TinyMCE core easier. You can replace an entire TinyMCE folder with a new version, and know that the Responsive File Manager is not lost.</p>\n<p>I would recommend splitting any external plugins (like Responsive File Manager, or anything else you write yourself too) to a separate folder outside of the TinyMCE folder - in the long run, just makes it easier to maintain.</p>\n<p>Alternatively, you could use the TinyMCE cloud version - which means you don't need to host it yourself, and you would get the minor point updates as they come out (which for the 5 version have had some really nice features added). To do this, you can visit tiny.cloud and sign up for an API key, which is free. They offer premium plugins at a cost if there are features that you want to use.</p>\n<p>For the config.php file, that all looks fine - it's about tweaking it to suit your folder structure.</p>\n<p>In your init.js file, I'm assuming you have two different TinyMCE configs? If that is <em>not</em> the case, and you only have one configuration, then you don't need your second init call - the one that references "demoBaseConfig" could be removed.</p>\n<p>The first call is initialising TinyMCE on any textarea, using the plugins and toolbar as stated, and hooking in to the Responsive File Manager.</p>\n<p>If you wanted to clean it up, you could slim down your plugins array to only include those that you're actually using. There are some plugins here that you don't have in your toolbar, so could slim down the configuration further.</p>\n<p>One thing I have done when using TinyMCE is have a number of JS objects that store different configurations, with a selector of "textarea.simple" or "textarea.full" (for two editor types).</p>\n<p>The two configurations here are a simple editor (such as maybe basic text choices, adding links, etc) where as the full is a more feature-rich experience too. There are times when you may want to give your users a HTML editor but without too many options (such as for a bio or small snippet) and others where they need a full suite of options (like an article editor). This is more about UX, but just something to be aware of - not every TinyMCE instance needs to look the same.</p>\n<p>If you were to go down this path, you would have one init call per configuration option, such as:</p>\n<pre><code>tinymce.init({\n selector: "textarea.simple",\n ... \n [whatever simple config options you need]\n});\n\ntinymce.init({\n selector: "textarea.full",\n ... \n [whatever full suite config options you need]\n});\n</code></pre>\n<p>Just remember to add the appropriate class to your textarea and you'll be good to go.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T02:37:42.753",
"Id": "479425",
"Score": "0",
"body": "Thank you Marty for such a helpful answer and I see that you are a new contributor so good luck buddy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T03:26:26.640",
"Id": "479426",
"Score": "0",
"body": "You're welcome! First time contributor, but long time TinyMCE user (I also write some blog posts for the Tiny team too)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T20:05:35.627",
"Id": "480845",
"Score": "0",
"body": "aam as you said you are a long time tinymce user can I have some help from you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T23:48:36.580",
"Id": "481003",
"Score": "0",
"body": "Sure thing - perhaps create a new question here just to keep on topic - or send me an email (contact form is on my website, and link is in my profile). Happy to help where I can."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T16:31:25.173",
"Id": "481126",
"Score": "0",
"body": "I replied to you on the contact form of your website, my email was graphicson28@gmail.com"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T00:26:50.593",
"Id": "244209",
"ParentId": "244174",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "244209",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T15:36:57.327",
"Id": "244174",
"Score": "7",
"Tags": [
"javascript",
"beginner",
"php",
"text-editor"
],
"Title": "Using TinyMCE with responsive file manager PHP and Javascript"
}
|
244174
|
<p>I am writing an array-like data structure for types other than 8 16 32 64 – the usual type sizes.</p>
<p>Ideally, my interface is the following for addressing the array.</p>
<pre><code>void setindex(uint8_t *array, size_t width, size_t index, uint64_t value);
uint64_t getindex(uint8_t *array, size_t width, size_t index);
</code></pre>
<p>This is basically an array of unsigned integers of size <code>width</code>. A <code>uint8_t</code> value would contain 4 elements for <code>width=2</code>, at max.
This should hold no more metadata than that. So in theory, it should work with any blob of allocated memory. Bound-checks should be done by the caller.</p>
<p>I have the following code, packed as a very small header library:</p>
<pre><code>#include <cstdio>
#include <iostream>
#include <bitset>
#include <cassert>
using namespace std;
uint64_t getindex(uint64_t *A, size_t width, size_t index)
{
uint64_t mask, mask1, mask2, ret, shift;
uint64_t size, d, m;
size = sizeof A[0] * 8;
mask = (1 << width) - 1;
shift = index * width;
// Any decent compiler does this in one instruction
d = (index + 1) * width / size;
m = (index + 1) * width % size;
if (!d) {
ret = (*A & (mask << (shift))) >> shift;
} else {
mask1 = (1 << m) - 1;
mask2 = (1 << (width - m)) - 1;
ret = (A[d] & mask1) << (width - m) | (A[d - 1] & (mask2 << (size - (width - m)))) >> (size - (width - m));
}
return ret;
}
uint64_t setindex(uint64_t *A, size_t width, size_t index, uint64_t value)
{
uint64_t mask, mask1, mask2, shift;
uint64_t size, d, m;
assert(value < (1 << width));
size = sizeof A[0] * 8;
mask = (1 << width) - 1;
shift = index * width;
// Any decent compiler does this in one instruction
d = (index + 1) * width / size;
m = (index + 1) * width % size;
if (!d) {
A[0] = (A[0] & ~(mask << (shift))) | (value << shift);
} else {
mask1 = (1 << m) - 1;
mask2 = (1 << (width - m)) - 1;
A[d] = (A[d] & ~mask1) | (((mask1 << (width - m)) & value) >> (width - m));
A[d - 1] = A[d - 1] & ~(mask2 << size - m) | ((mask2 & value) << (size - (width - m)));
}
return value;
}
</code></pre>
<p>I come from C, so the code may be very C-like, as I don't fully know most of the C++ features well.</p>
<p>Can this be simplified and made more robust? The above code may have problems with bit shifting and undefined behavior. I have the feeling that this problem is very well suited for <code>for</code>s and <code>divmod</code>s algorithms, like those used to construct <code>gcd</code>. But in my implementation, I did not manage to do that. Are there existing libraries I can better use?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:08:03.500",
"Id": "479362",
"Score": "1",
"body": "@Reinderien Done, I was trying out a new config for my editor, and I hadn't changed the defaults."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T11:08:16.463",
"Id": "479756",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Please consider asking a new question instead and feel free to add links back-and-forth."
}
] |
[
{
"body": "<ul>\n<li><p><code>using namespace std;</code> is a bad practice.</p>\n</li>\n<li><p>The code is plain C. You have two options:</p>\n<ol>\n<li><p>Admit this fact, change your <code>#include</code>s to the C-style, and declare your functions as <code>extern "C"</code>. This way they are callable from both C and C++ code.</p>\n</li>\n<li><p>Make a class, and overload <code>operator[](std::size_t)</code> and <code>operator[](std::size_t) const</code>. The <code>width</code> shall be a class member. Much more C++ish.</p>\n</li>\n</ol>\n</li>\n<li><p>An <code>A</code> parameter to <code>getindex</code> should be <code>const</code>-qualified.</p>\n</li>\n<li><p>Declare variables as close to use as possible. E.g. instead of</p>\n<pre><code> uint64_t mask1;\n ....\n if () {\n ....\n } else {\n mask1 = ....;\n }\n</code></pre>\n<p>do</p>\n<pre><code> ....\n if () {\n } else {\n uint64_t mask2 = ....\n</code></pre>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:19:33.743",
"Id": "244178",
"ParentId": "244175",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T15:39:41.853",
"Id": "244175",
"Score": "3",
"Tags": [
"c++",
"array",
"bitwise"
],
"Title": "Array-like data structure for fixed sized types with non-machine-word sizes"
}
|
244175
|
<p>The program is to get the nearest prime number to a number while adding a number. I solved the problem but I wish to optimize the code.</p>
<pre><code>import time
def isprime(a ,d):
b=a
c=0
f=b**(0.5)
for i in range(1,int(f)+1):
if a%i==0 and c<=1:
c+=1
if c==1:
return d.append(b)
else:
b=a+1
isprime(b,d)
start=time.time()
b=[89, 54,36, 74, 44, 19, 12] # Input
d=[]
for i in b:
isprime(i,d) #function call
print(d) #output is [89, 59, 37, 79, 47, 19, 13]
stop=time.time()
print(stop-start) #0.0001347064971923828 Seconds
</code></pre>
<p>Help with Code optimization. I'm just a beginner I know code is of lower. Help to learn bit of coding.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:40:17.607",
"Id": "479408",
"Score": "0",
"body": "Sympy has a [nextprime](https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.generate.nextprime), which practically does what’s in the title of your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T04:15:19.497",
"Id": "479427",
"Score": "0",
"body": "@Graipher I don't want a nearest prime. I want which number is add to get a prime"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T05:12:34.033",
"Id": "479429",
"Score": "0",
"body": "@Deepan Then you should [edit] your question and change your explanation."
}
] |
[
{
"body": "<p>To be cheeky, the ultimate optimization is "don't use Python for numerics", and the next-best optimization is "use a library rather than writing this yourself".</p>\n<p>It's worth having a read through <a href=\"https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python\">https://stackoverflow.com/questions/4114167/checking-if-a-number-is-a-prime-number-in-python</a></p>\n<p>Also consider calling into <a href=\"https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.primetest.isprime\" rel=\"nofollow noreferrer\">https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.primetest.isprime</a> .</p>\n<p>Otherwise:</p>\n<h2>Roots</h2>\n<p>I do not trust Python to do the right thing here:</p>\n<pre><code>b**(0.5)\n</code></pre>\n<p>Just call <code>isqrt</code> instead, which will be more likely to get an optimized implementation. This is confirmed here: <a href=\"https://stackoverflow.com/questions/327002/which-is-faster-in-python-x-5-or-math-sqrtx\">https://stackoverflow.com/questions/327002/which-is-faster-in-python-x-5-or-math-sqrtx</a></p>\n<h2>Variable names</h2>\n<p>You need to get out of the habit of single-letter variable names. I have no idea what <code>b</code> means other than inferring based on context.</p>\n<h2>Time measurement</h2>\n<p>Use <code>timeit</code>. Your current implementation only has a single iteration for each of the input values and is thus extremely vulnerable to CPU thread-switching noise, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T04:50:01.257",
"Id": "479428",
"Score": "2",
"body": "Actually, [`isqrt(x)`](https://docs.python.org/3.8/library/math.html#math.isqrt) is the function you want to use. It remains accurate even when the input exceeds the value which can be accurately represented in a `float`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T10:11:27.997",
"Id": "479437",
"Score": "0",
"body": "Single letter variable names are not a bad habit. I'd much rather see a for loop indexed with \"i\" than something stupid like \"l_loop_index\". Similarly, temporary computation variables are perfectly fine to be called a,b,x,y,..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T02:25:50.157",
"Id": "479512",
"Score": "0",
"body": "@CaptainCodeman I disagree, and `i_loop_index` is a poor counter-example, because it's just as meaningless as `i`. Given the choice between (say) `i` and `factor_index` I would prefer the latter every time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T09:37:06.163",
"Id": "479627",
"Score": "0",
"body": "@Reinderien If you cannot keep track of abstract concepts like \"i\" you have no business in software development. Try a career in teaching."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T18:37:20.080",
"Id": "244187",
"ParentId": "244179",
"Score": "6"
}
},
{
"body": "<p>First, some comments on your code:</p>\n<ul>\n<li><p><code>return d.append(b)</code> is not very nice. You would think this function actually returns something, but this just returns <code>None</code>. Instead you modify a list being passed in as a parameter. This is a very C thing to do. Instead, just return the boolean value and use it to build a list using a list comprehension:</p>\n<pre><code> d = [x for x in b if isprime(x)]\n</code></pre>\n</li>\n<li><p>Note that this now no longer solves the problem. That is because your naming should be improved. The <code>isprime</code> function does not actually check if a number is prime. It does that somewhere in its implementation, but that is not what it really does. I would rename the function to something like <code>nearest_prime</code>. You should also try to avoid single letter variable names. A few exceptions like integers called <code>i</code> might exist, but not too many.</p>\n</li>\n<li><p>You also generally want to avoid writing recursive functions in Python. Python has a maximum recursion limit, it does not do tail call optimization. Instead make your function iterative.</p>\n</li>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using spaces around <code>=</code> when using it for assignment.</p>\n</li>\n<li><p>You should always add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a> to your functions.</p>\n</li>\n</ul>\n<hr />\n<p>This part of the answer assumes that you want what is written in your title, and not what is written in the question. The number you want is the next larger prime, unless the number is prime itself.</p>\n<p>In any case, you can greatly speed up your code by pre-computing the primes. This will be only really worth it if you query enough numbers.</p>\n<p>For getting lots of prime numbers fast, you want to use a prime sieve. Here is the most simple one, the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>:</p>\n<pre><code>def prime_sieve(limit):\n """Generator that yields all prime number up to `limit`."""\n prime = [True] * limit\n prime[0] = prime[1] = False\n\n for i, is_prime in enumerate(prime):\n if is_prime:\n yield i\n for n in range(i * i, limit, i):\n prime[n] = False\n</code></pre>\n<p>The hard part is then knowing up to which number to get the primes. I'm going to ignore this and just use a large enough number (since I know all numbers you are going to test). In your code you might want to automate finding that number.</p>\n<p>For finding the next bigger prime, or the number itself, we just have to look in the list of primes until we either find our number or a number that is bigger than our number. We could do a linear search for it, but it will be faster to do a binary search (since the primes are already sorted). For this you can use the <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"nofollow noreferrer\"><code>bisect</code></a> module, which is in the standard library:</p>\n<pre><code>from bisect import bisect_left\n\ndef nearest_prime(x, primes):\n """Find the first prime number from `primes` greater or equal to `x`."""\n return primes[bisect_left(primes, x)]\n</code></pre>\n<p>And that's really already it. Just add your calling code under a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == "__main__":</code> guard</a> to allow importing from this module without the example code being run and you're done:</p>\n<pre><code>if __name__ == "__main__":\n primes = list(prime_sieve(100))\n numbers = [89, 54, 36, 74, 44, 19, 12]\n nearest_primes = [nearest_prime(x, primes) for x in numbers]\n print(nearest_primes)\n # [89, 59, 37, 79, 47, 19, 13]\n</code></pre>\n<p>On my machine, your code takes 0.00015s, while this takes 0.00004s. But as I said, this will be even faster the more numbers you check.</p>\n<hr />\n<p>If you really do mean the nearest prime (so it can also be smaller), it takes only one extra step, we also need to check the prime number before the index we get:</p>\n<pre><code>def nearest_prime(x, primes):\n """Find the closest prime number to `x` in `primes`."""\n i = bisect_left(primes, x)\n return min(primes[i - 1], primes[i], key=lambda y: abs(x - y))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T18:56:33.333",
"Id": "479388",
"Score": "0",
"body": "_You also want to avoid writing recursive functions in Python_ - ish. This is a true statement only if it's qualified with _for unbounded input_ . In some cases, where the maximum recursion depth is well-known, it's a good solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:13:19.227",
"Id": "479389",
"Score": "1",
"body": "@Reinderien: I agree *-ish*. First note that in this case the input is potentially unbounded. The gap between prime numbers increases, so eventually you will hit the stack limit. Although in practice the input is limited, which I have also used in my answer. But then I think while there are use cases where the input is bounded so you know it is less than the stack limit, most of the time it is still better to rewrite it iteratively. Once because IMO it is more readable (probably because I'm not used to recursive code) and then because it gets you into the habit of not writing recursive code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:43:54.923",
"Id": "479394",
"Score": "0",
"body": "Also because Python doesn't have tail recursion optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:05:14.433",
"Id": "479399",
"Score": "0",
"body": "@Reinderien: Yes, that is the technical reason."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T14:16:30.320",
"Id": "479462",
"Score": "1",
"body": "Thanks for your recommendations"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T18:53:07.673",
"Id": "244188",
"ParentId": "244179",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T16:35:30.957",
"Id": "244179",
"Score": "8",
"Tags": [
"python",
"performance",
"primes"
],
"Title": "Add a number to a number to be prime number in python"
}
|
244179
|
<p>I am using PHP for detecting a user's IP address and displaying their details, and I use <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow noreferrer">OOP</a> (i.e. object-oriented programming).</p>
<p>Are there any problems in it or is it well-written?</p>
<h3>index.php:</h3>
<pre><code><?php
require('UserInfo.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>UserInfo Demo</title>
<style>
table {
margin-top: 20px;
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: center;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
h2{font-family: sans-serif,'Helvetica';}
</style>
</head>
<body>
<center><h2>UserInfo demo</h2></center>
<table>
<tr>
<th>Ip</th>
<th>Device</th>
<th>Os</th>
<th>Browser</th>
</tr>
<tr>
<td><?= UserInfo::get_ip();?></td>
<td><?= UserInfo::get_device();?></td>
<td><?= UserInfo::get_os();?></td>
<td><?= UserInfo::get_browser();?></td>
</tr>
</table>
</body>
</html>
</code></pre>
<h3>UserInfo.php</h3>
<pre><code><?php
class UserInfo{
private static function get_user_agent() {
return $_SERVER['HTTP_USER_AGENT'];
}
public static function get_ip() {
$mainIp = '';
if (getenv('HTTP_CLIENT_IP'))
$mainIp = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$mainIp = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$mainIp = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$mainIp = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$mainIp = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$mainIp = getenv('REMOTE_ADDR');
else
$mainIp = 'UNKNOWN';
return $mainIp;
}
public static function get_os() {
$user_agent = self::get_user_agent();
$os_platform = "Unknown OS Platform";
$os_array = array(
'/windows nt 10/i' => 'Windows 10',
'/windows nt 6.3/i' => 'Windows 8.1',
'/windows nt 6.2/i' => 'Windows 8',
'/windows nt 6.1/i' => 'Windows 7',
'/windows nt 6.0/i' => 'Windows Vista',
'/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
'/windows nt 5.1/i' => 'Windows XP',
'/windows xp/i' => 'Windows XP',
'/windows nt 5.0/i' => 'Windows 2000',
'/windows me/i' => 'Windows ME',
'/win98/i' => 'Windows 98',
'/win95/i' => 'Windows 95',
'/win16/i' => 'Windows 3.11',
'/macintosh|mac os x/i' => 'Mac OS X',
'/mac_powerpc/i' => 'Mac OS 9',
'/linux/i' => 'Linux',
'/ubuntu/i' => 'Ubuntu',
'/iphone/i' => 'iPhone',
'/ipod/i' => 'iPod',
'/ipad/i' => 'iPad',
'/android/i' => 'Android',
'/blackberry/i' => 'BlackBerry',
'/webos/i' => 'Mobile'
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$os_platform = $value;
}
}
return $os_platform;
}
public static function get_browser() {
$user_agent= self::get_user_agent();
$browser = "Unknown Browser";
$browser_array = array(
'/msie/i' => 'Internet Explorer',
'/Trident/i' => 'Internet Explorer',
'/firefox/i' => 'Firefox',
'/safari/i' => 'Safari',
'/chrome/i' => 'Chrome',
'/edge/i' => 'Edge',
'/opera/i' => 'Opera',
'/netscape/i' => 'Netscape',
'/maxthon/i' => 'Maxthon',
'/konqueror/i' => 'Konqueror',
'/ubrowser/i' => 'UC Browser',
'/mobile/i' => 'Handheld Browser'
);
foreach ($browser_array as $regex => $value) {
if (preg_match($regex, $user_agent)) {
$browser = $value;
}
}
return $browser;
}
public static function get_device(){
$tablet_browser = 0;
$mobile_browser = 0;
if (preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
$tablet_browser++;
}
if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {
$mobile_browser++;
}
if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))) {
$mobile_browser++;
}
$mobile_ua = strtolower(substr(self::get_user_agent(), 0, 4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda ','xda-');
if (in_array($mobile_ua,$mobile_agents)) {
$mobile_browser++;
}
if (strpos(strtolower(self::get_user_agent()),'opera mini') > 0) {
$mobile_browser++;
//Check for tablets on opera mini alternative headers
$stock_ua = strtolower(isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])?$_SERVER['HTTP_X_OPERAMINI_PHONE_UA']:(isset($_SERVER['HTTP_DEVICE_STOCK_UA'])?$_SERVER['HTTP_DEVICE_STOCK_UA']:''));
if (preg_match('/(tablet|ipad|playbook)|(android(?!.*mobile))/i', $stock_ua)) {
$tablet_browser++;
}
}
if ($tablet_browser > 0) {
// do something for tablet devices
return 'Tablet';
}
else if ($mobile_browser > 0) {
// do something for mobile devices
return 'Mobile';
}
else {
// do something for everything else
return 'Computer';
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>IP Detection.</h2>\n<p>You are confusing an IP address with an <strong>HTTP header</strong>, the latter being utterly unreliable. It is ridiculously simple to fake an HTTP header. There is an <a href=\"https://blog.ircmaxell.com/2012/11/anatomy-of-attack-how-i-hacked.html\" rel=\"nofollow noreferrer\">old cautionary tale by Anthony Ferrara</a> about how he unintentionally hacked Stack Overflow by manipulating headers. You may want to read about it. Not to mention that even if you catch one of these headers, it is quite possible that it would belong to a private network, whicih would make it essentially useless.</p>\n<p>In short, just use <code>REMOTE_ADDR</code> if you need an IP address and you have no good reason to use something else. For example, some web-servers are using a local proxy, and in this case <code>REMOTE_ADDR</code> always contains the proxy's IP, not the outside IP, while the latter being stored in some of the headers. In this particular case you can write a similar translator, but of course not a code that picks a random HTTP header out of the pile, but a certain header that is deliberately set by the proxy.</p>\n<h2>OOP</h2>\n<p>Sorry, there is no OOP. It's just a collection of functions, which are, for some reason, combined into a single class. You'd save yourself a few keystrokes if just remove the class and keep these methods as functions.</p>\n<p>If you want to learn OOP, maybe you could create a class to parse the user agent. It could accept the user agent string in the constructor and then give you various details through methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T12:10:59.097",
"Id": "479445",
"Score": "3",
"body": "*\"may be you could create a class to parse the user agent\"* - Although be aware that they too are unreliable and some browsers are even beginning to [phase them out](https://www.infoq.com/news/2020/03/chrome-phasing-user-agent/), so this should only really be done as a learning experience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T15:12:28.707",
"Id": "479466",
"Score": "0",
"body": "And the *inconsistent* indentation and use of empty lines?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T05:27:35.797",
"Id": "479517",
"Score": "0",
"body": "Thanks @Cody. I had something similar in my mind in making the link more descriptive but failed formulating. And thanks for the other edits."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T20:20:33.890",
"Id": "244194",
"ParentId": "244185",
"Score": "15"
}
},
{
"body": "<blockquote>\n<p>Are there any problems in it or is it well-written?</p>\n</blockquote>\n<p>Well, it is not really written in a simple manner - it is very redundant. 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>. For example, the following block:</p>\n<pre><code> if (getenv('HTTP_CLIENT_IP'))\n $mainIp = getenv('HTTP_CLIENT_IP');\n else if(getenv('HTTP_X_FORWARDED_FOR'))\n $mainIp = getenv('HTTP_X_FORWARDED_FOR');\n else if(getenv('HTTP_X_FORWARDED'))\n $mainIp = getenv('HTTP_X_FORWARDED');\n else if(getenv('HTTP_FORWARDED_FOR'))\n $mainIp = getenv('HTTP_FORWARDED_FOR');\n else if(getenv('HTTP_FORWARDED'))\n $mainIp = getenv('HTTP_FORWARDED');\n else if(getenv('REMOTE_ADDR'))\n $mainIp = getenv('REMOTE_ADDR');\n else\n $mainIp = 'UNKNOWN';\n return $mainIp;\n</code></pre>\n<p>Could be simplified by putting each key into an array:</p>\n<pre><code>$ipKeys = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', ...];\n</code></pre>\n<p>or that could be stored in a constant:</p>\n<pre><code>const IP_KEYS = ['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', ...];\n</code></pre>\n<p>Then iterate over those keys to set the value once a value is found:</p>\n<pre><code>foreach ($ipKeys as $key) {\n if (getenv($key)) {\n return getenv($key);\n }\n}\nreturn 'UNKNOWN';\n</code></pre>\n<p>As <a href=\"https://codereview.stackexchange.com/questions/244185/ip-address-detection-code/244200#comment479533_244200\">Gwyn Evans suggests</a> the return value of the call to <code>getenv()</code> can be stored in a variable and if that value doesn't evaluate to <code>false</code> then the variable can be returned, though this may go against an accepted coding standard/style guide so use with caution:</p>\n<pre><code>foreach ($ipKeys as $key) {\n if ($value = getenv($key)) {\n return $value;\n }\n}\nreturn 'UNKNOWN';\n</code></pre>\n<hr />\n<p>Also in the end of the method <code>get_device()</code> there are multiple <code>return</code> statements, which is fine, but each one is in a conditional block:</p>\n<blockquote>\n<pre><code> if ($tablet_browser > 0) {\n // do something for tablet devices\n return 'Tablet';\n }\n else if ($mobile_browser > 0) {\n // do something for mobile devices\n return 'Mobile';\n }\n else {\n // do something for everything else\n return 'Computer';\n }\n</code></pre>\n</blockquote>\n<p>The <code>else</code> keyword is not needed in the second and third cases, since the <code>return</code> in the previous cases would exit the method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T16:07:12.040",
"Id": "479471",
"Score": "0",
"body": "Isn't it possible to avoid the explicit loop by [predicates, array filters, or something like that](https://stackoverflow.com/questions/27720218/how-to-apply-a-function-to-every-foreach-result)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T11:55:11.923",
"Id": "479533",
"Score": "4",
"body": "Surely DRY suggests that the two calls to getenv() should be replaced with a single call with a saved result that's used for the test and return?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T18:28:56.887",
"Id": "479688",
"Score": "0",
"body": "@GwynEvans - good call. I have incorporated that advice. Many thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T21:20:14.940",
"Id": "479701",
"Score": "0",
"body": "The single-line condition with assignment can be split into two lines and maintain the same logic without risking any conflict with coding styles/standards."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:21:49.180",
"Id": "244200",
"ParentId": "244185",
"Score": "10"
}
},
{
"body": "<ul>\n<li><p>I don't see any value in writing a private method that fetches <code>$_SERVER</code> data. I mean, all you have to do is nominate the key and the value is accessed and I can't really foresee the need to change the source of the data -- so avoid the unnecessary overhead.</p>\n</li>\n<li><p>Running with YCS's advice to only rely on <code>REMOTE_ADDR</code>, that condition block can be reduced to a single line levering a ternary operator (i.e. <code>?:</code>).</p>\n</li>\n<li><p>Regex is great and powerful, but it should only be used when it offers a valuable advantage over simpler/faster methods. With the exception of <code>Mac OS X</code> (which employs an alternative/pipe), the <code>$os_array</code> is merely checking for the case-insensitive existence of a substring in the string -- this is performed by <code>stripos()</code> without rolling out the regex engine. Unless you are planning on finding multiple matches and returning the last match, you should write a conditional <code>break</code>/<code>return</code> for best efficiency in your loop.</p>\n</li>\n<li><p>Same advice again for <code>get_browser()</code>.</p>\n</li>\n<li><p>In <code>get_device()</code>, you only care if there is a generated value greater than 0 before your conditional expressions are satisfied -- so why bother counting higher than 1? Don't, of course, unless there is something in your script that you are not telling us (e.g. <code>// do something for tablet devices</code>). As soon as you have what you want, short circuit the flow and take the desired action(s).</p>\n</li>\n<li><p>Your first <code>$tablet_browser</code> regex pattern has unnecessary parentheses which can be removed without damaging the pattern logic. It is pointless to call <code>strtolower()</code> if your pattern has a case-insensitive flag on it. Omit the unneeded function call.</p>\n</li>\n<li><p>You didn't escape the dots in your regex pattern (<code>up.browser|up.link</code>), this makes your pattern potentially less accurate.</p>\n</li>\n<li><p>As a general piece of advice, pay closer attention to spacing and tabbing. Keeping your script in good spacing makes it easier to read and maintain.</p>\n</li>\n<li><p>Writing <code>else if</code> as two words in PHP is <a href=\"https://www.php-fig.org/psr/psr-12/#:%7E:text=The%20keyword%20elseif%20SHOULD%20be%20used%20instead%20of%20else%20if%20so%20that%20all%20control%20keywords%20look%20like%20single%20words.\" rel=\"nofollow noreferrer\">a violation of PSR-12 guidelines</a>. It is effectively using two separate <a href=\"https://www.php.net/manual/en/reserved.keywords.php\" rel=\"nofollow noreferrer\">control structures</a> -- the former of which is not enjoying the expected curly brace syntax.</p>\n</li>\n<li><p>It is good practice to define the return data type from each method.</p>\n</li>\n</ul>\n<p>Code:</p>\n<pre><code>class UserInfo\n{ \n public static function get_ip(): string\n {\n return getenv('REMOTE_ADDR') ?: 'UNKNOWN';\n }\n\n public static function get_os(): string\n {\n $os_array = [\n 'windows nt 10' => 'Windows 10',\n 'windows nt 6.3' => 'Windows 8.1',\n 'windows nt 6.2' => 'Windows 8',\n 'windows nt 6.1' => 'Windows 7',\n 'windows nt 6.0' => 'Windows Vista',\n 'windows nt 5.2' => 'Windows Server 2003/XP x64',\n 'windows nt 5.1' => 'Windows XP',\n 'windows xp' => 'Windows XP',\n 'windows nt 5.0' => 'Windows 2000',\n 'windows me' => 'Windows ME',\n 'win98' => 'Windows 98',\n 'win95' => 'Windows 95',\n 'win16' => 'Windows 3.11',\n 'macintosh' => 'Mac OS X',\n 'mac os x' => 'Mac OS X',\n 'mac_powerpc' => 'Mac OS 9',\n 'linux' => 'Linux',\n 'ubuntu' => 'Ubuntu',\n 'iphone' => 'iPhone',\n 'ipod' => 'iPod',\n 'ipad' => 'iPad',\n 'android' => 'Android',\n 'blackberry' => 'BlackBerry',\n 'webos' => 'Mobile'\n ];\n\n foreach ($os_array as $substring => $value) {\n if (stripos($_SERVER['HTTP_USER_AGENT'], $substring) !== false) {\n return $value;\n }\n } \n return "Unknown OS Platform";\n }\n\n public static function get_browser(): string\n {\n $browser_array = [\n 'msie' => 'Internet Explorer',\n 'Trident' => 'Internet Explorer',\n 'firefox' => 'Firefox',\n 'safari' => 'Safari',\n 'chrome' => 'Chrome',\n 'edge' => 'Edge',\n 'opera' => 'Opera',\n 'netscape' => 'Netscape',\n 'maxthon' => 'Maxthon',\n 'konqueror' => 'Konqueror',\n 'ubrowser' => 'UC Browser',\n 'mobile' => 'Handheld Browser'\n ];\n\n foreach ($browser_array as $substring => $value) {\n if (stripos($_SERVER['HTTP_USER_AGENT'], $substring) !== false) {\n return $value;\n }\n }\n return "Unknown Browser";\n }\n\n public static function get_device(): string\n {\n if (preg_match('/tablet|ipad|playbook|android(?!.*(mobi|opera mini))/i', $_SERVER['HTTP_USER_AGENT'])) {\n // do something for tablet devices\n return 'Tablet';\n }\n if (stripos($_SERVER['HTTP_USER_AGENT'], 'opera mini') !== false) {\n $stock_ua = $_SERVER['HTTP_X_OPERAMINI_PHONE_UA'] ?? $_SERVER['HTTP_DEVICE_STOCK_UA'] ?? '';\n if (preg_match('/tablet|ipad|playbook|android(?!.*mobile)/i', $stock_ua)) {\n // do something for tablet devices\n return 'Tablet';\n }\n // do something for mobile devices\n return 'Mobile';\n }\n\n $mobile_keywords = ['up.browser', 'up.link', 'mmp', 'symbian', 'smartphone', 'midp', 'wap', 'phone', 'android', 'iemobile'];\n foreach ($mobile_keywords as $keyword) {\n if (stripos($_SERVER['HTTP_USER_AGENT'], $keyword) !== false) {\n // do something for mobile devices\n return 'Mobile';\n }\n }\n\n if (stripos($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') > 0 || isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {\n // do something for mobile devices\n return 'Mobile';\n }\n\n $mobile_agents = [\n 'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',\n 'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',\n 'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',\n 'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',\n 'newt', 'noki', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox', 'qwap',\n 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar', 'sie-',\n 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-', 'tosh',\n 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp', 'wapr',\n 'webc', 'winw', 'winw', 'xda ', 'xda-'\n ];\n if (in_array(strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4)), $mobile_agents)) {\n // do something for mobile devices\n return 'Mobile';\n }\n\n // do something for everything else\n return 'Computer';\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:13:16.360",
"Id": "244267",
"ParentId": "244185",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244194",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T17:52:58.603",
"Id": "244185",
"Score": "11",
"Tags": [
"php",
"object-oriented",
"html",
"css",
"ip-address"
],
"Title": "IP address detection code"
}
|
244185
|
<p>I'm posting my C++ code for LeetCode's <a href="https://leetcode.com/problems/snapshot-array/" rel="nofollow noreferrer">Snapshot Array</a>. If you have time and would like to review, please do so. Thank you!</p>
<h2>Problem</h2>
<blockquote>
<p>Implement a SnapshotArray that supports the following interface:</p>
<ul>
<li>SnapshotArray(int length) initializes an array-like data structure with the given length. Initially, each element equals 0.</li>
<li>void set(index, val) sets the element at the given index to be equal to val.</li>
<li>int snap() takes a snapshot of the array and returns the snap_id: the total number of times we called snap() minus 1.</li>
<li>int get(index, snap_id) returns the value at the given index, at the time we took the snapshot with the given snap_id</li>
</ul>
<h3>Example 1:</h3>
<p>Input: ["SnapshotArray","set","snap","set","get"]
[[3],[0,5],[],[0,6],[0,0]] Output: [null,null,0,null,5] Explanation:</p>
<ul>
<li>SnapshotArray snapshotArr = new SnapshotArray(3); // set the length to be 3</li>
<li>snapshotArr.set(0,5); // Set array[0] = 5</li>
<li>snapshotArr.snap(); // Take a snapshot, return snap_id = 0</li>
<li>snapshotArr.set(0,6);</li>
<li>snapshotArr.get(0,0); // Get the value of array[0] with snap_id = 0, return 5</li>
</ul>
<h3>Constraints:</h3>
<ul>
<li>1 <= length <= 50000</li>
<li>At most 50000 calls will be made to set, snap, and get.</li>
<li>0 <= index < length</li>
<li>0 <= snap_id < (the total number of times we call snap())</li>
<li>0 <= val <= 10^9</li>
</ul>
</blockquote>
<h3>LeetCode Template</h3>
<pre><code>class SnapshotArray {
public:
SnapshotArray(int length) {
}
void set(int index, int val) {
}
int snap() {
}
int get(int index, int snap_id) {
}
};
/**
* Your SnapshotArray object will be instantiated and called as such:
* SnapshotArray* obj = new SnapshotArray(length);
* obj->set(index,val);
* int param_2 = obj->snap();
* int param_3 = obj->get(index,snap_id);
*/
</code></pre>
<h3>Accepted C++</h3>
<pre><code>class SnapshotArray {
public:
SnapshotArray(const int array_length) {}
int curr_shot_id = 0;
std::unordered_map<int, std::vector<pair<int, int>>> id_map;
// Returns current snapshot O(1)
const int snap() {
return curr_shot_id++;
}
// Setter with unordered_map
const void set(const int key, const int shot_id) {
if (id_map[key].empty() || id_map[key].back().first != curr_shot_id) {
id_map[key].push_back({curr_shot_id, shot_id});
} else {
id_map[key].back().second = shot_id;
}
}
// Getter with binary searching -> O(1) memory O(log N) time
const int get(const int key, const int shot_id) {
const auto iter = std::upper_bound(id_map[key].begin(), id_map[key].end(), std::pair<int, int>(shot_id, INT_MAX));
return iter == std::begin(id_map[key]) ? 0 : std::prev(iter)->second;
}
};
</code></pre>
<h3>Reference</h3>
<p>LeetCode is a platform only for <a href="https://leetcode.com/discuss/interview-question?currentPage=1&orderBy=hot&query=" rel="nofollow noreferrer">interviewing</a> and <a href="https://leetcode.com/contest/globalranking" rel="nofollow noreferrer">competitive programming</a>. On LeetCode, there is a class usually named <code>Solution</code> (for this post is <code>SnapshotArray</code>) with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><a href="https://leetcode.com/problems/evaluate-division/" rel="nofollow noreferrer">Question</a></li>
<li><a href="https://leetcode.com/problems/evaluate-division/discuss/" rel="nofollow noreferrer">Discussion</a></li>
</ul>
|
[] |
[
{
"body": "<p>The class template provided provides the necessary public interface, anything else should be private rather than public. Therefore the variable <code>int curr_shot_id</code> and the variable <code>std::unordered_map<int, std::vector<pair<int, int>>> id_map;</code> should be declared after <code>private:</code>.</p>\n<p>The variable <code>curr_shot_id</code> should be initialized by the constructor <code>SnapshotArray(int length)</code>.</p>\n<pre><code> SnapshotArray(int length)\n : curr_shot_id{0}\n { }\n</code></pre>\n<p>It's not clear that you need a binary search of the map since a map is a direct access memory structure which means that the key will be hashed and that provides a direct reference to the object stored.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:59:37.360",
"Id": "479411",
"Score": "1",
"body": "The protected classification is if there are classes that will inherit from the SnapshotArray class and need access to those fields. In this case there will be no inheritance so they can be private."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:45:16.070",
"Id": "244197",
"ParentId": "244186",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244197",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T18:22:22.303",
"Id": "244186",
"Score": "1",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 1146: Snapshot Array"
}
|
244186
|
<p><a href="https://i.stack.imgur.com/Ck8Pz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ck8Pz.jpg" alt="enter image description here" /></a></p>
<p><strong>Here is my solution:
I want to know if my solution fits the requirement 100%? Or if there is any better solution?</strong></p>
<p><strong>Constraint of the question:</strong></p>
<ol>
<li>must be singly linkedlist</li>
<li>must use recursion, and no helper methods allowed.</li>
<li>The method must return the head node of the merged list.</li>
</ol>
<pre><code>class Solution{
Node dummy=new Node(0,null);// the dummy node to store the merged result
public Node mergeAscend(Node a,Node b){
if(a==null&&b==null){//base case
return null;
}
else{
if((a!=null&&b==null)||a.value>=b.value){// insert "b" after dummy
//store the next node of current a, before pointing a.next to dummy.next;
Node store_a_next_node=a.next;
//insert Node "a" between dummy and dummy.next
a.next=dummy.next;
dummy.next=a;
mergeAscend(store_a_next_node,b);
}
else if((a==null&&b!=null)||a.value<b.value){//insert "a" after dummy
Node store_b_next_node=b.next;
b.next=dummy.next;
dummy.next=b;
mergeAscend(a,store_b_next_node);
}
}
return dummy.next;
}
}
</code></pre>
<pre><code>class Node {
public int value;
public Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T23:24:38.590",
"Id": "479418",
"Score": "0",
"body": "Hello, for information, the `Node` class is missing, it's a bit hard to do a proper code review when the code is not compiling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T14:42:24.283",
"Id": "479465",
"Score": "0",
"body": "Thank you for reminding me. I just added Node class"
}
] |
[
{
"body": "<h2>Compilation Error</h2>\n<p>The first problem is to solve the compiling error.</p>\n<p>Just follow the interface:</p>\n<pre><code> public Node<Integer> mergeAscend(Node<Integer> a, Node<Integer> b) \n</code></pre>\n<h2>Warnings and Code convention</h2>\n<p>You should add the type information to the store_next_a_node variable (and store_next_b_node). Additionally, in <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">Java naming conversion</a>, variable names use camel case. Therefore, I suggest substitute:</p>\n<pre><code> Node store_next_a_node = a.next;\n ...\n Node store_next_b_node = b.next;\n\n</code></pre>\n<p>By...</p>\n<pre><code> Node<Integer> nextNode = a.next;\n</code></pre>\n<h3>Simple "Test Case"</h3>\n<p>The code bellow is just an example and not a full automated test (for more information, look for Java automated tests. eg: <a href=\"https://www.vogella.com/tutorials/JUnit/article.html\" rel=\"nofollow noreferrer\">junit tutorial</a>).But it is enough to give us some hints what is going on. For example, we can see the original code does not solve the problem. Let us write a simple test case:</p>\n<pre><code> public static void main(String[] args) {\n Solution solution = new Solution();\n int[] a = { 6, 4, 2 };\n Node<Integer> h1 = new Node<>(8, null);\n Node<Integer> previous = h1;\n for (int value : a) {\n Node<Integer> node = new Node<>(value, null);\n previous.next = node;\n previous = node;\n }\n\n\n int[] b = { 7, 5, 3, 1 };\n Node<Integer> h2 = new Node<>(9, null);\n previous = h2;\n for (int value : b) {\n Node<Integer> node = new Node<>(value, null);\n previous.next = node;\n previous = node;\n }\n solution.mergeAscend(h1, h2);\n Node<Integer> iterator = solution.dummy;\n while (iterator != null) {\n System.out.println(iterator.value);\n iterator = iterator.next;\n }\n }\n\n</code></pre>\n<p>The expected output would be the numbers printed in ascending order as the exercise suggests.</p>\n<h2>NullPointerException</h2>\n<p>With the test case, we can execute the code and and we will get a null pointer exception during the execution:</p>\n<pre><code>Exception in thread "main" java.lang.NullPointerException\n at Solution.mergeAscend(Solution.java:13)\n at Solution.mergeAscend(Solution.java:19)\n at Solution.mergeAscend(Solution.java:24)\n at Solution.mergeAscend(Solution.java:19)\n at Solution.mergeAscend(Solution.java:24)\n at Solution.mergeAscend(Solution.java:19)\n at Solution.mergeAscend(Solution.java:24)\n at Solution.mergeAscend(Solution.java:19)\n at Solution.mergeAscend(Solution.java:24)\n at Solution.main(Solution.java:50)\n</code></pre>\n<h3>Bug</h3>\n<p>If you look the code, the following statement is suspicious:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if((a!=null&&b==null)||a.value>=b.value)\n</code></pre>\n<p>What if <code>a</code> is null and b is not null? First condition is false and Java interpreter will try to evaluate the second condition. Unfortunately, a.value will throw a NullPointerException.</p>\n<p><em>Next Step: How to fix it ?</em></p>\n<h2>Clean Code makes our life easier</h2>\n<p>Let's make the code cleaner . In our case, we want to preserve the original code ideas and just simplifying what is possible. Hopefully we will remove the conditions that make the code to fail.</p>\n<h3>Remove unnecessary else-statement</h3>\n<p>First, after the base case, we don't need a else-statement. Change..</p>\n<pre class=\"lang-java prettyprint-override\"><code> if (a == null && b == null) {//base case\n return null;\n }\n else {\n ...\n }\n\n</code></pre>\n<p>to</p>\n<pre class=\"lang-java prettyprint-override\"><code> if (a == null && b == null) {//base case\n return null;\n }\n ...\n\n</code></pre>\n<h3>Nullability test only once</h3>\n<p>Second, remove the complication of testing <code>a</code> nullability all the time.</p>\n<p>Just add the following check after the base case.</p>\n<pre class=\"lang-java prettyprint-override\"><code> if (a == null)\n return mergeAscend(b, a);\n</code></pre>\n<p>With that, now we know that <code>a</code> is the longest list and we don't need to check again and again that condition.</p>\n<p>So, your second "if-statement" can be change from</p>\n<pre class=\"lang-java prettyprint-override\"><code> if ( (a!=null && b==null) || a.value >= b.value)\n</code></pre>\n<p>to:</p>\n<pre class=\"lang-java prettyprint-override\"><code> if (b == null || a.value >= b.value) // insert "b" after dummy\n</code></pre>\n<h3>Remove unnecessary if-statement</h3>\n<p>After that, we might think about it... we don't need the third "if-statement". Just remove it.</p>\n<pre class=\"lang-java prettyprint-override\"><code> else if((a==null&&b!=null)||a.value<b.value){\n ...\n }\n</code></pre>\n<p>To...</p>\n<pre class=\"lang-java prettyprint-override\"><code> else {\n ...\n }\n</code></pre>\n<h3>Congrats, your code now works!</h3>\n<pre class=\"lang-java prettyprint-override\"><code> public Node<Integer> mergeAscend(Node<Integer> a, Node<Integer> b) {\n if (a == null && b == null) {//base case\n return null;\n }\n if (a == null)\n return mergeAscend(b, a);\n if (b == null || a.value >= b.value) {// insert "a" after dummy\n //store the next node of current a, before pointing a.next to dummy.next;\n Node<Integer> nextNode = a.next;\n //insert Node "a" between dummy and dummy.next\n a.next = dummy.next;\n dummy.next = a;\n mergeAscend(nextNode, b);\n } else {\n Node<Integer> nextNode = b.next;\n b.next = dummy.next;\n dummy.next = b;\n mergeAscend(a, nextNode);\n }\n return dummy.next;\n }\n</code></pre>\n<p>Test it!</p>\n<h3>PS: Another Minor Thing - Comment misleading</h3>\n<p>Your code comments are misleading. In the second if-statement, if the statement evaluate the expression as true, code below add <code>a</code> between dummy and dummy.next.</p>\n<p>change</p>\n<pre class=\"lang-java prettyprint-override\"><code>// insert "b" after dummy\n</code></pre>\n<p>To</p>\n<pre class=\"lang-java prettyprint-override\"><code>// insert "a" after dummy\n</code></pre>\n<h2>PS2: Symmetric symplification</h2>\n<p>Evaluating the code again, we might found the code is a little redundant. It means, part of the code is doing exactly the same thing, but the variable names are just swapped. In that case, we can simplify it further.</p>\n<pre class=\"lang-java prettyprint-override\"><code> public Node<Integer> mergeAscend(Node<Integer> a, Node<Integer> b) {\n if (a == null && b == null) {//base case\n return dummy.next;\n }\n if (a == null || (b != null && a.value < b.value)) { // symmetric case\n return mergeAscend(b, a);\n }\n //store the next node of current a, before pointing a.next to dummy.next;\n //insert Node "a" between dummy and dummy.next\n Node<Integer> nextNode = a.next;\n a.next = dummy.next;\n dummy.next = a;\n return mergeAscend(nextNode, b);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T20:38:38.573",
"Id": "479500",
"Score": "0",
"body": "Wow,Thank you soooo much for this super detailed explanation! I have learned a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T17:05:11.893",
"Id": "244235",
"ParentId": "244192",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244235",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T19:53:31.310",
"Id": "244192",
"Score": "5",
"Tags": [
"java",
"algorithm",
"linked-list",
"recursion",
"mergesort"
],
"Title": "How to merge two descending singly linkedlist into one ascending linkedlist using Recursion without any helper method?"
}
|
244192
|
<p>I incorporated the substantial changes suggested in my <a href="https://codereview.stackexchange.com/questions/244074/webscraping-tennis-data?noredirect=1#comment479401_244074">previous question</a> that involved building a web-scraper for gathering tennis data.</p>
<p>The improved code is shown below:</p>
<p><code>Scraper</code> class:</p>
<pre><code>package scraper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;
public class Scraper {
private final String urlPrefix;
private final String urlSuffix;
private final Duration timeout;
public Scraper(final String urlPrefix, final String urlSuffix, final Duration timeout) {
this.urlPrefix = urlPrefix;
this.urlSuffix = urlSuffix;
this.timeout = timeout;
}
private List<WeeklyResult> scrape() throws ScraperException {
final List<String> weeks = loadWeeks();
return loadResults(weeks);
}
private List<String> loadWeeks() throws ScraperException {
final Document document = loadDocument(urlPrefix);
final Elements elements = selectRankingWeeksElements(document);
final List<String> weeks = extractWeeks(elements);
return noEmptyElseThrow(weeks);
}
private Document loadDocument(final String url) throws ScraperException {
try {
return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();
} catch (IOException e) {
throw new ScraperException("Error loading ATP website: " + e.toString());
}
}
private static Elements selectRankingWeeksElements(final Document document) {
// extract ranking weeks from the dropdown menu
final Elements result = document.getElementsByAttributeValue("data-value", "rankDate")
.select("ul li");
Collections.reverse(result);
return result;
}
private static List<String> extractWeeks(final Collection<Element> elements) {
return elements.stream()
.map(Scraper::extractWeek)
.collect(Collectors.toList());
}
private static List<String> noEmptyElseThrow(final List<String> weeks) throws ScraperException{
if (weeks.isEmpty()) {
throw new ScraperException("Please provide a historical time range! Cannot rank otherwise!");
} else {
return weeks;
}
}
private List<WeeklyResult> loadResults(final List<String> weeks) throws ScraperException {
final List<WeeklyResult> result = new ArrayList<>();
for (String week : weeks) {
loadWeeklyResult(week).ifPresent(result::add);
}
return result;
}
private Optional<WeeklyResult> loadWeeklyResult(final String week) throws ScraperException {
final Document document = loadDocument(weeklyResultUrl(week));
final Element playerCell = selectPlayerCellElement(document);
return Optional.ofNullable(playerCell).map(element -> new WeeklyResult(week, element.text()));
}
private String weeklyResultUrl (final String week) {
return urlPrefix+"rankDate="+week+urlSuffix;
}
private static Element selectPlayerCellElement(final Document document) {
return document.getElementsByClass("player-cell").first();
}
private static String extractWeek(final Element li) {
return li.text().replaceAll("\\.", "-");
}
public static void main() throws ScraperException {
final Scraper scraper =
new Scraper("https://www.atptour.com/en/rankings/singles?", "&rankRange=0-100", Duration.ofSeconds(90));
List<WeeklyResult> weeklyResults = scraper.scrape();
System.out.println(weeklyResults);
for (final WeeklyResult weeklyResult : weeklyResults) {
System.out.println("Week: " + weeklyResult.getWeek() + " No.1: " + weeklyResult.getPlayerName());
}
}
}
</code></pre>
<p><code>WeeklyResult</code> class:</p>
<pre><code>package scraper;
// A POJO that encapsulates a ranking week and the name of the corresponding No.1 player
public class WeeklyResult {
private final String week;
private final String playerName;
public WeeklyResult(final String week, final String playerName) {
this.week = week;
this.playerName = playerName;
}
public String getWeek() {
return week;
}
public String getPlayerName() {
return playerName;
}
}
</code></pre>
<p><code>ScraperException</code> class:</p>
<pre><code>package scraper;
public class ScraperException extends Exception {
final String message;
public ScraperException (String message) {
this.message = message;
}
@Override
public String toString() {
return this.message;
}
}
</code></pre>
<hr />
<p>I had some follow up questions to ensure I've truly understood <a href="https://codereview.stackexchange.com/a/244087/223813">Marv's feedback</a> from my previous question:</p>
<ol>
<li><p>I like the fact that <code>ScraperException</code> can now provide informative messages to handle exceptions, and importantly groups exceptions for all scraper-related logic. The only thing irking me is the try catch block in <code>loadDocument</code> where I wrap the <code>IOException</code> and re-throw it as a ScraperException. I find it to be kind of ugly, to be honest, and was wondering if there was a more efficient method.</p>
</li>
<li><p>Expanding on this, and stemming from Marv's suggestion:</p>
</li>
</ol>
<blockquote>
<p>There's something to be said about throwing a checked exception, which might be some further reading points as well.</p>
</blockquote>
<p>I did some further <a href="http://tutorials.jenkov.com/java-exception-handling/checked-or-unchecked-exceptions.html" rel="nofollow noreferrer">research</a>; from what I understand, it <strong>seems like some degree of boilerplate try-catch code is a necessary evil while wrapping checked exceptions</strong>. Would that be correct?</p>
|
[] |
[
{
"body": "<p>I see you used your custom <code>ScraperException</code> exception in two different modes: the first is below:</p>\n<pre><code>private static List<String> noEmptyElseThrow(final List<String> weeks) throws ScraperException{\n if (weeks.isEmpty()) {\n throw new ScraperException("Please provide a historical time range! Cannot rank otherwise!");\n } else {\n return weeks;\n }\n}\n</code></pre>\n<p>To handle this situation, it could be better use the core java <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html\" rel=\"nofollow noreferrer\">IllegalArgumentException</a> thrown to indicate that a method has been passed an illegal or inappropriate argument and because it is a subclass of <code>RuntimeException</code> and then an <em>unchecked</em> exception there is no need to declare it in the signature of the method. So you could write :</p>\n<pre><code>private static List<String> noEmptyElseThrow(final List<String> weeks) {\n if (weeks.isEmpty()) {\n throw new IllegalArgumentException("Please provide a historical time range! Cannot rank otherwise!");\n } else {\n return weeks;\n}\n</code></pre>\n<p>Note: from comments' section you can check @Marv suggested that the illegal argument is not directly connected to the user's actions but to the site structure. An alternative to my solution could be to maintain the old <code>ScraperException</code> with a more significative message like "weeks calendar cannot be empty", hiding all other aspects to the user.</p>\n<p>The second mode is this:</p>\n<pre><code>private Document loadDocument(final String url) throws ScraperException {\n try {\n return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();\n } catch (IOException e) {\n throw new ScraperException("Error loading ATP website: " + e.toString());\n }\n}\n</code></pre>\n<p>Because you are not hiding the true cause of the <code>ScraperException</code> adding the string representation of the <code>IOException</code> to your custom exception, you could use the fact that exceptions are chainable throwing a new IOException in this way :</p>\n<pre><code>private Document loadDocument(final String url) throws IOException {\n try {\n return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();\n } catch (IOException e) {\n throw new IOException("Error loading ATP website: ", e);\n }\n}\n</code></pre>\n<p>Note: from comments' section you can check @Marv suggested to apply chain of exceptions to the old <code>ScraperException</code>. In this case the old <code>ScraperException</code> class could be rewritten like below:</p>\n<pre><code>public class ScraperException extends Exception {\n private final String message;\n \n public ScraperException (String message) {\n this.message = message;\n }\n\n public ScraperException(String message, Throwable cause) {\n super(cause);\n this.message = message;\n }\n \n @Override\n public String toString() {\n return this.message;\n }\n}\n</code></pre>\n<p>The method <code>loadDocument</code> consequently could be rewritten in this way:</p>\n<pre><code>private Document loadDocument(final String url) throws ScraperException {\n try {\n return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();\n } catch (IOException e) {\n throw new ScraperException("Error loading ATP website: ", e);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T11:44:12.440",
"Id": "479442",
"Score": "2",
"body": "The first error is not directly linked to an illegal argument. It could also be empty if the website had an internal error and produced bad HTML.\n\nFor your second point, I agree that chaining exceptions is the right thing to do, but you can simply add `Exception`s `(String, Throwable)` constructor to `ScraperException` and then use that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T12:22:05.273",
"Id": "479450",
"Score": "0",
"body": "@Marv You got an interesting point, because even if the first method takes an illegal argument (empty list) it is unknown if there is bad HTML or there is a correct HTML and the name of tags are simply changed so an empty list is obtained. Maybe in this case changing the error message like \"weeks calendar cannot be empty\" would work, For the second one I'm agree with you to have all methods throwing the same `ScraperException`. Later I add this conversation to my post as a possible alternative to my original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T19:53:54.697",
"Id": "479485",
"Score": "0",
"body": "one clarifying point @dariosicily, I'm a bit confused when you refer to the \"modes\" of ScraperException, are you saying that all occurences of `ScraperException` should be thrown in the same format? That is, it's recommended to use the `(String, Throwable)` constructor in the \"weeks calendar cannot be empty\" situation as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T20:37:24.727",
"Id": "479499",
"Score": "1",
"body": "@cloudy_eclispse My words were a bit misleading, I was referring to the two different situations you are handling using the same exception in two different contexts. I started from the idea of using the already existing core java exceptions to solve the two problems, but after comments by marv , I am convinced that your idea of all methods throwing the same custom exception is correct because the user doesn't need to know all the details. I decided to leave the first solution just for comparison with the second solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T11:51:06.983",
"Id": "479759",
"Score": "0",
"body": "@cloudy_eclispse if you catch an Exception to throw one of a different type, use an Exception constructor that accepts the previous Exception. This way, the Exception you throw will have the whole stack trace."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T10:10:11.600",
"Id": "244222",
"ParentId": "244195",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244222",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:15:10.673",
"Id": "244195",
"Score": "4",
"Tags": [
"java",
"web-scraping"
],
"Title": "Webscraping tennis data 1.1"
}
|
244195
|
<p>I'm creating a GOLang Linux distribution installer. The architecture is straight forward. I have N parameters and uses them in N installation steps. Summarizing:</p>
<ul>
<li>Every step implements a interface with the Run method.</li>
<li>For each step S, do S.Run(parameters), <strong>if failed, handle the error</strong>.</li>
</ul>
<p>The complete source code is here: <a href="https://github.com/Munix-Developers/munix-standalone-installer/blob/master/installer/partitions-step.go" rel="nofollow noreferrer">https://github.com/Munix-Developers/munix-standalone-installer/blob/master/installer/partitions-step.go</a></p>
<p>I've created a Partition Step. Used to create the desired partitions on the disk. The main loop for the step is as follows:</p>
<pre><code>func (p PartitionsStep) Run(c parser.InstallConfig) error {
log.Println("starting partition step")
var err error = nil
for _, d := range c.Storage.Devices {
log.Printf("creating gpt label for %s", d.Device)
err = createGptLabel(d)
if err != nil {
return err
}
for _, p := range d.Partitions {
err = createPartition(d, p)
if err != nil {
return err
}
}
err = discoverPartitionDevices(&d)
if err != nil {
return err
}
}
return nil
}
</code></pre>
<p>Looking at this code, I've noticed that there is too many "if err != nil; return error". In the inner functions there are more if statements like that, for example in the <code>discoverPartitionsDevice</code> function:</p>
<pre><code>// Since parted doesn't returns which is the device that was created, we need to find it manually. This function searches
// for partitions where the label starts with "mx" and exists in the configuration
func discoverPartitionDevices(d *parser.DeviceConfig) error {
blkidOut, err := runBlkid()
if err != nil {
return err
}
sort.SliceStable(d.Partitions, func(i, j int) bool {
return d.Partitions[i].Mount <= d.Partitions[j].Mount
})
for _, line := range strings.Split(blkidOut, "\n") {
line = strings.ReplaceAll(line, ": PARTLABEL=", " ")
line = strings.ReplaceAll(line, "\"", "")
data := strings.Split(line, " ")
err = proccessBlkidLine(d, data)
if err != nil {
return err
}
}
return nil
}
</code></pre>
<p>So, is there a better way to handle this type of error in GOLang?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T21:38:21.310",
"Id": "244196",
"Score": "2",
"Tags": [
"error-handling",
"go"
],
"Title": "Is there a better way to handle errors in these functions?"
}
|
244196
|
<p>I want to familiarize myself with more data structures. As such I implemented a Node, singly-linked-list, as well as an algorithm to sum the digits of two such lists where each node contains the digits of a number. The order of the digits can either be largest digits first or smallest. Taking the number <code>1,234</code> as an example:</p>
<ul>
<li>Smallest digits first: the linked list will contain 4 as the <code>Data</code> property on the <code>Head</code> node, then 3, then 2, and lastly 1 (4->3->2->1).</li>
<li>Largest digits first: <code>Head.Data</code> contains 1, then 2, etc... (1->2->3->4).</li>
</ul>
<p>In the linked list I overrode the Equals method to permit value equality rather than reference equality for comparison with another list.</p>
<hr />
<p>Algorithm logic: I first solved the algorithm manually and implemented the result in code.</p>
<p>Smallest digits first: Starting from the <code>LinkedList.Head</code> each nodes <code>Data</code> property can be sequentially accessed and added together. This process is repeated until the end of both lists has been reached. I thought of a Queue data structure but didn't see the need to traverse each list twice so omitted it.</p>
<p>Largest digits first: the position of the digits may not line up. Given a list containing 1->2 and another with 3->4->5->6 should produce <code>12 + 3456 = 3468</code>. I thought it best to access each node in the list to <code>Push</code> them onto a stack. After all nodes had been accessed this way, each digit could be <code>Pop</code>ed off to add their values together.</p>
<hr />
<p>The logic for each type of list is duplicated as they are essentially checking the same conditions. I would like to eliminate this duplication to have the logic in one location. The thought crossed my mind of converting the largest digits first to a smallest digits first. Doing that doesn't feel correct however.</p>
<p>Below are my implementations.</p>
<hr />
<p>Node implementation:</p>
<pre><code>using System.Collections.Generic;
using System.Diagnostics;
[DebuggerDisplay("{Data}")]
public class Node
{
public Node(int d)
{
Data = d;
}
public int Data { get; }
public Node Next { get; set; } = null;
}
</code></pre>
<p>LinkedList implementation:</p>
<pre><code>using System.Collections.Generic;
using System.Diagnostics;
[DebuggerDisplay("{ToString()}")]
public class LinkedList
{
public LinkedList()
{
}
public LinkedList(int data)
{
Head = new Node(data);
}
public LinkedList(IEnumerable<int> values)
{
int count = 0;
foreach (var value in values)
{
if (count == 0)
{
Head = new Node(value);
}
else
{
AddNode(value);
}
count++;
}
}
public LinkedList(Node headNode)
{
Head = headNode;
}
public Node Head { get; set; }
public void AddNodes(IEnumerable<int> value)
{
foreach (var i in value)
{
AddNode(i);
}
}
public void AddNode(int value)
{
AddNode(new Node(value));
}
public void AddNode(Node node)
{
if (Head == null)
{
Head = node;
return;
}
Node n = Head;
while (n.Next != null)
{
n = n.Next;
}
n.Next = node;
}
public override string ToString()
{
var sb = new StringBuilder();
var node = Head;
while (node != null)
{
sb.Append(node.Data);
node = node.Next;
}
return sb.ToString();
}
public override bool Equals(object obj)
{
return obj is LinkedList other
? Equals(other)
: false;
}
public bool Equals(LinkedList other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (Head.Data != other.Head.Data)
{
return false;
}
if (OnlyOneNodeNull(Head.Next, other.Head.Next))
{
return false;
}
var thisNode = Head.Next;
var otherNode = other.Head.Next;
while (thisNode != null && otherNode != null)
{
if (OnlyOneNodeNull(Head.Next, other.Head.Next))
{
return false;
}
if (thisNode.Data != otherNode.Data)
{
return false;
}
thisNode = thisNode.Next;
otherNode = otherNode.Next;
}
return true;
}
private bool OnlyOneNodeNull(Node lhs, Node rhs)
{
return lhs.Next == null && rhs.Next != null
|| lhs.Next != null && rhs.Next == null;
}
public override int GetHashCode()
{
return 1473396059 + EqualityComparer<Node>.Default.GetHashCode(Head);
}
}
</code></pre>
<p>Algorithm implementation:</p>
<pre><code>using System.Collections.Generic;
public class SumLinkedListDigits
{
public LinkedList SmallestDigitsFirst(LinkedList ll1, LinkedList ll2)
{
var left = ll1.Head;
var right = ll2.Head;
var ll = new LinkedList();
int carriedValue = 0;
int onesValue = 0;
while (left != null && right != null)
{
(carriedValue, onesValue) = AdditionValues(left.Data, right.Data, carriedValue);
ll.AddNode(new Node(onesValue));
left = left.Next;
right = right.Next;
}
if (left == null)
{
while (right != null)
{
(carriedValue, onesValue) = AdditionValues(0, right.Data, carriedValue);
ll.AddNode(onesValue);
right = right.Next;
}
if (carriedValue != 0)
{
ll.AddNode(carriedValue);
}
}
if (right == null)
{
while (left != null)
{
(carriedValue, onesValue) = AdditionValues(left.Data, 0, carriedValue);
ll.AddNode(onesValue);
left = left.Next;
}
if (carriedValue != 0)
{
ll.AddNode(carriedValue);
}
}
return ll;
}
public LinkedList LargestDigitsFirst(LinkedList ll1, LinkedList ll2)
{
var left = StackFromLinkedList(ll1);
var right = StackFromLinkedList(ll2);
int previouslyCarried = 0;
int onesValue = 0;
Node node = null;
while (left.Count > 0 && right.Count > 0)
{
var leftValue = left.Pop();
var rightValue = right.Pop();
(previouslyCarried, onesValue) = AdditionValues(leftValue, rightValue, previouslyCarried);
node = PrefixValuesToLargestDigitFirstNode(node, onesValue);
}
if (left.Count == 0 && right.Count == 0)
{
return previouslyCarried == 0
? new LinkedList(node)
: new LinkedList(PrefixValuesToLargestDigitFirstNode(node, previouslyCarried));
}
if (left.Count == 0)
{
return PrefixRemainingStackValues(node, right, previouslyCarried);
}
if (right.Count == 0)
{
return PrefixRemainingStackValues(node, left, previouslyCarried);
}
return null;
}
private LinkedList PrefixRemainingStackValues(Node node, Stack<int> stack, int previouslyCarried)
{
int onesValue = 0;
while (stack.Count > 0)
{
(previouslyCarried, onesValue) = AdditionValues(stack.Pop(), 0, previouslyCarried);
}
var updatedNode = PrefixValuesToLargestDigitFirstNode(node, onesValue);
return previouslyCarried == 0
? new LinkedList(updatedNode)
: new LinkedList(PrefixValuesToLargestDigitFirstNode(updatedNode, onesValue));
}
private Node PrefixValuesToLargestDigitFirstNode(Node node, int value)
{
var newFirst = new Node(value)
{
Next = node
};
return newFirst;
}
private (int carryDigit, int onesValue) AdditionValues(int left, int right, int carriedValue)
{
int carry = 0;
int onesValue = 0;
int summed = left + right + carriedValue;
if (summed > 9)
{
carry = 1;
onesValue = summed % 10;
}
else
{
carry = 0;
onesValue = summed;
}
return (carry, onesValue);
}
private Stack<int> StackFromLinkedList(LinkedList linkedList)
{
var node = linkedList.Head;
var stack = new Stack<int>();
while (node != null)
{
stack.Push(node.Data);
node = node.Next;
}
return stack;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>I don't think exposing the Node class is useful. It should probably be mostly an internal class within your class (or at least package/namespace)</li>\n<li><code>Node</code> could be using generics, so <code>Node<T></code> instead of always having an <code>int</code></li>\n<li>At least some of your <code>AddNode</code>-methods could simply be called <code>Add</code> instead. Because they're actually adding a number, a list of numbers, or something else that is not exactly a <code>Node</code>.</li>\n<li>Think about the current time complexity of <code>AddNodes(IEnumerable<int> value)</code> and think about if it's possible to improve it somehow. <em>(Hint: Yes, it is. A single <code>AddNode</code> operation gets more and more costly the more you add, but adding a bunch of them at the same time could be almost as cheap as simply adding just one)</em></li>\n<li><code>OnlyOneNodeNull</code> can be simplified by using the XOR operator: <code>lhs.Next == null ^ rhs.Next == null</code>.</li>\n</ul>\n<p>Overall, good job :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T11:40:08.350",
"Id": "479439",
"Score": "0",
"body": "(For bools, I find `!=` clearer than `^`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T11:54:12.797",
"Id": "479443",
"Score": "1",
"body": "@canton7 That's also a good option yes. In this particular case I think it might be a bit confusing to mix `==`, `!=` and `==`, but it'd definitely be a valid option and might just be preference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:47:29.957",
"Id": "244203",
"ParentId": "244199",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "244203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:11:09.933",
"Id": "244199",
"Score": "7",
"Tags": [
"c#",
"algorithm",
"linked-list"
],
"Title": "Summing digits of a singly linked list"
}
|
244199
|
<p>I'm posting my C++ code for LeetCode's <a href="https://leetcode.com/problems/longest-duplicate-substring/" rel="nofollow noreferrer">Longest Duplicate Substring</a>. If you have time and would like to review, please do so. Thank you!</p>
<h2>Problem</h2>
<blockquote>
<ul>
<li><p>Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may
overlap.)</p>
</li>
<li><p>Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is
"".)</p>
</li>
</ul>
<h3>Example 1:</h3>
<ul>
<li>Input: "banana"</li>
<li>Output: "ana"</li>
</ul>
<h3>Example 2:</h3>
<ul>
<li>Input: "abcd"</li>
<li>Output: ""</li>
</ul>
<h3>Note:</h3>
<ul>
<li>2 <= S.length <= 10^5</li>
<li>S consists of lowercase English letters.</li>
</ul>
</blockquote>
<h3>Accepted C++</h3>
<pre><code>class Solution {
private:
const int prime = 19260817;
const int a_decimal = 65;
const int char_size = 26;
std::string res = "";
std::vector<int> exponent;
// Wikipedia
// The Rabin–Karp algorithm or Karp–Rabin algorithm is a string - searching algorithm that uses hashing to find an exact match of a pattern string in a text.
// It uses a rolling hash to quickly filter out positions of the text that cannot match the pattern,
// and then checks for a match at the remaining positions.
const std::string rabin_karp_search(const int length, const string& base) {
if (length == 0) {
return "";
}
std::unordered_map<int, vector<int>> hash_map = unordered_map<int, vector<int>>(); // hash memorization
long long curr = 0; // current hash
int index;
for (index = 0; index < length; index++) {
curr = ((curr * char_size) % prime + (base[index] - a_decimal)) % prime;
}
hash_map[curr] = std::vector<int>(1, 0);
for (index = length; index < base.length(); index++) {
curr = ((curr - (long long) exponent[length - 1] * (base[index - length] - a_decimal)) % prime + prime) % prime;
curr = (curr * char_size + (base[index] - a_decimal)) % prime;
if (hash_map.find(curr) == hash_map.end()) {
hash_map[curr] = std::vector<int>(1, -~index - length);
} else {
for (const auto iter : hash_map[curr]) {
if (std::strcmp((base.substr(iter, length)).data(), base.substr(-~index - length, length).data()) == 0) {
return base.substr(iter, length);
}
}
hash_map[curr].push_back(-~index - length);
}
}
return "";
}
// Wikipedia
// binary search is a search algorithm that finds the position of a target value within a sorted array.
// Binary search compares the target value to the middle element of the array.
// If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half,
// again taking the middle element to compare to the target value, and repeating this until the target value is found.
// If the search ends with the remaining half being empty, the target is not in the array.
const std::string get_longest_binary_search(std::string base_string, std::string res) {
int lo = 0;
int hi = base_string.length();
while (lo <= hi) {
int mid = lo + ((hi - lo) >> 1);
std::string temp = rabin_karp_search(mid, base_string);
if (temp.length() == 0) {
hi = mid - 1;
} else {
if (temp.length() > res.length()) {
res = temp;
}
lo = -~mid;
}
}
return res;
}
public:
const std::string longestDupSubstring(const std::string base_string) {
res = "";
exponent = std::vector<int>(base_string.length(), 1);
int index;
for (index = 1; index < base_string.length(); index++) {
exponent[index] = (exponent[index - 1] * char_size) % prime;
}
return get_longest_binary_search(base_string, res);
}
};
</code></pre>
<h3>LeetCode Solution in Java with additional comments (Not for review)</h3>
<pre><code>class Solution {
/*
Rabin-Karp with polynomial rolling hash.
Search a substring of given length
that occurs at least 2 times.
Return start position if the substring exits and -1 otherwise.
*/
public int search(int L, int a, long modulus, int n, int[] nums) {
// compute the hash of string S[:L]
long h = 0;
for(int i = 0; i < L; ++i) h = (h * a + nums[i]) % modulus;
// already seen hashes of strings of length L
HashSet<Long> seen = new HashSet();
seen.add(h);
// const value to be used often : a**L % modulus
long aL = 1;
for (int i = 1; i <= L; ++i) aL = (aL * a) % modulus;
for(int start = 1; start < n - L + 1; ++start) {
// compute rolling hash in O(1) time
h = (h * a - nums[start - 1] * aL % modulus + modulus) % modulus;
h = (h + nums[start + L - 1]) % modulus;
if (seen.contains(h)) return start;
seen.add(h);
}
return -1;
}
public String longestDupSubstring(String S) {
int n = S.length();
// convert string to array of integers
// to implement constant time slice
int[] nums = new int[n];
for(int i = 0; i < n; ++i) nums[i] = (int)S.charAt(i) - (int)'a';
// base value for the rolling hash function
int a = 26;
// modulus value for the rolling hash function to avoid overflow
long modulus = (long)Math.pow(2, 32);
// binary search, L = repeating string length
int left = 1, right = n;
int L;
while (left <= right) {
L = left + (right - left) / 2;
if (search(L, a, modulus, n, nums) != -1) left = L + 1;
else right = L - 1;
}
int start = search(left - 1, a, modulus, n, nums);
return S.substring(start, start + left - 1);
}
}
</code></pre>
<h3>Reference</h3>
<p>LeetCode is a platform only for <a href="https://leetcode.com/discuss/interview-question?currentPage=1&orderBy=hot&query=" rel="nofollow noreferrer">interviewing</a> and <a href="https://leetcode.com/contest/globalranking" rel="nofollow noreferrer">competitive programming</a>. On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/longest-duplicate-substring/" rel="nofollow noreferrer">1044. Longest Duplicate Substring - Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/longest-duplicate-substring/discuss/" rel="nofollow noreferrer">1044. Longest Duplicate Substring - Discuss</a></p>
</li>
<li><p><a href="https://en.wikipedia.org/wiki/Binary_search_algorithm" rel="nofollow noreferrer">Binary Search</a></p>
</li>
<li><p><a href="https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm" rel="nofollow noreferrer">Rabin Karp</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Avoid unnecessary member variables</h1>\n<p>You added <code>res</code> and <code>exponent</code> as member variables. However, they are only used inside <code>longestDupSubString()</code> and functions called by it. You should just declare them inside <code>longestDupSubString()</code> instead, and pass them by reference to other functions if necessary. But see below for why these variables might not be necessary at all.</p>\n<h1>Use character constants</h1>\n<p>Write <code>const int a_decimal = 'a'</code>, so there is no need to know the ASCII table and no possibility for errors. However, then the question is, why define <code>a_decimal</code> at all? It seems you want to force integer promotion, but you can make that more explicit. Instead of <code>base[index] - a_decimal</code>, you can write <code>(int)base[index] - 'a'</code>.</p>\n<p>But this makes me wonder, why subtract <code>'a'</code> at all? Sure, the question says the input consists of only lowercase English numbers, but you can keep your solution generic.</p>\n<h1>Don't return <code>const</code> values</h1>\n<p>There is no point in returning something by <code>const</code> value. The following is perfectly valid:</p>\n<pre><code>const std::string foo() {\n return "foo";\n}\n\nstd::string bar = foo();\n</code></pre>\n<p>It only makes sense to make the return type <code>const</code> if you are return a pointer or reference.</p>\n<h1>Avoid <code>using namespace std</code> and/or <code>#include <bits/stdc++.h></code></h1>\n<p>I see you forgot to add <code>std::</code> to some standard library types, implying that you have <code>using namespace std</code> somewhere or are using the non-standard <code>#include <bits/stdc++.h></code>.</p>\n<h1>Give proper names to variables</h1>\n<p>Some of your naming choices are questionable:</p>\n<ul>\n<li><code>char_size</code>: sounds like it would hold the result of <code>sizeof(char)</code>, but unstead it's the number of letters in the alphabet. Maybe <code>alphabet_size</code> would be better.</li>\n<li><code>hash_map</code>: the name is equivalent to the type (<code>std::unordered_map</code>), but what you should have used is something that represents what information the hash map holds: substrings that you already visited. So maybe <code>visited_substrings</code> is a better name.</li>\n<li><code>index</code>: this is one of the few times you can use a one-letter variable, like <code>i</code>, since that is the idiomatic name for a loop counter in C++.</li>\n<li><code>iter</code>: in <code>for(const auto iter: hash_map[curr])</code>, the variable <code>iter</code> is not an iterator, but actually holds the value of one of the elements of a <code>std::vector<int></code>. So <code>element</code>, <code>item</code> or <code>entry</code> would already be a better name, but even better is a name that reflects what that elements represents, namely an offset into the base string, so <code>offset</code> would be a good name here.</li>\n</ul>\n<h1>Your hash function can have collisions, and is unnecessary</h1>\n<p>Your hash function can have collisions if you ever have substrings longer than 32 / log₂(26) = 6 characters. A collision would not be a problem if you would handle them, but you don't. Also, there is no need to create a hash yourself, since <code>std::unordered_map</code> already does that for you! Just pass the substring to it directly:</p>\n<pre><code>std::unordered_map<std::string, std::vector<int>> visited_substrings;\n\nauto substring = base.substr(0, length);\nvisited_substrings[substring] = {0};\n</code></pre>\n<h1>Avoid repeating type names</h1>\n<p>There are a few places where you can avoid repeating type names. As shown above, when declaring a variable of type <code>std::unordered_map</code>, it is already initialized to be an empty map, so no need to explicity initialize it with another empty map.</p>\n<p>When assigning to an element of a <code>std::unordered_map</code>, you can use an initializer list, and since the compiler knows the type of the map elements, you don't have to repeat that yourself. So <code>visited_substrings[substring] = {0}</code> will initialize the vector with one integer with value <code>0</code>.</p>\n<h1>Don't use C library functions if there are perfectly fine C++ equivalents</h1>\n<p>When comparing C++ strings, don't use <code>strcmp()</code>, but rather use the tools the <code>std::string</code> class provides you. In particular, you can just use the <code>==</code> operator:</p>\n<pre><code>if (base.substr(offset, length) == base.substr(index + 1 - length, length)) {\n return base.substr(offset, length);\n}\n</code></pre>\n<p>Also, <code>std::string</code> comes with the member function <code>compare()</code> that can compare substrings directly:</p>\n<pre><code>if (base.compare(offset, length, base, index + 1 - length, length) == 0) {\n return base.substr(offset, length);\n}\n</code></pre>\n<p>Although it doesn't look like much of an improvement, it avoids having to create new temporary strings to hold the substrings.</p>\n<h1>Don't use bit twiddling tricks unnecessarily</h1>\n<p>There is no need to write <code>-~index</code> when you can just write <code>index + 1</code>. The latter is much clearer. Also, <code>-~index</code> being equivalent to <code>index + 1</code> assumes <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow noreferrer\">two's complement</a> representation of integers, which is not guaranteed in C++17 (it is only since C++20).</p>\n<p>Also, in <code>int mid = lo + ((hi - lo) >> 1)</code>, just write <code>int mid = lo + (hi - lo) / 2</code>, it is much clearer what the intention is. If you could use C++20, then you should use <a href=\"https://en.cppreference.com/w/cpp/numeric/midpoint\" rel=\"nofollow noreferrer\"><code>std::midpoint()</code></a> here, since there are <a href=\"https://www.youtube.com/watch?v=sBtAGxBh-XI\" rel=\"nofollow noreferrer\">many pitfalls</a> in your simple approach, although it works fine in the constraints of this LeetCode problem.</p>\n<h1>Use unsigned integers where appropriate</h1>\n<p>For array indices, sizes and non-negative offsets, you should unsigned integers, or even better <code>size_t</code>. There are several reasons for this:</p>\n<ul>\n<li>There's less chance of overflow. Note that unintended overlow might be a security issue.</li>\n<li>When using unsigned integers as function parameters, you never have to check whether they are non-negative if that is not allowed.</li>\n<li>There are less surprises when doing bitwise operations on unsigned integers.</li>\n<li>Some common standard library functions, such as <code>std::string::size()</code>, also return unsigned integers, so you won't get warnings about comparing signed to unsigned numbers.</li>\n</ul>\n<p>Regarding that last point, ensure you have compiler warnings enabled and fix all warnings it produces.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T11:55:58.673",
"Id": "479444",
"Score": "1",
"body": "Please add indexes to the list of where unsigned integers are appropriate. It might be good to explain why unsigned is better (integer overflow comes to mind)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T12:39:42.107",
"Id": "479451",
"Score": "1",
"body": "Wow, that's a pretty long video, but it's worth viewing every minute of it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T11:19:06.520",
"Id": "244225",
"ParentId": "244202",
"Score": "4"
}
},
{
"body": "<p>G. Sliepen wrote a rather comprehensive review, I'm going to expand on one point in their review, and add 2 others.</p>\n<blockquote>\n<p><strong>Avoid using namespace std and/or #include <bits/stdc++.h></strong></p>\n</blockquote>\n<blockquote>\n<p>I see you forgot to add std:: to some standard library types, implying that you have using namespace std somewhere or are using the non-standard #include <bits/stdc++.h>.</p>\n</blockquote>\n<p>The LeetCode is doing this for you and it is promoting bad habits that you need to unlearn. The proper includes for this code are</p>\n<pre><code>#include <vector>\n#include <string>\n#include <unordered_map>\n</code></pre>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<p><strong>More on Private, Protected and Public</strong><br />\nI see that you do learn from your <a href=\"https://codereview.stackexchange.com/questions/244186/leetcode-1146-snapshot-array\">previous reviews</a> and that is a good thing. In the following code the keyword <code>private:</code> is not necessary, when you first open a class declaration and variables, methods and functions are private by default.</p>\n<pre><code>class Solution {\nprivate:\n const int prime = 19260817;\n const int a_decimal = 65;\n const int char_size = 26;\n std::string res = "";\n std::vector<int> exponent;\n</code></pre>\n<p>You will find that a lot of C++ programmers are no long using the first section of a class declaration because it is better to put the public interfaces at the beginning of a class so that users of that class can find the public interfaces easily. This actually applies to most object oriented programming languages. The general hierarchy is public first, then protected and then private.</p>\n<p><strong>Class File Structure</strong><br />\nMy concern here is that you're only learning C++ through <code>LeetCode</code> that you are learning some bad habits that will need to be replaced at some point. C++ is generally broken up into header files and source files. You are fairly familiar with the header file grammar but you are not familiar with the source file grammar.</p>\n<p>Historically the C++ programming language grew out of the C programming language which already had separate header files and source files. Unlike Java and C# most of the member functions and methods have function prototypes in the class declaration and the actual functions are defined in a <code>.cpp</code> file. There are a couple of reasons for this, the first is that it allows bugs to be fixed in the code while not affecting the public interfaces. This means that patches or updated dynamically linked libraries can be developed and shipped to fix bugs without redoing the entire application. The other reason is that compile / build times are improved by reducing the contents of the header files.</p>\n<p>There are 2 exceptions to this,</p>\n<ol>\n<li>For performance reasons if a function or method is not very complex it can be included in the header so that the compiler can try to <code>inline</code> it. This means that the code of the function will replace the function call where it is used.</li>\n<li>There are complete libraries such as the <a href=\"https://www.boost.org/\" rel=\"nofollow noreferrer\">Boost Library</a> in <code>.hpp</code> files that provide a great deal of additional functionality (maybe even a binary search).</li>\n</ol>\n<p>This is what the solutions class might look like in this case:</p>\n<p><strong>Solution.h</strong></p>\n<pre><code>#ifndef LEETCODE1044_SOLUTION_H\n#define LEETCODE1044_SOLUTION_H\n\n#include <vector>\n#include <string>\n#include <unordered_map>\n\nclass Solution {\nprivate:\n const int prime = 19260817;\n const int a_decimal = 65;\n const int char_size = 26;\n std::string res = "";\n std::vector<int> exponent;\n\n // Wikipedia\n // The Rabin–Karp algorithm or Karp–Rabin algorithm is a string - searching algorithm that uses hashing to find an exact match of a pattern string in a text.\n // It uses a rolling hash to quickly filter out positions of the text that cannot match the pattern,\n // and then checks for a match at the remaining positions.\n const std::string rabin_karp_search(const int length, const std::string& base);\n\n // Wikipedia\n // binary search is a search algorithm that finds the position of a target value within a sorted array.\n // Binary search compares the target value to the middle element of the array.\n // If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half,\n // again taking the middle element to compare to the target value, and repeating this until the target value is found.\n // If the search ends with the remaining half being empty, the target is not in the array.\n\n const std::string get_longest_binary_search(std::string base_string, std::string res);\n\npublic:\n const std::string longestDupSubstring(const std::string base_string);\n\n};\n\n#endif //LEETCODE1044_SOLUTION_H\n</code></pre>\n<p><strong>Solution.cpp</strong></p>\n<pre><code>#include "Solution.h"\n\nconst std::string Solution::rabin_karp_search(const int length, const std::string &base)\n{\n if (length == 0) {\n return "";\n }\n\n std::unordered_map<int, std::vector<int>> hash_map = std::unordered_map<int, std::vector<int>>(); // hash memorization\n long long curr = 0; // current hash\n int index;\n\n for (index = 0; index < length; index++) {\n curr = ((curr * char_size) % prime + (base[index] - a_decimal)) % prime;\n }\n\n hash_map[curr] = std::vector<int>(1, 0);\n\n for (index = length; index < base.length(); index++) {\n curr = ((curr - (long long) exponent[length - 1] * (base[index - length] - a_decimal)) % prime + prime) % prime;\n curr = (curr * char_size + (base[index] - a_decimal)) % prime;\n\n if (hash_map.find(curr) == hash_map.end()) {\n hash_map[curr] = std::vector<int>(1, -~index - length);\n\n } else {\n for (const auto iter : hash_map[curr]) {\n if (std::strcmp((base.substr(iter, length)).data(), base.substr(-~index - length, length).data()) == 0) {\n return base.substr(iter, length);\n }\n }\n\n hash_map[curr].push_back(-~index - length);\n }\n }\n\n return "";\n}\n\nconst std::string Solution::get_longest_binary_search(std::string base_string, std::string res)\n{\n int lo = 0;\n int hi = base_string.length();\n\n while (lo <= hi) {\n int mid = lo + ((hi - lo) >> 1);\n std::string temp = rabin_karp_search(mid, base_string);\n\n if (temp.length() == 0) {\n hi = mid - 1;\n\n } else {\n if (temp.length() > res.length()) {\n res = temp;\n }\n\n lo = -~mid;\n }\n }\n\n return res;\n}\n\nconst std::string Solution::longestDupSubstring(const std::string base_string)\n{\n res = "";\n exponent = std::vector<int>(base_string.length(), 1);\n int index;\n\n for (index = 1; index < base_string.length(); index++) {\n exponent[index] = (exponent[index - 1] * char_size) % prime;\n }\n\n return get_longest_binary_search(base_string, res);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T13:15:44.203",
"Id": "479452",
"Score": "1",
"body": "Good points about bad habits taught by LeetCode. Another one is that a `class` is used at all. That might be necessary in Java, but in C++ `longestDupSubString()` could just be a stand-alone function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T13:24:07.970",
"Id": "479453",
"Score": "1",
"body": "@G.Sliepen You're correct, it is forcing the usage of C++ as an object oriented language when it doesn't need to, but it also encapsulates all the code (any supporting functions)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T13:00:29.893",
"Id": "244226",
"ParentId": "244202",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244225",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T22:35:58.877",
"Id": "244202",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 1044: Longest Duplicate Substring"
}
|
244202
|
<p>Recently, I've been trying to get back into Haskell, so I tried coding up a <a href="https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Storer%E2%80%93Szymanski" rel="noreferrer">LZSS</a> implementation. I realize this is much more easily implemented imperatively, but I wanted to challenge myself. The last time I tried doing this was back in my Functional Programming class and it went poorly. It worked, but the compression was extremely slow and I was only using prelude Lists and ByteStrings. So, my goal this time around was to make something faster and memory efficient while also still being Haskell code.</p>
<p>This implementation of the algorithm is based off of one I found in an old 16-bit Sega Genesis game. It goes as follows: The data length is one byte with the sign bit indicating repeated data, meaning a length of 127 bytes (plus one). The repeated data length gets converted to its positive representation. If the sign bit is set, then the next byte is the lookback offset meaning a 256 byte window. Otherwise, the following bytes are literal data.</p>
<p>My questions are: What can I do to improve memory/speed performance? How easy is my code to follow? What could I do to make my code more idiomatically Haskell?</p>
<pre><code>{-# LANGUAGE ViewPatterns, PatternSynonyms #-}
module Lib (
compress,
uncompress
) where
import Control.Parallel.Strategies
import Data.Bits (Bits,complement)
import Data.Int (Int8)
import Data.List (unfoldr, null)
import Data.Monoid ((<>),mconcat,mempty)
import Data.Word (Word8)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL (toStrict)
import Data.ByteString.Builder
import qualified Data.Vector.Storable as V
import Data.Vector.Storable.ByteString
import Foreign.Storable(sizeOf)
import Numeric (showHex)
infixr 5 :<
pattern b :< bs <- (B.uncons -> Just (b, bs))
pattern Empty <- (B.uncons -> Nothing)
prettyPrint :: B.ByteString -> String
prettyPrint = B.foldr showHex ""
signed :: Word8
signed = 0x80
breakEven :: Int
breakEven = fromIntegral $ 2 * sizeOf maxWord8
maxInt8 = maxBound::Int8
maxWord8 = maxBound::Word8
maxLength :: Int
maxLength = fromIntegral maxInt8 + 1
maxOffset :: Int
maxOffset = fromIntegral maxWord8
twosComplement :: (Bits a, Integral a) => a -> a
twosComplement a = 1 + complement a
uncompress :: B.ByteString -> B.ByteString
uncompress bs = uncompress' bs V.empty
uncompress' :: B.ByteString -> V.Vector Word8 -> B.ByteString
uncompress' Empty vs = vectorToByteString vs
uncompress' (b :< bs) vs
| b > signed = let
l = fromIntegral $ (twosComplement b) + 1
o = fromIntegral $ B.head bs
rs = V.slice (V.length vs - o) (min l o) vs
rss = if l > o then V.fromList $ take (l - o) $ concat $ repeat $ V.toList rs else V.empty
in uncompress' (B.tail bs) (vs V.++ rs V.++ rss)
| otherwise = let
t = fromIntegral b + 1
in uncompress' (B.drop t bs) (vs V.++ (byteStringToVector $ B.take t bs))
compress :: B.ByteString -> B.ByteString
compress bs = BL.toStrict $ toLazyByteString $ compress' (byteStringToVector bs) 0 B.empty
compress' :: V.Vector Word8 -> Int -> B.ByteString -> Builder
compress' bs i ns
| endOfData = literalData
| literalDataLength == maxLength = flushBuffer
| i == 0 || repeatNotLongEnough = checkNextPosition
| otherwise = lz77Block
where
endOfData = i == V.length bs
flushBuffer = literalData <> compress' bs i B.empty
literalData = if B.null ns then mempty else (word8 (fromIntegral literalDataLength - 1)) <> byteString ns
literalDataLength = B.length ns
repeatNotLongEnough = not (B.null ns) && maxRepeated <= breakEven || maxRepeated < breakEven
maxRepeated = fst optimalLength
optimalLength = maximum $ parMap rpar (offsetMatchLength bs i) [i - o | o <- [1..maxOffset], i - o >= 0]
checkNextPosition = compress' bs (i + 1) (B.snoc ns (bs V.! i))
lz77Block = literalData <> repeatedData <> compress' bs (i + repeatLength) B.empty
repeatLength = maxRepeated - if repeatRemainder < breakEven then repeatRemainder else 0
repeatRemainder = maxRepeated `mod` maxLength
optimalOffset = word8 $ fromIntegral $ snd optimalLength
repeatedData = mconcat $ unfoldr (\r ->
if r < breakEven then Nothing
else Just (
(word8 $ fromIntegral $ twosComplement $ (min r maxLength) - 1) <> optimalOffset,
r - maxLength
)
) maxRepeated
offsetMatchLength :: V.Vector Word8 -> Int -> Int -> (Int,Int)
offsetMatchLength bs c l = (V.length $ V.takeWhile (\a -> a) $ V.zipWith (==) (V.drop l bs) (V.drop c bs), l)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T00:11:43.840",
"Id": "244207",
"Score": "7",
"Tags": [
"haskell",
"compression"
],
"Title": "Feedback on LZSS implementation"
}
|
244207
|
<p>How could I reduce this schedule checker? There are too many conditions.</p>
<p>This code is supposed to make sure we're not booking events for employees that are already booked in a specified timeframe.</p>
<pre><code>for i in range(len(employeesChosen)):
info = get_employee_info(employeesChosen[i])
event_done = False
if employeesChosen[i] not in currentEmployees and check_employee_availability(service,employeesChosen[i],currentStart,currentEnd,currentStart,calendarEnd):
event_done = True
else:
for event in events:
if employeesChosen[i] == event['summary']:
if str2datetime(currentStart) >= str2datetime(event['start']['dateTime'].split('+')[0]) and str2datetime(currentEnd) <= str2datetime(event['end']['dateTime'].split('+')[0]):
event_done = False
break
elif str2datetime(currentStart) <= str2datetime(event['start']['dateTime'].split('+')[0]) and str2datetime(currentEnd) <= str2datetime(event['end']['dateTime'].split('+')[0]):
event_done = False
break
elif str2datetime(currentStart) >= str2datetime(event['start']['dateTime'].split('+')[0]) and str2datetime(currentEnd) >= str2datetime(event['end']['dateTime'].split('+')[0]):
event_done = False
break
elif str2datetime(currentStart) <= str2datetime(event['start']['dateTime'].split('+')[0]) and str2datetime(currentEnd) >= str2datetime(event['end']['dateTime'].split('+')[0]):
event_done = False
break
elif str2datetime(currentStart) < str2datetime(event['start']['dateTime'].split('+')[0]): #rdv avant un qui est deja set
event_info = {'location': get_company_location(event['description']),'datetime': event['end']['dateTime'].split('+')[0]}
start_first_event = {'location': get_company_location(event['description']),'datetime': event['start']['dateTime'].split('+')[0]}
event_fabricant_info = {'location': get_company_location(event_fabricant),'datetime': currentStart}
end_second_event = {'location': get_company_location(event_fabricant),'datetime': currentEnd}
if check_event_possibility_if_before(event_info, event_fabricant_info, end_second_event, start_first_event, info[0]):
event_done = True
else:
event_done = False
elif str2datetime(currentStart) > str2datetime(event['end']['dateTime'].split('+')[0]) or str2datetime(currentEnd): #rdv apres un qui est deja set
event_info={'location': get_company_location(event['description']), 'datetime': event['end']['dateTime'].split('+')[0]}
start_first_event ={'location': get_company_location(event['description']), 'datetime': event['start']['dateTime'].split('+')[0]}
event_fabricant_info = {'location': get_company_location(event_fabricant), 'datetime': currentStart}
end_second_event = {'location': get_company_location(event_fabricant), 'datetime': currentEnd}
if check_event_possibility(event_info, event_fabricant_info, end_second_event,start_first_event, info[0]):
event_done=True
else:
event_done=False
else: event_done = False
</code></pre>
|
[] |
[
{
"body": "<h2>Specific suggestions</h2>\n<ol>\n<li><p>You can pull out variables for the several repeated calls (such as <code>str2datetime(currentStart)</code>) to massively simplify the code.</p>\n</li>\n<li><p>The idiomatic way to write</p>\n<pre><code>for counter in range(len(foos)):\n foo = foos[counter]\n</code></pre>\n<p>is</p>\n<pre><code>for foo in foos:\n</code></pre>\n</li>\n</ol>\n<h2>Tool support</h2>\n<ol>\n<li>Use a formatter like <a href=\"https://pypi.org/project/black/\" rel=\"nofollow noreferrer\">Black</a> to format the code to be more idiomatic.</li>\n<li>Use a linter like <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">flake8</a> to recommend further changes like using <code>snake_case</code> variable names.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T11:07:00.330",
"Id": "244223",
"ParentId": "244208",
"Score": "3"
}
},
{
"body": "<p>After introducing the variables <code>start_datetime</code> and <code>end_datetime</code> as @l0b0 suggested, your code becomes much clearer and more readable. It seems like your first 4 if/elif statements will always be True so the later statements will never be reached.</p>\n<pre><code>start_datetime = str2datetime(currentStart)\nend_datetime = str2datetime(currentEnd)\nevent_start = str2datetime(event['start']['dateTime'].split('+')[0])\nevent_end = str2datetime(event['end']['dateTime'].split('+')[0])\n\nif start_datetime >= event_start and end_datetime <= event_end:\n event_done = False\n break\n\nelif start_datetime <= event_start and end_datetime <= event_end:\n event_done = False\n break\n\nelif start_datetime >= event_start and end_datetime >= event_end :\n event_done = False\n break\n\nelif start_datetime <= event_start and end_datetime >= event_end:\n event_done = False\n break\n</code></pre>\n<p>I suppose that's not what you actually meant to do so you should change that first. If this is the behaviour you want; you can change this entire part to</p>\n<pre><code>event_done = False\n</code></pre>\n<p>and delete all conditions after this.</p>\n<p>Something else, try to make your code <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> compliant. These are guidelines for how to format your code like making your lines max 79 characters long.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:39:53.407",
"Id": "244315",
"ParentId": "244208",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T00:18:06.340",
"Id": "244208",
"Score": "1",
"Tags": [
"python",
"scheduled-tasks"
],
"Title": "Schedule Checker"
}
|
244208
|
<p>I have a use case where I need to run multiple tasks in series. Each task is required to perform some database operations. In my code <code>step_1</code>, <code>step_2</code> and <code>step_3</code> are these task which get executed in series (<a href="https://caolan.github.io/async/v3/docs.html#waterfall" rel="nofollow noreferrer">Async Waterfall</a>)</p>
<p>Following is my code</p>
<pre><code>const config = require('config.json');
var mysql = require('mysql');
var async = require("async");
const pool = mysql.createPool({
host: config.database.dbhost,
user: config.database.dbuser,
password: config.database.dbpassword,
database: config.database.dbname
});
exports.handler = (event, context, callback) => {
pool.getConnection((err, connection) => {
if (err) throw new Error("Unable to get connection " + JSON.stringify(err));
async.waterfall([
step_1,
step_2,
step_3
], function (err, result) {
if(err){
throw new Error("something went south : "+ JSON.stringify(err));
}else{
connection.release();
callback(null, "SUCCESS: " + JSON.stringify(result));
}
});
function step_1(cb){
connection.query("step 1 query", function (error, response) {
if (error){
cb(null,error,null);
}
let id=result.insertId;
cb(null,null,id);
});
}
function step_2(error,id,cb){
if(error){
cb(null,error);
}else{
connection.query("step 2 query",,function (err,result){
if (err){
connection.query("error logging query",
function(er,result){
if (er) cb(null,er,null);
});
cb(null,err,null);
}
cb(null,null, id, result);
});
}
}
function step_3(error, id,result,cb){
if(error){
cb(error,null);
}else{
connection.query("step 3 query",function(err,result){
if (err) cb(err,null);
cb(null,result);
});
}
}
});
};
</code></pre>
<p>Although I have used a library to avoid nesting callbacks within callbacks, it still feels like bit callback-ish. Is there a better way to achieve my use case? Anything I can improve in my code, any suggestions please.</p>
<p>I have only included relevant parts of code, kindly let me know if any additional information is required.</p>
|
[] |
[
{
"body": "<p>A couple of helper functions will aid in flattening your callback chain:</p>\n<pre><code>function getConnection() {\n return new Promise((res, rej) => {\n pool.getConnection(function (err, connection) {\n if (err) {\n rej(err);\n } else {\n res(connection);\n }\n });\n });\n}\n\nfunction query(connection, sql, params) {\n return new Promise((res, rej) => {\n connection.query(sql, params, function (err, rows) {\n if (err) {\n rej(err);\n } else {\n res(rows);\n }\n });\n });\n}\n</code></pre>\n<p>Then you can do something like:</p>\n<pre><code>async function step_1(connection) {\n const rows = await query(connection, 'step 1 query');\n return rows.insertId;\n}\n\nfunction step_2(connection, id) {\n return query(connection, 'step 2 query', id);\n}\n\nfunction step_3(connection, id, result) {\n return query(connection, 'step 3 query', id, result);\n}\n\nexports.handler = async (event) => {\n const connection = await getConnection();\n try {\n const id = await step_1(connection);\n const rows = await step_2(connection, id);\n const result = await step_3(connection, id, rows);\n return JSON.stringify(result);\n } finally {\n connection.release();\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:01:04.213",
"Id": "479629",
"Score": "1",
"body": "Welcome to Code Review, answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted. To avoid this possibility you can check [how to answer](https://codereview.stackexchange.com/help/how-to-answer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:13:36.333",
"Id": "479712",
"Score": "0",
"body": "Thank you for your time. returning promises and using them with await is quite useful +1 for that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T08:54:17.903",
"Id": "244313",
"ParentId": "244210",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244313",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T02:56:13.690",
"Id": "244210",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"asynchronous",
"async.js"
],
"Title": "NodeJS executing multiple database queries using async library"
}
|
244210
|
<p><strong>I need to add search filters for firebase So that I can get search result easily and precisely</strong></p>
<p>I was altering the code from here<a href="https://medium.com/flutterdevs/implement-searching-with-firebase-firestore-flutter-de7ebd53c8c9" rel="nofollow noreferrer">This Medium Post</a></p>
<p>I would like to optimize this code.</p>
<pre><code>void main() {
print(setSearchParam("Dr apj abdul Kalam"));
}
setSearchParam(String caseNumber) {
List<String> caseSearchList = List();
String temp = "";
String temp2 = "";
String temp3 = "";
if (caseNumber.split(" ").length > 1) {
String firstWord = caseNumber.split(" ")[0];
String secondWord = caseNumber.split(" ")[1];
String thirdWord = caseNumber.split(" ")[2];
for (int i = 0; i < firstWord.length; i++) {
temp = temp + firstWord[i];
caseSearchList.add(temp);
}
for (int i = 0; i < secondWord.length; i++) {
temp2 = temp2 + secondWord[i];
caseSearchList.add(temp2);
}
for (int i = 0; i < thirdWord.length; i++) {
temp3 = temp3 + thirdWord[i];
caseSearchList.add(temp3);
}
} else {
for (int i = 0; i < caseNumber.length; i++) {
temp = temp + caseNumber[i];
caseSearchList.add(temp);
}
}
return caseSearchList;
}
</code></pre>
<p>OutPuts are like List of each word letters = [D, Dr, a, ap, apj, a, ab, abd, abdu, abdul]</p>
<p>I am pushing these lists to firebase so that I can get search results easily...
if there is an alternative for searching in firebase, then pls let me know...</p>
<p>if anyone still didn't understand my question, pls look at the link I provide above.</p>
|
[] |
[
{
"body": "<p>I have tried make a more optimized version here which also will work for string of any sizes and any number of words:</p>\n<pre><code>void main() {\n print(setSearchParam("Dr apj abdul Kalam"));\n // [D, Dr, a, ap, apj, a, ab, abd, abdu, abdul, K, Ka, Kal, Kala, Kalam]\n\n print(searchParamWord('test'));\n}\n\nList<String> setSearchParam(String caseNumber) =>\n caseNumber.split(' ').expand(searchParamWord).toList();\n\nIterable<String> searchParamWord(String word) sync* {\n final sb = StringBuffer();\n\n for (var i = 0; i < word.length; i++) {\n yield (sb..writeCharCode(word.codeUnitAt(i))).toString();\n }\n}\n</code></pre>\n<p>I have split the logic of your code into two parts.</p>\n<p><code>searchParamWord</code> takes one word and split it into its components like "(t, te, tes, test)" and returns a lazy evaluated iterator. This iterator can then later be used by <a href=\"https://api.dart.dev/stable/dart-core/Iterable/expand.html\" rel=\"nofollow noreferrer\"><code>expand</code></a> in <code>setSearchParam</code> where we split the long <code>String</code> into each separate word.</p>\n<p><strong>By request, example how to upper case first letter in each word</strong></p>\n<pre><code>void main() {\n print(setSearchParam("Dr apj abdul Kalam"));\n // [D, Dr, A, Ap, Apj, A, Ab, Abd, Abdu, Abdul, K, Ka, Kal, Kala, Kalam]\n\n print(searchParamWord('test'));\n}\n\nList<String> setSearchParam(String caseNumber) =>\n caseNumber.split(' ').expand(searchParamWord).toList();\n\nIterable<String> searchParamWord(String word) sync* {\n final sb = StringBuffer();\n\n for (var i = 0; i < word.length; i++) {\n yield (i == 0)\n ? (sb..write(word[i].toUpperCase())).toString()\n : (sb..writeCharCode(word.codeUnitAt(i))).toString();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T16:00:42.570",
"Id": "479470",
"Score": "0",
"body": "bro can you help me to make the first letter of each word capitalized"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T16:33:04.627",
"Id": "479473",
"Score": "0",
"body": "So we are talking about the same code but you want it do return: `[D, Dr, A, Ap, Apj, A, Ab, Abd, Abdu, Abdul, K, Ka, Kal, Kala, Kalam]` instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T16:34:10.523",
"Id": "479474",
"Score": "0",
"body": "yes bro.....thanks for replying....."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T16:40:08.970",
"Id": "479476",
"Score": "0",
"body": "Updated my answer with an example of how to do it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T08:49:25.987",
"Id": "244216",
"ParentId": "244213",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "244216",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T05:55:32.327",
"Id": "244213",
"Score": "4",
"Tags": [
"firebase",
"dart",
"flutter"
],
"Title": "Search filter for words in dart"
}
|
244213
|
<p>I'm using GraphQL and <a href="https://github.com/go-pg/pg" rel="nofollow noreferrer">go-pg</a>.</p>
<p>I have many entities like these:</p>
<pre class="lang-golang prettyprint-override"><code>type Player struct {
ID int
CreatedAt time.Time `pg:"default:now(),notnull"`
TeamID int `pg:",notnull"`
Team *Team
Type int
Score int64 `pg:",notnull"`
Note *string
// and others...
}
type PlayerInput struct {
TeamID int
Type int
Score int64
Note *string
// and others...
}
</code></pre>
<p>I have many times functions like these:</p>
<pre class="lang-golang prettyprint-override"><code>func (db *postgres) Update(context context.Context, id int, input types.PlayerInput) (*types.Player, error) {
var actualPlayer types.Player
newPlayer := graphqlToDB(&input)
tx, err := db.Begin()
//handle err
err = tx.Model(&actualPlayer).Where("id = ?", id).For("UPDATE").Select()
// handle err and rollback
actualPlayer.TeamID = dbo.TeamID
actualPlayer.Type = dbo.Type
actualPlayer.Score = dbo.Score
actualPlayer.Note = dbo.Note
// and others...
_, err = tx.Model(&actualPlayer).WherePK().Update()
// handle err and rollback
err = tx.Commit()
//handle err
return &actualPlayer, nil
}
func graphqlToDB(input *types.PlayerInput) *types.Player {
var output = &types.Player{
TeamID: input.TeamID,
Type: input.Type,
Score: input.Score,
Note: input.Note,
// and others...
}
if input.Type == "example" {
output.Score = 10000000
}
return output
}
</code></pre>
<p>I have this code for each entity in my project and I would like to limit/avoid redundant code, specially:</p>
<ol>
<li><p>transformation from Graphql input type every time</p>
<pre class="lang-golang prettyprint-override"><code>newPlayer := graphqlToDB(&input)
</code></pre>
</li>
<li><p>manual updating of these (and other) fields every time</p>
<pre class="lang-golang prettyprint-override"><code>actualPlayer.TeamID = dbo.TeamID
actualPlayer.Type = dbo.Type
actualPlayer.Score = dbo.Score
actualPlayer.Note = dbo.Note
</code></pre>
</li>
<li><p>opening and closing DB transaction every time</p>
<pre class="lang-golang prettyprint-override"><code>tx, err := db.Begin()
</code></pre>
</li>
</ol>
<p>Am I asking for the moon?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T08:08:04.303",
"Id": "244214",
"Score": "2",
"Tags": [
"design-patterns",
"go"
],
"Title": "Refactoring Golang to avoid manual fields updating between similar structs and other redundant code"
}
|
244214
|
<p>I'm trying to create a dependent dynamic dropdown in jQuery, in which the number of dropdowns is not fixed. Let's say we've four provinces, each has cities, and each city has sections. Each section <strong>may or may not</strong> have a sub-section, and the list continues to ten or more dropdowns.</p>
<p>I wrote a sample code and it works, but I believe there are better ways to do so. First there's an <code>array(Obj)</code> to keep the data for each dropdown depending on the selected item. The id for dropdown in this sample is <code>#1,#2,#3 ...</code> By clicking on each item, it'll get the index of the dropdown, and set the index of newDropdown. Then there's a set of <code>if</code> logic to check existence of second dropdown. At the end, if the parent dropdown is changed, the rest of the dropdowns must be removed except the first child.</p>
<p>and here's the complete sample code <a href="https://jsfiddle.net/zahra_ahn/3q5p92ce/9/" rel="nofollow noreferrer">run the code here</a></p>
<pre><code> $('body').on('click', '.combo', function() {
var selectedValue = $(this).val();
//alert(this.id);
if (this.id < objs) {
var childVal = obj[this.id][selectedValue];
}
//get the index of current combobox
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
// set the index of new combobox
var newComboBoxIndex = thisComboBoxIndex + 1;
var id = newComboBoxIndex
//if we clicked on the dropdown and dropdown already exists:
// then just update dropdown items
if ($("#" + id).length && childVal) {
jQuery('#' + id).children().remove();
jQuery.each(childVal, function(val, text) {
jQuery('#' + id).append(
jQuery('<option></option').val(val).html(text)
);
})
}
//if dropdown does not exists:
//then add the dropdown
if ($("#" + id).length == 0 && childVal) {
jQuery('body').append('<select class= "combo" data-index="' + newComboBoxIndex + '" id="' + id + '"></select>');
jQuery.each(childVal, function(val, text) {
jQuery('#' + id).append(
jQuery('<option></option').val(val).html(text)
);
})
}
//if there's no value, then remove dropdown
if ($("#" + id).length && !childVal) {
jQuery('#' + id).remove();
}
//if we changed the item of parent, remove the children
if (this.id >= 0) {
var id_changed_combo = this.id;
// Gets the number of elements with class .combo
var numItems = $('.combo').length
$(".combo").each(function(index, element) {
if (index > (parseInt(id_changed_combo) + 1)) {
jQuery('#' + index).remove();
}
});
}
});
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T09:00:29.173",
"Id": "244217",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "Dynamic dependent dropdown in jquery"
}
|
244217
|
<p>This code works, and solves the problem, but doesn't satisfy some time requirements, especially when the 'nums' array can have a length of over 1000. How can this be optimized?</p>
<p>Just reference:
This function does <code>x</code> number of <code>operations</code> on any element in the <code>nums</code> array so that the sum of all elements in the final array is always as small as possible. As a result, you have to perform the <code>operation</code> on the elements with the highest values first.</p>
<pre><code>function minSum(nums, x) {
if (nums.length === 0) {
return false;
}
function operation(max) {
let redcuedMax = Math.floor(max / 10);
return redcuedMax
}
let ops = x;
while (ops > 0) {
let max = Math.max(...nums);
const ofNumber = (element) => element >= max ;
let maxIndex = nums.findIndex(ofNumber)
let operated = operation(max);
nums[maxIndex] = operated;
ops--
}
return nums.reduce((prev,next) => prev + next, 0)
}
minSum([400,209,77], 4) //out: 31
minSum([5000,5000,5000,5000,5000,], 4) //out: 7000
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>You can simplify the code (and maybe accelarate it) by not assigning variables for values that are used once.</li>\n<li>spreading the nums array is slow (<code>Math.max</code>), <a href=\"https://medium.com/coding-at-dawn/the-fastest-way-to-find-minimum-and-maximum-values-in-an-array-in-javascript-2511115f8621\" rel=\"nofollow noreferrer\">see\nalso</a>. <code>Math.max</code> with spreading or the faster alternative (<code>Math.max.apply</code>) for a larger array (somewhere between 120.000 - 130.000 elements) will throw a <code>Range Error</code>, so use a loop for it.</li>\n<li><code>reduce</code> is (a lot) slower than a regular loop, so use a\nloop to determine the sum</li>\n<li><code>Math.floor</code> can be replaced by a bitwise operator\n(it's slightly faster)</li>\n<li>Side note: <a href=\"https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/\" rel=\"nofollow noreferrer\">alway use semicolons</a></li>\n</ul>\n<p>The first snippet shows the aforementioned optimizations</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const testLongerArray = [...Array(2000)].map((v, i) => i && i*10 || 1);\nconst testVeryLongArray = [...Array(200000)].map((v, i) => i && i*10 || 1);\nconsole.log(minSum(testLongerArray, 600)); // out 10812701\nconsole.log(minSum(testVeryLongArray, 1600)); // out 197130527201\nconsole.log(minSum([209,400,77], 4)); //out: 31\nconsole.log(minSum([5000,5000,5000,5000,5000,], 4)); //out: 7000\n\nfunction maxValue(arr) {\n let max = 0;\n let i = arr.length;\n while (i--) {\n max = arr[i] > max && arr[i] || max;\n }\n return max;\n};\n\nfunction minSum(nums, x) {\n if (nums.length === 0) {\n return false;\n }\n const start = performance.now();\n \n while (x--) {\n // Note: a loop for max is the fastest\n // and for very large arrays spreading and Math.max.apply\n // will throw, so using the loop here\n const max = maxValue(nums);\n const maxIndex = nums.indexOf(max);\n // ^ use indexOf\n nums[maxIndex] = (max / 10) | 0;\n // ^ Math.floor replacement\n }\n \n // replace reduce with a loop\n let len = nums.length;\n let sum = 0;\n \n while (len--) {\n sum += nums[len];\n }\n\n return `sum: ${sum}, time: ${(performance.now() - start).toFixed(2)} ms`;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Now you don't have to iterate through the whole array. If you sort the input array descending, you can take a subset of the first [<code>x</code> length] elements of the sorted input array and perform the operation on the elements of that subset. Adding up the subset elements and the elements of the original sorted array minus its first <code>x</code> elements should give the desired result.</p>\n<p>That's worked out in the second snippet. In both snippets the performance is timed, so you can compare both snippets (especially for the longer arrays).</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const testLongerArray = [...Array(2000)].map((v, i) => i && i * 10 || 1);\nconst testVeryLongArray = [...Array(200000)].map((v, i) => i && i * 10 || 1);\nconsole.log(minSum(testLongerArray, 600)); // out 10812701\nconsole.log(minSum(testVeryLongArray, 1600)); // out 197130527201\nconsole.log(minSum([209, 400, 77], 4)); //out: 31\nconsole.log(minSum([5000, 5000, 5000, 5000, 5000, ], 4)); //out: 7000\n\nfunction minSum(nums, x) {\n if (nums.length === 0) {\n return false;\n }\n const start = performance.now();\n const operation = v => (v / 10) | 0;\n nums.sort((a, b) => b - a);\n let subset = nums.slice(0, x);\n let sum = 0;\n nums = nums.slice(x);\n\n while (x--) {\n const maxVal = maxValue(subset);\n subset[subset.indexOf(maxVal)] = operation(maxVal);\n }\n nums = nums.concat(subset);\n x = nums.length;\n \n while (x--) {\n sum += nums[x];\n }\n\n return `sum: ${sum}, time: ${(performance.now() - start).toFixed(2)} ms`;\n}\n\nfunction maxValue(arr) {\n let max = 0;\n let i = arr.length;\n while (i--) {\n max = arr[i] > max && arr[i] || max;\n }\n return max;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T03:35:19.737",
"Id": "479514",
"Score": "0",
"body": "Hey that's not very fair. I was trying to show the OP how to analyse And improve time complexity of his code without actually writing down the code for him. And you take it And write that code into your own answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T04:06:10.417",
"Id": "479515",
"Score": "0",
"body": "Before we get into argument. I realize that you could have made that insight on your own without reading my answer first. But from the timeline we can see that it Is possible that you stole it from my answer, because you edited your answer to include that only after my answer was posted. Although I cannot prove you stole And you cannot prove you did not. And im actually not angry if you stole the idea. What i dont like Is that you spoil the Fun for OP to figure it out on his own using those hints because I believe that showing the thoughts Is gonna teach more then showing the optimized code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T07:47:22.450",
"Id": "479520",
"Score": "0",
"body": "I can't prove it either (and why should I have to?), but the second optimization was _not_ based on your answer. It lasted a while because I was testing several ways to work it out in vscode. The benefit of wheter including worked out code in the answer or not is a matter of opinion (imho, pun intended)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T08:14:16.090",
"Id": "479521",
"Score": "0",
"body": "It would be strange to ask you to prove it and at the same time say that it cannot be proven :) I'm just saying that it's rather unfortunate that I tried to make OP implement the theory, I layed out, himself. And you spoil it by providing a possible implementation. Unlike here on stack exchange, in practice a code review hardly ever includes new code, it usualy just points to places that deserve improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T08:14:51.290",
"Id": "479522",
"Score": "0",
"body": "Anyway, I'm not asking you to remove that snippet, nor attribute it to be baesd on my answer, nor anything like that. But if you could place a reference to my answer before continue reading that part of your answer, it would be nice :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T09:44:12.610",
"Id": "244220",
"ParentId": "244218",
"Score": "5"
}
},
{
"body": "<p>First let me point out a few details.</p>\n<p>Use <code>const</code> intead of <code>let</code> unless you are going to modify the value after initialization. You use it for the <code>ofNumber</code> variable, but there are more that deserve it.</p>\n<p>But actually there's often no need to define a variable at all if it is used only once. Similarily, storing a return value to a variable and immediately returning that variable is redundant, just return the value returned by the function directly.</p>\n<pre><code>function operation(max) {\n return Math.floor(max / 10);\n}\n</code></pre>\n<p>But you could also stay consistent with the <code>ofNumber</code> callback like this:</p>\n<pre><code>const operation = (max) => Math.floor(max / 10);\n</code></pre>\n<p>Another thing is that we usualy use <code>for</code> loop in theese cases.</p>\n<pre><code>for (let ops = x; ops > 0; --ops) {...}\n</code></pre>\n<p>Now, let's analyse the big-O time complexity of your algorithm.\nAdding a comment above each statement in your code. <code>n=nums.length</code>.</p>\n<pre><code>function minSum(nums, x) {\n // O(1)\n if (nums.length === 0) {\n return false;\n }\n function operation(max) {\n // O(1)\n let redcuedMax = Math.floor(max / 10);\n return redcuedMax\n }\n let ops = x;\n // O(x * inner)\n while (ops > 0) {\n // O(n)\n let max = Math.max(...nums);\n // O(1)\n const ofNumber = (element) => element >= max ;\n // O(n)\n let maxIndex = nums.findIndex(ofNumber)\n // O(1)\n let operated = operation(max);\n // O(1)\n nums[maxIndex] = operated;\n // O(1)\n ops--\n }\n // O(n)\n return nums.reduce((prev,next) => prev + next, 0)\n}\n</code></pre>\n<p>That makes for <code>O(x * n)</code> in time. <code>O(1)</code> in space of course, because you are never making any copies of the array.</p>\n<p>How can we optimize this?</p>\n<p>Well first thing i see is that there are 2 <code>O(n)</code> operations in the loop body.\nMaybe we can find the maximum's element index in <code>O(n)</code>.And if we do, we can access the maximum element in <code>O(1)</code>. This optimization will be less efective if the input is sorted or almost sorted in descendant order, because the second <code>O(n)</code> operation is basically <code>O(1)</code> for such sorted input.</p>\n<p>Another thing is that after the loop, there is another <code>O(n)</code> operation. Maybe we can keep track of the sum (updating it in <code>O(1)</code> time) ever since the first time we needed to scan the entire array. Although, this optimization is <code>x</code> times less significant, for small <code>x</code> it may help.</p>\n<p>Of course, the most significant improvement can only arise from changing the entire algorithm's big-O complexity from <code>O(x * n)</code> to something with slower rate of change. Even if it costs us increased memory complexity to say <code>O(n)</code>.</p>\n<p>To do that we have to leave the code for now and let's think about the problem itself.</p>\n<p>You wrote:</p>\n<blockquote>\n<p>As a result, you have to perform the operation on the elements with the highest values first.</p>\n</blockquote>\n<p>Good. But is there more? How many of the highest elements will you actually need?</p>\n<p>At most <code>x</code>, right? Either the highest element divided by 10 remains the highest element, in which case you continue with that one, or the next highest element will become the current highest. So maybe we dont want to track just 1 highest element, but <code>x</code> of them. This may raise our memory complexity to <code>O(min(x,n))</code>, but that would be still a good tradeoff.</p>\n<p>Well, and I think I will break off at this point. I don't wanna write it for you. I hope I gave you enough hints to come up with a faster solution on your own. Just one more thing to say, don't be afraid to use your own specialized loops in such optimizations even if it means your code will grow. It's always trade-offs. Time, space, readability/code size, ... you improve one, you loose on the other... well sometimes not if you got it very wrong on the first shot :D (not saying this is the case:)).</p>\n<p>EDIT: I found this article (<a href=\"https://www.google.com/amp/s/www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/amp/\" rel=\"nofollow noreferrer\">https://www.google.com/amp/s/www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/amp/</a>) which shows several ways to find the x largest elements of an array, some of them seem to be faster then actually sorting the entire array in <code>O(n * log(n))</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T10:07:42.153",
"Id": "244221",
"ParentId": "244218",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T09:02:28.610",
"Id": "244218",
"Score": "7",
"Tags": [
"javascript",
"time-limit-exceeded"
],
"Title": "Minimize sum of array by applying specific operation on x carefully chosen elements"
}
|
244218
|
<p>I am trying to restructure a function more clearly and readable that has multiple return statements.</p>
<p><strong>Usecase</strong></p>
<p>Get a token:</p>
<ol>
<li>if the token does not exist in the database then generate a new one and return it.</li>
<li>if the token exists -check if expired, if expired update it with a new one, -if not expired then return the same token.</li>
</ol>
<p><strong>Code</strong></p>
<pre><code> export const GetToken = async () => {
const db = new DB();
const check = await db.GetItem();
if(check.Count === 0) {
const token = await GenerateToken();
return token;
}
if(check.Count >= 1) {
const db_token = check.Items[0];
const isExpired = isTokenExpired(db_token);
if(isExpired) {
const token = await UpdateToken(db_token);
return token;
}
return db_token;
}
}
</code></pre>
<p>There are 3 return statements in this function and there is not a base return function.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T14:04:26.393",
"Id": "479460",
"Score": "0",
"body": "The question is basically a good one, but the title was a little too common for code review. The title has been changed to bring it more in line with what is expected on code review. The title should state what the code does rather than what your concerns about the code are, put the concerns in the body of the question. Please see our [guidelines](https://codereview.stackexchange.com/help/how-to-ask), especially the title section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:32:30.827",
"Id": "479505",
"Score": "0",
"body": "@pacmaninbw i disagree, its less about returning a token from the database and more about how to handle multiple return statements in a function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:34:55.960",
"Id": "479506",
"Score": "0",
"body": "That title can make the question off-topic, which is why I changed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T23:48:38.117",
"Id": "479507",
"Score": "0",
"body": "Do you have a goal of changing the function so that it only has one return statement? If so, is there a particular reason why you want to do that?"
}
] |
[
{
"body": "<p>I'm no expert in JavaScript, but it seems to me if you changed the scope of <code>token</code> so that it is defined at the beginning of the function and then just modify the value as necessary that you can have only one return statement after all the if statements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T14:10:47.767",
"Id": "244229",
"ParentId": "244228",
"Score": "3"
}
},
{
"body": "<p>There is some simplification to be done.</p>\n<ol>\n<li>The second if statement is superfluous. I'm assuming that if <code>.Count</code> is not 0, then you know it's going to be <code>>=1</code>, so you don't need to write a second if-statement.</li>\n<li>You don't need to save variables the values of which you only use once.</li>\n</ol>\n<pre><code>export const GetToken = async () => {\n const check = await new DB().GetItem();\n\n if (check.Count === 0) {\n return await GenerateToken();;\n }\n\n const db_token = check.Items[0];\n if (isTokenExpired(db_token)) {\n return await UpdateToken(db_token);\n }\n \n return db_token;\n}\n</code></pre>\n<p>I'm not all too against having multiple return statements since this is a very short function. For longer functions, having multiple exit points can be confusing. If you do want to have fewer return statements (which is not a bad idea at all), then I agree with pacmaninbw's answer that you could have a single variable at the start of the function, populate that with the return value, and then just return that variable at the end of the function.</p>\n<pre><code>export const GetToken = async () => {\n let retToken;\n const check = await new DB().GetItem();\n\n if (check.Count === 0) {\n retToken = await GenerateToken();;\n }\n\n const db_token = check.Items[0];\n if (isTokenExpired(db_token)) {\n retToken = await UpdateToken(db_token);\n } else {\n retToken = db_token;\n }\n \n return retToken;\n}\n</code></pre>\n<p>(By the way, javascript typically uses <code>camelCase</code> for variable names and not <code>snake_case</code>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:24:58.807",
"Id": "479503",
"Score": "0",
"body": "Since you removed the second if statement to check if it is >= 1 you are doing some unnecessary operations such as checking if the token is expired. The assumption is that when you generate a new token it does not need to be checked to see if the token has expired. This was the reason for the second if statement - expiry check can be skipped if a new token was generated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:26:37.153",
"Id": "479504",
"Score": "0",
"body": "given the above i guess i can just add a `return refToken = await GenerateToken()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T01:04:22.710",
"Id": "479508",
"Score": "0",
"body": "`For longer functions, having multiple exit points can be confusing` I disagree on that point. Multiple return statements make it _easier_ to understand a long function, because once you hit one you know the rest of the function doesn't matter for the branch you took.\n\nYour first method is also better because it guarantees you don't return an uninitialized value, while your second method requires you to check every branch to make sure you don't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:17:13.853",
"Id": "479554",
"Score": "0",
"body": "@Kay That is fair. I didn't quite understand the system you were dealing with so clearly that is a judgement you needed to make yourself, and I agree entirely with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:17:47.363",
"Id": "479555",
"Score": "0",
"body": "@Turksarama Interesting perspective. I've read different opinions on multiple exit points versus one single. I like your point of view."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T14:44:51.923",
"Id": "244230",
"ParentId": "244228",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244229",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T13:36:00.170",
"Id": "244228",
"Score": "4",
"Tags": [
"javascript",
"node.js"
],
"Title": "How to handle multiple return statements"
}
|
244228
|
<p>My answer to <a href="https://projecteuler.net/problem=4" rel="nofollow noreferrer">Project Euler problem 4</a> (largest palindrome of product of two 3-digit numbers) is below.<br />
Please suggest improvements, style changes, indentation, commenting, naming, ...</p>
<p>And nitpicks are welcome!</p>
<p>Other than general <em>stuff</em> about the code below, I'd like to ask specifically about</p>
<ol>
<li><code>assert</code> is good to use? Frowned upon? Has possible drawbacks?</li>
<li><code>progn</code> looks like a 2nd class construct. Is the usage in the final function correct? Are there other (more Lispy-like) options?</li>
</ol>
<pre><code>(defun e004-digits (n &optional (base 10))
"return a list with the digits of n"
(assert (and (integerp n) (>= n 1)
(integerp base) (>= base 2)))
(loop with remainder
while (> n 0)
do (setf (values n remainder) (floor n base))
collect remainder))
(defun e004-palindrome6p (n6)
"determine if the 6-digit number n6 is a palindrome (in base 10)"
(assert (and (integerp n6) (>= n6 100000) (<= n6 999999)))
(let ((dd (e004-digits n6)))
(and (= (nth 2 dd) (nth 3 dd))
(= (nth 1 dd) (nth 4 dd))
(= (nth 0 dd) (nth 5 dd)))))
(defun e004-largest-palindrome-in-square (siz)
"find maximum palindrome product"
(do* ((a siz)
(b siz)
(nextb)
(sum (+ siz siz))
(p (* a b) (* a b)))
((e004-palindrome6p p) p)
;; following half diagonals ensures (proof needed?)
;; the first palindrome product found is the largest
(setf a (+ a 1))
(setf b (- b 1))
(if (> a siz) ; start next diagonal
(progn (setf (values a nextb) (floor sum 2))
(setf b (+ a nextb -1))
(setf sum (- sum 1))))))
(defun e004 ()
(e004-largest-palindrome-in-square 999))
</code></pre>
<p><sup>code also available on <a href="https://github.com/pm62eg/" rel="nofollow noreferrer">github</a></sup></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T18:05:01.430",
"Id": "481138",
"Score": "0",
"body": "`progn` usage in last function is correct and needed as `if`'s then clause must be a single expression. Note however that `setf` can take multiple pairs of places and values like `(setf x y a b)` so you could do that *instead* of using `progn`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:37:41.817",
"Id": "495336",
"Score": "1",
"body": "I'd personally consider changing the `(if <condition> (progn ...))` to `(when <condition> ...)`. It feels as if it flows a bit better."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T15:52:01.920",
"Id": "244232",
"Score": "2",
"Tags": [
"beginner",
"programming-challenge",
"lisp",
"common-lisp"
],
"Title": "Lispy code? Palindrome of product"
}
|
244232
|
<p>What I am trying to do, is to get weather data, data about bike trips and populate the postgresql database in order to be able to work with this data from Power BI/Tableau/any other tool.</p>
<p>I have two different data sources. The first of them is yr.no API, which I am using to access weather data. The second one is oslobysykkel.no, from where I get data related to bike trips.</p>
<p>The goal is to have this initial load done with docker containers and azure blob storages, as I would like to learn more about them. But that would be the second stage. I have not really done any "ETL-ish" processing in python before, so I would love to get some feedback from you related to my code and flow.</p>
<p>The current structure looks like that:</p>
<p><a href="https://i.stack.imgur.com/CwSIo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CwSIo.png" alt="enter image description here" /></a></p>
<p>I am not really sure if that looks OK but I was thinking about having two different docker containers(one for extract/process part and the second one for loading the data to postgresql.</p>
<p>The first one to be created is calendar table:</p>
<pre><code>import pandas as pd
from datetime import datetime
import os
"""
Simple script, using pandas library to create a date table. One time job.
"""
local_path_processed = os.environ.get('LOCAL_PATH_PROCESSED')
start_date = '2010-01-01'
end_date = '2030-12-31'
"""
#Additional settings for pandas to make printouts more clear in the console, it's getting easier to debug.
pd.set_option('display.max_columns',12)
desired_width=320
pd.set_option('display.width', desired_width)
"""
def create_date_table(start_date, end_date):
df = pd.DataFrame({"date_hour": pd.date_range(start_date, end_date,freq='H')})
df["date"] = df.date_hour.dt.date
df["hour"] = df.date_hour.dt.hour
df["day"] = df.date_hour.dt.day
df["day_name"] = df.date_hour.dt.day_name()
df["week"] = df.date_hour.dt.weekofyear
df["quarter"] = df.date_hour.dt.quarter
df["year"] = df.date_hour.dt.year
df["year_half"] = (df.quarter + 1) // 2
return df
timestampStr = datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")
"""
Create date table
"""
date_df = create_date_table(start_date,end_date)
"""
Add date id, ETL timestamp and write down data
"""
date_df["date_id"] = date_df.date_hour.apply(lambda x: x.strftime('%Y%m%d%H')).astype(int)
date_df["etl_timestamp"] = datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")
date_df_sorted = date_df[ ['date_id'] + [ col for col in date_df.columns if col != 'date_id' ] ]
date_df_sorted.to_csv(local_path_processed + 'date_table.csv',index=False)
</code></pre>
<p>Table with bike trips. First, I am getting raw files using selenium(one file is one month) and then I am doing some simple transformations.</p>
<pre><code>import pandas as pd
import glob, os
import time
"""
#Additional settings for pandas to make printouts more clear in the console, it's getting easier to debug.
pd.set_option('display.max_columns',12)
desired_width=320
pd.set_option('display.width', desired_width)
"""
"""
Get raw data using selenium and oslo bysykkel website. It takes some time to download data depending on your internet connectione.
Therefore I have used time(sleep) in order to avoid running further processing on partial data.
"""
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
local_path_raw = os.environ.get('LOCAL_PATH_RAW')
local_path_processed = os.environ.get('LOCAL_PATH_PROCESSED')
remote_path = "https://developer.oslobysykkel.no/apne-data/historisk"
def download_data(remote_path, local_path, options,month_range):
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': local_path}}
driver.execute("send_command", params)
driver.implicitly_wait(5)
driver.get(remote_path)
for month in range(1,month_range):
driver.find_element_by_xpath('//*[@id="__next"]/div/div[2]/div/div/article/ul[1]/li[{}]/div/div[2]/a[2]/button'.format(month)).click()
op = Options()
op.add_argument('--disable-notifications')
op.add_experimental_option("prefs",{
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True
})
download_data(remote_path, local_path_raw, op, 15)
time.sleep(30)
"""
Processing part:
Merging all raw csv files into one dataframe.
Processing of dataframe, adding all columns that I use for the reporting layer.
"""
os.chdir(local_path_raw)
counter = 0
for file in glob.glob("*.csv"):
if os.stat(local_path_raw+"\{}".format(file)).st_size <= 264:
pass
else:
if counter == 0:
bike_trip_df = pd.read_csv(file)
else:
bike_trip_df.append(pd.read_csv(file))
counter += 1
def process_df(dataframe):
dataframe['bike_trip_id'] = dataframe.index
dataframe['started_at_floor'] = pd.to_datetime(dataframe['started_at']).dt.floor(freq='H')
dataframe['ended_at_floor'] = pd.to_datetime(dataframe['ended_at']).dt.floor(freq='H')
dataframe['date_id'] = dataframe.apply(lambda x: list(pd.date_range(x['started_at_floor'], x['ended_at_floor'], freq="1H")), axis='columns')
dataframe = dataframe.explode('date_id')
dataframe['date_id'] = dataframe['date_id'].dt.strftime('%Y%m%d%H')
return dataframe
bike_trip_df = process_df(bike_trip_df)
bike_trip_df.to_csv(local_path_processed+"bike_trip.csv",sep=";")
</code></pre>
<p>Then a table with weather observations. I am getting hourly data for each day. YYYYMMDDHH is also a key that I want to use in my data model to connect everything. In the next stage, I would like to use azure blob storages instead of local memory, so that I can create those independent docker images as well:</p>
<pre><code>import requests
import pandas as pd
import datetime
from datetime import datetime, timedelta
from dateutil import parser
import os
"""
#Additional settings for pandas to make printouts more clear in the console, it's getting easier to debug.
pd.set_option('display.max_columns',12)
desired_width=320
pd.set_option('display.width', desired_width)
"""
start_date = os.environ.get('START_DATE_WEATHER')
end_date = os.environ.get('END_DATE_WEATHER')
local_path_processed = os.environ.get('LOCAL_PATH_PROCESSED')
def get_date_range(begin, end):
beginDate = parser.parse(begin)
endDate = parser.parse(end)
delta = endDate-beginDate
numdays = delta.days + 1
dayList = [datetime.strftime(beginDate + timedelta(days=x), '%m-%d-%Y') for x in range(0, numdays)]
return dayList
list_of_dates = get_date_range(start_date,end_date)
def call_api(list_of_dates):
row_values = []
for date in list_of_dates:
try:
raw_json = requests.get('https://www.yr.no/api/v0/locations/1-72837/observations/{}'.format(date)).json()
for day in raw_json.get('historical').get('days'):
for hour in day.get('hours'):
row_object = {}
for key, value in hour.items():
try:
row_object[key] = next(iter(value.values()))
except:
row_object[key] = value
for key, value in row_object.items():
try:
if len(value) == 0:
row_object[key] = None
except:
pass
row_values.append(row_object)
except:
pass
return process_dataframe(row_values)
def process_dataframe(row_values):
df = pd.DataFrame(row_values)
df['date'] = pd.to_datetime(df['time'])
df['date_id'] = df.date.apply(lambda x: x.strftime('%Y%m%d%H'))
df['rush_hour'] = df.date_id.apply(
lambda x: "Yes" if (int(x[:-2]) in range(6, 10) or int(x[-2:])) in range(15, 19) else "No")
return df
observation_df = call_api(list_of_dates)
observation_df["etl_timestamp"] = datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")
observation_df.to_csv(local_path_processed + "weather_observation.csv",sep=";")
</code></pre>
<p>And finally, I am writing data to three different tables in my postgresql database.</p>
<pre><code>import psycopg2.extras
import pandas as pd
import io
import psycopg2
import os
base_path = os.environ.get('BASE_PATH')
database = os.environ.get('DATABASE')
username = os.environ.get('USERNAME')
password = os.environ.get('PASSWORD')
host = os.environ.get('HOST')
def db_connect (db_parm, username_parm, host_parm, pw_parm):
credentials = {'host': host_parm, 'database': db_parm, 'user': username_parm, 'password': pw_parm}
conn = psycopg2.connect(**credentials,cursor_factory=psycopg2.extras.RealDictCursor)
conn.autocommit = True
cur = conn.cursor()
print ("Connected Successfully to DB: " + str(db_parm) + "@" + str(host_parm))
return conn, cur
def db_insert(filename, table_name, file_path, conn, cur):
dataframe = pd.read(file_path+filename)
output = io.StringIO()
dataframe.to_csv(output, sep='\t', header=True, index=False)
output.seek(0)
copy_query = "COPY {} FROM STDOUT csv DELIMITER '\t' NULL '' ESCAPE '\\' HEADER ".format(table_name) # Replace your table name in place of mem_info
cur.copy_expert(copy_query, output)
conn.commit()
conn, cur = db_connect(database, username, host, password)
db_insert("filename", "date", base_path, conn, cur)
db_insert("filename", "weather_observation", base_path, conn, cur)
db_insert("filename", "bike_trip", base_path, conn, cur)
</code></pre>
<p>Thank you in advance for any feedback & suggestions!</p>
|
[] |
[
{
"body": "<h2>Shadowing</h2>\n<p>You declare these globals:</p>\n<pre><code>start_date = '2010-01-01'\nend_date = '2030-12-31'\n</code></pre>\n<p>and also these parameters:</p>\n<pre><code>def create_date_table(start_date, end_date):\n</code></pre>\n<p>That is confusing; the local parameters will take priority. One way to distinguish the two is to capitalize the global constants, which is standard anyway.</p>\n<h2>snake_case</h2>\n<p><code>timestampStr</code> should be <code>timestamp_str</code>.</p>\n<h2>Selenium</h2>\n<p>I don't know a lot about the website, but a brief visit makes it seem like this is simple enough for you to avoid Selenium - which tries to emulate a browser - and do direct HTTP using the Requests library plus BeautifulSoup, which will be much more efficient.</p>\n<h2>pathlib</h2>\n<p>This:</p>\n<pre><code>os.stat(local_path_raw+"\\{}".format(file))\n</code></pre>\n<p>will be simplified using <code>pathlib.Path(local_path_raw)</code>.</p>\n<h2>Exception swallowing</h2>\n<p>This:</p>\n<pre><code> except:\n pass\n</code></pre>\n<p>is extremely dangerous. It will prevent user break (Ctrl+C) from working, and will hide anything going wrong in that section of the code - even if it's a critical failure. At the absolute least, <code>except Exception</code> instead of <code>except</code>, and ideally print what's gone wrong.</p>\n<h2>os.environ.get</h2>\n<p>You don't seem to be treating these parameters as optional; you don't provide defaults. So this will create some failures later than they should occur. Use <code>[]</code> instead to move the failure up to a point where it's more obvious that a parameter is missing.</p>\n<h2>Autocommit</h2>\n<p>Since you've enabled this, why do you also</p>\n<pre><code>conn.commit()\n</code></pre>\n<p>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T14:46:00.840",
"Id": "244266",
"ParentId": "244233",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T16:43:24.117",
"Id": "244233",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"api",
"postgresql",
"docker"
],
"Title": "Getting weather and cycling data (yr.no, oslobysykkel)"
}
|
244233
|
<p>I have this code that fetches data from a 3rd party api and sends it to my backend to be processed. The 3rd party api needs to target the user's localhost address so it has to come from the front end. I have the code below which works perfectly fine but it looks messy, I'm sure there is a better way to write it. Any suggestions?</p>
<p>I am using fetch for the original request because if I use axios to the 3rd party api I get a cors error.</p>
<pre><code> getLogs = () => {
const { user } = this.props.auth;
fetch(`http://127.0.0.1:60000/onexagent/api/registerclient?name=${user.id}`)
.then((res) => res.text())
.then((result) => {
const regxml = new XMLParser().parseFromString(result);
if (regxml.attributes.ResponseCode === "0") {
axios.post(`/api/avaya/register/${user.id}`, regxml);
}
console.log(regxml);
});
fetch(`/api/avaya/getid/${user.id}`)
.then((res) => res.text())
.then((result) => {
fetch(
`http://127.0.0.1:60000/onexagent/api/nextnotification?clientid=${result}`
)
.then((res) => res.text())
.then((result) => {
const xml = new XMLParser().parseFromString(result);
axios.post(`/api/avaya/getlogs/${user.id}`, xml);
});
});
};
timer = (time) => {
const date = new Date(time);
return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
};
componentDidMount() {
this.getLogs();
this.interval = setInterval(this.getLogs, 5000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:39:36.337",
"Id": "479561",
"Score": "0",
"body": "I think using async/await could improve the readability of your code. But I am not an expert on this topic. Actually I am learning it at the moment. Maybe you will find this video helpful: https://bit.ly/2V7hRZn"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:31:00.490",
"Id": "479737",
"Score": "0",
"body": "Other than you *think* it looks messy (an opinion) is there another issue and/or concern about the code? It's true that using async/await can reduce some of the \"boiler-plate\"y-ness of Promise-chains, I don't really see where that'd help you much. Only minor issue I see is that the second fetch's second fetch chain can be flattened down (i.e. un-nested). Perhaps factoring each fetch into smaller functions could help. TBH, the code appears fairly clean and readable to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T05:58:45.403",
"Id": "480083",
"Score": "0",
"body": "The second `fetch` might be a good example of when to use `await` to get rid of the callback hell created by the nested `.then`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T07:23:37.030",
"Id": "480758",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T13:51:57.170",
"Id": "480924",
"Score": "2",
"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)*. Consider posting a new question instead, linking back to this one."
}
] |
[
{
"body": "<p>Let me share my <code>async await</code> solution for that:</p>\n<ul>\n<li>Because Your fetch function is pretty similar till the <code>res.text()</code>, I would create an own function (<code>fetchData </code>) for that, what is returning a <code>Promise</code>, what is resolving a <code>res.text()</code></li>\n<li>Now you can assign an <code>async</code> to your <code>getLogs</code>function</li>\n<li>Lets reorganise your code above</li>\n<li><b>Error handling is missing here, but take care about it </b></li>\n</ul>\n<p>:</p>\n<pre><code> fetchData = (url) => {\n return new Promise((res, rej) => {\n fetch(url)\n .then(r => r.text())\n .then(text => {\n res(text)\n })\n .catch(e => rej(e));\n });\n }\n\n getLogs = async () => {\n const { user } = this.props.auth;\n const regxmlPromise = fetchData(`http://127.0.0.1:60000/onexagent/api/registerclient?name=${user.id}`);\n const secondDataPromise = fetchData(`/api/avaya/getid/${user.id}`);\n \n const resolves = await Promise.all([regxmlPromise, secondDataPromise]);\n \n const [firstResultStepOne, secondResultStepOne] = resolves || [];\n \n const secondResultStepTwo = await fetchData(`http://127.0.0.1:60000/onexagent/api/nextnotification?clientid=${secondResultStepOne}`);\n\n if (firstResultStepOne) {\n const regxml = new XMLParser().parseFromString(firstResultStepOne);\n if (regxml.attributes.ResponseCode === "0") {\n axios.post(`/api/avaya/register/${user.id}`, regxml);\n }\n console.log(regxml);\n }\n \n if (secondResultStepTwo) {\n const xml = new XMLParser().parseFromString(secondResultStepTwo);\n axios.post(`/api/avaya/getlogs/${user.id}`, xml);\n }\n };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:03:37.087",
"Id": "480926",
"Score": "1",
"body": "This looks really good, i tried it in my code and works perfectly. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:23:03.347",
"Id": "480928",
"Score": "0",
"body": "btw, is there a way to visualize in which order each steps happen? I assume the variable assignment first, then the if statement and then the promises resolve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:25:55.273",
"Id": "480929",
"Score": "1",
"body": "The code runs from the top to the buttom step by step. variable assignment first, promises resolve(because we are `await`ing it) and then the if statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:36:29.573",
"Id": "480932",
"Score": "0",
"body": "The if has to happen before the promises resolve because the firstResultStepOne will register the client which returns a client id. The secondResultStepTwo uses the client ID that was generated by firstResultStepOne and then posted to the user obj after the if statement checks firstResultStepOne to see if response is 0 meaning client is not already registered. secondResultStepOne will fetch the client id from the user doc in Mongodb and then it can be used in secondResultStepTwo. So my understanding here is that the If statement seem to run first, or am i understanding this wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:47:32.217",
"Id": "480936",
"Score": "1",
"body": "The if can not happen before the promises resolving, because we need the results from all `promises`. \n2 `promise`can fires in the same time, and `àwait`for both results here: `const resolves = await Promise.all([regxmlPromise, secondDataPromise]);`\nThis result will be an array with 2 element.(2x result from the backend).\nWe need to await them, because would reuse the data from the `secondResultStepOne ` in the `const secondResultStepTwo = await fetchData...`. After we having a result from the last promise (no errors), we can process the `firstResultStepOne ` and the `secondResultStepTwo`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:47:46.897",
"Id": "480937",
"Score": "1",
"body": "Ok i console.logged the steps to find out what is happening. It is working in the order you say it does. The secondResultStepTwo runs before the if statements and returns a response code 2 which means the client is not registered as it's trying to use the old client id that it fetched in secondResultStepOne. Then the if statement runs, uploads the new client id, and the whole thing runs again as it's on a setinterval loop and this time secondResultStepTwo returns the correct value as it is now using the new client id."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T22:28:14.903",
"Id": "244858",
"ParentId": "244236",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244858",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T17:06:58.203",
"Id": "244236",
"Score": "7",
"Tags": [
"javascript",
"node.js",
"react.js",
"express.js",
"axios"
],
"Title": "How do I refactor this fetch request?"
}
|
244236
|
<p>Ok so my name is qqqiiiiiiiifdff and I made this code that simulates a perceptual color picker algorithm that selects the nearest color by iterating over the color array and selecting the minimum error, processing the calculations in a perceptual manner.</p>
<p>This is an example:</p>
<pre><code>#include <stdint.h>
#include <math.h>
inline double square(double x){return x*x;}
inline double sRGBtolinear(double input){
if(input < 0) return -sRGBtolinear(-input);
else if(input > 0.0404482362771082) return pow((input+0.055)/1.055, 2.4);
else return input/12.92;
}
inline double lineartosRGB(double input){
if(input < 0) return -lineartosRGB(-input);
else if(input > 0.00313066844250063) return pow(input, 0.4166666666666667)*1.055-0.055;
else return input*12.92;
}
inline double lineartosRGBderivative(double input){
if(input < 0) return lineartosRGBderivative(-input);
else if(input > 0.00313066844250063) return pow(input, -0.5833333333333334)*0.4166666666666667*1.055;
else return 12.92;
}
uint64_t selectnearest(uint32_t* palette, uint64_t palettelength, uint32_t color){
uint64_t index = 0;
double maxerror = 1.0/0.0;
for(uint64_t i=0; i<palettelength; i++){
double color1[3];
double color2[3];
color1[0] = sRGBtolinear((color/65536%256)/255.0);
color1[1] = sRGBtolinear((color/256%256)/255.0);
color1[2] = sRGBtolinear((color%256)/255.0);
color2[0] = sRGBtolinear((palette[i]/65536%256)/255.0);
color2[1] = sRGBtolinear((palette[i]/256%256)/255.0);
color2[2] = sRGBtolinear((palette[i]%256)/255.0);
double initdistance = sqrt((square(212671.0*(color1[0]-color2[0]))+square(715160.0*(color1[1]-color2[1]))+square(72169.0*(color1[2]-color2[2])))/561891144402.0);
double brightness1 = ((212671.0*color1[0])+(715160.0*color1[1])+(72169.0*color1[2]))/1000000.0;
double brightness2 = ((212671.0*color2[0])+(715160.0*color2[1])+(72169.0*color2[2]))/1000000.0;
double sRGBbrightness1 = lineartosRGB(brightness1);
double sRGBbrightness2 = lineartosRGB(brightness2);
double brightnessdifference = brightness2 - brightness1;
double sRGBbrightnessdifference = sRGBbrightness2 - sRGBbrightness1;
if(brightness1 == brightness2){
brightnessdifference = 1;
sRGBbrightnessdifference = lineartosRGBderivative(brightness1);
}
double result = initdistance*(sRGBbrightnessdifference/brightnessdifference);
if(result < maxerror){
index = i;
maxerror = result;
}
}
return index;
}
int main(){
const uint64_t amountofcolors = 216;
uint32_t palette[amountofcolors];
for(uint64_t i=0; i<216; i++){
palette[i] = i%6*0x000033 + i/6%6*0x003300 + i/36%6*0x330000;
} // sample palette
volatile uint32_t color;
for(uint64_t i=0; i<65536; i++){
color = (rand()%4096)+(rand()%4096*4096);
color = palette[selectnearest(palette, amountofcolors, color)];
}
}
</code></pre>
<p>To a person who does not know any code, this does not appear inefficient until it is run. What happened here? The process returned zero, and the execution time is 31.141 seconds. Now, it might seem like this is quite fast for 65536 colors to quantize to the palette, however you could imagine how a dynamic script to play a 256×256 movie in a reduced palette will play in 0.03 fps. Could this be a processing error and I have to try again? No, because the next time it is not much better at 31.085 seconds, and again at 31.110 seconds. Now, you could argue that a different color picker algorithm would be faster, however that is not the point because they don't pick colors the same way, the point is to make this specific algorithm faster, but still pick the colors about the same way. What should be done in order to improve the efficiency of this method?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T21:02:32.060",
"Id": "479501",
"Score": "0",
"body": "Does the time improve when you compile -O3 which is the maximum optimization the compiler can perform?"
}
] |
[
{
"body": "<p>I have come up with some suggestions to <em>improve your code performance</em></p>\n<ul>\n<li>Extract from the loops any variable declaration.</li>\n<li>If a variable is called only to assign a value or execute an operation <em>only one</em> time, you should replace the value assigned to that variable in its place.</li>\n<li>Numeric values which are in the code should be either avoided or if they are needed, turned in constants.</li>\n<li>Repeated lines or code blocks are candidates to be written as functions.</li>\n<li>If you use compiler optimization it could make your code run faster (but be careful, some unexpected things may happen).</li>\n</ul>\n<p>I made the following refactor to your code in order to optimize it:</p>\n<pre>double compute_brightness(double *color) //pointer = avoids array copy\n{\n return ((212671.0*color[0])+(715160.0*color[1])+(72169.0*color[2]))/1000000.0;\n}\n\n//this value is constant but it gets created each time the function is called\n//(consider to use INFINITY from <cmath>)\nconst double maxerror = 1.0/0.0;\n\nuint64_t selectnearest(uint32_t* palette, uint64_t palettelength, uint32_t color)\n{\n uint64_t index = 0;\n double color1[3];\n double color2[3];\n double brightness1;\n double brightness2;\n double brightnessdifference;\n double sRGBbrightnessdifference;\n double result;\n for (uint64_t i = 0; i < palettelength; i++)\n {\n //...\n brightness1 = compute_brightness(color1);//the same operation is applied\n brightness2 = compute_brightness(color2);//to these arrays\n //the value of `brightnessdifference` and `sRGBbrightnessdifference`\n //depends on this if, the else avoids to compute unused values\n if (brightness1 == brightness2)\n {\n brightnessdifference = 1;\n sRGBbrightnessdifference = lineartosRGBderivative(brightness1);\n }\n else\n {\n brightnessdifference = brightness2 - brightness1;\n sRGBbrightnessdifference = lineartosRGB(brightness2) - lineartosRGB(brightness1);\n }\n result = sqrt((square(212671.0*(color1[0]-color2[0])) + \n square(715160.0*(color1[1]-color2[1]))+square(72169.0*(color1[2]-color2[2])))/561891144402.0) *\n (sRGBbrightnessdifference/brightnessdifference);\n if (result < maxerror)\n {\n index = i;\n maxerror = result;\n }\n }\n return index;\n}\n\nint main()\n{\n //...\n volatile uint32_t color;\n for (uint64_t i = 0; i < 65536; i++)\n color = palette[selectnearest(palette, amountofcolors, (rand()%4096)+(rand()%4096*4096))];\n}\n</pre>\n<p>I hope it helps you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:12:04.900",
"Id": "479502",
"Score": "1",
"body": "Any code that includes division by zero should be looked at hard."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T20:07:11.730",
"Id": "244240",
"ParentId": "244237",
"Score": "2"
}
},
{
"body": "<p><strong>Obsolete Keywords</strong><br />\nThe C++ keyword inline is a <a href=\"https://stackoverflow.com/questions/29796264/is-there-still-a-use-for-inline\">recommendation to the compiler</a> and it won't necessarily do anything. It has been basically obsolete since C++03. When the optimization flags are used during compilation, the compiler will decide what can be inlined and take care of it.</p>\n<p><strong>Division by Zero</strong><br />\nThis program should either throw a <code>division by zero</code> exception or the compiler should complain on the following line (my compiler complained and wouldn't build the code).</p>\n<pre><code>double maxerror = 1.0/0.0;\n</code></pre>\n<p><strong>Inconsistent Usage of Symbolic Constants</strong><br />\nThis code in main is inconsistent:</p>\n<pre><code>int main(){\n const uint64_t amountofcolors = 216;\n uint32_t palette[amountofcolors];\n for(uint64_t i=0; i<216; i++){\n palette[i] = i%6*0x000033 + i/6%6*0x003300 + i/36%6*0x330000;\n } // sample palette\n</code></pre>\n<p>The use of the numeric constant 216 in the for loop should be changed to use <code>amountofcolors</code>. That way if the value of <code>amountofcolors</code> changes the for loop will use the correct value.</p>\n<p><strong>The use of uint64_t</strong><br />\nRather than specify uint32_t or uint64_t just use <code>unsigned</code>, <code>unsigned int</code>, <code>unsigned long</code> or <code>size_t</code>. This will automatically choose the size of the value based on the word size of the computer and that will provide the fastest code.</p>\n<p><strong>More Symbolic Constants Are Better</strong><br />\nThe numeric constants <code>0x000033</code>, <code>0x003300</code> and <code>0x330000</code> are apparently some versions of RED, GREEN and BLUE. It might help others that need to modify the code if they had a better idea of what the values were so use symbolic constants, it won't hurt the performance.</p>\n<p>The numeric constant <code>12.92</code> is used in 3 inline functions, if it has the same meaning for all 3 functions then a symbolic constant is called for so that all 3 functions can be changed at the same time</p>\n<p><strong>Use of the <code>rand()</code> Function Without Seeding</strong><br />\nThere is nothing random about this code since rand was never seeded.</p>\n<pre><code> color = (rand()%4096)+(rand()%4096*4096);\n</code></pre>\n<p><strong>Using C Include Headers in C++</strong><br />\nIn C++ standard C include headers can be included by adding a <code>c</code> to the front of the name and removing the <code>.h</code>.</p>\n<pre><code>#include <cstdint>\n#include <cmath>\n</code></pre>\n<p>I'm going to stop here because there is enough to fix without addressing any more, post a follow up question when you've taken care of this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T09:32:41.653",
"Id": "479626",
"Score": "0",
"body": "No, a compiler should not throw an exception or refuse to compile the code. 1.0/0.0 is defined as postiive infinity according to IEEE754 and any compiler not doing so will violate the C specification (https://en.wikipedia.org/wiki/Division_by_zero#Computer_arithmetic)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:10:35.220",
"Id": "244241",
"ParentId": "244237",
"Score": "2"
}
},
{
"body": "<p>There are a lot of performance aspects that can be improved in your code. I will cover general suggestions assuming that this code is for Win32 target. I will use minGw compiler with c11 standard.</p>\n<p><strong>Compiler Optimizations:</strong>\nWithout optimization code runs about 12.8 seconds on my PC. With -O3 optimization flag it takes about 10.6 seconds (about 17% faster).</p>\n<p><strong>Data types and arithmetic operations:</strong>\ndouble type and constants with high precision are used in the code. Do you really need this precision? Moreover infinity is used in maxerror variable: <code>double maxerror = 1.0/0.0;</code> Consider to use <code>DBL_MAX</code> instead of inf. If performance is important then general algorythm of data types selection is following:</p>\n<ol>\n<li>Can I use integer arithmetics? Prefereably int/uint types with logical/shift operations.</li>\n<li>If not, then can I use float?</li>\n<li>If not, then chose double or more precise types.</li>\n<li>If floating point data types are used then consider NOT using floating point exceptions, NaN, Inf and denormal values. All these things can be very slow.</li>\n</ol>\n<p>For example, you extract color components in the following way:</p>\n<pre><code>color1[0] = sRGBtolinear((color/65536%256)/255.0);\n</code></pre>\n<p>Here integer division can be replaced by bitwise/shift operations which is much faster. Assembly code will be almost 3 times shorter.</p>\n<pre><code>color1[0] = sRGBtolinear(((color >> 16) & 0xff)/255.0);\n</code></pre>\n<p><strong>Inlining:</strong>\nAs it has been already mentioned <code>inline</code> keyword is confusing nowadays. Compilers have attributes or pragmas to always_inline/force_inline or noinline functions, because it is very important in some cases. E.g. if you want to insert assembly code with label in function wich compiler decided to inline. In this case compilation will fail. Only prohibiting inlining can help. In our case functions <code>lineartosRGBOrig</code> and <code>lineartosRGBderivativeOrig</code> can't be inlined because they are recursive. By the way, this recursion is not needed because input to these functions is always positive in current algorithm.</p>\n<p><strong>Algorithm changes and code rearrangment:</strong></p>\n<ul>\n<li>It is better to move variables declarations from the loop.</li>\n<li>Values related to <code>color</code> in function <code>selectnearest</code> can be calculated only once istead of recalculation <code>palettelength</code> times.</li>\n<li><code>RGBtolinear</code> data can be precalculated as a table with 255 elements to significantly improve performance.</li>\n<li><code>initdistance</code> and brightness values are used only in comparison which allows us to remove <code>sqrt</code> operation and some divisions because we don't need exact values. Only relation is important.</li>\n</ul>\n<p><strong>Some brief optimizations:</strong>\nI have made some optimizations that improved performance by 86% to original code compiled with -O3 flag and by 89% to code compiled without optimization. The code is not perfect but it is much faster.</p>\n<pre><code>#pragma GCC push_options\n#pragma GCC optimize ("O3")\n\ndouble gRgbToLinearTable[255];\n\nvoid InitRgbToLinearTable(){\n for (size_t i = 0u; i < 255u; ++i)\n {\n double val = i / 255.0;\n gRgbToLinearTable[i] = (val > 0.0404482362771082 ? pow((val+0.055)/1.055, 2.4) : val/12.92);\n }\n}\n\n[[gnu::always_inline]] inline double square(double x) { return x*x; }\n\n[[gnu::always_inline, gnu::flatten]] inline void sRGBtolinear(double* outComponents, uint32_t color){\n outComponents[0] = gRgbToLinearTable[(color >> 16) & 0xff];\n outComponents[1] = gRgbToLinearTable[(color >> 8) & 0xff];\n outComponents[2] = gRgbToLinearTable[color & 0xff];\n}\n\n[[gnu::always_inline, gnu::flatten]] inline double lineartosRGB(double input){\n if (input > 0.00313066844250063)\n return (pow(input, 0.4166666666666667)*1.055-0.055);\n else\n return input*12.92;\n}\n\n[[gnu::always_inline, gnu::flatten]] inline double lineartosRGBderivative(double input){\n if(std::abs(input) > 0.00313066844250063) return pow(input, -0.5833333333333334)*0.4166666666666667*1.055;\n else return 12.92;\n}\n\nsize_t selectnearest(const uint32_t* palette, size_t palettelength, uint32_t color)\n{\n size_t index = 0;\n double maxerror = DBL_MAX;\n double colors[2][3];\n double initdistance, brightness[2], rgbBrightness[2], brightnessdifference, sRGBbrightnessdifference;\n sRGBtolinear(colors[0], color);\n brightness[0] = (0.212671*colors[0][0])+(0.715160*colors[0][1])+(0.072169*colors[0][2]);\n rgbBrightness[0] = lineartosRGB(brightness[0]);\n\n for (size_t i = 0; i < palettelength; i++)\n {\n if (palette[i] != color)\n {\n sRGBtolinear(colors[1], palette[i]);\n\n initdistance = (square(0.212671*(colors[0][0]-colors[1][0]))+square(0.212671*(colors[0][1]-colors[1][1]))+square(0.072169*(colors[0][2]-colors[1][2])));\n brightness[1] = (0.212671*colors[1][0])+(0.715160*colors[1][1])+(0.072169*colors[1][2]);\n rgbBrightness[1] = lineartosRGB(brightness[1]);\n\n if(brightness[0] != brightness[1])\n {\n brightnessdifference = brightness[1] - brightness[0];\n sRGBbrightnessdifference = rgbBrightness[1] - rgbBrightness[0];\n }\n else\n {\n brightnessdifference = 1.0 ;\n sRGBbrightnessdifference = lineartosRGBderivative(brightness[0]);\n }\n\n double result = initdistance*(sRGBbrightnessdifference/brightnessdifference);\n if(result < maxerror){\n index = i;\n maxerror = result;\n }\n }\n else\n {\n return i;\n }\n }\n\n return index;\n}\n\nuint32_t* MakeSamplePalette(size_t amountOfColors)\n{\n uint32_t* pResult = new uint32_t[amountOfColors];\n for(size_t i = 0; i < amountOfColors; i++)\n {\n pResult[i] = i%6*0x000033 + i/6%6*0x003300 + i/36%6*0x330000;\n }\n\n return pResult;\n}\n\nint main()\n{\n const size_t amountofcolors = 216u;\n uint32_t* palette = MakeSamplePalette(amountofcolors);\n volatile uint32_t color;\n\n InitRgbToLinearTable();\n for(size_t i = 0; i < 65536u; i++){\n color = (static_cast<unsigned int>(rand()) & 0xfff)+(static_cast<unsigned int>((rand()) & 0xfff) << 12);\n color = palette[selectnearest(palette, amountofcolors, color)];\n }\n\n delete[] palette;\n return color;\n}\n#pragma GCC pop_options\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T21:19:36.343",
"Id": "244287",
"ParentId": "244237",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T19:13:36.220",
"Id": "244237",
"Score": "5",
"Tags": [
"c++",
"performance",
"beginner"
],
"Title": "Nearest color algorithm efficiency"
}
|
244237
|
<p>I recently had cause to write some code which would take an object like</p>
<pre><code>const obj = {
a: 1,
c: {
d: 1,
e: 1
}
};
</code></pre>
<p>Which we regard as a rooted labelled tree, I then want the rooted labelled subtrees, e.g. in this example</p>
<pre><code>{ c: { e: 1, d: 1 }, a: 1 }
{ c: { e: 1, d: 1 } }
{ c: { e: 1 }, a: 1 }
{ c: { e: 1 } }
{ c: { d: 1 }, a: 1 }
{ c: { d: 1 } }
{ c: {}, a: 1 }
{ c: {} }
{ a: 1 }
{}
</code></pre>
<p>It was important to me that the function be a generator function, and that I avoid making any deep copies of the initial object.</p>
<p>So I wrote the following</p>
<pre><code>function* generateRootedSubtreesOfObject(tree) {
const children = Object.keys(tree);
if (children.length === 0) {
yield tree;
return;
}
const firstChild = children[0];
const firstSubtree = tree[firstChild];
const isLeaf =
typeof firstSubtree !== "object" || Array.isArray(firstSubtree);
delete tree[firstChild];
for (const remainingSubtree of generateRootedSubtreesOfObject(tree)) {
const elSubtrees = isLeaf
? [firstSubtree]
: generateRootedSubtreesOfObject(firstSubtree);
for (const firstChildSubtree of elSubtrees) {
remainingSubtree[firstChild] = firstChildSubtree;
yield remainingSubtree;
delete remainingSubtree[firstChild];
}
yield remainingSubtree;
}
tree[firstChild] = firstSubtree;
}
</code></pre>
<p>Which works as desired, but is extremely cryptic in my opinion. The idea is simple enough, go to the first child of the root, find the rooted subtrees with this as the root, and combine this in all the possible ways with the rooted subtrees once you detach this child. But the current implementation I think is too subtle.</p>
<p>How could this be improved?</p>
<p>Re error handling, please assume (it is true in my case) that the caller of this function will know it is appropriate to call.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:16:19.810",
"Id": "244242",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Generating rooted labelled subtrees of a JS object"
}
|
244242
|
<p><strong>Summary</strong></p>
<p>I have been playing with Rust for a couple of days, so I thought I would implement something rather simple. This code generates a random variation of board for well-known game of <a href="https://en.wikipedia.org/wiki/Battleship_(game)" rel="nofollow noreferrer">Battleship</a>. In this variation, there are one 4-cell ship, two 3-cell ships, three 2-cell ships and four 1-cell ships.</p>
<p>There's definitely a room for improvement both algorithm- and style-wise. Much appreciate the help!</p>
<pre><code>use itertools::Itertools;
use rand::rngs::SmallRng;
use rand::seq::SliceRandom;
use rand::{Rng, SeedableRng};
const FIELD_SIZE: isize = 10;
#[rustfmt::skip]
const DIRECTIONS: [(isize, isize); 9 as usize] = [(0, 0), (0, 1), (0, -1), (-1, 0), (1, 0), (-1, 1), (1, -1), (-1, -1), (1, 1)];
#[derive(Clone, PartialEq, Copy)]
enum CellType {
EMPTY,
UNAVAILABLE,
OCCUPIED,
}
struct Field {
field: [CellType; (FIELD_SIZE * FIELD_SIZE) as usize],
}
impl std::fmt::Display for Field {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Ok(for (index, element) in self.field.iter().enumerate() {
#[rustfmt::skip]
let char_repr = match element {
CellType::EMPTY => '.',
CellType::UNAVAILABLE => 'o',
CellType::OCCUPIED => 'X',
};
if index % FIELD_SIZE as usize == 0 {
writeln!(f)?;
}
write!(f, "{}", char_repr)?;
})
}
}
fn is_valid_formation(
field: &Field,
mut x: isize,
mut y: isize,
dx: isize,
dy: isize,
ship_size: usize,
) -> bool {
// I. Construct a bounding box for the placed ship.
let bounds = 0..FIELD_SIZE;
for ship_size in 0..ship_size {
let x = x + (dx * ship_size as isize);
let y = y + (dy * ship_size as isize);
// Move in every box direction.
for direction in DIRECTIONS.iter() {
// Indices cannot be negative or >= FIELD_SIZE.
if !bounds.contains(&(x + direction.0)) || !bounds.contains(&(y + direction.1)) {
continue;
}
let bounding_box_cell =
field.field[((x + direction.0) + ((y + direction.1) * FIELD_SIZE)) as usize];
// If there's a ship within a bounding box, halt the loop -- we cannot place the ship here.
if bounding_box_cell == CellType::OCCUPIED {
return false;
}
}
}
// II. Check whether the cells that are being used to place the ship onto are occupied.
for _ in 0..ship_size {
if !bounds.contains(&x) || !bounds.contains(&y) {
return false;
}
let current_cell = field.field[(y * FIELD_SIZE + x) as usize];
if let CellType::OCCUPIED | CellType::UNAVAILABLE = current_cell {
return false;
}
x += dx;
y += dy;
}
true
}
fn get_available_cells(
field: &Field,
dx: isize,
dy: isize,
ship_size: usize,
) -> Vec<(isize, isize)> {
(0..FIELD_SIZE)
.cartesian_product(0..FIELD_SIZE)
.filter(|(x, y)| is_valid_formation(&field, *x, *y, dx, dy, ship_size))
.collect()
}
fn emplace_ships(field: &mut Field, ship_size: usize, rng: &mut SmallRng) {
// Flip a coin to determine an alignment (horizontal / vertical).
let (dx, dy) = if rng.gen() { (1, 0) } else { (0, 1) };
// Get the vector of appropriate cells.
let cell_coordinates = get_available_cells(&field, dx, dy, ship_size);
let (mut x, mut y) = cell_coordinates.choose(rng).unwrap();
// Place a ship!
for _ in 0..ship_size {
field.field[(x + y * FIELD_SIZE) as usize] = CellType::OCCUPIED;
x += dx;
y += dy;
}
}
impl Field {
fn generate() -> Self {
/* Generating the field. */
let mut f = Field { field: [CellType::EMPTY; (FIELD_SIZE * FIELD_SIZE) as usize] };
let mut rng: SmallRng = SmallRng::from_entropy();
for ship_size in [4, 3, 3, 2, 2, 2, 1, 1, 1, 1].iter() {
emplace_ships(&mut f, *ship_size, &mut rng);
}
f
}
}
fn main() {
let field = Field::generate();
println!("{}", field);
}
</code></pre>
|
[] |
[
{
"body": "<p>Looks good overall! For example, good job using <code>enum</code>s, and writing helpful comments. A few additional possible improvements, implemented below:</p>\n<ul>\n<li>In the declaration for <code>DIRECTIONS</code>, you don't need to cast <code>9</code> to <code>usize</code>; it can do so implicitly.</li>\n<li>Move the code for <code>char_repr</code> to an implementation of <code>Display</code> for <code>CellType</code>.</li>\n<li>Consider making more things <code>usize</code> instead of <code>isize</code>.</li>\n<li>A few minor things suggested by <code>clippy</code>, such as using <code>for x in &[...]</code> instead of <code>for x in [...].iter()</code></li>\n<li>Comment what <code>index % FIELD_SIZE as usize == 0</code> does.</li>\n<li>Implement <a href=\"https://doc.rust-lang.org/std/ops/trait.Index.html\" rel=\"nofollow noreferrer\"><code>Index(Mut)</code></a> for <code>Field</code>.</li>\n<li>Make things methods on <code>Field</code>.</li>\n<li>Rename <code>is_valid_formation</code> to <code>can_place_ship</code>.</li>\n<li>Create a <code>Ship</code> struct that implements <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html\" rel=\"nofollow noreferrer\"><code>Iterator</code></a> or <a href=\"https://doc.rust-lang.org/std/iter/trait.IntoIterator.html\" rel=\"nofollow noreferrer\"><code>IntoIterator</code></a>.</li>\n<li>Use <code>impl Rng</code> instead of <code>SmallRng</code> for code that doesn't care what kind of RNG is used.</li>\n</ul>\n<p>Other things to consider, not implemented below:</p>\n<ul>\n<li>Unit tests</li>\n<li>Creating a <code>Coordinate</code> struct (may or may not be an improvement)</li>\n</ul>\n<p>Final code:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>#![warn(clippy::all)]\n#![warn(clippy::pedantic)]\n#![warn(clippy::nursery)]\n#![allow(clippy::cast_possible_wrap)]\n#![allow(clippy::cast_sign_loss)]\n\nuse itertools::Itertools;\nuse rand::rngs::SmallRng;\nuse rand::seq::SliceRandom;\nuse rand::{Rng, SeedableRng};\nuse std::fmt;\nuse std::ops::{Index, IndexMut};\n\nconst FIELD_SIZE: usize = 10;\n#[rustfmt::skip]\nconst DIRECTIONS: [(isize, isize); 9] = [(0, 0), (0, 1), (0, -1), (-1, 0), (1, 0), (-1, 1), (1, -1), (-1, -1), (1, 1)];\n\n#[derive(Clone, PartialEq, Copy)]\nenum CellType {\n EMPTY,\n UNAVAILABLE,\n OCCUPIED,\n}\n\nimpl fmt::Display for CellType {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n write!(\n f,\n "{}",\n match self {\n Self::EMPTY => '.',\n Self::UNAVAILABLE => 'o',\n Self::OCCUPIED => 'X',\n }\n )\n }\n}\n\n#[derive(Copy, Clone)]\nstruct ShipShape {\n dx: usize,\n dy: usize,\n size: usize,\n}\n\n#[derive(Copy, Clone)]\nstruct Ship {\n x: usize,\n y: usize,\n shape: ShipShape,\n}\n\n// If you prefer, you can use `IntoIterator` here instead.\n#[allow(clippy::copy_iterator)]\nimpl Iterator for Ship {\n type Item = (usize, usize);\n\n fn next(&mut self) -> Option<(usize, usize)> {\n if self.shape.size > 0 {\n let result = (self.x, self.y);\n self.x += self.shape.dx;\n self.y += self.shape.dy;\n self.shape.size -= 1;\n Some(result)\n } else {\n None\n }\n }\n}\n\nstruct Field {\n field: [CellType; (FIELD_SIZE * FIELD_SIZE) as usize],\n}\n\nimpl fmt::Display for Field {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n for (index, element) in self.field.iter().enumerate() {\n // Start of line\n if index % FIELD_SIZE as usize == 0 {\n writeln!(f)?;\n }\n write!(f, "{}", element)?;\n }\n Ok(())\n }\n}\n\nimpl Index<(usize, usize)> for Field {\n type Output = CellType;\n\n fn index(&self, (x, y): (usize, usize)) -> &CellType {\n &self.field[x + y * FIELD_SIZE]\n }\n}\n\nimpl IndexMut<(usize, usize)> for Field {\n fn index_mut(&mut self, (x, y): (usize, usize)) -> &mut CellType {\n &mut self.field[x + y * FIELD_SIZE]\n }\n}\n\nimpl Field {\n fn can_place_ship(&self, ship: Ship) -> bool {\n // I. Construct a bounding box for the placed ship.\n let bounds = 0..(FIELD_SIZE as isize);\n for (x, y) in ship {\n // Move in every box direction.\n for direction in &DIRECTIONS {\n // Indices cannot be negative or >= FIELD_SIZE.\n if !bounds.contains(&(x as isize + direction.0))\n || !bounds.contains(&(y as isize + direction.1))\n {\n continue;\n }\n let bounding_box_cell = self[(\n (x as isize + direction.0) as usize,\n (y as isize + direction.1) as usize,\n )];\n // If there's a ship within a bounding box, halt the loop -- we cannot place the ship here.\n if bounding_box_cell == CellType::OCCUPIED {\n return false;\n }\n }\n }\n\n // II. Check whether the cells that are being used to place the ship onto are occupied.\n let bounds = 0..FIELD_SIZE;\n for (x, y) in ship {\n if !bounds.contains(&x) || !bounds.contains(&y) {\n return false;\n }\n let current_cell = self[(x, y)];\n if let CellType::OCCUPIED | CellType::UNAVAILABLE = current_cell {\n return false;\n }\n }\n true\n }\n\n fn get_available_cells(&self, shape: ShipShape) -> Vec<(usize, usize)> {\n (0..FIELD_SIZE)\n .cartesian_product(0..FIELD_SIZE)\n .filter(|&(x, y)| self.can_place_ship(Ship { x, y, shape }))\n .collect()\n }\n\n fn emplace_ships(&mut self, size: usize, rng: &mut impl Rng) {\n // Flip a coin to determine an alignment (horizontal / vertical).\n let (dx, dy) = if rng.gen() { (1, 0) } else { (0, 1) };\n let shape = ShipShape { dx, dy, size };\n // Get the vector of appropriate cells.\n let cell_coordinates = self.get_available_cells(shape);\n let (x, y) = *cell_coordinates.choose(rng).unwrap();\n let ship = Ship { x, y, shape };\n // Place a ship!\n for (x, y) in ship {\n self[(x, y)] = CellType::OCCUPIED;\n }\n }\n\n fn generate() -> Self {\n /* Generating the field. */\n let mut result = Self {\n field: [CellType::EMPTY; FIELD_SIZE * FIELD_SIZE],\n };\n let mut rng: SmallRng = SmallRng::from_entropy();\n for ship_size in &[4, 3, 3, 2, 2, 2, 1, 1, 1, 1] {\n result.emplace_ships(*ship_size, &mut rng);\n }\n result\n }\n}\nfn main() {\n let field = Field::generate();\n println!("{}", field);\n}\n</code></pre>\n<p><sup>Playground: <a href=\"https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=da8fca6fff5803ad9fe26957c3e70afa\" rel=\"nofollow noreferrer\">https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=da8fca6fff5803ad9fe26957c3e70afa</a></sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T22:47:03.420",
"Id": "480057",
"Score": "1",
"body": "Thanks! Besides; I think there is a way to get rid of unnecessary allocations by declaring an instance of StaticVec to pass into generating function. This significantly speeds things up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T08:30:52.217",
"Id": "503902",
"Score": "0",
"body": "Hello, on-line version works great, but in the final code I changed this line to get it running, from `use rand::rngs::StdRng;` to `use rand::rngs::StdRng as SmallRng;`. Cargo v1.49.0, rand=\"0.8.3\", itertools=\"0.10.0\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-30T20:51:30.280",
"Id": "503944",
"Score": "1",
"body": "@Malipivo You can also add the `small_rng` feature, see https://docs.rs/crate/rand/0.8.3/features and https://doc.rust-lang.org/cargo/reference/features.html. IIRC, you can use `rand = { version = \"0.8.3\", features = [\"small_rng\"] }`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T16:32:11.763",
"Id": "244452",
"ParentId": "244243",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244452",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T22:33:51.063",
"Id": "244243",
"Score": "5",
"Tags": [
"game",
"rust",
"battleship"
],
"Title": "Battleship Game Field Generator"
}
|
244243
|
<p>Beginner level script for a countdown timer. Would appreciate if you could point the things I could do to be more efficient.</p>
<p>Basically, I would want to check if the current day is either a "workday"(Mon - Wed) or a "freeday"(Thur-Sun) and achieve the following:</p>
<ol>
<li><p>If it's a workday, and the current hour is a working hour (7:00:00 AM - 5:00:00 PM), then count
how many hour(s) remaining till end of the shift (5PM) base on the current time.</p>
</li>
<li><p>If it's a workday, and the current hour is outside of working hours (5:00:01 PM to 6:59:59 AM), say that it is not yet a working hour.</p>
</li>
<li><p>If it's a freeday, count till the next Monday.</p>
</li>
</ol>
<p>I wouldn't want to rely on the if statements if possible, but my understanding level for Python is at this point only. Is there a better way to do it?</p>
<p>Thank you in advance! Happy coding.</p>
<pre><code>import time, datetime
# Add the value to get the next Monday
get_future_monday = {
0: 1,
1: 2,
2: 3,
3: 4
}
def time_state():
# Check what day of the week
# 0 == Monday, 6 == Sunday
check_day = datetime.datetime.today().weekday()
# Get future Monday
future_monday = 6 - check_day
# Check current time
check_time_now = datetime.datetime.now()
# Parse current time
# Get the year, month and day
get_year = check_time_now.year
get_month = check_time_now.month
get_day = check_time_now.day
# Define timespan for each routine
working_hours = datetime.time(7, 0, 0)
after_hours_am = datetime.time(6, 59, 59)
after_hours_pm = datetime.time(17, 0, 1)
if check_day == 0 and check_time_now.time() < after_hours_am: # If Monday and current time not yet 7 AM
print("It's not time yeeeet!")
return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)
elif check_day == 2 and check_time_now.time() > after_hours_pm: # If Wednesday and current time past 5 PM
print("Time to gooooo!")
return datetime.datetime(get_year, get_month, (get_day + get_future_monday[future_monday]), 7, 0, 0)
elif check_day <= 2 and check_time_now.time() < after_hours_am: # If day in Tuesday, Wed and current time not yet 7 AM
print("Get ready to grind...")
return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)
elif check_day <= 2 and check_time_now.time() > after_hours_pm: # If day in Tuesday, Wed and current time not yet 5 PM
print("Free at last!")
return datetime.datetime(get_year, get_month, (get_day + 1), 7, 0, 0)
elif check_day <= 2 and check_time_now.time() >= working_hours and check_time_now.time() <= after_hours_pm: # If day in Mon - Wed and current time not yet 5 PM
print("Focus focus focus!!!")
return datetime.datetime(get_year, get_month, get_day, 17, 0, 0)
else:
print("Playtime foo UwU")
return datetime.datetime(get_year, get_month, (get_day + get_future_monday[future_monday]), 7, 0, 0) # Playtime
def countdown(time_state):
time_state = time_state
clock_tick = time_state - datetime.datetime.now()
days = clock_tick.total_seconds() / 86400
hours, rem = divmod(clock_tick.total_seconds(), 3600)
mins, secs = divmod(rem, 60)
print(f"{int(days):02d}:{int(hours):02d}:{int(mins):02d}:{int(secs):02d}")
time.sleep(1)
def main():
while True:
a = time_state()
countdown(a)
main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Variable names</h2>\n<p>I find the <code>get_</code> prefixes unnecessary on these:</p>\n<pre><code>get_year = check_time_now.year\nget_month = check_time_now.month\nget_day = check_time_now.day\n</code></pre>\n<p>That makes them look like functions.</p>\n<h2>Boundaries</h2>\n<p>This:</p>\n<pre><code>working_hours = datetime.time(7, 0, 0)\nafter_hours_am = datetime.time(6, 59, 59)\n</code></pre>\n<p>should probably just use 7:00 for <code>after_hours_am</code>. Otherwise, the time 6:59:59 given your current usage will still be considered working hours.</p>\n<p>Likewise, this:</p>\n<pre><code>check_time_now.time() > after_hours_pm\n</code></pre>\n<p>should use <code>>=</code>.</p>\n<p>An easy convention to follow that makes your boundary checking consistent is to always use intervals that are closed at the beginning and open at the end, i.e. 7:00 <= time < 8:00.</p>\n<h2>Redundant <code>else</code></h2>\n<p>This:</p>\n<pre><code> return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)\n\nelif ...\n</code></pre>\n<p>can use an <code>if</code> instead of an <code>elif</code> due to the previous return.</p>\n<h2>Don't repeat yourself</h2>\n<p>This return:</p>\n<pre><code> return datetime.datetime(get_year, get_month, get_day, 7, 0, 0)\n</code></pre>\n<p>shares many commonalities with the other returns in its function. Factor out a <code>new_day</code> and <code>new_hour</code> variable assignment, then at the end of your function,</p>\n<pre><code>return datetime.datetime(get_year, get_month, new_day, new_hour)\n</code></pre>\n<p>Note that 0 is the default for the remaining parameters.</p>\n<h2>Timespan division</h2>\n<p>Trying not to do your own time math, this would be one option that doesn't require knowledge of time position multiples:</p>\n<pre><code>days = clock_tick.days\nrem = clock_tick - timedelta(days=days)\nhours = rem // timedelta(hours=1)\nrem -= timedelta(hours=hours)\nmins = rem // timedelta(minutes=1)\nrem -= timedelta(minutes=mins)\nsecs = int(rem.total_seconds())\n</code></pre>\n<p>I don't like it, but built-in Python time libraries are kind of bad. Third-party libraries will reduce this to a one-liner format call. This is educational:</p>\n<p><a href=\"https://stackoverflow.com/questions/538666/format-timedelta-to-string\">https://stackoverflow.com/questions/538666/format-timedelta-to-string</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:49:19.743",
"Id": "244264",
"ParentId": "244244",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244264",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-20T23:40:52.503",
"Id": "244244",
"Score": "6",
"Tags": [
"python"
],
"Title": "Simple Countdown Timer"
}
|
244244
|
<p>I am new to Python and I am using Python 3.8 and Selenium.
This is a follow up of <a href="https://codereview.stackexchange.com/q/241940/201050">my previous question</a>. Since I received several useful suggestions I have re-written the following code.</p>
<p>The code works fine and is much better than previous version. But I wonder if I can convert my code to be Page Object based. Will this improve the speed or readability etc?<br />
I tried to achieve this with classes. Except when creating directories and selecting particular districts or complexes. The rest of the functions inside those classes remain static.</p>
<p>I don't expect any one to rewrite the code for me, but an elaboration on approach, a pointer on how refactor or any other improvements would be appreciated.<br />
<strong>Note</strong>: kindly ignore comments, <code>#</code>, they are not yet well formed.</p>
<pre><code>import base64
from typing import List
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
import time
import os
from PIL import Image
from io import BytesIO
import cv2
from pytesseract import pytesseract
from selenium.common.exceptions import NoSuchElementException, TimeoutException, ElementNotInteractableException
import logging
# set logging
logging.basicConfig(filename='/home/sangharshmanuski/EcourtsData/logging_files'
'/ecourts_log_file.log',
filemode='a',
level=logging.INFO,
format='%(asctime)s %(message)s',
datefmt='%d/%m/%Y %I:%M:%S %p')
# constants
url = r'https://districts.ecourts.gov.in/'
options = FirefoxOptions()
options.add_argument("--headless")
options.add_argument("--private-window")
driver = webdriver.Firefox(options=options)
# base dir path for downloading files:
main_Directory = r'/path to the directory/downloads6'
combo_identifier = '#sateist'
wait = WebDriverWait(driver, 180)
waitShort = WebDriverWait(driver, 3)
# FUNCTIONS
def get_states(driver) -> List[str]:
"""Get list of States/UT from combo box
Return a list of strings
"""
try:
# wait for combo box to be ready
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, combo_identifier)))
except TimeoutException:
logging.exception('list of states failed to load')
states_combo = Select(driver.find_element_by_css_selector(combo_identifier))
# return list of non-empty values from combo box
state_list = [o.get_attribute("value") for o in states_combo.options if o.get_attribute("value") != '']
logging.info('state list ready')
return state_list
def get_districts():
"""
Get list of districts form options
It returns two values.
1 is name (text from the element) of the district
2 is value (attribute value) of that district
"""
try:
# wait for page to open and banner of district court to appear.
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.region')))
except TimeoutException:
logging.exception('districts not loaded')
states_combo = Select(driver.find_element_by_css_selector(combo_identifier))
# return list of non-empty values from combo box
districts_names = [o.get_attribute(
"text") for o in states_combo.options if o.get_attribute("value") != '']
district_values = [o.get_attribute(
"value") for o in states_combo.options if o.get_attribute("value") != '']
for each_district, number in enumerate(districts_names, start=1):
logging.info(f'all the districts are:')
logging.info(f'[{number}]: {each_district}')
logging.info(f'district list ready. total districts: {len(districts_names)}.')
return districts_names, district_values
def single_district(dist_number, some_districts_names=None, some_districts_values=None):
# returns single district name and value of the district
name_dist = some_districts_names[dist_number]
value_dist = some_districts_values[dist_number]
district_option = Select(driver.find_element_by_css_selector(combo_identifier))
district_option.select_by_value(value_dist)
logging.info(f'\n \n \n new district: {name_dist} selected. It\'s number: {dist_number}')
return name_dist, value_dist
def match_heading(some_district_name=None):
heading_dist = driver.find_element_by_css_selector('.heading')
heading_dist_lower = heading_dist.text.lower()
some_district_name_lower = some_district_name.lower()
while heading_dist_lower != some_district_name_lower:
time.sleep(1)
logging.info('waiting')
else:
logging.info(f'district: {some_district_name} '
f'page loaded fully. Selecting case status by act')
return True
def case_status_by_act():
wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.accordion2:nth-child(2)'))).click()
select_case_status_by_act = wait.until(EC.element_to_be_clickable(
(By.CSS_SELECTOR,
'div.panel:nth-child(3) > ul:nth-child(1) > li:nth-child(6) > a:nth-child(1)')))
select_case_status_by_act.click()
logging.info('Case status by act selected. new tab will open')
return select_case_status_by_act
def court_complex_list():
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '#court_complex_code')))
complex_combo = Select(driver.find_element_by_css_selector('#court_complex_code'))
# return list of non-empty values from combo box
court_complex_names = [o.get_attribute("text")
for o in complex_combo.options if o.get_attribute("value") != '0']
court_complex_values = [o.get_attribute("value")
for o in complex_combo.options if o.get_attribute("value") != '0']
logging.info(f'number of court complexes available: {len(court_complex_names)}')
return court_complex_names, court_complex_values
def single_court_complex(complex_number, value_complex_list=None, name_complex_list=None):
# returns single court complex name and value of the same
complex_combo = Select(driver.find_element_by_css_selector('#court_complex_code'))
value_complex = value_complex_list[complex_number]
name_complex = name_complex_list[complex_number]
complex_combo.select_by_value(value_complex)
logging.info(f'\n {name_complex} selected. checking for records')
return name_complex
def select_act(some_name_complex=None):
"""Populates list of acts.
if the list is empty it waits for a 1 sec and tries again
after trying 10 times it closes the effort and returns"""
acts = Select(driver.find_element_by_css_selector('#actcode'))
act_list = acts.options
second = 0
while len(act_list) < 2:
if second < 10:
time.sleep(1)
second += 1
logging.info('waiting for act list to be ready...')
else:
logging.info(f"sorry no act in {some_name_complex}")
return False
else:
logging.info(f'PoA selected')
acts.select_by_value('33')
return True
def accept_alert(tab=None):
try:
waitShort.until(EC.alert_is_present())
driver.switch_to.alert.accept()
driver.switch_to.window(tab)
logging.info('alert accepted')
return True
except (NoSuchElementException, TimeoutException):
logging.exception('no alert present')
return False
def wait_msg():
try:
please_wait = driver.find_element_by_css_selector('#waitmsg')
if please_wait.is_displayed():
logging.info('please wait')
return True
else:
return False
except NoSuchElementException:
logging.exception('no wait msg was present')
return False
def wait_msg_wait():
# wait for wait msg to disappear only for 5 sec
# in case of alert wait msg remains for ever so waiting only for 5 sec is imp
sleep = 1
while wait_msg():
if sleep < 6:
time.sleep(sleep)
sleep += 1
continue
else:
break
logging.info('captcha result ready')
return
def invalid_captcha():
# if captcha is invalid it returns true.
try:
incorrect = driver.find_element_by_css_selector('#errSpan > p:nth-child(1)').text
in_valid_captcha = "Invalid Captcha"
if incorrect == in_valid_captcha:
logging.info(f'{incorrect}, try again')
return True
else:
logging.info('captcha cracked correctly')
return False
except NoSuchElementException:
logging.info('captcha cracked, but may be no records found...checking')
return False
def no_record_found(courtcomplex=None):
# checks if no record found message is displayed
try:
no_record = driver.find_element_by_css_selector('#errSpan > p:nth-child(1)').text
no_record_available = "Record Not Found"
if no_record == no_record_available:
logging.info(f'no record @ {courtcomplex} please go to next court complex')
return True
except NoSuchElementException:
logging.info('captcha cracked, record available, download now')
return False
def captcha_to_text():
# captures the captcha image
logging.info('working on captcha now...')
elem = driver.find_element_by_id("captcha_image")
loc = elem.location
size = elem.size
left = loc['x']
top = loc['y']
width = size['width']
height = size['height']
box = (int(left), int(top), int(left + width), int(top + height))
screenshot = driver.get_screenshot_as_base64()
img = Image.open(BytesIO(base64.b64decode(screenshot)))
area = img.crop(box)
full_path = r'/home/sangharshmanuski/Documents/e_courts/captcha'
area.save(os.path.join(full_path, 'file_trial.png'), 'PNG')
img = cv2.imread(os.path.join(full_path, 'file_trial.png'), 0)
ret, thresh1 = cv2.threshold(img, 111, 255, cv2.THRESH_BINARY)
cv2.imwrite(
'/home/sangharshmanuski/Documents/e_courts/editC/oneDisNoLoop.png', thresh1)
# know the text with pytesseract
captcha_text = pytesseract.image_to_string(
Image.open(
'/home/sangharshmanuski/Documents/e_courts/editC/oneDisNoLoop.png'))
logging.info(f'text of the captcha: {captcha_text}')
return captcha_text
def submit_form():
# "enters captcha text taken from crack_captcha(..) function"
captcha = driver.find_element_by_id('captcha')
captcha.send_keys(captcha_to_text())
driver.find_element_by_css_selector('input.button:nth-child(1)').click()
time.sleep(1)
logging.info('form submitted')
def download(some_district=None, some_complex=None):
logging.info(f'okay, downloading record for {some_complex} in {some_district}')
WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a.someclass')))
list_all_view = driver.find_elements_by_css_selector(
'a.someclass')
logging.info(f'total number of records: {len(list_all_view)}')
record = 0
for view in list_all_view:
logging.info(f'downloading {list_all_view.index(view)} record')
view.click()
wait.until(EC.presence_of_element_located((By.ID, 'back_top')))
open_file = open(
os.path.join(main_Directory, some_district,
some_complex, "file_" + str(record) + ".html"), "w")
open_file.write(driver.page_source)
open_file.close()
back = driver.find_element_by_id('back_top')
back.click()
record += 1
logging.info(f'{some_complex} in {some_district} downloaded')
def dist_dir(some_district_name=None):
district_directory = os.path.join(
main_Directory, some_district_name) # create new
if not os.path.exists(district_directory): # if not directory exists, create one
os.mkdir(district_directory)
logging.info(f'directory for {some_district_name} created')
else:
logging.info(f'directory for {some_district_name} was already there')
pass
return district_directory
def court_complex_dir(district_directory=None, name_complex=None):
# makes separate directory particular court complex
court_complex_directory = os.path.join(
main_Directory, district_directory, name_complex) # create new
if not os.path.exists(court_complex_directory): # if not directory exists, create one
os.mkdir(court_complex_directory)
logging.info(f'directory for {name_complex} in '
f'{district_directory} created')
else:
logging.info(f'directory for {name_complex} in '
f'{district_directory} was already there')
pass
return court_complex_directory
# MAIN CODE
# load the main page
driver.get(url)
print('working in progress. see the log file')
# Step 1 - select a state from list of states
# fixed selection from list. As only Maharashtra is covered now.
state_option = Select(driver.find_element_by_css_selector(combo_identifier))
state = state_option.select_by_value('maharashtra')
list_districts_names, list_districts_values = get_districts()
# Step 2 - district object created
for x in list_districts_names:
logging.info(f'district loop started. iteration: '
f'{list_districts_names.index(x)}')
# step 2.1- select single district
this_district, this_value = single_district(list_districts_names.index(x),
list_districts_names,
list_districts_values)
dist_dir(this_district)
match_heading(this_district)
# step 2.3.a create variable for window handle
current = driver.window_handles[0]
# step 2.4 - a. select case status by act and b. switch to new window
case_status_by_act()
wait.until(EC.number_of_windows_to_be(2))
# define new tab by differentiating from current tab.
newWindow = [window for window in driver.window_handles if window != current][0]
# 2.4.a
# switch to the new tab. ref:
# https://stackoverflow.com/questions/41571217
# /python-3-5-selenium-how-to-handle-a-new-window-and-wait-until-it-is-fully-lo
driver.switch_to.window(newWindow)
# 2.4.b new object from Formfilling(districtCourt)
this_name_complex_list, this_value_complex_list = court_complex_list()
# 2.4.c loop over all complexes
for i in this_name_complex_list:
logging.info(f'\n iterating each complex. currently at no.: {this_name_complex_list.index(i)}')
# 2.4.1.1 select court complex
this_name_complex = single_court_complex(this_name_complex_list.index(i),
this_value_complex_list,
this_name_complex_list)
# 2.4.1.2 select act.
# If the acts are not available go to the next court complex
# or if option for particular act is not present go to next court complex
if not select_act(this_name_complex):
driver.find_element_by_css_selector('input.button:nth-child(2)').click()
single_court_complex(this_name_complex_list.index(i),
this_value_complex_list,
this_name_complex_list)
if not select_act(this_name_complex):
continue
while True:
submit_form()
if accept_alert(newWindow):
driver.find_element_by_css_selector('#captcha_container_2 '
'> div:nth-child(1) > div:nth-child(1) '
'> span:nth-child(3) > a:nth-child(7) '
'> img:nth-child(1)').click()
time.sleep(1)
logging.info('captcha image refreshed')
continue
if not invalid_captcha():
break
else:
continue
# 2.4.5 if no record found go the next court complex
if no_record_found(this_name_complex):
continue # skip rest of the code and continue the for loop from start.
else:
# 2.4.6 make new directory
court_complex_dir(this_district, this_name_complex)
# 2.4.7 download all the records
try:
download(this_district, this_name_complex)
except (TimeoutException, NoSuchElementException, ElementNotInteractableException):
driver.refresh()
logging.exception(f'exception was present. Recheck {this_name_complex} again.')
logging.info(f'skipping {this_name_complex} for now')
continue
logging.info(f'all court complexes in {this_district} completed')
print(f'all court complexes in {this_district} completed')
driver.close()
driver.switch_to.window(current)
logging.info('all districts in maharashtra completed')
# 2.4.8 close the form page
driver.close()
# 2.5 all districts completed print statement and go to state-option page.
driver.back()
</code></pre>
<p>Thank you.</p>
|
[] |
[
{
"body": "<h2>Log paths</h2>\n<p>It is not a good idea to hard-code this:</p>\n<pre><code>logging.basicConfig(filename='/home/sangharshmanuski/EcourtsData/logging_files'\n '/ecourts_log_file.log',\n</code></pre>\n<p>Probably use <code>pathlib.Path.home()</code> to replace that hard-coded prefix. Also, the usual thing to do for posix filesystems like that is <code>~/.EcourtsData</code> - most home-local data directories are dotted.</p>\n<h2>Capitalized constants</h2>\n<pre><code>url = r'https://districts.ecourts.gov.in/'\n</code></pre>\n<p>should be</p>\n<pre><code>URL = r'https://districts.ecourts.gov.in/'\n</code></pre>\n<h2>Incomplete type hints</h2>\n<p>What is <code>driver</code>, here?</p>\n<pre><code>def get_states(driver) -> List[str]:\n</code></pre>\n<p>You have a type hint for the return value but not the parameter.</p>\n<h2>Odd string format</h2>\n<p>This:</p>\n<pre><code>f'\\n \\n \\n new district: {name_dist} selected. It\\'s number: {dist_number}'\n</code></pre>\n<p>First of all, the spaces between the newlines should not be there. Second, you can avoid needing to escape that single quote by using double quotes for the string. Third, I don't think the single quote should be there at all; it looks like a grammar mistake.</p>\n<h2>OCR on a captcha</h2>\n<p>This is a deeply bad idea. First, if someone has a captcha on their site, it means they specifically don't want you scraping it, so this entire program is likely in bad faith. Beyond that, it's fragile and unlikely to consistently work.</p>\n<h2>Selenium</h2>\n<p>Selenium is a last resort when a website is doing something so horribly complicated in JS that the only way to interact with it is to fake mouse clicks. In this case, thankfully, your website really isn't that complicated. It copies the <code>value</code> attribute of that <code>option</code> to the URL. You should be hitting the website directly with Requests; this should get you started:</p>\n<pre><code>from dataclasses import dataclass\nfrom typing import Iterable\n\nfrom requests import Session\nfrom bs4 import BeautifulSoup\n\nBASE = 'https://districts.ecourts.gov.in/'\nSTATE = 'maharashtra'\n\n\ndef doc_for_path(sess: Session, path: str) -> BeautifulSoup:\n with sess.get(BASE + path) as resp:\n resp.raise_for_status()\n return BeautifulSoup(resp.text, 'html.parser')\n\n\n@dataclass\nclass District:\n key: str\n name: str\n act_link: str = None\n\n def fill_act_link(self, sess: Session):\n doc = doc_for_path(sess, self.key)\n anchor = next(\n a\n for a in doc.select('div.panel a')\n if a.text == 'Act'\n )\n self.act_link = anchor['href']\n\n def __str__(self):\n return self.name\n\n\ndef get_districts(sess: Session) -> Iterable[District]:\n doc = doc_for_path(sess, STATE)\n return (\n District(opt['value'], opt.text)\n for opt in doc.select('#sateist > option')\n if opt['value']\n )\n\n\ndef main():\n with Session() as sess:\n districts = tuple(get_districts(sess))\n for i, district in enumerate(districts, 1):\n print(f'Getting act link for {district}, {i}/{len(districts)}...', end='\\r')\n district.fill_act_link(sess)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T04:07:26.290",
"Id": "479516",
"Score": "0",
"body": "Edited to show that requests should be used instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T19:02:50.527",
"Id": "479573",
"Score": "0",
"body": "Good advice overall. The only point that I'd like to raise here is the usage of `sess` instead of the whole word: `session` or `session_` if it shadows any builtin that I'm unware of ^^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T19:03:37.003",
"Id": "479574",
"Score": "0",
"body": "It doesn't shadow anything; it's just a short form. `session` would be fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T18:23:23.580",
"Id": "479686",
"Score": "0",
"body": "Thank you very much @Reinderien . Agree with you on captcha. The \"bs4\" part is fantastic. But, little extra for me. Can't digest it, even after breaking my head at it for hours. I tried to understand what and how the code is working... decoded it to some extent but then, not sure how to use it finally....my head is blowing! :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T02:50:06.243",
"Id": "244247",
"ParentId": "244245",
"Score": "4"
}
},
{
"body": "<p>In <code>captcha_to_text</code>:</p>\n<pre><code>full_path = r'/home/sangharshmanuski/Documents/e_courts/captcha'\n</code></pre>\n<p>Use a <strong><a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">temp file</a></strong> instead, if it's going to be discarded anyway (unless you want to investigate failures later).</p>\n<hr />\n<p>In that same procedure and in other parts of your code you have multiple references to <code>/home/sangharshmanuski</code>. Define a global variable instead.</p>\n<p>But you have a global variable already: <code>main_Directory = r'/path to the directory/downloads6'</code>, which is completely different. You are mixing disparate paths so I would suggest more consistency here.</p>\n<hr />\n<p>Function <code>get_states</code> does not seem to be used. I think you kept it as an example. Remove unused portions of the code, declutter as much as possible.</p>\n<hr />\n<p>Some <strong>logging</strong> messages should be <strong>debug</strong> level I think. When the application is mature enough, you'll probably want less verbosity and decrease the reporting level. So for dumping variables or application state etc use <code>logging.debug</code> instead of <code>logging.info</code>.</p>\n<p>Since you are now using the logging module and this is a good thing, you can add more traces to better follow execution of your program. I would perhaps add a <code>logger.debug</code> line in each function so that you can track progress of your code and you can also verify that functions are not called multiple times or out of loop. Tracing execution is important.</p>\n<hr />\n<p>Some functions I still find a bit perplexing:\n<code>wait_msg_wait</code>: instead of doing <code>time.sleep</code> in a loop why not use Selenium functions eg:\n<code>WebDriverWait(driver, 10).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '#theselector')))</code> if you are waiting for an element to disappear. Since you are using Selenium you have a lot of choice between implicit and explicit wait functions.</p>\n<p>Seems to me that <code>wait_msg_wait</code> and <code>wait_msg</code> can be combined into one single function.</p>\n<hr />\n<p>Scope: <code>variable combo_identifier = '#sateist'</code> is defined on top of the code. But if it's used in only one function, move it to that function to keep scope as limited as possible and avoid distraction.</p>\n<hr />\n<p>Some functions are little or not commented\nExample: <code>dist_dir</code>, <code>download</code></p>\n<p>In <code>download</code>:</p>\n<pre><code>os.path.join(main_Directory, some_district,\n some_complex, "file_" + str(record) + ".html"), "w")\n</code></pre>\n<p>You can use an F-string to avoid concatenation.</p>\n<hr />\n<p>Since the project is not easy breaking up the code in small functions makes it more manageable. But I think this approach could have been pushed further. The main section remains very procedural and not that easy to follow.\nFor example, if I pick on line at random:</p>\n<pre><code>match_heading(this_district)\n</code></pre>\n<p>It's not immediately clear what this line does. For an outsider, more detailed comments would be welcome.</p>\n<p>I would now try to split the main section in small functions as well like:</p>\n<ul>\n<li>load_home_page()</li>\n<li>break_captcha()</li>\n<li>dismiss_alert()</li>\n<li>get_states()</li>\n<li>download_court_records()</li>\n<li>go_back()</li>\n</ul>\n<p>etc. The idea is to clearly identify the tasks involved, and better separate them.</p>\n<hr />\n<p>Since there is a lot of code you could create a module to keep your functions in a separate file, then you import the module. Thus your main routine will be small and more manageable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:36:57.143",
"Id": "244274",
"ParentId": "244245",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T01:54:27.097",
"Id": "244245",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"selenium"
],
"Title": "Crawling a court website and downloading records"
}
|
244245
|
<p>The following data structure is meant for manipulating algebraic/mathematical sets.</p>
<p>I want <code>Set<T></code> to be compatible and interchangeable with any similar data structure available in .NET. I didn't use <code>HashSet<T></code> because I don't like the fact that <code>HashSet<T></code> is unordered.</p>
<p>Kindly review it for design and efficiency.</p>
<p>What is your comment on the inheritance hierarchy? Do you think <code>ISet<T></code> and <code>Set<T></code> inherited or implemented proper interfaces?</p>
<hr />
<p>Source code:</p>
<pre><code>public interface ISet<T>: ICloneable, IEnumerable<T>, IList<T>
{
IEnumerable<T> Union(IEnumerable<T> set2);
IEnumerable<T> Difference(IEnumerable<T> set2);
IEnumerable<T> Intersection(IEnumerable<T> set2);
IEnumerable<T> Complement(IEnumerable<T> universalSet);
bool Disjoint(IEnumerable<T> set2);
void AddRange(IEnumerable<T> set);
IEnumerable<T> ToEnumerable();
}
public class Set<T> : ISet<T>, ICloneable, IEnumerable<T>, IList<T>, IList, ICollection, IEnumerable
{
private List<T> m_ListContainer = null;
public Set()
{
m_ListContainer = new List<T>();
}
public Set(IEnumerable<T> collection)
{
m_ListContainer = new List<T>(collection);
}
#region IList<T> implementations
public T this[int index]
{
get
{
return m_ListContainer[index];
}
set
{
m_ListContainer[index] = value;
}
}
object IList.this[int index]
{
get
{
return m_ListContainer[index];
}
set
{
m_ListContainer[index] = (T)value;
}
}
public int Count
{
get
{
return m_ListContainer.Count;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void Add(T item)
{
m_ListContainer.Add(item);
}
public void Clear()
{
m_ListContainer.Clear();
}
public bool Contains(T item)
{
return m_ListContainer.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
m_ListContainer.CopyTo(array, arrayIndex);
}
public IEnumerator<T> GetEnumerator()
{
return m_ListContainer.GetEnumerator();
}
public int IndexOf(T item)
{
return m_ListContainer.IndexOf(item);
}
public void Insert(int index, T item)
{
m_ListContainer.Insert(index, item);
}
public bool Remove(T item)
{
return m_ListContainer.Remove(item);
}
public void RemoveAt(int index)
{
m_ListContainer.RemoveAt(index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return m_ListContainer.GetEnumerator();
}
#endregion
/// <summary>
/// complement the current list on the basis of universalset
/// </summary>
/// <param name="universalSet"></param>
public IEnumerable<T> Complement(IEnumerable<T> universalSet)
{
// create a copy of the universalSet
List<T> list = new List<T>(universalSet);
foreach (T item in m_ListContainer)
{
list.Remove(item);
}
return list;
}
/// <summary>
/// return [this - set2]
/// </summary>
/// <param name="set2"></param>
/// <returns></returns>
public IEnumerable<T> Difference(IEnumerable<T> set2)
{
List<T> newSet = new List<T>(m_ListContainer.ToArray());
foreach (T item in m_ListContainer)
{
if (((ISet<T>) set2).Contains(item))
{
newSet.Remove(item);
}
}
return newSet;
}
/// <summary>
/// Two sets A and B are mutually exclusive or disjoint if they
/// do not have any shared elements; i.e., their intersection is
/// the empty set, A∩B=∅.
/// </summary>
/// <param name="set1"></param>
/// <param name="set2"></param>
/// <returns></returns>
public bool Disjoint(IEnumerable<T> set2)
{
foreach (T item in m_ListContainer)
{
if (((ISet<T>)set2).Contains(item))
{
return false;
}
}
return true;
}
/// <summary>
/// The intersection of two sets A and B, denoted by A∩B, consists of all elements
/// that are both in A and B. For example, {1,2}∩{2,3}={2}.
/// </summary>
/// <param name="set1"></param>
/// <param name="set2"></param>
/// <returns></returns>
public IEnumerable<T> Intersection(IEnumerable<T> set2)
{
List<T> newSet = new List<T>(m_ListContainer.ToArray());
foreach (T item in m_ListContainer)
{
if(!((ISet<T>) set2).Contains(item))
{
newSet.Remove(item);
}
}
return newSet;
}
/// <summary>
/// return Union [this, set2]
/// </summary>
/// <param name="set2"></param>
/// <returns></returns>
public IEnumerable<T> Union(IEnumerable<T> set2)
{
IEnumerable<T> unionList = m_ListContainer.ToArray();//clone the currect data
List<T> list = new List<T>(unionList);
list.AddRange(set2);
return list.ToArray();
}
/// <summary>
/// Implementing IClonable.
/// </summary>
/// <returns></returns>
public object Clone()
{
T [] objects = new T[m_ListContainer.Count];
int i = 0;
foreach (T item in m_ListContainer)
{
objects[i] = item;
i++;
}
return objects;
}
public void AddRange(IEnumerable<T> set)
{
m_ListContainer.AddRange(set);
}
public IEnumerable<T> ToEnumerable()
{
return m_ListContainer.ToArray();
}
public void Show()
{
foreach (var item in m_ListContainer)
{
Console.Write(item + ", ");
}
Console.ReadLine();
}
public int Add(object value)
{
this.Add((T)value);
return m_ListContainer.Count - 1;
}
public bool Contains(object value)
{
T item = (T)value;
return this.Contains(item);
}
public int IndexOf(object value)
{
T item = (T)value;
return this.IndexOf(item);
}
public void Insert(int index, object value)
{
T item = (T)value;
this.Insert(index, item);
}
public void Remove(object value)
{
T item = (T)value;
this.Remove(item);
}
public void CopyTo(Array array, int index)
{
T[] arr = (T[])array.Clone();
this.CopyTo(arr, index);
}
public bool IsFixedSize
{
get
{
return false;
}
}
private Object _syncRoot;
public object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
public bool IsSynchronized
{
get
{
return true;
}
}
}
</code></pre>
<p><strong>Note:</strong> Each element must be unique. I missed that in my implementation.</p>
<p><strong>Edit:</strong> replace <code>Add()</code> with the following to add the missing "unique" functionality:</p>
<pre><code>public void Add(T item)
{
if(!m_ListContainer.Contains(item))
{
m_ListContainer.Add(item);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T10:00:29.953",
"Id": "479523",
"Score": "0",
"body": "I am confused. Do you want to allow duplicate elements in your collection? Use a `List<T>`. If you don't want duplicate elements: firstly, your collection doesn't do that; but secondly, why not use a `HashSet<T>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T12:55:04.603",
"Id": "479541",
"Score": "0",
"body": "But please clarify -- is this collection allowed to have unique (either by value equality, or at least by reference equality) values, or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T21:36:54.520",
"Id": "479590",
"Score": "0",
"body": "_I missed that in my implementation_ I don't know if it's possible to review for efficiency without an implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T22:43:36.657",
"Id": "479598",
"Score": "0",
"body": "@ZevSpitz, done. check `public void Add(T item)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T22:51:06.120",
"Id": "479599",
"Score": "2",
"body": "Please don't change your code after the question has been answered. The code needs to stay the same for all readers and reviewers after an answer has been posted. See [What should I do after someone answers](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<h2>Wrap <code>ISet<T></code> in a namespace to avoid conflicts</h2>\n<p>I presume you're already doing this, but there already exists an incompatible <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.iset-1\" rel=\"nofollow noreferrer\"><code>ISet<T></code></a>; you should wrap your interface with a namespace to avoid a collision.</p>\n<h2>Replace your internal <code>List<T></code> with a <code>HashSet<T></code></h2>\n<p>You noted in the comments that elements should be unique; a trivial way to do this would be for your internal container to be a <code>HashSet<T></code> instead of <code>List<T></code>, which would enforce uniqueness.</p>\n<p>But this causes another issue.</p>\n<h2>Using a <code>HashSet<T></code> renders the indexers meaningless</h2>\n<p>With a <code>HashSet<T></code>, there is no guaranteed order, and you cannot set an item at a particular index; I believe this is intentional, as the order of elements within the <code>HashSet<T></code> is arbitrary. In that case, the getter index is also meaningless.</p>\n<p>A <code>SortedIndex<T></code> maintains the sort order even while elements are added and removed, but it still doesn't make sense to place an item at a particular index, because the <code>SortedSet<T></code> will in any case reorder as needed; and thus also not to read an element from a particular index.</p>\n<h2>Consider removing overloads that take <code>object</code> only to cast to <code>T</code> and pass to other overloads</h2>\n<p>If the object is of <code>T</code>, the <code>T</code>-accepting overload will be called and succeed.</p>\n<p>If the object is not of <code>T</code>, an exception will be thrown on the cast. I feel this is out of the responsibility of the collection class.</p>\n<p>And if the only point of these overloads is to implement the non-generic <code>IList</code> and <code>ICollection</code>, perhaps you don't need to implement these interfaces. I don't think <code>IList</code> and <code>ICollection</code> add much over <code>IList<object></code> and <code>ICollection<object></code>.</p>\n<h2>Implement <code>Show</code> as an extension method on <code>IEnumerable</code></h2>\n<p>Better yet, implement a <code>Joined</code> extension method <a href=\"https://github.com/zspitz/ZSpitz.Util/blob/master/ZSpitz.Util/Extensions/IEnumerableT.cs#L31\" rel=\"nofollow noreferrer\">like this</a>. That way you have an extension method that you could use for any <code>IEnumerable<T></code>, and use the resultant produced <code>string</code> in other contexts as well.</p>\n<h2><code>IClonable</code> is deprecated</h2>\n<p>There are a number of issues with implementing <code>IClonable<T></code>:</p>\n<ol>\n<li>It's not clear <a href=\"https://stackoverflow.com/a/536357/111794\">whether a deep or shallow copy is being made</a></li>\n<li>What is supposed to happen if the base class implements <code>IClonable<T></code>? How does that relate to the derived class? <a href=\"https://stackoverflow.com/a/536362/111794\">link</a></li>\n</ol>\n<p>From the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.icloneable?view=netcore-3.1#notes-to-implementers\" rel=\"nofollow noreferrer\">docs</a>:</p>\n<blockquote>\n<p>The ICloneable interface simply requires that your implementation of the Clone() method return a copy of the current object instance. It does not specify whether the cloning operation performs a deep copy, a shallow copy, or something in between. Nor does it require all property values of the original instance to be copied to the new instance. For example, the Clone() method performs a shallow copy of all properties except the IsReadOnly property; it always sets this property value to false in the cloned object. Because callers of Clone() cannot depend on the method performing a predictable cloning operation, we recommend that ICloneable not be implemented in public APIs.</p>\n</blockquote>\n<h2>Use method-bodied members</h2>\n<p>This will make your class definition much easier to read and parse. Readonly properties can be written like this:</p>\n<pre><code> public int Count => m_ListContainer.Count;\n</code></pre>\n<p>while your indexers (and read/write properties) can be written like this:</p>\n<pre><code>public T this[int index] {\n get => m_ListContainer[index];\n set => m_ListContainer[index] = value;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:43:08.933",
"Id": "479562",
"Score": "0",
"body": "What is your comment on the inheritance hierarchy? Do you think `ISet<T>` and `Set<T>` inherited or implemented proper interfaces?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:44:57.817",
"Id": "479564",
"Score": "0",
"body": "Secondly, Why must I use `HashSet<T>` when I can just add a filter in the `Add()` method to check to see if the element is already there? Or, why not use `Dictionary<TKey, TVal>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:50:37.567",
"Id": "479566",
"Score": "0",
"body": "@user366312 RE: filter in `Add` -- Let's turn the question around. What do you think `HashSet<T>.Add` does, if not precisely that? So what do you gain by reinventing the wheel? And `Dictionary<TKey, TVal>` is indeed unique in its' keys; presumably you would use the dictionary keys as the elements of your collection; but how is that any better than `HashSet<T>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:52:29.253",
"Id": "479567",
"Score": "0",
"body": "@user366312 RE: inheritance hierarchy -- You may have a valid use case for implementing all these interfaces, but I wouldn't implement them until I had a specific use case for them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:54:33.370",
"Id": "479568",
"Score": "0",
"body": "*You may have a valid use case for implementing all these interfaces* --- I want Set to be compatible and interchangeable with any similar data structure available in .NET."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:55:20.240",
"Id": "479569",
"Score": "0",
"body": "*So what do you gain by reinventing the wheel?* --- I don't like the fact that `HasgSet<T>` is unordered."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:25:02.683",
"Id": "244271",
"ParentId": "244246",
"Score": "3"
}
},
{
"body": "<h1>The data structure</h1>\n<p><code>List<T></code> is great most of the time. What it is not great at, is this:</p>\n<blockquote>\n<pre><code>public bool Contains(T item)\n{\n return m_ListContainer.Contains(item);\n}\n</code></pre>\n</blockquote>\n<p>Which unfortunately is an important operation for a set.</p>\n<p>There are different ways to set up a set that maintains insertion order that have different trade offs. For example:</p>\n<ul>\n<li>A hash set (for <code>contains</code> queries, and to avoid inserting duplicates) plus a <code>List<T></code> (just to remember the insertion order). Removing an item still requires searching in/removing from the list, so remove stays linear time. Adding items and indexing are constant time. Iterating over the data in insertion order is fast. <code>IndexOf</code> stays slow.</li>\n<li>The <code>LinkedHashSet</code>: it's based on a hash set, but every item also acts as node in a doubly-linked list which remembers the insertion order. Using a doubly-linked list here enables constant time removal of arbitary items. However, indexing takes linear time this way, and maybe shouldn't even be offered. An iterator that yields the items in insertion order can certainly be offered. <code>IndexOf</code> stays slow.</li>\n<li>A <code>Dictionary<T, int></code>, where the <code>int</code> indicates the current index of the corresponding key. Good for <code>Add</code> and <code>Contains</code> and even <code>IndexOf</code>, but <code>Remove</code> has to decrement the indexes of all the items that come after the removed item, indexing is slow, and even iterating in the proper order is slow.</li>\n<li>A <code>Dictionary<T, int></code> plus an other <code>Dictionary<int, T></code> (or list), based on the previous data structure, but also with a "reverse dictionary". <code>Add</code>, <code>Contains</code> and <code>IndexOf</code> stay fast, <code>Remove</code> stays slow (gets slower practically, now there are two dictionaries to fix up), but now indexing and iterating in order become efficient (at a significant cost in size).</li>\n</ul>\n<h1>Set operations, algorithm</h1>\n<p>Starting off with a copy and then conditionally removing from it works, but since the items are being removed from a <code>List<T></code>, that's a O(n m) algorithm (for sets of sizes n and m). One there is a set implementation that has a constant time <code>Contains</code>, the quadratic time is avoidable by switching the logic around to: start with an empty list/set, add an item if it should be in the result.</p>\n<h1>Set operations, interface</h1>\n<p>The set operations take an <code>IEnumerable<T></code> and then sometimes cast it with <code>((ISet<T>)set2)</code>. That's not nice, you can pass something to those methods that isn't an <code>ISet<T></code>, reasonably expect it to work, and then it fails at runtime.</p>\n<p>There are two good solutions, either make it work without the cast, or change the type of parameter so the cast is unnecessary. For example <code>Disjoint</code> could easily work by iterating over the <code>IEnumerable<T></code> and calling <code>Contains</code> on <code>this</code>, then it doesn't matter whether the second set is an <code>ISet<T></code> or maybe just a <code>T[]</code>.</p>\n<p>Returning <code>IEnumerable<T></code> is strange because it limits how the operations can be "chained". For example that makes it impossible to do <code>a.Complement(b).Union(b.Complement(a))</code>, which would be a way to implement the symmetric difference, which the <code>ISet<T></code> interface does not offer.</p>\n<h1>Redundant <code>ToArray</code></h1>\n<blockquote>\n<pre><code>new List<T>(m_ListContainer.ToArray())\n</code></pre>\n</blockquote>\n<p>There is no need for <code>ToArray</code>, a copy of the list is made either way but that temporary array does not need to exist.</p>\n<blockquote>\n<pre><code>public IEnumerable<T> Union(IEnumerable<T> set2)\n{\n IEnumerable<T> unionList = m_ListContainer.ToArray();\n List<T> list = new List<T>(unionList);\n list.AddRange(set2);\n return list.ToArray();\n}\n</code></pre>\n</blockquote>\n<p>Neither of these <code>ToArray</code> calls are necessary. <code>new List<T>(m_ListContainer)</code> would do the trick, and the resulting <code>list</code> itself can be returned.</p>\n<p>Interestingly, <code>Clone()</code> could have been implemented equivalently with <code>ToArray</code>, though it is unexpected that <code>Clone</code> returns something so different than the cloned-from object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T01:41:46.110",
"Id": "244298",
"ParentId": "244246",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244298",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T02:14:42.760",
"Id": "244246",
"Score": "4",
"Tags": [
"c#",
"set"
],
"Title": "Set<T> data structure in C#"
}
|
244246
|
<p>In my project, so this controller is working perfectly, my objective is to read the log file from the server which is created on daily basis, so I have to read the log file which is heavier in size around maybe 2GB, so my question is that please review the below code and advise my is my code is smart enough to read such heavy log file, or should I need to do some modifications in it to read such file in chunks and also look if any modifications I need to introduce into from performance point of view or exceptional handling point of view and from REST practices point of view</p>
<pre><code>@GetMapping("/download")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Resource> download(@RequestParam String filename) {
File file = new File(serverLocation + File.separator + filename + EXTENSION);
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename + EXTENSION);
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");
Path path = get(file.getAbsolutePath());
Resource resource = null;
try {
resource = new InputStreamResource(Files.newInputStream(path));
} catch (IOException e) {
LOGGER.error(String.format("Exception occurred while reading the log file%s", e));
}
return ResponseEntity.ok()
.headers(header) .contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(resource);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T12:48:59.387",
"Id": "479539",
"Score": "0",
"body": "Please scratch the word \"review\" from the title of your question, to make it follow [this site's standards](/help/how-to-ask)."
}
] |
[
{
"body": "<p>In my opinion, there are two ways with Spring to do that; your way is one of them (using the Spring Resource), and the other is to inject the file bytes directly in the <code>javax.servlet.http.HttpServletResponse</code>.</p>\n<p>Your version can be improved, since you can use the <a href=\"https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/FileSystemResource.html\" rel=\"nofollow noreferrer\"><code>FileSystemResource</code></a> instead of the <a href=\"https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/InputStreamResource.html\" rel=\"nofollow noreferrer\"><code>InputStreamResource</code></a>.</p>\n<p>The <a href=\"https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/InputStreamResource.html\" rel=\"nofollow noreferrer\"><code>InputStreamResource</code></a> is good when there are no other options available, as stated in the Java documentation since there are lots of other implementations to use.</p>\n<pre><code>Should only be used if no specific Resource implementation is applicable[...]\n</code></pre>\n<p>The <a href=\"https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/FileSystemResource.html\" rel=\"nofollow noreferrer\"><code>FileSystemResource</code></a> will remove the need to open the file and make the code shorter.</p>\n<pre class=\"lang-java prettyprint-override\"><code>HttpHeaders header = new HttpHeaders();\nheader.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename + EXTENSION);\nheader.add("Cache-Control", "no-cache, no-store, must-revalidate");\nheader.add("Pragma", "no-cache");\nheader.add("Expires", "0");\n\nFile file = new File(serverLocation + File.separator + filename + EXTENSION);\nResource resource = new FileSystemResource(file);\n\nreturn ResponseEntity.ok()\n.headers(header)\n.contentLength(file.length())\n.contentType(MediaType.parseMediaType("application/octet-stream"))\n.body(resource);\n\n</code></pre>\n<p>The thing that concerns me with your code, is the potential <a href=\"https://owasp.org/www-community/attacks/Path_Traversal\" rel=\"nofollow noreferrer\">Path Traversal</a> vulnerability that you have when reading the file, from the parameter. If I pass the <code>filename</code> value of <code>..\\..\\..\\system.log</code>, this could potentially be a problem, because we could download file out of the scope of your application.</p>\n<pre class=\"lang-java prettyprint-override\"><code>File file = new File(serverLocation + File.separator + filename + EXTENSION);\n</code></pre>\n<p>One way to prevent that is to compare the base path / location of the file with the <code>serverLocation</code>, if the <a href=\"https://portswigger.net/web-security/file-path-traversal\" rel=\"nofollow noreferrer\">path is different</a>, you ignore the request.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T12:40:34.603",
"Id": "244258",
"ParentId": "244249",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T06:56:53.863",
"Id": "244249",
"Score": "2",
"Tags": [
"java",
"api",
"rest",
"spring"
],
"Title": "Reviewing the file download controller in spring rest"
}
|
244249
|
<p>This program displays a list of TV characters. You can kill them off by random or bring them back by name. I have used the <code>random.choice</code> function. I've defined a couple of functions so that the <code>while loop</code> looks a little more clean. In two of the functions, <code>bring_back</code> and <code>check_decision</code>, we assign True to <code>invalid_input</code> if user input is invalid, like a flag.
This program is for learning purposes.</p>
<pre><code>from random import choice
tv_characters = [
'john', 'henry', 'maria', 'jason',
'max', 'lara', 'gilbert', 'paris'
]
killed_tv_characters = []
valid_decision_input = ['kill off', 'bring back']
start_prompt = "Would you like to start (yes/no)?"
decision_prompt = "\nWould you like to bring back a character you killed?"
decision_prompt += "\nOr would you like to kill off another character?"
decision_prompt += "\nEnter 'kill off' or 'bring back' ->"
character_from_dead_prompt = "\nPlease enter the name of character you would like to bring back: "
confirm_kill_prompt = "\nEnter 'kill off' to kill your first character: "
def kill_tv_characters():
"""Kills a random tv character and displays the name on the screen."""
if tv_characters:
killed_tv_character = choice(tv_characters)
tv_characters.remove(killed_tv_character)
print(f"You have killed off {killed_tv_character.title()}")
killed_tv_characters.append(killed_tv_character)
else:
print("You have killed off all the characters!")
def bring_back(name):
"""Brings back a dead character."""
name = name.lower().strip()
if name in killed_tv_characters:
killed_tv_characters.remove(name)
tv_characters.append(name)
print(f"\nYou have brought {name.title()} back to life!")
elif name in tv_characters:
print(f"{name} isn't dead!")
invalid_input = True
else:
print(f"{name} isn't a character!")
invalid_input = True
def check_decision(user_input):
"""Checks user input for decision."""
if user_input in valid_decision_input and user_input == 'kill off':
return user_input
elif user_input in valid_decision_input and user_input == 'bring back':
return user_input
else:
invalid_input == True
print("Please enter a valid input!")
print("\nYou can kill off characters randomly and add them back my name!")
start = input(start_prompt)
if start == 'yes':
start = True
else:
start = False
while tv_characters and start:
invalid_input = None
print("\nThese are the living TV characters:")
for tv_character in tv_characters:
print(tv_character.title())
if killed_tv_characters:
user_decision = input(decision_prompt)
decision = check_decision(user_decision)
if invalid_input:
continue
if decision == 'kill off':
kill_tv_characters()
if decision == 'bring back':
character_from_dead = input(character_from_dead_prompt)
bring_back(character_from_dead)
if invalid_input:
continue
else:
confirm_kill = input(confirm_kill_prompt)
if confirm_kill != 'kill off':
print("You have entered an invalid input.")
continue
kill_tv_characters()
if tv_characters == False:
print("You have killed off all the characters.")
print("Thanks for playing!")
else:
print("Goodbye")
</code></pre>
|
[] |
[
{
"body": "<h2>User interface decisions</h2>\n<p>Having a <code>start</code> option is an odd choice. If the user started the program itself, is it likely that they don't want to start the rest of its logic?</p>\n<h2>Successive concatenation</h2>\n<p>This:</p>\n<pre><code>decision_prompt = "\\nWould you like to bring back a character you killed?"\ndecision_prompt += "\\nOr would you like to kill off another character?"\ndecision_prompt += "\\nEnter 'kill off' or 'bring back' ->"\n</code></pre>\n<p>is better off as</p>\n<pre><code>DECISION_PROMPT = '''\nWould you like to bring back a character you killed?\nOr would you like to kill off another character?\nEnter 'kill off' or 'bring back' ->'''\n</code></pre>\n<h2>Data structures</h2>\n<p>It seems that the order of <code>killed_tv_characters</code> does not matter, so it should be a <code>set</code>, not a <code>list</code>.</p>\n<h2>Input validation</h2>\n<p>This:</p>\n<pre><code>"""Checks user input for decision."""\nif user_input in valid_decision_input and user_input == 'kill off':\n return user_input\nelif user_input in valid_decision_input and user_input == 'bring back':\n return user_input\nelse:\n invalid_input == True\n print("Please enter a valid input!")\n</code></pre>\n<p>has a few problems:</p>\n<ul>\n<li><code>invalid_input == True</code> doesn't do what you think it does; it's a no-effect statement</li>\n<li>This doesn't really benefit from the combination of <code>valid_decision_input</code> (which should be a <code>set</code>) and checking for specific strings</li>\n<li>Early-return means that you don't need to use <code>else</code></li>\n</ul>\n<p>Here is an alternative:</p>\n<pre><code>if user_input in valid_decision_input:\n return user_input\ninvalid_input = True\nprint("Please enter a valid input!")\n</code></pre>\n<p>Other concerns:</p>\n<ul>\n<li>This will set a local <code>invalid_input</code> unless you declare it <code>global</code> at the top</li>\n<li>Rather than returning a string, consider returning an <code>Enum</code> to narrowly represent user choice</li>\n</ul>\n<h2>Booleans</h2>\n<p>This:</p>\n<pre><code>if tv_characters == False:\n</code></pre>\n<p>should be</p>\n<pre><code>if not tv_characters:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T06:56:11.570",
"Id": "479616",
"Score": "0",
"body": "Why do I need a set, doesn’t a list do the job too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T13:59:40.057",
"Id": "479647",
"Score": "0",
"body": "_do the job_ is a little loaded. Certainly a list will work, but a set will be more efficient for your application in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:01:20.320",
"Id": "479648",
"Score": "0",
"body": "The \"why\" is because `valid_decision_input` is being used for membership tests, which have better time complexity in sets than in sequences."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:05:21.543",
"Id": "244259",
"ParentId": "244250",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "244259",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T08:19:02.473",
"Id": "244250",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Killing and reviving TV Characters"
}
|
244250
|
<p>I am working on a utility to manage shared content libraries for Work from Home scenarios. Basically I have libraries of thousands of Autodesk Revit family files, and I want to host those files on AWS S3, and then manage a local copy of the library based on what is hosted on S3. To that end I have developed an XML "index" file that lists all the folders and files in a given library, along with size, last modified date and file hash for the files. The idea being I can compare size and date in the index with size and date of file on disk and recalculate the hash only on files that need it, to ensure the "local index" represents the current state of the local library. Then I can download the "master index" and quickly compare them to determine which local files and folders to delete because they are no longer in the "master index", and more importantly which files to download because they have changed, as indicated by the different file hash. Files can change either because the user modified a local file which then need replaced with the master file again, or because the master file got revisions and the old local file needs replaced.</p>
<p>An index file looks like this, but a real file would have as many as 10,000 items.</p>
<pre><code><?xml version="1.0"?>
<rootDirectory>
<item>OOTB</item>
<item>OOTB\Data</item>
<item>OOTB\Data\IES</item>
<item size="583" date="03/22/2019 22:09:40" hash="B4A02121565CCADAA601C7092BD598F5BA0A9DED">OOTB\Data\IES\1x4 3Lamp.ies</item>
<item size="582" date="06/21/2020 06:50:36" hash="CF3B1F5E8F072DE2722E940EECDE90157F3BF2EC">OOTB\Data\IES\1x4 4Lamp.ies</item>
<item>OOTB\Data\Lookup Tables</item>
<item>OOTB\Data\Lookup Tables\Conduit</item>
<item size="443" date="03/22/2019 22:09:44" hash="303A0011DC5834F8072337492C4F9B305D3B0DEA">OOTB\Data\Lookup Tables\Conduit\M_Conduit Body - Type C - Aluminum.csv</item>
<item size="380" date="03/22/2019 22:09:44" hash="60CE25A7D805BD1B3746FD21E3CF8BA9B31ACB80">OOTB\Data\Lookup Tables\Conduit\M_Conduit Body - Type C - PVC.csv</item>
<item>OOTB\Data\Lookup Tables\Pipe</item>
<item size="871" date="03/22/2019 22:09:44" hash="E4D246B7F9B530A82F87BFDD7680A4C150CD3015">OOTB\Data\Lookup Tables\Pipe\Elbow - Flanged - GI - Class 125.csv</item>
<item size="731" date="03/22/2019 22:09:44" hash="DA22BD74071BFC5A4A5FB00DAABE87A5F348D647">OOTB\Data\Lookup Tables\Pipe\Elbow - Flanged - GI - Class 25.csv</item>
<item size="879" date="03/22/2019 22:09:44" hash="2F3AE63C2A44370A48497AA2DDEC0339CAABA126">OOTB\Data\Lookup Tables\Pipe\Elbow - Flanged - GI - Class 250.csv</item>
</rootDirectory>
</code></pre>
<p>I have been profiling some code to update the "local index" and I have arrived at this.</p>
<pre><code>$oldIndex = 'C:\Assets\Revit\oldIndex.xml'
$newIndex = 'C:\Assets\Revit\newIndex.xml'
$path = 'C:\Assets\Revit\2020'
CLS
[xml]$xml = Get-Content $oldIndex
$rootNode = $xml.SelectSingleNode('/*')
$rootPath = $rootNode.path
# Delete
(Measure-Command {
foreach ($item in $rootNode.ChildNodes) {
$itemPath = "$rootPath\$($item.'#text')"
if (-not (Test-Path $itemPath)) {
$rootNode.RemoveChild($item)
}
}
}).TotalSeconds
# Add or revise
(Measure-Command {
foreach ($filesystemItem in (Get-ChildItem $path -recurse)) {
$itemPath = $filesystemItem.FullName.TrimStart($rootPath)
$itemXPath = '//*[text()="' + $itemPath + '"]'
if ($indexItem = $xml.SelectSingleNode('//*[text()="' + $itemPath + '"]')) {
if ($indexItem.size -and $indexItem.date) {
[String]$newSize = $filesystemItem.Length
[String]$newDate = ([System.IO.FileInfo]::new($filesystemItem.FullName)).LastWriteTime
if (($indexItem.size -ne $newSize) -or ($indexItem.date -ne $newDate)) {
$indexItem.size = $newSize
$indexItem.date = $newDate
$indexItem.hash = (Get-FileHash -Path:$filesystemItem.FullName -Algorithm:SHA1).Hash
}
}
} else {
$childNode = $xml.CreateElement('item')
$childNode.InnerText = $filesystemItem.FullName.TrimStart($path)
if ($filesystemItem.GetType() -eq [System.IO.FileInfo]) {
$childNode.SetAttribute('size', $filesystemItem.Length)
$childNode.SetAttribute('date', (([System.IO.FileInfo]::new($filesystemItem.FullName))).LastWriteTime)
$childNode.SetAttribute('hash', (Get-FileHash -Path:$filesystemItem.FullName -Algorithm:SHA1).Hash)
}
$rootNode.AppendChild($childNode)
}
}
}).TotalSeconds
# Resort
(Measure-Command {
$sortedNodes = $rootNode.ChildNodes | Sort-Object {$_.InnerXml}
$rootNode.RemoveAll()
foreach ($sortedNode in $sortedNodes) {
[void]$rootNode.AppendChild($sortedNode)
}
}).TotalSeconds
$xml.Save($newIndex)
</code></pre>
<p>My performance issue is in the Add or Revise section. On my test data set, of 8,000 or so files, it takes a full 17 seconds to process, even when there are only one or two changes. I have already tried using <code>Select-Xml</code> instead of <code>.SelectSingleNode()</code> as seen here.</p>
<pre><code>$oldIndex = 'C:\Assets\Revit\oldIndex.xml'
[xml]$xml = Get-Content $oldIndex
$XPath = '//*[text()="OOTB\Libraries\US Imperial\Annotations\Architectural"]'
Measure-Command {
foreach ($i in 1..1000) {
Select-Xml -xml:$xml -xpath:$XPath
}
}
Measure-Command {
foreach ($i in 1..1000) {
$xml.SelectSingleNode($XPath)
}
}
</code></pre>
<p><code>.SelectSingleNode()</code> out performs <code>Select-Xml</code> 700 ms to 2900 ms on my test data.
I have also done some other tests looking at how long it takes to iterate over the files and the differences between MD5 and SHA1 for the hashing. Both where minor. I also simply remarked out the actual update lines, and I am still seeing 17 or so seconds. So it seems the root issue is in repeatedly searching the XML to determine if an item already exists and needs to be tested for revision, or doesn't exist and needs to be added. So this line</p>
<pre><code>if ($indexItem = $xml.SelectSingleNode('//*[text()="' + $itemPath + '"]')) {
</code></pre>
<p>What I am hoping for in a review is some suggestions on optimizations in the Add or Revise section, or a verification that there really is no optimization possible.</p>
<p>The issue for me is the fact that I need to do this at least at every user logon, and a given machine could have multiple libraries to be indexed, perhaps even as many as 10, each with an excess of 20,000 files. If performance scales with my current numbers, I will easily be looking at close to a minute just to verify the local index of a single library, so 10 libraries is a very long process, even before I start downloading any files from S3.</p>
<p>Also, I should mention that I do know I could skip the sorting. For now it's really there just to facilitate me being able to review results. But given that a resort takes less than 2 seconds, compared to the 17+ for the actual required work, I may just leave the sorting in place to keep the XML "neat" in any case.</p>
<p>I should also mention, I considered keeping the date of the last successful index in the XML file, so I could only rehash files that had been changed since then. However, editing a file isn't the only way to get out of sync with the master library. Someone could have a copy of a much older file somewhere, and move that to the local library. Then the date isn't newer than the last successful index, but the file is still wrong and needs a new hash for comparison with the master index. So, comparing current file date and size with last indexed date and size seems like the best way to minimize hashing (which does massively impact overall time) while still ensuring that hashes are up to date.</p>
|
[] |
[
{
"body": "<p>This won't affect performance at all, but:</p>\n<ul>\n<li>Your <code>date</code> attribute uses a localized date format, but should use an ISO8601 machine-readable format instead.</li>\n<li>Your XML uses attributes in a sane way - thank you! I would take it even further and make <code>item</code> a self-closing tag, moving the text into a <code>filename</code> attribute.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:51:27.593",
"Id": "479743",
"Score": "0",
"body": "Funnily enough, one of my complaints with my previous results was that the path was hard to relate to other paths, because the data moved around thanks to the other data coming first. So, moving the path to an attribute and making it the first attribute makes for better XML, and more readable XML. Switched my dates as well, as that is definitely better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:25:16.973",
"Id": "244269",
"ParentId": "244251",
"Score": "1"
}
},
{
"body": "<p>Reinderien's comments definitely improve the result overall, but since my original question was about performance, I thought I should provide the answer I came up with. The main performance issue was excessive use of SelectSingleNode, when looping through all the existing files and looking to see if it was in the XML. By building two arrays, one for indexed files and one for indexed folders, I could dramatically improve the search speed. This due to <code>.Contains()</code> being much faster than <code>.SelectSingleNode()</code> and splitting folders and files into independent arrays. I have as many as 1000 folders indexed, and 8000 files, in a typical data set, and searching all 9000 items 9000 times is a lot slower than searching 1000 folders 1000 times and 8000 files 8000 times. Both of those indexes are also unsorted as there is no value in sorting them, but a slight performance penalty when creating them sorted.\nThe last refinements where only sorting and saving the final XML if changes where actually made.\nWith all those changes, I got total performance down to 10 seconds, when also checking all existing files to see if they have changed and need rehashed, and adding a few new files which would also need hashing. 10 seconds per library is quite manageable.</p>\n<p>So, final code</p>\n<pre><code>$oldIndex = 'C:\\Assets\\Revit\\oldIndex.xml'\n$newIndex = 'C:\\Assets\\Revit\\newIndex.xml'\n$path = 'C:\\Assets\\Revit\\2020'\n\nfunction Get-FileInfo {\n param (\n [String]$path,\n [switch]$hash\n )\n\n $file = Get-Item $path\n $fileInfo = @{\n size = $file.Length\n date = (([System.IO.FileInfo]::new($path)).LastWriteTime).ToString('O')\n hash = $null\n }\n if ($hash) {\n $fileInfo.hash = (Get-FileHash -Path:$path -Algorithm:SHA1).Hash\n }\n\n $fileInfo\n}\n\nCLS\n(Measure-Command {\n$logAdd = [System.Collections.Generic.List[string]]::new()\n$logMove = [System.Collections.Generic.List[string]]::new()\n$logDelete = [System.Collections.Generic.List[string]]::new()\n$logUpdate = [System.Collections.Generic.List[string]]::new()\n\n$currentFolders = Get-ChildItem $path -Directory -recurse | Select -ExpandProperty FullName\n$currentFiles = Get-ChildItem $path -File -recurse | Select -ExpandProperty FullName\n\n[xml]$xml = Get-Content $oldIndex\n$rootNode = $xml.SelectSingleNode('/*')\n$rootPath = $rootNode.path\n\n# Array to search for indexed items\n$indexedFolders = [System.Collections.Generic.List[string]]::new()\n$indexedFiles = [System.Collections.Generic.List[string]]::new()\nforeach ($item in $rootNode.ChildNodes) {\n $indexedItems.Add($item.path)\n if ($item.hash) {\n $indexedFiles.Add($item.path)\n } else {\n $indexedFolders.Add($item.path)\n }\n}\n\n\nforeach ($item in $xml.SelectNodes('//item')) {\n $fullPath = "$rootPath\\$($item.path)"\n $status = $null\n if (Test-Path $fullPath) {\n # Test for need to update\n if ($item.hash) { # for files only\n $fileInfo = Get-FileInfo $fullPath\n if (($item.size -ne $fileInfo.size) -or ($item.date -ne $fileInfo.date)) {\n $fileInfo = Get-FileInfo $fullPath -hash\n $item.SetAttribute('size', $fileInfo.size)\n $item.SetAttribute('date', $fileInfo.date)\n $item.SetAttribute('hash', $fileInfo.hash)\n $logUpdate.Add($fullPath.TrimStart($rootPath))\n }\n }\n } else {\n if ($item.hash) { # files\n $status = 'deleted' # assume deleted\n :current foreach ($currentFile in $currentFiles) {\n if ($currentFile.EndsWith((Split-Path $item.path -leaf))) {\n # Only consider something moved if size and date have not changed, otherwise delete and consider it new\n $newItemPath = $currentFile.TrimStart($rootPath)\n $index = [array]::IndexOf($indexedFiles, $item.path)\n $fileInfo = Get-FileInfo $currentFile\n if (($item.size -eq $fileInfo.size) -and ($item.date -eq $fileInfo.date)) {\n $status = 'moved'\n }\n Break :current\n }\n }\n } else { # folders\n $index = [array]::IndexOf($indexedFolders, $item.path)\n $status = 'deleted' # assume deleted, since a folder with the same name could exist in another sub folder and falsely indicate a move\n }\n\n switch ($status) {\n 'deleted' {\n if ($item.hash) {\n $indexedFiles.RemoveAt($index)\n } else {\n $indexedFolders.RemoveAt($index)\n }\n [void]$rootNode.RemoveChild($item)\n $logDelete.Add($item.path)\n }\n 'moved' {\n $item.path = $newItemPath\n if ($item.hash) {\n $indexedFiles[$index] = $newItemPath\n } else {\n $indexedFolders[$index] = $newItemPath\n }\n $logMove.Add($newItemPath)\n }\n default {\n }\n }\n }\n}\n\nforeach ($folder in $currentFolders) {\n $itemPath = $folder.TrimStart($rootPath)\n if (-not $indexedFolders.Contains($itemPath)) {\n $itemNode = $xml.CreateElement('item')\n $itemNode.SetAttribute('path', $itemPath)\n $rootNode.AppendChild($itemNode)\n \n $logAdd.Add($itemPath)\n }\n}\n\nforeach ($file in $currentFiles) {\n $itemPath = $file.TrimStart($rootPath)\n if (-not $indexedFiles.Contains($itemPath)) {\n $fileInfo = Get-FileInfo $file -hash\n $itemNode = $xml.CreateElement('item')\n $itemNode.SetAttribute('path', $itemPath)\n $itemNode.SetAttribute('size', $fileInfo.size)\n $itemNode.SetAttribute('date', $fileInfo.date )\n $itemNode.SetAttribute('hash', $fileInfo.hash)\n $rootNode.AppendChild($itemNode)\n $logAdd.Add($itemPath)\n }\n}\n\nif (($logDelete.Count -gt 0) -or ($logMove.Count -gt 0) -or ($logAdd.Count -gt 0) -or ($logUpdate.Count -gt 0)) {\n $sortedNodes = $rootNode.ChildNodes | Sort-Object {$_.path}\n $rootNode.RemoveAll()\n $rootNode.SetAttribute('path', $path)\n\n foreach ($sortedNode in $sortedNodes) {\n $rootNode.AppendChild($sortedNode)\n }\n\n $rootNode.SetAttribute('date', (Get-Date).ToUniversalTime().ToString('O'))\n\n $xml.Save($newIndex)\n}\n\n}).TotalSeconds\n\n\n\nWrite-Host "moved:$($logMove.Count) deleted:$($logDelete.Count) updated:$($logUpdate.Count) added:$($logAdd.Count)"\n\n\nif ($logDelete) {\n Write-Host "Deleted:"\n foreach ($item in $logDelete) {\n Write-Host " $item"\n }\n}\nif ($logMove) {\n Write-Host "Moved:"\n foreach ($item in $logMove) {\n Write-Host " $item"\n }\n}\nif ($logAdd) {\n Write-Host "Added:"\n foreach ($item in $logAdd) {\n Write-Host " $item"\n }\n}\nif ($logUpdate) {\n Write-Host "Updated:"\n foreach ($item in $logUpdate) {\n Write-Host " $item"\n }\n}\n</code></pre>\n<p>And the XML looks like this now.</p>\n<pre><code><?xml version="1.0"?>\n<rootDirectory path="C:\\Assets\\Revit\\2020" date="2020-06-23T08:02:20.3126654Z">\n <item path="OOTB" />\n <item path="OOTB\\Data" />\n <item path="OOTB\\Data\\IES" />\n <item path="OOTB\\Data\\IES\\1x4 3Lamp.ies" size="583" date="2019-03-22T22:09:40.0000000+01:00" hash="B4A02121565CCADAA601C7092BD598F5BA0A9DED" />\n <item path="OOTB\\Data\\IES\\1x41T12.ies" size="1207" date="2019-03-22T22:09:40.0000000+01:00" hash="D36BFBA468A66DD21775D0B9797479F4DBE40A19" />\n <item path="OOTB\\Data\\Lookup Tables" />\n <item path="OOTB\\Data\\Lookup Tables\\Conduit" />\n <item path="OOTB\\Data\\Lookup Tables\\Conduit\\Conduit Body - Type C - Aluminum.csv" size="441" date="2019-03-22T22:09:42.0000000+01:00" hash="4E63184FEBADD10007012C94E816979B044BEF36" />\n <item path="OOTB\\Data\\Lookup Tables\\Conduit\\Conduit Body - Type C - Aluminum.csv" size="441" date="2019-03-22T22:09:42.0000000+01:00" hash="4E63184FEBADD10007012C94E816979B044BEF36" />\n <item path="OOTB\\Data\\Lookup Tables\\Pipe" />\n <item path="OOTB\\Data\\Lookup Tables\\Pipe\\Bend Double - PVC - Sch 40 - DWV.csv" size="224" date="2019-03-22T22:09:44.0000000+01:00" hash="30C7DCD5BFC70E67CD79861CC508D72BC987F158" />\n <item path="OOTB\\Data\\Lookup Tables\\Pipe\\Bend Long Sweep - PVC - Sch 40 - DWV.csv" size="290" date="2019-03-22T22:09:44.0000000+01:00" hash="E6A8D01A99082E443744EBDE16E55612AE47611A" />\n <item path="OOTB\\Libraries" />\n <item path="OOTB\\Libraries\\Generic" />\n <item path="OOTB\\Libraries\\Generic\\place_holder.txt" size="0" date="2019-03-22T22:42:14.0000000+01:00" hash="DA39A3EE5E6B4B0D3255BFEF95601890AFD80709" />\n <item path="OOTB\\Libraries\\US Imperial" />\n <item path="OOTB\\Libraries\\US Imperial\\Annotations" />\n <item path="OOTB\\Libraries\\US Imperial\\Annotations\\Architectural" />\n <item path="OOTB\\Libraries\\US Imperial\\Annotations\\Architectural\\Casework Tag.rfa" size="274432" date="2019-03-22T22:20:42.0000000+01:00" hash="D31C94C25A2C333AAA03A122036303C6AAE0D994" />\n <item path="OOTB\\Libraries\\US Imperial\\Annotations\\Architectural\\Ceiling Tag w Height.rfa" size="274432" date="2019-03-22T22:20:42.0000000+01:00" hash="8DA9958E3A746D22429175E819D620ECB78AE93E" />\n <item path="OOTB\\Templates" />\n <item path="OOTB\\Templates\\Families" />\n <item path="OOTB\\Templates\\Families\\English Imperial" />\n <item path="OOTB\\Templates\\Families\\English Imperial\\Annotations" />\n <item path="OOTB\\Templates\\Families\\English Imperial\\Annotations\\Callout Head.rft" size="311296" date="2019-03-22T22:20:40.0000000+01:00" hash="F248371D4A9179147E6CEA0D63CF27B5D862A979" />\n <item path="OOTB\\Templates\\Families\\English Imperial\\Annotations\\Data Device Tag.rft" size="307200" date="2019-03-22T22:20:22.0000000+01:00" hash="BA9421D1B4741AF773CCE716CEB81BBD4F9CA856" />\n <item path="OOTB\\Templates\\Families\\English Imperial\\Annotations\\Door Tag.rft" size="307200" date="2019-03-22T22:20:40.0000000+01:00" hash="684E61A81D70BC73D0F2B62E55072D00A717A6D8" />\n <item path="OOTB\\Templates\\Projects" />\n <item path="OOTB\\Templates\\Projects\\Generic" />\n <item path="OOTB\\Templates\\Projects\\Generic\\Default_I_ENU.rte" size="3248128" date="2019-03-22T22:42:14.0000000+01:00" hash="1527A4C4F7181A32F04F42233D968E4935139B90" />\n <item path="OOTB\\Templates\\Projects\\US Imperial" />\n <item path="OOTB\\Templates\\Projects\\US Imperial\\Commercial-Default.rte" size="6410240" date="2019-03-22T22:20:30.0000000+01:00" hash="CEF8BEB4CBEF05DD9D02EAF98BC8F3E1E7657224" />\n</rootDirectory>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T08:07:39.210",
"Id": "244367",
"ParentId": "244251",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T09:19:07.203",
"Id": "244251",
"Score": "4",
"Tags": [
"xml",
"powershell"
],
"Title": "Powershell XML search performance"
}
|
244251
|
<p>I have designed a logger class to log messages to a file. It uses an independent thread to log the messages save to a queue previously using the main thread. I want to receive reviews about it.</p>
<pre><code>#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <fstream>
#include <atomic>
#include <string>
using namespace std::chrono_literals;
class Logger
{
std::mutex queueMutex;
std::condition_variable condVar;
std::queue<std::string> messagesQueue;
std::thread loggingThread;//background process launcher
std::atomic_bool exit = false;//safety condition
void processEntries()//the background process
{
// Open log file.
std::ofstream logFile("log.txt");
if (logFile.fail()) {
std::cerr << "Failed to open logfile." << std::endl;
return;
}
// Start processing loop. It process only one message for each iteration
// to gain more performance
while (!exit) {
std::unique_lock lock(queueMutex);
// Wait for a notification and don't wakeup unless the queue isn't empty.
condVar.wait(lock, [this]{return !messagesQueue.empty();});
//log to the file
logFile << messagesQueue.front() << std::endl;
messagesQueue.pop();
}
//At the end, if the queue has some messages. here you don't need mutexes
// because you have reached the destructor i.e you won't enqueue any messages anymore
while(exit && !messagesQueue.empty()){
//log to the file
logFile << messagesQueue.front() << std::endl;
messagesQueue.pop();
}
}
public:
Logger()
{
//the default ctor launches the background process task
loggingThread = std::thread{ &Logger::processEntries, this };
}
Logger(const Logger& src) = delete;
Logger& operator=(const Logger& rhs) = delete;
//logs the messages to the queue
void log(std::string_view entry)
{
std::unique_lock lock(queueMutex);
messagesQueue.push(std::string(entry));
condVar.notify_all();
}
~Logger()
{
exit = true;
loggingThread.join();
}
};
int main(){
Logger lg;
for(int i = 1;i < 10000;i++){
lg.log("This is the message number " + std::to_string(i));
}
std::this_thread::sleep_for(10ms);
for(int i = 10000;i < 20001;i++){
lg.log("This is the message number " + std::to_string(i));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T12:52:38.297",
"Id": "479540",
"Score": "0",
"body": "I' would suggest, when using the start value different from zero in for loops to use <= instead <, seems more idiomatic to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:09:38.537",
"Id": "479544",
"Score": "0",
"body": "The problem with the code is that you are keeping the lock even when you you writing to file. This is time consuming, and it would cause unnecessary stalls of the calling thread. You need to release the lock once you acquired the message, before writing to the file. You also need to put some limit on the size of the queue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:35:02.947",
"Id": "479547",
"Score": "0",
"body": "@llkhd Does that mean If I used an std::string to save the message instead of writing to the file directly, then wrote to the file after releasing the lock, it would be more performant? –"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:36:39.463",
"Id": "479548",
"Score": "0",
"body": "@Ilkhd Your comments should be an answer."
}
] |
[
{
"body": "<p>Pretty good for a beginning, but I would have a lot of feature requests if I were a user.</p>\n<ol>\n<li>Allow the user to provide a full file specification so that the file appears where the user expects it.</li>\n<li>The logger should get the day and time of day and report that in each message.</li>\n<li>The logger should be initialized with the program name so that the all the messages contain the program name, this way if multiple processes are writing to the same file one will know which process made the log entry.</li>\n</ol>\n<p>Make it into a library by providing a header file and a C++ source file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T14:13:54.560",
"Id": "479550",
"Score": "0",
"body": "If I used an `std::string` to save the message instead of writing to the file directly, then wrote to the file after releasing the lock, would it be more performant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:06:10.243",
"Id": "479553",
"Score": "0",
"body": "std::ofstream is already buffered, but you are negating the buffering by using `std::endl`, because endl flushes the buffer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:48:21.113",
"Id": "244263",
"ParentId": "244257",
"Score": "2"
}
},
{
"body": "<ol>\n<li><p><code>std::ofstream logFile("log.txt");</code> the name should be configurable. Or at least have current time/date as a part of its name; otherwise you'll overwrite your log file each time you launch your program.</p>\n</li>\n<li><p>You should have an option to print messages to console.</p>\n</li>\n<li><p>The pop-from-queue implementation in <code>processEntries</code> is bugged.</p>\n<pre><code>while (!exit) {\n std::unique_lock lock(queueMutex);\n\n condVar.wait(lock, [this]{return !messagesQueue.empty();});\n ....\n }\n</code></pre>\n</li>\n</ol>\n<p>Now, when will it leave the wait if exit is called but no more messages are being forwarded? To make a proper wait, make <code>exit</code> part of the condition (you'll also have to lock the mutex whenever you change <code>exit</code>, so just make it a bool instead of atomic).</p>\n<ol start=\"4\">\n<li><p>You should force-flush the stream once every few seconds. At times people want to see the log during run and they won't be able to if it isn't flushed. Without flushing you may also lose lots of log-information during crashes - like 16KB of text. However, force-flushing every message like you do with <code>std::endl</code> is a poor idea in terms of performance.</p>\n</li>\n<li><p><code>log(std::string_view entry)</code> there is a general debate as to what is faster, copy a string or move a string - it surely depends on the size of the string... regardless, you should have a version that doesn't use a <code>string_view</code> but a <code>string</code> so you don't make an extra allocation in the queue. It improves health of memory fragmentation.</p>\n</li>\n<li><p>Normally, I'd expect a logger to print information "when" (time), "what"(log level - info, warning, error), and "who" (source of message) in addition to the message itself. It is important for logging.</p>\n</li>\n<li><p>You lack message filtration options depending on log-level as well as desired verbose level.</p>\n</li>\n</ol>\n<p>To implement 6 and 7, consider separating logger into two classes - one for writing log to file/console and another that wraps functionality and generates the messages - with former begin the shared state across all units while the latter being copied and modified for each unit so it can store private information of "who" sends the message as well as some configuration regarding importance of the log message.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T07:00:50.637",
"Id": "479617",
"Score": "0",
"body": "thanks a lot for catching the bug"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T03:17:07.130",
"Id": "244302",
"ParentId": "244257",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244302",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T12:22:02.840",
"Id": "244257",
"Score": "4",
"Tags": [
"c++",
"multithreading",
"c++17",
"logging"
],
"Title": "C++ multithreading logger class"
}
|
244257
|
<p>It's an assignment from <a href="https://www.theodinproject.com/lessons/caesar-cipher" rel="nofollow noreferrer">the Odin Project.</a></p>
<p>Here's my implementation:</p>
<pre><code>#!/usr/bin/env ruby
def caesar_cipher(str, shift)
low_alpha = ("a".."z").to_a
high_alpha = ("A".."Z").to_a
length_alpha = low_alpha.length
chars = str.split("")
ciphered = ""
chars.each do |char|
if low_alpha.include? char
i = low_alpha.index(char)
shifted = (i + shift) % length_alpha
ciphered << low_alpha[shifted]
elsif high_alpha.include? char
i = high_alpha.index(char)
shifted = (i + shift) % length_alpha
ciphered << high_alpha[shifted]
else
ciphered << char
end
end
ciphered
end
puts caesar_cipher("What a string!", 5) # Bmfy f xywnsl!
puts caesar_cipher("Abc", 5) # Fgh
puts caesar_cipher("Xyz", 3) # Abc
puts caesar_cipher("Test", 1) # Uftu
puts caesar_cipher("Zoo", 10) # Jyy
</code></pre>
<p><strong>What points could be improved? What would you have done differently and why?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T17:48:18.950",
"Id": "479565",
"Score": "0",
"body": "It could be simplified if you used `.ord` (example `'a'.ord` shows 97), it shows the numerical value of the character, so instead of checking if the character is in an array you could check if it is present in a range making the comparison more efficient."
}
] |
[
{
"body": "<h1>Indentation</h1>\n<p>The standard indentation style in Ruby is two spaces, not four.</p>\n<h1>Single-quoted strings</h1>\n<p>If you don't use string interpolation, it is helpful if you use single quotes for your strings. That way, it is immediately obvious that no string interpolation is taking place.</p>\n<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files. In your case, you are only actually mutating one of the many strings in your code, the one assigned to <code>ciphered</code>.</p>\n<p>You can make <em>only</em> this string mutable by either not using a literal to initialize it:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>ciphered = String.new\n</code></pre>\n<p>Or by using the <a href=\"https://ruby-doc.org/core/String.html#method-i-2B-40\" rel=\"nofollow noreferrer\">unary prefix <code>String#+@</code> operator for strings</a>, which turns a frozen string into a mutable string:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>ciphered = +''\n</code></pre>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect all of the style violations I pointed out, and also was able to autocorrect all of them. Note, however, that automatically adding the magic comment broke the code originally, because Rubocop does not automatically detect which strings are mutated. So, I had to add the <code>+</code> manually afterwards. That's where good tests come in handy!</p>\n<h1>Inconsistent use of parentheses</h1>\n<p>Sometimes, you use parentheses around arguments, and sometimes you don't. The general rule is to always use parentheses around arguments <em>if</em> you have arguments, and leave out the parentheses only for "procedure-like" methods such as <code>puts</code>, <code>attr_reader</code>, <code>require</code>, <code>private</code>, etc.</p>\n<p>For example, you are using parentheses for <code>split</code> and <code>index</code> but not for <code>include?</code>.</p>\n<h1>Constants</h1>\n<p>There is no need to re-compute <code>low_alpha</code>, <code>high_alpha</code>, and <code>length_alpha</code> every time you call the method. Their values will always be the same. Therefore, it makes sense to turn them into <em>constants</em> and initialize them at the beginning of the file:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>LOW_ALPHA = ('a'..'z').to_a\nHIGH_ALPHA = ('A'..'Z').to_a \nLENGTH_ALPHA = LOW_ALPHA.length\n</code></pre>\n<h1>Object#freeze</h1>\n<p><a href=\"https://ruby-doc.org/core/Object.html#method-i-freeze\" rel=\"nofollow noreferrer\"><code>Object#freeze</code></a> is a method that allows you to freeze an object. A frozen object will no longer allow itself to be modified. It is good practice in general to freeze objects that you don't intend to modify, both as a signal to the reader that this object will not be modified, and as a safety net, in case you ever accidentally try to modify it regardless.</p>\n<p>We already made all but one of our strings frozen, so let's do that with the arrays as well:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>LOW_ALPHA = ('a'..'z').to_a.freeze\nHIGH_ALPHA = ('A'..'Z').to_a.freeze\nLENGTH_ALPHA = LOW_ALPHA.length\n</code></pre>\n<p>Numbers are immutable anyway, no need to freeze them.</p>\n<h1><code>length</code> vs. <code>size</code></h1>\n<p>Many Ruby collections have both <code>length</code> and <code>size</code> methods, but some have only one. In general, <em>IFF</em> a collection has a <code>size</code> method, then that method is guaranteed to be "efficient" (usually constant time), whereas <code>length</code> may or may not be efficient (linear time for iterating through the collection and counting all the elements), depending on the collection.</p>\n<p>In your case, you are using an array, for which both are constant time, but if you want to guarantee efficiency, then it is better to explicitly use <code>size</code> instead.</p>\n<h1><code>String#chars</code></h1>\n<p>Instead of using <a href=\"https://ruby-doc.org/core/String.html#method-i-split\" rel=\"nofollow noreferrer\"><code>String#split</code></a>, you can use <a href=\"https://ruby-doc.org/core/String.html#method-i-chars\" rel=\"nofollow noreferrer\"><code>String#chars</code></a> to create an array of characters:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>chars = str.chars\n</code></pre>\n<h1><code>String#each_char</code></h1>\n<p>Actually, you don't need the array of characters at all. Instead, you can use the <a href=\"https://ruby-doc.org/core/String.html#method-i-each_char\" rel=\"nofollow noreferrer\"><code>String#each_char</code></a> iterator directly:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>str.each_char do |char|\n</code></pre>\n<h1>The conditional expression is … an expression</h1>\n<p>In Ruby, the <em>conditional expression</em> <code>if</code> / <code>else</code> is an <em>expression</em>, not a statement. (In fact, everything in Ruby is an expression, there are no statements.) Therefore, the conditional expression evaluates to a value, it evaluates to the value of the branch that was taken.</p>\n<p>This means you can remove the duplicated <code>ciphered << X</code> from each branch, and instead pull it out of the conditional expression:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>ciphered << if LOW_ALPHA.include?(char)\n i = LOW_ALPHA.index(char)\n shifted = (i + shift) % LENGTH_ALPHA\n\n LOW_ALPHA[shifted]\n elsif HIGH_ALPHA.include?(char)\n i = HIGH_ALPHA.index(char)\n shifted = (i + shift) % LENGTH_ALPHA\n\n HIGH_ALPHA[shifted]\n else\n char\n end\n</code></pre>\n<h1>Code duplication</h1>\n<p>Speaking of duplicated code: Your <code>then</code> branch and your <code>elsif</code> branch are virtually identical. We can simplify them by extracting the duplicated code into a method:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def encrypt_letter(char, alphabet, shift)\n i = alphabet.index(char)\n shifted = (i + shift) % LENGTH_ALPHA\n\n alphabet[shifted]\nend\n</code></pre>\n<p>and then using this method in the two branches instead:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>ciphered << if LOW_ALPHA.include?(char)\n encrypt_letter(char, LOW_ALPHA, shift)\n elsif HIGH_ALPHA.include?(char)\n encrypt_letter(char, HIGH_ALPHA, shift)\n else\n char\n end\n</code></pre>\n<h1>Higher-level iterators</h1>\n<p>Ruby has many powerful iteration methods in its collections library. Using <code>each</code> (or in this case <code>each_char</code>) directly is almost always sub-optimal. This particular pattern that you are using:</p>\n<ul>\n<li>Initialize an accumulator. (In this case the string assigned to <code>ciphered</code>.)</li>\n<li>Iterate over the collection and add to the accumulator.</li>\n<li>Return the accumulator.</li>\n</ul>\n<p>Is known as a <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>Fold</em></a>, and is available in Ruby in two forms, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_with_object\" rel=\"nofollow noreferrer\"><code>Enumerable#each_with_object</code></a> and <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-inject\" rel=\"nofollow noreferrer\"><code>Enumerable#inject</code></a>. Using <code>Enumerable#each_with_object</code>, we can further simplify your code to:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def caesar_cipher(str, shift)\n str.each_char.each_with_object(+'') do |char, ciphered|\n ciphered << if LOW_ALPHA.include?(char)\n encrypt_letter(char, LOW_ALPHA, shift)\n elsif HIGH_ALPHA.include?(char)\n encrypt_letter(char, HIGH_ALPHA, shift)\n else\n char\n end\n end\nend\n</code></pre>\n<h1>The <em>right</em> higher-level iterator!</h1>\n<p>But actually, what you are doing here is simply transforming each element of the collection. You don't need something as powerful as a <em>fold</em> for that. This is a much simpler operation called <a href=\"https://wikipedia.org/wiki/Map_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>Map</em></a>, and it is also available in Ruby as <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-map\" rel=\"nofollow noreferrer\"><code>Enumerable#map</code></a>:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>str.each_char.map do |char|\n if LOW_ALPHA.include?(char)\n encrypt_letter(char, LOW_ALPHA, shift)\n elsif HIGH_ALPHA.include?(char)\n encrypt_letter(char, HIGH_ALPHA, shift)\n else\n char\n end\nend.join\n</code></pre>\n<h1>Rubocop, revisited</h1>\n<p>I didn't mention this before, but in addition to the style violations I mentioned at the beginning, Rubocop was also complaining about the complexity and the length of the <code>caesar_cipher</code> method. At this point, Rubocop is actually happy with everything!</p>\n<p>But we can do better.</p>\n<h1>The Algorithm</h1>\n<p>What the Caesar Cipher is really doing, is shifting the alphabet. You have recognized this, as can be seen by your variable names (<code>shift</code>), but you are not really taking advantage of it.</p>\n<p>What we can do, is take our alphabets, <em>shift them</em>, and then use them for a key-value mapping, i.e. a <a href=\"https://ruby-doc.org/core/Hash.html\" rel=\"nofollow noreferrer\"><code>Hash</code></a>:</p>\n<p>Now, our entire code looks like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>#!/usr/bin/env ruby\n# frozen_string_literal: true\n\nLOW_ALPHA = ('a'..'z').to_a.freeze\nHIGH_ALPHA = ('A'..'Z').to_a.freeze\n\ndef caesar_cipher(str, shift)\n low_encrypted = LOW_ALPHA.rotate(shift)\n high_encrypted = HIGH_ALPHA.rotate(shift)\n\n character_map =\n Hash.new { |_, k| k }\n .merge((LOW_ALPHA.zip(low_encrypted) + HIGH_ALPHA.zip(high_encrypted)).to_h)\n .freeze\n\n str.each_char.map(&character_map).join\nend\n</code></pre>\n<p>Okay, there's a lot going on here. We are using <a href=\"https://ruby-doc.org/core/Array.html#method-i-rotate\" rel=\"nofollow noreferrer\"><code>Array#rotate</code></a> to create the shifted character arrays:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>LOW_ALPHA.rotate(3)\n# => ["d", "e", "f", …, "a", "b", "c"]\n</code></pre>\n<p>Then we use <a href=\"https://ruby-doc.org/core/Array.html#method-i-zip\" rel=\"nofollow noreferrer\"><code>Array#zip</code></a> to create an array of pairs with the original character and the encrypted character:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>LOW_ALPHA.zip(LOW_ALPHA.rotate(3))\n# => [["a", "d"], ["b", "e"], ["c", "f"], …, ["x", "a"], ["y", "b"], ["z", "c"]]\n</code></pre>\n<p>With <a href=\"https://ruby-doc.org/core/Array.html#method-i-2B\" rel=\"nofollow noreferrer\"><code>Array#+</code></a> we concatenate the two arrays together, and then call <a href=\"https://ruby-doc.org/core/Array.html#method-i-to_h\" rel=\"nofollow noreferrer\"><code>Array#to_h</code></a>, which turns an arrays of pairs (two-element arrays) into a hash, which looks like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>{\n 'a' => 'd',\n 'b' => 'e',\n 'c' => 'f',\n# …\n 'x' => 'a',\n 'y' => 'b',\n 'z' => 'c',\n\n 'A' => 'D',\n 'B' => 'E',\n 'C' => 'F',\n# …\n 'X' => 'A',\n 'Y' => 'B',\n 'Z' => 'C',\n}\n</code></pre>\n<p>This contains our entire encryption scheme.</p>\n<p>We have already created a hash with a default value that will simply return the key for any unknown key (so that, e.g. <code>'!'</code> maps to <code>'!'</code>) and use <a href=\"https://ruby-doc.org/core/Hash.html#method-i-merge\" rel=\"nofollow noreferrer\"><code>Hash#merge</code></a> to merge these two hashes into one.</p>\n<p>Last, we call <code>map</code> as before, but now, as our transformation function, we simply pass the hash itself. For that, we use the <code>&</code> operator, which turns a <a href=\"https://ruby-doc.org/core/Proc.html\" rel=\"nofollow noreferrer\"><code>Proc</code></a> into a block. But wait, we don't have a <code>Proc</code>, we have a <code>Hash</code>? Indeed, but <code>Hash</code> implements <a href=\"https://ruby-doc.org/core/Hash.html#method-i-to_proc\" rel=\"nofollow noreferrer\"><code>Hash#to_proc</code></a>, which converts the hash into a proc that is equivalent to using the hash's <a href=\"https://ruby-doc.org/core/Hash.html#method-i-5B-5D\" rel=\"nofollow noreferrer\"><code>Hash#[]</code></a> method.</p>\n<h1>The power of strings</h1>\n<p>The <a href=\"https://ruby-doc.org/core/String.html\" rel=\"nofollow noreferrer\"><code>String</code></a> class in Ruby is really powerful as well. For example, it has the method <a href=\"https://ruby-doc.org/core/String.html#method-i-tr\" rel=\"nofollow noreferrer\"><code>String#tr</code></a> which does the same thing as the <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/utilities/tr.html\" rel=\"nofollow noreferrer\">POSIX <code>tr</code> utility</a>, it <em>translates</em> characters in a string. This is really the right method to use for this job:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>#!/usr/bin/env ruby\n# frozen_string_literal: true\n\nLOW_ALPHA = ('a'..'z')to_a.join.freeze\nHIGH_ALPHA = ('A'..'Z')to_a.join.freeze\n\ndef caesar_cipher(str, shift)\n low_encrypted = LOW_ALPHA.chars.rotate(shift).join.freeze\n high_encrypted = HIGH_ALPHA.chars.rotate(shift).join.freeze\n\n str.tr(LOW_ALPHA + HIGH_ALPHA, low_encrypted + high_encrypted)\nend\n</code></pre>\n<h1>Final thoughts</h1>\n<p>Lastly, I just want to give you something to think about, without any comments from me:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n\nclass CaesarCipher\n LOWER = ('a'..'z').to_a.join.freeze\n UPPER = ('A'..'Z').to_a.join.freeze\n\n def initialize(key)\n self.encrypted = (LOWER.chars.rotate(key) + UPPER.chars.rotate(key)).join.freeze\n end\n\n def encrypt(str)\n str.tr(LOWER + UPPER, encrypted)\n end\n\n alias_method :call, :encrypt\n\n def to_proc\n ->str { encrypt(str) }\n end\n\n private\n\n attr_accessor :encrypted\n\n freeze\nend\n\ncaesar5 = CaesarCipher.new(5)\n\nputs caesar5.encrypt('What a string!') # Bmfy f xywnsl!\nputs caesar5.('Abc') # Fgh\nputs CaesarCipher.new(3).('Xyz') # Abc\nputs CaesarCipher.new(1).('Test') # Uftu\nputs CaesarCipher.new(10).('Zoo') # Jyy\n\nputs ['What a string!', 'Abc'].map(&caesar5)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-28T14:24:55.327",
"Id": "244662",
"ParentId": "244262",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244662",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T13:47:53.507",
"Id": "244262",
"Score": "1",
"Tags": [
"algorithm",
"ruby",
"cryptography",
"caesar-cipher"
],
"Title": "Caesar Cipher, done in Ruby"
}
|
244262
|
<p>The array "scores" tells the total points for each person involved in a contest. So for example:</p>
<pre><code>User A: 100 points
User B: 90 points
User C: 90 points
User D: 80 points
User E: 75 points
User F: 60 points
</code></pre>
<p>According to above scores we also have this ranking:</p>
<pre><code>User A: #1
User B: #2
User C: #2
User D: #3
User E: #4
User F: #5
</code></pre>
<p>This ranking method follows the Dense Ranking method.</p>
<p>Then we have a user named alice. If she gets 55 points, she will rank at position #6 (according to ranking above).
If she scores 90 points, she will rank at position #2. And so on.</p>
<p>I actually have an array containing different "sessions" for alice. So having for example:<br />
[55, 90]</p>
<p>This means that first time will alice be ranked at position #6. While second time she will be ranked at position #2.</p>
<p>I coded this, and it work. However, this does not seem to be very effective. For large datasets, with half million entries in the scores-array, it times out. This is the code:</p>
<pre><code>const getPosition = (element, scores) => {
scores.push(element);
scores.sort(function (a,b) { return b-a; });
return scores.indexOf(element)+1;
}
function climbingLeaderboard(scores, alice) {
var uniqueSet = new Set(scores);
scores = [...uniqueSet];
var positions = [];
let aliceIndex = 0;
while(aliceIndex < alice.length){
positions.push(getPosition(alice[aliceIndex], scores));
aliceIndex++;
}
return positions;
}
function main() {
const scores = [100, 90, 90, 80, 75, 60];
const alice = [50, 65, 77, 90, 102];
let result = climbingLeaderboard(scores, alice);
console.log(result.join("\n") + "\n");
}
</code></pre>
<p>I guess the "sort"-function and/or searching for the element in the array with indexOf is the problem. But I could not find a way to make these two operations more efficient.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T15:20:38.200",
"Id": "479556",
"Score": "1",
"body": "You shouldn't be sorting the array multiple timtes over. Instead just sort the array without Alice once, and then use a binary search to find out where Alice's score should go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T20:58:59.070",
"Id": "479587",
"Score": "0",
"body": "@Countingstuff The array is already sorted by default. IN that case I would not need to sort. You are saying that I would need to make a loop and for each iteration, I would need to just put the score in the \"right position\" in the array? And also get back the index where to element was added? I tried to google this, but could not find that much. Would be great if you hade some link to share."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T21:35:17.357",
"Id": "479589",
"Score": "0",
"body": "Note quite that, in fact there is no need to do insertions either. Please clarify a point for me and I will post an answer. Your solution with scores = [100, 100, 100, 100] and alice = [100, 100, 102, 101] gives 1, 1, 1, 2. Is this correct or should it be 2, 2, 1, 2? Or something else"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T22:10:52.197",
"Id": "479594",
"Score": "0",
"body": "Ok. It should give: 1, 1, 1, 2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T23:41:31.320",
"Id": "479604",
"Score": "1",
"body": "Sorry, I posted an answer but then I realise I'm still not sure about the expected output. For scores = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] and alice = [ 0, 0, 0, -1 ] your function gets 1,1,1,5. Is this correct? Should it not be 1,1,1,2?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T08:07:19.060",
"Id": "479621",
"Score": "0",
"body": "Your solution worked! Thank you very much, Gonna study it. Thanks again."
}
] |
[
{
"body": "<p>The following function sort of agrees with your function. Except that for example your function given\nscores = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] and alice = [ 0, 0, 0, -1 ] gets 1,1,1,5, while I think it should be 1,1,1,2.</p>\n<p>Anyway, it easily handles scores arrays of sizes 10^7 for scores and 10^5 for alice.</p>\n<p>The idea is, we already know scores is sorted as per your comment. We can then go through the scores array. We sort the alices array while remembering the original order. Then we go through the scores array, we first look at the largest alice, once we hit an element >= it, it is time to note that down, we remember the score and whether it was a tie and the position it happened at. We continue traversing scores, now looking at the next biggest alice, etc.</p>\n<p>At the end of this we know where each alice would be ranked in the original array. Now we just need to account for the rank increases that come from prior alices, basically the rule is, if you are alice 7, then you look at the previous scores from alices 1 to 6 which resulted in a rank increase, and count 1 each time their score was larger than yours. We can do this fairly quickly by maintaining a sorted array of the previous scores using a binary search to find where to insert the next element. Remembering to account for ties amongst Alices scores.</p>\n<pre><code>function binarySearch(array, targetValue) {\n if (array.length === 0) {\n return 0;\n }\n let min = 0;\n let max = array.length;\n let guess;\n\n while (max - min > 1) {\n guess = Math.floor((max + min) / 2);\n\n if (array[guess] > targetValue) {\n min = guess;\n } else {\n max = guess;\n }\n }\n\n return array[min] < targetValue ? min : min + 1;\n}\n\n\nfunction climbingLeaderboard(scores, alice) {\n if (alice.length === 0) {\n return [];\n }\n const sortedAliceWithIndex = alice.map((s, i) => [s, i]).sort(([a], [b]) => b - a);\n\n let aliceInd = 0;\n let currAlice = sortedAliceWithIndex[aliceInd][0];\n const ranks = [];\n let i = 0;\n let effectiveCount = 0;\n while (true) {\n const currScore = scores[i];\n if (currScore !== undefined && currScore > currAlice) {\n i++;\n if (!(scores[i] === scores[i - 1])) {\n effectiveCount++;\n }\n continue;\n }\n\n ranks.push([\n effectiveCount,\n sortedAliceWithIndex[aliceInd][1],\n currAlice === currScore,\n currAlice\n ]);\n aliceInd++;\n\n if (aliceInd >= alice.length) {\n break;\n }\n currAlice = sortedAliceWithIndex[aliceInd][0];\n }\n\n const inOriginalAliceOrder = ranks.sort(([, i1], [, i2]) => i1 - i2);\n\n const accountingForRanks = [];\n let rankIncreases = [];\n for (let [i, _, tie, score] of inOriginalAliceOrder) {\n let rankUp = binarySearch(rankIncreases, score);\n\n if (rankIncreases[rankUp - 1] === score) {\n accountingForRanks.push(i + rankUp);\n } else {\n accountingForRanks.push(i + rankUp + 1);\n if (!tie) {\n rankIncreases.splice(rankUp, 0, score);\n }\n }\n }\n return accountingForRanks;\n}\n</code></pre>\n<p>The following runs in a couple of seconds for me.</p>\n<pre><code>function main() {\n let scores = new Array(10 ** 6);\n for (let i = 0; i < scores.length; i++) {\n scores[i] = 1 * Math.random();\n }\n scores.sort((a, b) => b - a);\n let alice = new Array(10 ** 5);\n for (let i = 0; i < alice.length; i++) {\n alice[i] = 2 * Math.random() - 1;\n }\n\n let result1 = climbingLeaderboard(scores, alice);\n\n console.log(result1);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T23:35:32.533",
"Id": "244293",
"ParentId": "244265",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244293",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T14:41:29.467",
"Id": "244265",
"Score": "2",
"Tags": [
"javascript",
"sorting",
"search"
],
"Title": "How to sort and search in JavaScript large set"
}
|
244265
|
<blockquote>
<h1>Inheritance Challenge 2 - Employees, Bosses and Trainees</h1>
</blockquote>
<blockquote>
<p>Create a main class with a Main Method, then a base class Employee with the properties Name, FirstName, Salary and the methods Work() and Pause().</p>
</blockquote>
<blockquote>
<p>Create a deriving class boss with the propertie CompanyCar and the method Lead(). Create another deriving class of employees - trainees with the properties WorkingHours and SchoolHourse and a method Learn().</p>
</blockquote>
<blockquote>
<p>Override the methods Work() of the trainee class so that it indicates the working hours of the trainee.</p>
</blockquote>
<blockquote>
<p>Don’t forget to create the constructors.</p>
</blockquote>
<blockquote>
<p>Create an object of each of the three classes (with arbitrary values) and call the methods, Lead() of Boss and Work() of Trainee.</p>
</blockquote>
<p>Just print out the respective text, what the respective employees do.</p>
<p>I feel like my biggest improvement here can be with access modifiers. Here are the scripts.</p>
<p><strong>Program.cs</strong></p>
<pre><code>using System;
namespace Employees__Bosses_and_Trainees
{
class Program
{
static void Main()
{
Employee employee = new Employee("Warlock", "Adam", 10.0);
Console.WriteLine("Printing Employee.");
Console.WriteLine("Last name: {0}.", employee.Name);
Console.WriteLine("First name: {0}.", employee.FirstName);
Console.WriteLine("Salary: ${0}.", employee.Salary);
employee.Work();
employee.Pause();
Console.WriteLine("");
Employee frank = new Employee
{
FirstName = "Frank",
Name = "Smith",
Salary = 10.0
};
Console.WriteLine("Printing Employee.");
Console.WriteLine("Last name: {0}.", frank.Name);
Console.WriteLine("First name: {0}.", frank.FirstName);
Console.WriteLine("Salary: ${0}.", frank.Salary);
frank.Work();
frank.Pause();
Console.WriteLine("");
Boss boss = new Boss("Boop", "Betty", 20.0);
Console.WriteLine("Printing Boss.");
Console.WriteLine("Does the Boss have a car? {0}", boss.CompanyCar);
Console.WriteLine("First Name: {0}.", boss.FirstName);
Console.WriteLine("Last name: {0}.", boss.Name);
Console.WriteLine("Salary: ${0}.", boss.Salary);
boss.Work();
boss.Lead();
boss.Pause();
Console.WriteLine("");
Boss james = new Boss();
Console.WriteLine("Printing Boss.");
Console.WriteLine("Does the Boss have a car? {0}", james.CompanyCar);
james.FirstName = "James";
james.Name = "Storm";
james.Salary = 20.0;
Console.WriteLine("First Name: {0}.", james.FirstName);
Console.WriteLine("Last name: {0}.", james.Name);
Console.WriteLine("Salary: ${0}.", james.Salary);
james.Work();
james.Lead();
james.Pause();
Console.WriteLine("");
Trainees trainee = new Trainees("Murphy", "Charlie", 15.0);
Console.WriteLine("Printing Trainees.");
Console.WriteLine("First Name: {0}.", trainee.FirstName);
Console.WriteLine("Last name: {0}.", trainee.Name);
Console.WriteLine("Salary: {0}.", trainee.Salary);
Console.WriteLine("School hours: {0}.", trainee.SchoolHours);
Console.WriteLine("Training hours {0}.", trainee.WorkingHours);
trainee.Learn();
trainee.Pause();
trainee.Work();
Console.WriteLine("");
Trainees nully = new Trainees();
Console.WriteLine("Printing Trainees.");
Console.WriteLine("First Name: {0}.", nully.FirstName);
Console.WriteLine("Last name: {0}.", nully.Name);
Console.WriteLine("Salary: {0}.", nully.Salary);
Console.WriteLine("School hours: {0}.", nully.SchoolHours);
Console.WriteLine("Training hours {0}.", nully.WorkingHours);
nully.Learn();
nully.Pause();
nully.Work();
}
}
}
</code></pre>
<p><strong>Boss.cs</strong></p>
<pre><code>using System;
namespace Employees__Bosses_and_Trainees
{
internal class Boss : Employee
{
// Properties
internal bool CompanyCar { get; set; }
// Constructor
internal Boss()
{
}
internal Boss(string name, string firstName, double salary) : base(name, firstName, salary)
{
Name = name;
FirstName = firstName;
Salary = salary;
CompanyCar = true;
}
// Methods
internal void Lead()
{
if (CompanyCar)
Console.WriteLine("{0} {1} earns ${2} an hour wage and has a company car.", FirstName, Name, Salary);
else
Console.WriteLine("{0} {1} earns ${2} an hour wage without a company car.", FirstName, Name, Salary);
}
}
}
</code></pre>
<p><strong>Employee.cs</strong></p>
<pre><code>using System;
namespace Employees__Bosses_and_Trainees
{
internal class Employee
{
// Properties
internal string Name { get; set; }
internal string FirstName { get; set; }
internal double Salary { get; set; }
// Constructors
internal Employee()
{
}
internal Employee(string name = null, string firstName = null, double salary = 0.0)
{
Name = name;
FirstName = firstName;
Salary = salary;
}
// Methods
public virtual void Work() => Console.WriteLine("{0} {1} earns ${2} an hour wage.", FirstName, Name, Salary);
internal void Pause() => Console.WriteLine("{0} is on break at work.", Name);
}
}
</code></pre>
<p><strong>Trainees.cs</strong></p>
<pre><code>using System;
namespace Employees__Bosses_and_Trainees
{
internal class Trainees : Employee
{
// Properties
internal double WorkingHours { get; set; }
internal double SchoolHours { get; set; }
// Constructors
internal Trainees()
{
}
internal Trainees(string name, string firstName, double salary, double workingHours = 8.0, double schoolHours = 4.0) : base(name, firstName, salary)
{
Name = name;
FirstName = firstName;
Salary = salary;
WorkingHours = workingHours;
SchoolHours = schoolHours;
}
// Methods
internal void Learn() => Console.WriteLine("{0} {1} is going to school {2} hours a week.", FirstName, Name, SchoolHours);
// Override
public override void Work() => Console.WriteLine("{0} {1} is working {2} a week as a trainer.", FirstName, Name, WorkingHours);
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T18:55:59.443",
"Id": "244277",
"Score": "1",
"Tags": [
"c#",
"beginner",
"inheritance",
"classes"
],
"Title": "Inheritance Challenge 2 - Employees, Bosses and Trainees in C#"
}
|
244277
|
<p>So I have a 12 x 6 2D numpy array for input which consists of 7 possible board objects (characters from 'abcdefg'). From a 2D numpy array I wish to generate all the possible unique 2D arrays, in whose parent array 2 adjacent elements in each row have been swapped. In the worst case this means 60 (5*12) swaps for each parent node. However 2 adjacent elements can be the same, so I omit the duplicate nodes where a swap doesn't generate a unique child array. For instance, given an array (simplified case):</p>
<pre><code>np.array([['a', 'a', 'c'],
['d', 'e', 'f'],
['g', 'a', 'b']])
</code></pre>
<p>I would get the following visited tuples for depth 1 (not in order of swapping cause it's a set):</p>
<pre><code>(('a', 'a', 'c'), ('d', 'e', 'f'), ('a', 'g', 'b'))
(('a', 'a', 'c'), ('d', 'e', 'f'), ('g', 'b', 'a'))
(('a', 'c', 'a'), ('d', 'e', 'f'), ('g', 'a', 'b'))
(('a', 'a', 'c'), ('d', 'e', 'f'), ('g', 'a', 'b')) # parent node
(('a', 'a', 'c'), ('e', 'd', 'f'), ('g', 'a', 'b'))
(('a', 'a', 'c'), ('d', 'f', 'e'), ('g', 'a', 'b'))
</code></pre>
<p>The aforementioned function is ran through a breadth-first search function, where given a certain depth, it will find all the unique visited nodes (as a set of tuple of tuples). Since the complexity of BFS is O(b^n), the non unique positions generated would be at least 60^4 (for depth 4), and under a billion for depth 5. For my current implementation depth 4 takes 80-90 seconds, depth 3 is about 2-3 seconds. My goal would be to try and optimize it to 5 seconds max for depth 5, which would be a satisfactory result. Here is the code:</p>
<pre><code>import numpy as np
import time
B = np.array([['a', 'a', 'c', 'a', 'a', 'b'],
['d', 'e', 'f', 'a', 'b', 'c'],
['a', 'b', 'd', 'd', 'e', 'b'],
['b', 'c', 'f', 'd', 'e', 'e'],
['a', 'b', 'd', 'b', 'd', 'd'],
['b', 'c', 'f', 'f', 'e', 'e'],
['d', 'e', 'f', 'g', 'b', 'c'],
['d', 'e', 'f', 'a', 'b', 'c'],
['a', 'b', 'd', 'b', 'd', 'd'],
['b', 'c', 'f', 'f', 'e', 'e'],
['d', 'e', 'f', 'a', 'b', 'c'],
['d', 'e', 'f', 'a', 'g', 'c']], dtype=object)
def elementswap_getchildren(matrix):
height, width = matrix.shape
for i, j in [(i, j) for i in range(height) for j in range(width - 1) if (matrix[i, j] != matrix[i, j + 1])]:
child = matrix.copy()
child[i, j], child[i, j + 1] = child[i, j + 1], child[i, j]
yield child
def bfs(initial, depth):
visited = set()
queue = [initial]
i, j, k, toggle = 0, 0, 0, 0
while queue:
node = queue.pop(0)
node_tuple = tuple(map(tuple, node))
if node_tuple not in visited:
visited.add(node_tuple)
if depth != 0:
for child in elementswap_getchildren(node):
queue.append(child)
i += 1
if toggle == 0:
k = i
depth -= 1
toggle = 1
j += 1
if j == k:
k = i
if depth != 0:
depth -= 1
return visited
start = time.time()
results = bfs(B, 3)
end = time.time()
print('Visited', len(results), 'positions')
print('This took', end - start, 'seconds')
</code></pre>
<p>Needles to say, most of the bottleneck is likely from the following areas that I have not been able to find a more optimal solution to:</p>
<ol>
<li>Using for loops instead of a vectorized way to do <code>a, b = b, a</code> but I haven't been able to figure out how to reduce that.</li>
<li>Having to use <code>copy()</code> on the argument 2D array for a temporary matrix every iteration of i*j. If I didn't use it inside the inner loop, each child wouldn't be swapping elements in the argument matrix (while keeping the argument matrix unchanged), but swapping elements in their earlier iterations, which is what I don't need.</li>
<li>The <code>queue</code> list in the BFS grows very big, about 50000 on depth 3. I'm not accessing it at all during operation, only pop()'ing it. It may be something I cannot implement differently due to it being essential to BFS.</li>
</ol>
<p>Another thing to point out is, I intend to give each unique board state, that is found before the max depth, a score/value depending on certain combinations of characters present. This will increase overhead, as well as reduce number of branches, because they do not need to be investigated further. But I refrain from complicating this problem before the tree search can't be further optimized.</p>
<p>This is my first time actually coding something this performance/optimization orientated, so I am simply stuck due to inexperience and lack of knowledge in further optimization.</p>
<p>Any help or pointers are welcome, as well as suggesting a completely different approach.</p>
|
[] |
[
{
"body": "<p>I have not completely thought this through but noticed that the swaps only occur in rows. Could you do this first row-by-row, recording the depth somehow, and then combine these row results with filtering out those with cumulative depth greater than the required depth?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T21:24:49.323",
"Id": "480052",
"Score": "0",
"body": "I can see how looking at the problem at a row-by-row basis would remove the need of copying of the whole matrix (I could just do copy() on 1 row per each row). I will try to optimise that.\n\nHowever to do all the depth permutations in the swapping function, as you pointed out, I would need to record depth in a intricate manner while doing this, because the degree (depth) of swapping matters. I think to have a row permutation function and at the same time record the depth, I would have to know which is the parent position (-1 depth). Instead I have tried to delegate depth to the function BFS."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T17:20:34.483",
"Id": "244519",
"ParentId": "244278",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T19:06:55.870",
"Id": "244278",
"Score": "4",
"Tags": [
"python",
"performance",
"numpy",
"matrix",
"breadth-first-search"
],
"Title": "Generating unique 2D numpy arrays with 2 adjacent row elements swapped while using BFS in Python"
}
|
244278
|
<p>I've been writing a little task manager in C++ in my spare time. It's also the first time I am posting here for a review, I hope someone can spot any mistakes.
There's still a lot to implement and optimise, but the idea is for this to be a task manager that optionally uses any platform-dependent threading API (otherwise can default to std::thread).</p>
<p>It works like this:</p>
<ul>
<li>Spawn N workers (where N is the specified concurrency)</li>
<li>Each worker pulls jobs from its own local queue</li>
<li>When the worker has no job available, it tries to steal from a random queue</li>
<li>Job dependencies work by resolving any child jobs first by waiting on the jobCount to be 1 (example #2, below)</li>
</ul>
<p>It's currently tested on Windows and Linux. What I'd like is to move to a lock-free queue at some point, as there seems to be a lot of contention with the current mechanism of job stealing.</p>
<p>Apologising in advance for the long post.</p>
<pre><code>#pragma once
#include <vector>
#include <atomic>
#include <algorithm>
#include <cstdlib>
#include <cassert>
#include <functional>
#include <algorithm>
#include <limits.h>
#include <memory.h>
#include <random>
#ifndef YATM_ENABLE_WORK_STEALING
#define YATM_ENABLE_WORK_STEALING (1u)
#endif // YATM_ENABLE_WORK_STEALING
#ifndef YATM_CACHE_LINE_SIZE
#define YATM_CACHE_LINE_SIZE (64u)
#endif // YATM_CACHE_SIZE
#ifndef YATM_DEFAULT_STACK_SIZE
#define YATM_DEFAULT_STACK_SIZE (1024u * 1024u)
#endif // YATM_DEFAULT_STACK_SIZE
#ifndef YATM_DEFAULT_JOB_SCRATCH_BUFFER_SIZE
#define YATM_DEFAULT_JOB_SCRATCH_BUFFER_SIZE (128u * 1024u)
#endif // YATM_DEFAULT_STACK_SIZE
#ifndef YATM_MAX_WORKER_MASK_STACK_DEPTH
#define YATM_MAX_WORKER_MASK_STACK_DEPTH (64u)
#endif // YATM_MAX_WORKER_MASK_STACK_DEPTH
#ifndef YATM_ASSERT
#define YATM_ASSERT(x) assert((x))
#endif // YATM_ASSERT
#ifndef YATM_TTY
#define YATM_TTY(x) std::cout << (x) << std::endl
#endif // YATM_TTY
#ifndef YATM_DEBUG
#ifdef _MSC_VER
#define YATM_DEBUG (_DEBUG)
#endif //_MSC_VER
#endif // YATM_DEBUG
// When STD_THREAD is defined, undef platform_specific.
#if YATM_STD_THREAD
#undef YATM_WIN64
#undef YATM_LINUX
#endif // YATM_STD_THREAD
#if YATM_WIN64
#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#elif YATM_LINUX
#include <unistd.h>
#elif YATM_STD_THREAD
#include <thread>
#include <condition_variable>
#include <atomic>
#include <chrono>
#endif // YATM_WIN64
#define YATM_USE_PTHREADS (YATM_LINUX)
#if YATM_USE_PTHREADS
#include <pthread.h>
#endif // YATM_USE_PTHREADS
// Some defaults for reserving space in the job queues
#ifndef YATM_DEFAULT_JOB_QUEUE_RESERVATION
#define YATM_DEFAULT_JOB_QUEUE_RESERVATION (1024u)
#endif // YATM_DEFAULT_JOB_QUEUE_RESERVATION
#ifndef YATM_DEFAULT_PENDING_JOB_QUEUE_RESERVATION
#define YATM_DEFAULT_PENDING_JOB_QUEUE_RESERVATION (128u)
#endif // YATM_DEFAULT_PENDING_JOB_QUEUE_RESERVATION
namespace yatm
{
static_assert(sizeof(void*) == 8, "Only 64bit platforms are currently supported");
// -----------------------------------------------------------------------------------------------
// std::bind wrapped, used specifically for the job callbacks.
// -----------------------------------------------------------------------------------------------
template<typename Fx, typename... Args>
static auto bind(Fx&& _function, Args&&... _args)
{
return std::bind(std::forward<Fx>(_function), std::forward<Args>(_args)..., std::placeholders::_1);
}
// -----------------------------------------------------------------------------------------------
// Align input to the next specified alignment.
// -----------------------------------------------------------------------------------------------
static size_t align(size_t _value, size_t _align)
{
return (_value + (_align - 1)) & ~(_align - 1);
}
// -----------------------------------------------------------------------------------------------
// Align pointer to the next specified alignment.
// -----------------------------------------------------------------------------------------------
static uint8_t* align_ptr(uint8_t* _ptr, size_t _align)
{
return (uint8_t*)align((size_t)_ptr, _align);
}
// -----------------------------------------------------------------------------------------------
// A representation of an OS mutex.
// -----------------------------------------------------------------------------------------------
class mutex
{
friend class condition_var;
public:
// -----------------------------------------------------------------------------------------------
mutex()
{
#if YATM_WIN64
InitializeCriticalSection(&m_cs);
#elif YATM_USE_PTHREADS
pthread_mutex_init(&m_pmtx, nullptr);
#endif // YATM_WIN64
}
// -----------------------------------------------------------------------------------------------
mutex(const mutex&) = delete;
mutex operator=(const mutex&) = delete;
// -----------------------------------------------------------------------------------------------
~mutex()
{
#if YATM_WIN64
DeleteCriticalSection(&m_cs);
#elif YATM_USE_PTHREADS
pthread_mutex_destroy(&m_pmtx);
#endif // YATM_WIN64
}
// -----------------------------------------------------------------------------------------------
// Lock the mutex, claiming ownership.
// -----------------------------------------------------------------------------------------------
void lock()
{
#if YATM_STD_THREAD
m_mutex.lock();
#elif YATM_WIN64
EnterCriticalSection(&m_cs);
#elif YATM_USE_PTHREADS
int32_t const errorCode = pthread_mutex_lock(&m_pmtx);
YATM_ASSERT(errorCode == 0);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Try to lock the mutex, returning true if it did.
// -----------------------------------------------------------------------------------------------
bool try_lock()
{
bool v = false;
#if YATM_STD_THREAD
v = m_mutex.try_lock();
#elif YATM_WIN64
v = TryEnterCriticalSection(&m_cs);
#elif YATM_USE_PTHREADS
v = (pthread_mutex_trylock(&m_pmtx) == 0);
#endif // YATM_STD_THREAD
return v;
}
// -----------------------------------------------------------------------------------------------
// Unlock the mutex, giving-up ownership.
// -----------------------------------------------------------------------------------------------
void unlock()
{
#if YATM_STD_THREAD
m_mutex.unlock();
#elif YATM_WIN64
LeaveCriticalSection(&m_cs);
#elif YATM_USE_PTHREADS
int32_t const errorCode = pthread_mutex_unlock(&m_pmtx);
YATM_ASSERT(errorCode == 0);
#endif // YATM_STD_THREAD
}
private:
#if YATM_STD_THREAD
std::mutex m_mutex;
#elif YATM_WIN64
CRITICAL_SECTION m_cs;
#elif YATM_USE_PTHREADS
pthread_mutex_t m_pmtx;
#endif // YATM_STD_THREAD
};
// -----------------------------------------------------------------------------------------------
// A scoped-lock mechanism for mutexes.
// -----------------------------------------------------------------------------------------------
template<typename T>
class scoped_lock
{
friend class condition_var;
public:
// -----------------------------------------------------------------------------------------------
scoped_lock(T* _mutex) : m_mutex(_mutex), m_locked(false)
{
lock();
}
// -----------------------------------------------------------------------------------------------
~scoped_lock()
{
unlock();
}
// -----------------------------------------------------------------------------------------------
scoped_lock(const scoped_lock&) = delete;
scoped_lock& operator=(const scoped_lock&) = delete;
// -----------------------------------------------------------------------------------------------
void lock()
{
if (!m_locked)
{
m_mutex->lock();
}
m_locked = true;
}
// -----------------------------------------------------------------------------------------------
void unlock()
{
if (m_locked)
{
m_mutex->unlock();
}
m_locked = false;
}
private:
bool m_locked;
T* m_mutex;
};
// -----------------------------------------------------------------------------------------------
// A representation of an OS condition variable.
// -----------------------------------------------------------------------------------------------
class condition_var
{
public:
// -----------------------------------------------------------------------------------------------
condition_var()
{
#if YATM_WIN64
InitializeConditionVariable(&m_cv);
#elif YATM_USE_PTHREADS
pthread_cond_init(&m_cv, nullptr);
#endif // YATM_WIN64
}
// -----------------------------------------------------------------------------------------------
~condition_var()
{
#if YATM_WIN64
#elif YATM_USE_PTHREADS
pthread_cond_destroy(&m_cv);
#endif // YATM_WIN64
}
// -----------------------------------------------------------------------------------------------
condition_var(const condition_var&) = delete;
condition_var& operator=(const condition_var&) = delete;
// -----------------------------------------------------------------------------------------------
// Notify all threads waiting on this condition variable.
// -----------------------------------------------------------------------------------------------
void notify_all()
{
#if YATM_STD_THREAD
m_cv.notify_all();
#elif YATM_WIN64
WakeAllConditionVariable(&m_cv);
#elif YATM_USE_PTHREADS
pthread_cond_broadcast(&m_cv);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Notify a thread waiting on this condition variable.
// -----------------------------------------------------------------------------------------------
void notify_one()
{
#if YATM_STD_THREAD
m_cv.notify_one();
#elif YATM_WIN64
WakeConditionVariable(&m_cv);
#elif YATM_USE_PTHREADS
pthread_cond_signal(&m_cv);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Wait on this condition variable.
// -----------------------------------------------------------------------------------------------
template<typename Condition>
void wait(mutex& _lock, const Condition& _condition)
{
#if YATM_STD_THREAD
m_cv.wait(_lock, _condition);
#elif YATM_WIN64
while (!_condition())
{
SleepConditionVariableCS(&m_cv, &_lock.m_cs, INFINITE);
}
#elif YATM_USE_PTHREADS
while (!_condition())
{
pthread_cond_wait(&m_cv, &_lock.m_pmtx);
}
#endif // YATM_STD_THREAD
}
private:
#if YATM_STD_THREAD
std::condition_variable_any m_cv;
#elif YATM_WIN64
CONDITION_VARIABLE m_cv;
#elif YATM_USE_PTHREADS
pthread_cond_t m_cv;
#endif // YATM_STD_THREAD
};
// -----------------------------------------------------------------------------------------------
// An atomic counter used for synchronisation.
// -----------------------------------------------------------------------------------------------
class counter
{
public:
// -----------------------------------------------------------------------------------------------
counter() : m_value(0u) { }
// -----------------------------------------------------------------------------------------------
counter(const counter&) = delete;
counter& operator=(const counter&) = delete;
// -----------------------------------------------------------------------------------------------
// Checks if the internal atomic counter has reached 0.
// -----------------------------------------------------------------------------------------------
bool is_done()
{
uint32_t expected = 0u;
#if YATM_STD_THREAD || YATM_USE_PTHREADS
return m_value.compare_exchange_weak(expected, get_current());
#elif YATM_WIN64
return get_current() == expected;
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Checks the internal atomic counter for quality.
// -----------------------------------------------------------------------------------------------
bool is_equal(uint32_t _value)
{
#if YATM_STD_THREAD || YATM_USE_PTHREADS
return m_value.compare_exchange_weak(_value, get_current());
#elif YATM_WIN64
return get_current() == _value;
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Increment the internal atomic counter and return its value.
// -----------------------------------------------------------------------------------------------
uint32_t increment()
{
YATM_ASSERT(get_current() < UINT_MAX);
#if YATM_STD_THREAD || YATM_USE_PTHREADS
return ++m_value;
#elif YATM_WIN64
return InterlockedIncrement(&m_value);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Decrement the internal atomic counter and return its value.
// -----------------------------------------------------------------------------------------------
uint32_t decrement()
{
YATM_ASSERT(get_current() != 0);
#if YATM_STD_THREAD || YATM_USE_PTHREADS
return --m_value;
#elif YATM_WIN64
return InterlockedDecrement(&m_value);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Returns the current value of the internal atomic counter.
// -----------------------------------------------------------------------------------------------
uint32_t get_current()
{
#if YATM_STD_THREAD || YATM_USE_PTHREADS
return m_value.load();
#elif YATM_WIN64
return InterlockedCompareExchange(&m_value, 0, 0);
#endif // YATM_STD_THREAD
}
private:
#if YATM_STD_THREAD || YATM_USE_PTHREADS
std::atomic_uint32_t m_value;
#elif YATM_WIN64
LONG m_value;
#endif // YATM_STD_THREAD
};
// -----------------------------------------------------------------------------------------------
// Describes a job that the scheduler can run.
// -----------------------------------------------------------------------------------------------
struct alignas(YATM_CACHE_LINE_SIZE) job
{
using JobFuncPtr = std::function<void(void* const)>;
JobFuncPtr m_function;
void* m_data;
counter* m_counter;
job* m_parent;
uint32_t m_workerMask;
counter m_pendingJobs;
};
// -----------------------------------------------------------------------------------------------
// A representation of an OS thread.
// -----------------------------------------------------------------------------------------------
class thread
{
typedef void(*ThreadEntryPoint)(void*);
public:
// -----------------------------------------------------------------------------------------------
thread()
:
m_stackSizeInBytes(0),
m_index(0)
#if YATM_WIN64
, m_handle(nullptr)
#endif // YATM_WIN64
{
}
// -----------------------------------------------------------------------------------------------
~thread()
{
#if YATM_WIN64
if (m_handle != nullptr)
{
TerminateThread(m_handle, 0u);
}
#elif YATM_USE_PTHREADS
pthread_exit(nullptr);
#endif // YATM_WIN64
}
// -----------------------------------------------------------------------------------------------
thread(const thread&) = delete;
thread& operator=(const thread&) = delete;
// -----------------------------------------------------------------------------------------------
void create(uint32_t _index, size_t _stackSizeInBytes, ThreadEntryPoint _function, void* const _data)
{
m_index = _index;
m_stackSizeInBytes = _stackSizeInBytes;
#if YATM_STD_THREAD
m_thread = std::thread(_function, _data);
#elif YATM_WIN64
m_handle = CreateThread(nullptr, m_stackSizeInBytes, (LPTHREAD_START_ROUTINE)_function, _data, 0, &m_threadId);
YATM_ASSERT(m_handle != nullptr);
#elif YATM_USE_PTHREADS
m_threadId = _index;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setstacksize (&attr, m_stackSizeInBytes);
int32_t const errorCode = pthread_create(&m_thread, &attr, (void*(*)(void*))_function, _data);
YATM_ASSERT(errorCode == 0);
pthread_attr_destroy(&attr);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
void join()
{
#if YATM_STD_THREAD
YATM_ASSERT(m_thread.joinable());
m_thread.join();
#elif YATM_WIN64
WaitForSingleObject(m_handle, INFINITE);
#elif YATM_USE_PTHREADS
pthread_join(m_thread, nullptr);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Get the thread worker index.
// -----------------------------------------------------------------------------------------------
uint32_t get_index() const { return m_index; }
// -----------------------------------------------------------------------------------------------
// Get the OS thread index.
// -----------------------------------------------------------------------------------------------
size_t get_id() const
{
#if YATM_STD_THREAD
std::hash<std::thread::id> h;
return h(m_thread.get_id());
#elif YATM_WIN64
#if YATM_DEBUG
DWORD h = GetThreadId(m_handle);
YATM_ASSERT(h == m_threadId);
#endif // YATM_DEBUG
return (size_t)m_threadId;
#elif YATM_LINUX
return m_threadId;
#endif // YATM_STD_THREAD
}
private:
#if YATM_STD_THREAD
std::thread m_thread;
#elif YATM_WIN64
HANDLE m_handle;
DWORD m_threadId;
#elif YATM_USE_PTHREADS
pthread_t m_thread;
uint32_t m_threadId;
#endif // YATM_STD_THREAD
size_t m_stackSizeInBytes;
uint32_t m_index;
};
// -----------------------------------------------------------------------------------------------
// A description for the scheduler to create the worker threads.
// -----------------------------------------------------------------------------------------------
struct scheduler_desc
{
uint32_t* m_threadIds; // Thread IDs, used to bind jobs to group of threads. Size must match m_numThreads and is initialised to defaults if not specified.
uint32_t m_numThreads; // How many threads to use.
uint32_t m_stackSizeInBytes = YATM_DEFAULT_STACK_SIZE; // Stack size in bytes of each thread (unsupported in YATM_STD_THREAD).
uint32_t m_jobScratchBufferInBytes = YATM_DEFAULT_JOB_SCRATCH_BUFFER_SIZE; // Size in bytes of the internal scratch allocator. This is used to allocate jobs and job data.
uint32_t m_jobQueueReservation = YATM_DEFAULT_JOB_QUEUE_RESERVATION; // How many jobs to reserve in the job vector.
uint32_t m_pendingJobQueueReservation = YATM_DEFAULT_PENDING_JOB_QUEUE_RESERVATION; // How many jobs to reserve in the pending job vector (jobs waiting to be kicked).
};
// -----------------------------------------------------------------------------------------------
// A queue containing jobs to be processed.
// -----------------------------------------------------------------------------------------------
class job_queue
{
public:
job_queue()
{
}
~job_queue()
{
m_queue.clear();
}
// -----------------------------------------------------------------------------------------------
// Lock this queue mutex.
// -----------------------------------------------------------------------------------------------
void lock()
{
m_mutex.lock();
}
// -----------------------------------------------------------------------------------------------
// Attempt to lock this queue mutex.
// -----------------------------------------------------------------------------------------------
bool try_lock()
{
return m_mutex.try_lock();
}
// -----------------------------------------------------------------------------------------------
// Unlock this queue mutex.
// -----------------------------------------------------------------------------------------------
void unlock()
{
m_mutex.unlock();
}
// -----------------------------------------------------------------------------------------------
// Notify the condition variable.
// -----------------------------------------------------------------------------------------------
void notify()
{
m_cv.notify_one();
}
// -----------------------------------------------------------------------------------------------
// Reserve N jobs for this queue.
// -----------------------------------------------------------------------------------------------
void reserve(size_t _size)
{
m_queue.reserve(_size);
}
// -----------------------------------------------------------------------------------------------
// Get the job at the specified index and remove it from the queue.
// -----------------------------------------------------------------------------------------------
job* const get_job(uint32_t _index)
{
YATM_ASSERT(_index < size());
job* const j = m_queue[_index];
m_queue.erase(m_queue.begin() + _index);
return j;
}
// -----------------------------------------------------------------------------------------------
// Get the job at the specified index and remove it from the queue. Similar to get_job, but this time the workerMask is checked against the desired worker index.
// -----------------------------------------------------------------------------------------------
job* const get_job(uint32_t _index, uint32_t _workerIndex)
{
YATM_ASSERT(_index < size());
job* const j = m_queue[_index];
if ( (j->m_workerMask & (1u << _workerIndex)) != 0)
{
m_queue.erase(m_queue.begin() + _index);
return j;
}
return nullptr;
}
// -----------------------------------------------------------------------------------------------
// Get the job at the specified index, but do not remove it from the queue.
// -----------------------------------------------------------------------------------------------
job* const peek_job(uint32_t _index) const
{
YATM_ASSERT(_index < size());
return m_queue[_index];
}
// -----------------------------------------------------------------------------------------------
// Push a job to the queue.
// -----------------------------------------------------------------------------------------------
void push_back(job* const _job)
{
m_queue.push_back(_job);
}
// -----------------------------------------------------------------------------------------------
// Perform work stealing from candidate queues.
// -----------------------------------------------------------------------------------------------
void steal(job_queue* _candidates, uint32_t _size)
{
#if YATM_ENABLE_WORK_STEALING
// If the queue job count is 0, then we can attempt to steal from another queue.
if (empty())
{
for (uint32_t i = 0; i < _size; ++i)
{
job_queue& otherQueue = _candidates[i];
// Skip empty queues and same index
if ((&otherQueue == this) || (_candidates[i].empty()))
{
continue;
}
// Find a compatible job for this queue.
otherQueue.lock();
job* stolen_job = nullptr;
uint32_t jobIndex = 0u;
if (!otherQueue.empty())
{
do
{
stolen_job = otherQueue.get_job(jobIndex, i);
} while ((stolen_job == nullptr) && (jobIndex++ < otherQueue.size()));
}
otherQueue.unlock();
if (stolen_job != nullptr)
{
push_back(stolen_job);
break;
}
}
}
#endif // YATM_ENABLE_WORK_STEALING
}
// -----------------------------------------------------------------------------------------------
// Get the current size of the queue.
// -----------------------------------------------------------------------------------------------
size_t size() const
{
return m_queue.size();
}
// -----------------------------------------------------------------------------------------------
// Check if the queue is empty or not.
// -----------------------------------------------------------------------------------------------
bool empty() const
{
return size() == 0;
}
// -----------------------------------------------------------------------------------------------
// Wait until the condition is fulfilled.
// -----------------------------------------------------------------------------------------------
template<typename T>
void wait(T _predicate)
{
m_cv.wait(m_mutex, _predicate);
}
private:
std::vector<job*> m_queue;
mutex m_mutex;
condition_var m_cv;
};
// -----------------------------------------------------------------------------------------------
// The task scheduler, used to dispatch tasks for consumption by the worker threads.
// -----------------------------------------------------------------------------------------------
class scheduler
{
private:
// -----------------------------------------------------------------------------------------------
// Used to pass in data when the workers are initialised.
// -----------------------------------------------------------------------------------------------
struct worker_thread_data
{
yatm::scheduler* m_scheduler;
uint32_t m_id;
};
// -----------------------------------------------------------------------------------------------
// Worker internal
// -----------------------------------------------------------------------------------------------
bool worker_internal(job* _job)
{
if (_job != nullptr)
{
// process job
if (_job->m_function != nullptr)
{
_job->m_function(_job->m_data);
}
// decrement the counter
if (_job->m_counter != nullptr)
{
_job->m_counter->decrement();
}
// Finish job, notifying parents recursively.
finish_job(_job);
}
else
{
// No jobs, simply yield.
yield();
}
return (_job != nullptr);
}
// -----------------------------------------------------------------------------------------------
// Get the next available compatible job and remove it from the queue.
// -----------------------------------------------------------------------------------------------
job* get_next_job(uint32_t _index)
{
job* current_job = nullptr;
job_queue& queue = m_queues[_index];
// Find the next job ready to be processed
for (uint32_t i = 0; i < queue.size(); ++i)
{
job* const j = queue.peek_job(i);
// Can this job be processed by this worker thread?
if (j->m_workerMask & (1u << _index))
{
// This job has 1 remaining task, which means that all its dependencies have been processed.
// Pick this task, removing it from the job queue.
if (j->m_pendingJobs.is_equal(1u))
{
current_job = queue.get_job(i);
break;
}
}
}
return current_job;
}
// -----------------------------------------------------------------------------------------------
// Worker entry point; pulls jobs from the global queue and processes them.
// -----------------------------------------------------------------------------------------------
void worker_entry_point(uint32_t _index)
{
while (m_isRunning)
{
YATM_ASSERT(_index < m_queueCount);
job_queue& queue = m_queues[_index];
job* current_job = nullptr;
{
queue.lock();
queue.steal(m_queues, m_queueCount);
// Wait for this thread to be woken up by the condition variable (there must be at least 1 job in the queue, or perhaps we want to simply stop)
queue.wait([this, &queue] { return !is_paused() && ((queue.size() > 0u) || !is_running()); });
current_job = get_next_job(_index);
queue.unlock();
}
worker_internal(current_job);
}
#if YATM_USE_PTHREADS
pthread_exit(nullptr);
#endif // YATM_USE_PTHREADS
}
public:
// -----------------------------------------------------------------------------------------------
scheduler() :
m_threads(nullptr), m_scratch(nullptr), m_currentWorkerMaskDepth(0u)
{
memset((void*)m_currentWorkerMasks, ~0u, sizeof(uint32_t) * YATM_MAX_WORKER_MASK_STACK_DEPTH);
#if YATM_STD_THREAD
m_hwConcurency = std::thread::hardware_concurrency();
#elif YATM_WIN64
SYSTEM_INFO info;
ZeroMemory(&info, sizeof(info));
GetSystemInfo(&info);
m_hwConcurency = info.dwNumberOfProcessors;
#elif YATM_LINUX
m_hwConcurency = sysconf(_SC_NPROCESSORS_CONF);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
virtual ~scheduler()
{
set_running(false);
// wait for workers to finish
join();
// free thread data array
delete[] m_threadData;
m_threadData = nullptr;
// free the thread array
delete[] m_threads;
m_threads = nullptr;
// free the scratch allocator
delete m_scratch;
m_scratch = nullptr;
delete[] m_queues;
}
// -----------------------------------------------------------------------------------------------
scheduler(const scheduler&) = delete;
scheduler& operator=(const scheduler&) = delete;
// -----------------------------------------------------------------------------------------------
// Initialise the scheduler.
// -----------------------------------------------------------------------------------------------
void init(const scheduler_desc& _desc)
{
m_numThreads = std::max(1u, std::min<uint32_t>(_desc.m_numThreads, get_max_threads()));
m_threadData = new worker_thread_data[m_numThreads];
for (uint32_t i = 0; i < m_numThreads; ++i)
{
m_threadData[i].m_scheduler = this;
// Optinally copy custom worker ids (these will be used bitmasks when picking a worker for each job).
m_threadData[i].m_id = (_desc.m_threadIds == nullptr) ? i : _desc.m_threadIds[i];
}
m_queueCount = m_numThreads;
m_queues = new job_queue[m_queueCount];
#if YATM_STD_THREAD
YATM_TTY("yatm is using std::thread, configurable stack size is not allowed");
#endif // YATM_STD_THREAD
m_stackSizeInBytes = align(_desc.m_stackSizeInBytes > 0 ? _desc.m_stackSizeInBytes : YATM_DEFAULT_STACK_SIZE, 16u);
m_threads = new thread[m_numThreads];
m_scratch = new scratch( align(_desc.m_jobScratchBufferInBytes, 16u), 16u);
// reserve some space in the global job queue
for (uint32_t i = 0; i < m_queueCount; ++i)
{
m_queues[i].reserve(_desc.m_jobQueueReservation);
}
// reserve some space in the currently pending job queue
m_pendingJobsToAdd.reserve(_desc.m_pendingJobQueueReservation);
// enable the scheduler and let its workers run
set_running(true);
set_paused(false);
// Create N worker threads and kick them off.
// Each worker will process the next available job item from the global queue, resolve its dependencies and carry on until no jobs are left.
for (uint32_t i = 0; i < m_numThreads; ++i)
{
auto func = [](void* data) -> void
{
worker_thread_data* d = reinterpret_cast<worker_thread_data*>(data);
d->m_scheduler->worker_entry_point(d->m_id);
};
m_threads[i].create(i, m_stackSizeInBytes, func, &m_threadData[i]);
}
}
// -----------------------------------------------------------------------------------------------
// Resets the internal scratch allocator.
// -----------------------------------------------------------------------------------------------
void reset()
{
YATM_ASSERT(m_scratch != nullptr);
m_scratch->reset();
}
// -----------------------------------------------------------------------------------------------
// Push a new worker mask depth, subsequent job allocations will be set to run on the specified workers.
// -----------------------------------------------------------------------------------------------
void push_worker_mask(uint32_t _workerMask)
{
YATM_ASSERT(m_currentWorkerMaskDepth < YATM_MAX_WORKER_MASK_STACK_DEPTH);
m_currentWorkerMasks[++m_currentWorkerMaskDepth] = _workerMask;
}
// -----------------------------------------------------------------------------------------------
// Pop worker mask depth.
// -----------------------------------------------------------------------------------------------
void pop_worker_mask()
{
YATM_ASSERT(m_currentWorkerMaskDepth > 0);
--m_currentWorkerMaskDepth;
}
// -----------------------------------------------------------------------------------------------
// Create a job from the scheduler scratch allocator.
// -----------------------------------------------------------------------------------------------
template<typename Function>
job* const create_job(const Function& _function, void* const _data, counter* _counter)
{
job* const j = allocate<job>();
j->m_function = _function;
j->m_data = _data;
j->m_parent = nullptr;
j->m_counter = _counter;
j->m_workerMask = m_currentWorkerMasks[m_currentWorkerMaskDepth];
// Initialise the job with 1 pending job (itself).
// Adding dependencies increments the pending counter, resolving dependencies decrements it.
j->m_pendingJobs.increment();
// Register this newly created job; all jobs are automatically added when the scheduler kicks-off the tasks.
scoped_lock<mutex> lock(&m_pendingJobsMutex);
m_pendingJobsToAdd.push_back(j);
return j;
}
// -----------------------------------------------------------------------------------------------
// Create a group from the scheduler scratch allocator. A group is simply a job without any work to be done, used as a dependency in other
// jobs to create a hierarchy of tasks.
// -----------------------------------------------------------------------------------------------
job* const create_group(job* const _parent = nullptr)
{
job* const group = create_job(nullptr, nullptr, nullptr);
// If a parent is specified, setup this dependency
if (_parent != nullptr)
{
depend(_parent, group);
}
return group;
}
// -----------------------------------------------------------------------------------------------
// Allocate a temporary array using the scheduler scratch allocator.
// -----------------------------------------------------------------------------------------------
template<typename T>
T* allocate(size_t _count, size_t _alignment = 16u)
{
uint8_t* mem = m_scratch->alloc(sizeof(T) * _count, _alignment);
return new(mem) T[_count];
}
// -----------------------------------------------------------------------------------------------
// Allocate a temporary object using the scheduler scratch allocator.
// -----------------------------------------------------------------------------------------------
template<typename T>
T* allocate(size_t _alignment = 16u)
{
uint8_t* mem = m_scratch->alloc(sizeof(T), _alignment);
T* obj = new(mem) T();
return obj;
}
// -----------------------------------------------------------------------------------------------
// Adds a job dependency on the specified job.
// -----------------------------------------------------------------------------------------------
void depend(job* const _target, job* const _dependency)
{
YATM_ASSERT(_dependency->m_parent == nullptr);
_dependency->m_parent = _target;
_target->m_pendingJobs.increment();
}
// -----------------------------------------------------------------------------------------------
// Creates a parallel for loop for the specified collection, launching _function per iteration.
// Blocks until all are complete.
// -----------------------------------------------------------------------------------------------
template<typename Iterator, typename Function>
void parallel_for(const Iterator& _begin, const Iterator& _end, const Function& _function)
{
const size_t n = std::distance(_begin, _end);
if (n > 0)
{
// When there is only 1 job, don't pass it through the scheduler.
if (n == 1)
{
_function(&(*(_begin)));
}
else
{
counter jobs_done;
for (uint32_t i = 0; i < n; ++i)
{
job* j = create_job(_function, &(*(_begin + i)), &jobs_done);
}
kick();
wait(&jobs_done);
}
}
}
// -----------------------------------------------------------------------------------------------
// Signal the worker threads that work has been added.
// -----------------------------------------------------------------------------------------------
void kick()
{
// Add the pending jobs to the global job queue and notify the worker threads that work has been added.
{
scoped_lock<mutex> lock(&m_pendingJobsMutex);
#if YATM_DEBUG
verify_job_graph();
#endif // YATM_DEBUG
for (auto& job : m_pendingJobsToAdd)
{
// Verify that the job and its data is allocated from scratch buffer.
YATM_ASSERT(m_scratch->is_from(job));
add_job(job);
}
m_pendingJobsToAdd.clear();
}
for (uint32_t i = 0; i < m_queueCount; ++i)
{
m_queues[i].notify();
}
}
// -----------------------------------------------------------------------------------------------
// Try to process the job on a compatible worker thread.
// -----------------------------------------------------------------------------------------------
void process_single_job()
{
uint32_t const index = get_random_queue_index();
// Find compatible job to process
if (m_queues[index].try_lock())
{
job* current_job = get_next_job(index);
m_queues[index].unlock();
worker_internal(current_job);
}
yield();
}
// -----------------------------------------------------------------------------------------------
// Wait for a single job to complete. In the meantime, try to process one pending job.
// -----------------------------------------------------------------------------------------------
void wait(job* const _job)
{
YATM_ASSERT(_job != nullptr);
while (!_job->m_pendingJobs.is_done())
{
process_single_job();
}
}
// -----------------------------------------------------------------------------------------------
// Wait for a counter to reach 0. In the meantime, try to process one pending job.
// -----------------------------------------------------------------------------------------------
void wait(counter* const _counter)
{
YATM_ASSERT(_counter != nullptr);
while (!_counter->is_done())
{
// Process jobs while waiting
process_single_job();
}
}
// -----------------------------------------------------------------------------------------------
// Yield the current thread and allow others to execute.
// -----------------------------------------------------------------------------------------------
void yield()
{
#if YATM_STD_THREAD
std::this_thread::yield();
#elif YATM_WIN64
SwitchToThread();
#elif YATM_USE_PTHREADS
pthread_yield();
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Return the maximum number of worker threads.
// -----------------------------------------------------------------------------------------------
uint32_t get_max_threads() const { return m_hwConcurency; }
// -----------------------------------------------------------------------------------------------
// Check if the scheduler is running worker functions.
// -----------------------------------------------------------------------------------------------
bool is_running() const { return m_isRunning; }
// -----------------------------------------------------------------------------------------------
// Stop the scheduler from processing, effectively shutting it down.
// -----------------------------------------------------------------------------------------------
void set_running(bool _running)
{
m_isRunning = _running;
for (uint32_t i = 0; i < m_queueCount; ++i)
{
m_queues[i].notify();
}
}
// -----------------------------------------------------------------------------------------------
// Check if the scheduler is paused.
// -----------------------------------------------------------------------------------------------
bool is_paused() const { return m_isPaused; }
// -----------------------------------------------------------------------------------------------
// Set the paused status of the scheduler. Worker threads will not process anything until status is resumed.
// -----------------------------------------------------------------------------------------------
void set_paused(bool _paused)
{
m_isPaused = _paused;
for (uint32_t i = 0; i < m_queueCount; ++i)
{
m_queues[i].notify();
}
}
// -----------------------------------------------------------------------------------------------
// Allow the current thread to sleep for specified duration in ms.
// -----------------------------------------------------------------------------------------------
void sleep(uint32_t ms)
{
#if YATM_STD_THREAD
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
#elif YATM_WIN64
Sleep(ms);
#elif YATM_LINUX
usleep(ms * 1000);
#endif // YATM_STD_THREAD
}
// -----------------------------------------------------------------------------------------------
// Wait for all the worker threads to stop executing, block the main thread.
// -----------------------------------------------------------------------------------------------
void join()
{
YATM_ASSERT(m_threads != nullptr);
for (uint32_t i = 0; i < m_numThreads; ++i)
{
m_threads[i].join();
}
}
private:
mutex m_pendingJobsMutex;
size_t m_stackSizeInBytes;
uint32_t m_hwConcurency;
uint32_t m_currentWorkerMasks[YATM_MAX_WORKER_MASK_STACK_DEPTH];
uint32_t m_currentWorkerMaskDepth;
uint32_t m_numThreads;
uint32_t m_queueCount;
worker_thread_data* m_threadData;
bool m_isRunning;
bool m_isPaused;
thread* m_threads;
job_queue* m_queues;
std::vector<job*> m_pendingJobsToAdd;
#if YATM_DEBUG
// -----------------------------------------------------------------------------------------------
// Verify the job graph.
// -----------------------------------------------------------------------------------------------
void verify_job_graph()
{
}
#endif // YATM_DEBUG
// -----------------------------------------------------------------------------------------------
// Get a random queue index
// -----------------------------------------------------------------------------------------------
uint32_t get_random_queue_index() const
{
uint32_t const index = std::rand() % m_queueCount;
return index;
}
// -----------------------------------------------------------------------------------------------
// Get a random queue.
// -----------------------------------------------------------------------------------------------
job_queue& get_random_queue()
{
uint32_t const index = get_random_queue_index();
return m_queues[index];
}
// -----------------------------------------------------------------------------------------------
// Adds a single job item to the scheduler. Assumes the caller ensures thread safety.
// -----------------------------------------------------------------------------------------------
void add_job(job* const _job)
{
YATM_ASSERT(_job != nullptr);
if (_job->m_counter != nullptr)
{
_job->m_counter->increment();
}
get_random_queue().push_back(_job);
}
// -----------------------------------------------------------------------------------------------
// Mark this job as finished by decrementing the pendingJobs counter and inform its parents recursively.
// -----------------------------------------------------------------------------------------------
void finish_job(job* const _job)
{
if (_job != nullptr)
{
const uint32_t p = _job->m_pendingJobs.decrement();
// If this job has finished, inform its parent.
if (p == 0)
{
finish_job(_job->m_parent);
}
}
}
// -----------------------------------------------------------------------------------------------
// A scratch allocator to handle data and job allocations.
// -----------------------------------------------------------------------------------------------
class scratch
{
public:
// -----------------------------------------------------------------------------------------------
scratch(size_t _sizeInBytes, size_t _alignment)
: m_sizeInBytes(_sizeInBytes), m_alignment(_alignment), m_begin(nullptr), m_end(nullptr), m_current(nullptr)
{
YATM_ASSERT(is_pow2(m_alignment));
m_begin = (uint8_t*)aligned_alloc(m_sizeInBytes, m_alignment);
YATM_ASSERT(m_begin != nullptr);
m_end = m_begin + m_sizeInBytes;
m_current = m_begin;
}
scratch(const scratch&) = delete;
scratch& operator=(const scratch&) = delete;
// -----------------------------------------------------------------------------------------------
~scratch()
{
if (m_begin != nullptr)
{
aligned_free(m_begin);
}
}
// -----------------------------------------------------------------------------------------------
// Reset the scratch current pointer.
// -----------------------------------------------------------------------------------------------
void reset()
{
m_current = m_begin;
}
// -----------------------------------------------------------------------------------------------
// Return the current (aligned) address of the scratch allocator and increment the pointer.
// -----------------------------------------------------------------------------------------------
uint8_t* alloc(size_t _size, size_t _align)
{
YATM_ASSERT(is_pow2(_align));
scoped_lock<mutex> lock(&m_mutex);
m_current = align_ptr(m_current, _align);
YATM_ASSERT(m_current + _size < m_end);
uint8_t* mem = m_current;
m_current += _size;
#if YATM_DEBUG
memset(mem, 0xbabababa, _size);
#endif // YATM_DEBUG
return mem;
}
// -----------------------------------------------------------------------------------------------
// Checks if the input pointer is within the scratch allocator's memory boundaries.
// -----------------------------------------------------------------------------------------------
bool is_from(void* _ptr)
{
const uint8_t* ptr = reinterpret_cast<const uint8_t*>(_ptr);
return (ptr >= m_begin && ptr < m_end);
}
private:
mutex m_mutex;
uint8_t* m_begin;
uint8_t* m_end;
uint8_t* m_current;
size_t m_sizeInBytes;
size_t m_alignment;
// -----------------------------------------------------------------------------------------------
// Checks if the input is a power of two.
// -----------------------------------------------------------------------------------------------
bool is_pow2(size_t _n)
{
return (_n & (_n - 1)) == 0;
}
public:
// -----------------------------------------------------------------------------------------------
// A portable aligned allocation mechanism.
//
// Thanks to: https://gist.github.com/dblalock/255e76195676daa5cbc57b9b36d1c99a
// -----------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------
void* aligned_alloc(size_t _size, size_t _alignment)
{
YATM_ASSERT(_alignment < UINT8_MAX);
// over-allocate using malloc and adjust pointer by the offset needed to align the memory to specified alignment
const size_t request_size = _size + _alignment;
uint8_t* buf = (uint8_t*)malloc(request_size);
// figure out how much we should offset our allocation by
const size_t remainder = ((size_t)buf) % _alignment;
const size_t offset = _alignment - remainder;
uint8_t* ret = buf + (uint8_t)offset;
// store how many extra bytes we allocated in the byte just before the pointer we return
*(uint8_t*)(ret - 1) = (uint8_t)offset;
return ret;
}
// -----------------------------------------------------------------------------------------------
void aligned_free(const void* const aligned_ptr)
{
// find the base allocation by extracting the stored aligned offset and free it
uint32_t offset = *(((uint8_t*)aligned_ptr) - 1);
free(((uint8_t*)aligned_ptr) - offset);
}
} *m_scratch;
};
}
</code></pre>
<p>Example usage #1:</p>
<pre><code>// -----------------------------------------------------------------------------------------------
void sample_parallel_for(yatm::scheduler& sch)
{
while (true)
{
sch.reset();
{
yatm::scoped_profiler profiler;
// Setup some data for processing
const uint32_t dataLength = 100u;
uint32_t uints[dataLength];
for (uint32_t i = 0; i < std::size(uints); i++)
{
uints[i] = i;
}
sch.push_worker_mask(~0u);
// Launch them in parallel:
// Creates as many tasks as the length of specified data, kicks them and blocks the caller thread until they are finished.
sch.parallel_for((uint32_t*)uints, (uint32_t*)uints + dataLength, [](void* const param)
{
uint32_t idx = *(uint32_t*)param;
// do some intensive work
const auto result = yatm::work(idx);
char t[64];
sprintf_fn(t, "Result for data %u: %ld\n", idx, result);
std::cout << t;
});
sch.pop_worker_mask();
}
sch.sleep(2000);
}
}
// -----------------------------------------------------------------------------------------------
int main()
{
yatm::scheduler sch;
yatm::init(sch);
sample_parallel_for(sch);
return 0;
}
</code></pre>
<p>Example usage #2</p>
<pre><code>// -----------------------------------------------------------------------------------------------
void sample_job_dependencies(yatm::scheduler& sch)
{
static uint32_t c_numChildTasks = 30; // group child tasks.
static uint32_t c_numIterations = ~0u; // -1 for infinite iterations
// Run for N iterations
uint32_t iter = 0u;
float averageMs = 0.0f;
while ((iter++ < c_numIterations) || (c_numIterations == ~0u))
{
sch.reset();
{
yatm::scoped_profiler profiler;
yatm::counter counter;
// Prepare the job graph
// This looks like this:
/*
[parent]
/ \
/ \
[group0] [group1]
/ \
/ \
[group0_job] [group1_job]
| |
| |
|---> child_0 |---> child_0
| .... | ...
|---> child_n |---> child_n
Expected result is the children of each [groupN_job] task to be executed first. When all of the dependencies of each [groupN_job] are resolved,
[groupN_job] will be executed. Once that happens, [groupN] is executed (being a simple group without a job function, it does nothing, simply used for grouping).
Once both [group0] and [group1] are finished, [parent] executes and the tasks are complete.
After [parent] is finished, sch.wait(parent) will unblock and main thread execution will continue.
An alternative way to wait for the tasks to finish is by using the yatm::counter object. This is atomically incremented when jobs that reference it are added to
the scheduler and decremented when jobs are finished. When the counter reached 0, it's assumed to be finished and sch.wait(&counter) will unblock the main thread.
*/
// Parent task depends on everything else below. This will be executed last.
yatm::job* const parent = sch.create_job
(
[](void* const data)
{
std::cout << "Parent, this should execute after all the groups have finished.\n";
}
,
nullptr,
&counter
);
// allocate data for the child tasks; they simply hold the loop index, but more complex structures can be used.
uint32_t* const data = sch.allocate<uint32_t>(c_numChildTasks, 16u);
// Make a few groups to put the children jobs under. Group0 will depend on children [0, N/2-1] and group1 will depend on children [N/2, N]
// Group0_job and group1_job will execute once their respective children have finished executing.
yatm::job* const group0 = sch.create_group(parent);
yatm::job* const group0_job = sch.create_job([](void* const data) { std::cout << "Group 0 job, executing after all child 0 are finished.\n"; }, nullptr, &counter);
sch.depend(group0, group0_job);
yatm::job* const group1 = sch.create_group(parent);
yatm::job* const group1_job = sch.create_job([](void* const data) { std::cout << "Group 1 job, executing after all child 1 are finished.\n"; }, nullptr, &counter);
sch.depend(group1, group1_job);
// Create child tasks
for (uint32_t i = 0; i < c_numChildTasks; ++i)
{
data[i] = i;
yatm::job* const child = sch.create_job
(
[](void* const data)
{
uint32_t idx = *(uint32_t*)data;
// do some intensive work
uint64_t result = yatm::work(idx);
const uint32_t group = idx < c_numChildTasks / 2 ? 0 : 1;
char str[512];
sprintf_fn(str, "Child %u (group %u). Children of groups should execute first, result: %ld.\n", idx, group, result);
std::cout << str;
},
&data[i],
&counter
);
if (i < c_numChildTasks / 2)
{
sch.depend(group0_job, child);
}
else
{
sch.depend(group1_job, child);
}
}
// Add the created tasks and signal the workers to begin processing them
sch.kick();
// Wait for finished tasks. Here we wait on the parent, as this will guarantee that all of the tasks will be complete.
sch.wait(parent);
// Or:
// sch.wait(&counter);
//
// The counter can also be only added on the parent (instead of all the tasks, as done above).
// Since the parent depends on all the other tasks, having the counter only on that single job is enough.
}
// Pause for a bit, resume after 1000ms
sch.set_paused(true);
sch.sleep(1000);
sch.set_paused(false);
}
sch.set_running(false);
sch.sleep(2000);
}
// -----------------------------------------------------------------------------------------------
int main()
{
yatm::scheduler sch;
yatm::init(sch);
sample_job_dependencies(sch);
return 0;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T19:33:09.290",
"Id": "244279",
"Score": "2",
"Tags": [
"c++",
"c++11",
"multithreading"
],
"Title": "C++ threaded task manager"
}
|
244279
|
<p>I'm posting my C++ code for LeetCode's LRU Cache. If you have time and would like to review, please do so. Thank you!</p>
<h3>Problem</h3>
<blockquote>
<ul>
<li><p>Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.</p>
</li>
<li><p>get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.</p>
</li>
<li><p>put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the
least recently used item before inserting a new item.</p>
</li>
<li><p>The cache is initialized with a positive capacity.</p>
</li>
</ul>
<p>Follow up:</p>
<ul>
<li>Could you do both operations in O(1) time complexity?</li>
</ul>
<h3>Example:</h3>
<pre><code>LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
</code></pre>
</blockquote>
<h3>Accepted C++</h3>
<pre><code>#include <list>
#include <unordered_map>
class LRUCache {
public:
const int size;
std::list<size_t> lru;
std::unordered_map<int, std::list<size_t>::iterator> cache;
std::unordered_map<int, int> key_val_map;
LRUCache(const int capacity) : size(capacity) {}
// Getter constant memory
int get(int key) {
if (key_val_map.count(key) == 0) {
return -1;
}
update(key);
return key_val_map[key];
}
// Setter constant memory
const void put(int key, int value) {
if (key_val_map.size() == size && key_val_map.count(key) == 0) {
clear();
}
update(key);
key_val_map[key] = value;
}
// Add a new key
const void update(int key) {
if (key_val_map.count(key)) {
lru.erase(cache[key]);
}
lru.push_front(key);
cache[key] = lru.begin();
}
// Erase cache
const void clear() {
key_val_map.erase(lru.back());
cache.erase(lru.back());
lru.pop_back();
}
};
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/lru-cache/" rel="nofollow noreferrer">146. LRU Cache - Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/lru-cache/discuss/" rel="nofollow noreferrer">146. LRU Cache - Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Use <code>size_t</code> for sizes</h1>\n<p>Although the LeetCode question specifies that the constructor takes an <code>int capacity</code>, using an <code>int</code> to hold a size is not appropriate for two reasons:</p>\n<ol>\n<li><code>int</code> might not be big enough to handle all possible sizes that fit into the available memory.</li>\n<li><code>int</code> is signed, and now you have to deal with potentially negative numbers.</li>\n</ol>\n<p>Also note that the standard library uses <code>size_t</code> for things like <code>.size()</code>, and the result of the <code>sizeof</code> operator is also a <code>size_t</code>. So it's best to internally store the capacity as a <code>size_t</code>. This will avoid compiler warnings about comparisons between signed and unsigned values.</p>\n<h1>Use types consistently</h1>\n<p>The one place you use <code>size_t</code> is in <code>std::list<size_t> lru</code>. But here, the list is actually holding keys. Everywhere else you write <code>int key</code>, so you should write <code>std::list<int> lru</code> here, otherwise your cache might not work correctly when using negative numbers for keys. The LeetCode question does not say whether or not negative <em>keys</em> are allowed, it only mentions only positive <em>values</em> are stored.</p>\n<h1>Make helper functions <code>private</code></h1>\n<p>Helper functions like <code>update()</code> and <code>clear()</code> are not part of the public API as specified by the LeetCode problem. So make them <code>private</code>.</p>\n<h1>Use proper names</h1>\n<p>The function <code>clear()</code>, despite its name and even the comment above it, does not erase the cache. Instead, it just removes the least recently used element. Make sure the name (and also the comment) reflects this. I would name it something like <code>pop_lru()</code>, or perhaps just <code>pop()</code>.</p>\n<p>Also, the name <code>update()</code> does not match the comment above it. I would remove the comment, and give a more descriptive name: <code>make_most_recent()</code>.</p>\n<h1>Useless use of <code>const</code></h1>\n<p>It does not make sense to have a function return <code>const void</code>. Just write <code>void</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T15:15:12.693",
"Id": "479660",
"Score": "0",
"body": "Ah, it seems the review was less impressive than you might have thought: I forgot that you need to move an entry in the middle of `lru` to the front. That's actually not O(1) with `std::deque`, although I don't know why it the `erase()` would throw an exception. I'll update the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T15:19:36.040",
"Id": "479662",
"Score": "1",
"body": "[Your changes](https://ideone.com/ZZJud5) look fine for the most part, but now you've changed the type of the key to `size_t`. You should keep using `int` for keys, since that is part of the API given by the LeetCode question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T13:57:07.383",
"Id": "244323",
"ParentId": "244281",
"Score": "4"
}
},
{
"body": "<p>You can use only one <code>unordered_map</code></p>\n<p>My solution:</p>\n<pre><code>class LRUCache {\npublic:\n LRUCache(int capacity) {\n size_ = capacity;\n }\n \n int get(int key) {\n auto it = m_.find(key);\n if (it == m_.end()) {\n return -1;\n }\n l_.splice(begin(l_), l_, it->second);\n return it->second->second;\n }\n \n void put(int key, int value) {\n auto it = m_.find(key);\n if (it != m_.end()) {\n l_.erase(it->second);\n }\n l_.push_front({key, value});\n m_[key] = l_.begin();\n if (m_.size() > size_) {\n int key_delete = l_.rbegin()->first;\n m_.erase(key_delete);\n l_.pop_back();\n }\n \n }\nprivate:\n int size_;\n list<pair<int, int>> l_; // key, val\n unordered_map<int, list<pair<int, int>>::iterator> m_;\n};\n\n/**\n * Your LRUCache object will be instantiated and called as such:\n * LRUCache* obj = new LRUCache(capacity);\n * int param_1 = obj->get(key);\n * obj->put(key,value);\n */\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T11:32:28.073",
"Id": "503379",
"Score": "0",
"body": "Nice use of `splice()`. I would avoid the single-letter variable names though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T10:49:33.580",
"Id": "255175",
"ParentId": "244281",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "244323",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T20:18:41.847",
"Id": "244281",
"Score": "6",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 146: LRU Cache I"
}
|
244281
|
<p>I am looking for a way to speed up my basic IP scanner/port scanner in Python 3.8.
My IP portion works, the port scan work, I just want to speed it up, in a format that someone learning python would understand.</p>
<pre><code>#testing scanner.py
import socket
import subprocess
import sys
from datetime import datetime
def scan():
# Ask for the IP address to scan, for this its a single IP
remoteServer = input("Enter a Starting IP: ")
remoteServerend = input("Enter the Ending IP: ")
print ("Starting Scan at: ",remoteServer)
print ("Ending Scan at: ",remoteServerend)
# change DNS to IPmail
#remoteServerIP = socket.gethostbyname(remoteServer)
#print ("remoteServerIP is ",remoteServerIP)
# Ask for starting port
startport = int(input("What port number do you want to start with? "))
# Ask for ending port
endport = int(input("What is the ending port number? "))
# Print 50 *'s to make a top border
print ("-" * 50)
# print wait here is the IP we are scanning
print ("Please wait, scanning remote host", remoteServer)
# print the bottom border
print ("-" * 50)
# Check what time the scan started
t1 = datetime.now()
# lets try the try statment for some error handeling and see if it can help?
try:
# trying our 1st port to our last port and replying if it is open, we don't care about closed ports
for port in range(startport,endport):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((remoteServer, port))
if result == 0:
print ("Port {}: Open".format(port))
sock.close()
# you got tied of waiting and quit
except KeyboardInterrupt:
print( "You pressed Ctrl+C")
sys.exit()
# failed DNS lookup
except socket.gaierror:
print( 'Hostname could not be resolved. Exiting')
sys.exit()
# no route to server?
except socket.error:
print( "Couldn't connect to server")
sys.exit()
# get ending time
t2 = datetime.now()
# calculate how long did the script run?
total = t2 - t1
# Printing the information to screen
print( 'Scanning Completed in: ', total)
scan()
</code></pre>
|
[] |
[
{
"body": "<h2>IP range</h2>\n<blockquote>\n<p>for this its a single IP</p>\n</blockquote>\n<p>It is? Then why do you ask for a range? Your 'end' is not used, so just delete it.</p>\n<h2>Fail-safe scanning</h2>\n<p>Consider rearranging this:</p>\n<pre><code>try:\n for port in range(startport,endport):\n</code></pre>\n<p>to:</p>\n<pre><code>for port in range(startport,endport):\n try:\n</code></pre>\n<p>In other words, some ports may fail and others may succeed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T20:50:25.950",
"Id": "244285",
"ParentId": "244282",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T20:37:21.410",
"Id": "244282",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "How to speed up this IP sweep, Port scanner python"
}
|
244282
|
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so.</p>
<h3>Problem</h3>
<blockquote>
<ul>
<li><p>Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.</p>
</li>
<li><p>get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.</p>
</li>
<li><p>put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the
least recently used item before inserting a new item.</p>
</li>
<li><p>The cache is initialized with a positive capacity.</p>
</li>
</ul>
<p>Follow up:</p>
<ul>
<li>Could you do both operations in O(1) time complexity?</li>
</ul>
<h3>Example:</h3>
<pre class="lang-cpp prettyprint-override"><code>LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
</code></pre>
</blockquote>
<h3>Accepted Python</h3>
<pre><code>class LRUCache:
def __init__(self, capacity: int) -> None:
self.cache = {}
self.capacity = capacity
self.next = {}
self.prev = {}
self.head = 'HEAD'
self.tail = 'TAIL'
self.connect(self.head, self.tail)
def connect(self, node_a: int, node_b: int) -> None:
self.next[node_a], self.prev[node_b] = node_b, node_a
def remove(self, key: int) -> None:
self.connect(self.prev[key], self.next[key])
del(self.prev[key], self.next[key], self.cache[key])
def append(self, key: int, val: int) -> None:
self.cache[key] = val
self.connect(self.prev[self.tail], key)
self.connect(key, self.tail)
if len(self.cache) > self.capacity:
self.remove(self.next[self.head])
def get(self, key: int) -> int:
if key not in self.cache:
return -1
val = self.cache[key]
self.remove(key)
self.append(key, val)
return val
def put(self, key: int, val: int) -> None:
if key in self.cache:
self.remove(key)
self.append(key, val)
</code></pre>
<h3>LeetCode's Solution (Not for review)</h3>
<pre><code>class DLinkedNode():
def __init__(self):
self.key = 0
self.value = 0
self.prev = None
self.next = None
class LRUCache():
def _add_node(self, node):
"""
Always add the new node right after head.
"""
node.prev = self.head
node.next = self.head.next
self.head.next.prev = node
self.head.next = node
def _remove_node(self, node):
"""
Remove an existing node from the linked list.
"""
prev = node.prev
new = node.next
prev.next = new
new.prev = prev
def _move_to_head(self, node):
"""
Move certain node in between to the head.
"""
self._remove_node(node)
self._add_node(node)
def _pop_tail(self):
"""
Pop the current tail.
"""
res = self.tail.prev
self._remove_node(res)
return res
def __init__(self, capacity):
"""
:type capacity: int
"""
self.cache = {}
self.size = 0
self.capacity = capacity
self.head, self.tail = DLinkedNode(), DLinkedNode()
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key):
"""
:type key: int
:rtype: int
"""
node = self.cache.get(key, None)
if not node:
return -1
# move the accessed node to the head;
self._move_to_head(node)
return node.value
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
node = self.cache.get(key)
if not node:
newNode = DLinkedNode()
newNode.key = key
newNode.value = value
self.cache[key] = newNode
self._add_node(newNode)
self.size += 1
if self.size > self.capacity:
# pop the tail
tail = self._pop_tail()
del self.cache[tail.key]
self.size -= 1
else:
# update the value.
node.value = value
self._move_to_head(node)
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/lru-cache/" rel="nofollow noreferrer">146. LRU Cache - Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/lru-cache/discuss/" rel="nofollow noreferrer">146. LRU Cache - Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Something smells funny here:</p>\n<pre><code> self.head = 'HEAD'\n self.tail = 'TAIL'\n self.connect(self.head, self.tail)\n\ndef connect(self, node_a: int, node_b: int) -> None:\n</code></pre>\n<p>Those are strings, not integers. Briefly looking through your code, there's nothing requiring that your node keys be integers; they only need to be <em>hashable</em>. This is probably what you want to use for your type hints:</p>\n<p><a href=\"https://docs.python.org/3/library/typing.html#typing.Hashable\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/typing.html#typing.Hashable</a></p>\n<p>Beyond that, though, I question using those strings for HEAD and TAIL. It would be safer to make sentinel objects <code>self.head = object(); self.tail = object()</code> that will not match anything the user provides.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-21T22:47:01.403",
"Id": "245842",
"ParentId": "244284",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245842",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T20:46:50.243",
"Id": "244284",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "LeetCode 146: LRU Cache II"
}
|
244284
|
<p>I'm posting my Java code for LeetCode's LRU Cache. If you have time and would like to review, please do so. Thank you!</p>
<h3>Problem</h3>
<blockquote>
<ul>
<li><p>Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.</p>
</li>
<li><p>get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.</p>
</li>
<li><p>put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the
least recently used item before inserting a new item.</p>
</li>
<li><p>The cache is initialized with a positive capacity.</p>
</li>
</ul>
<p>Follow up:</p>
<ul>
<li>Could you do both operations in O(1) time complexity?</li>
</ul>
<h3>Example:</h3>
<pre><code>LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
</code></pre>
</blockquote>
<h3>Accepted Java</h3>
<pre><code>public class LRUCache {
private final Node head = new Node(0, 0);
private final Node tail = new Node(0, 0);
private final Map<Integer, Node> cache;
private final int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
cache = new HashMap(capacity);
head.next = tail;
tail.prev = head;
}
public int get(int key) {
int value = -1;
if (cache.containsKey(key)) {
Node node = cache.get(key);
remove(node);
append(node);
value = node.value;
}
return value;
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
Node node = cache.get(key);
remove(node);
node.value = value;
append(node);
} else {
if (cache.size() == capacity) {
cache.remove(tail.prev.key);
remove(tail.prev);
}
Node node = new Node(key, value);
append(node);
cache.put(key, node);
}
}
private void remove(Node node) {
node.prev.next = node.next;
node.next.prev = node.prev;
}
private void append(Node node) {
Node headNext = head.next;
head.next = node;
headNext.prev = node;
node.prev = head;
node.next = headNext;
}
private class Node {
Node prev, next;
int key, value;
Node(int key, int value) {
this.key = key;
this.value = value;
}
}
}
</code></pre>
<h3>LeetCode's Solution (Not for review)</h3>
<pre><code>public class LRUCache {
class DLinkedNode {
int key;
int value;
DLinkedNode prev;
DLinkedNode next;
}
private void addNode(DLinkedNode node) {
/**
* Always add the new node right after head.
*/
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
private void removeNode(DLinkedNode node){
/**
* Remove an existing node from the linked list.
*/
DLinkedNode prev = node.prev;
DLinkedNode next = node.next;
prev.next = next;
next.prev = prev;
}
private void moveToHead(DLinkedNode node){
/**
* Move certain node in between to the head.
*/
removeNode(node);
addNode(node);
}
private DLinkedNode popTail() {
/**
* Pop the current tail.
*/
DLinkedNode res = tail.prev;
removeNode(res);
return res;
}
private Map<Integer, DLinkedNode> cache = new HashMap<>();
private int size;
private int capacity;
private DLinkedNode head, tail;
public LRUCache(int capacity) {
this.size = 0;
this.capacity = capacity;
head = new DLinkedNode();
// head.prev = null;
tail = new DLinkedNode();
// tail.next = null;
head.next = tail;
tail.prev = head;
}
public int get(int key) {
DLinkedNode node = cache.get(key);
if (node == null) return -1;
// move the accessed node to the head;
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
DLinkedNode node = cache.get(key);
if(node == null) {
DLinkedNode newNode = new DLinkedNode();
newNode.key = key;
newNode.value = value;
cache.put(key, newNode);
addNode(newNode);
++size;
if(size > capacity) {
// pop the tail
DLinkedNode tail = popTail();
cache.remove(tail.key);
--size;
}
} else {
// update the value.
node.value = value;
moveToHead(node);
}
}
}
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/lru-cache/" rel="nofollow noreferrer">146. LRU Cache - Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/lru-cache/discuss/" rel="nofollow noreferrer">146. LRU Cache - Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>I have some suggestions for you, good job on the code!</p>\n<h2>Always add the empty diamond operator, even if defined in the left-hand side</h2>\n<p>If you don’t add the diamond, Java will use the old raw types instead of the generic types; those are only kept for compatibility.</p>\n<p>Here is a good explanation with more details: <a href=\"https://stackoverflow.com/a/4167148/12511456\">https://stackoverflow.com/a/4167148/12511456</a></p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>cache = new HashMap(capacity);\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>cache = new HashMap<>(capacity);\n</code></pre>\n<h2>Check if the value is present in a Map</h2>\n<p>Since you are using both <code>java.util.Map#containsKey</code> and <code>java.util.Map#get</code>, you can save some computation by using the <code>get</code> only and check if the value is null.</p>\n<p>But, keep in mind this technique won’t work if you allow the map to have a null key :).</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (cache.containsKey(key)) {\n Node node = cache.get(key);\n //[...]\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Node node = cache.get(key);\nif (node != null) {\n //[...]\n}\n</code></pre>\n<h2>Return the value as soon you have it, instead of storing it in a variable</h2>\n<p>I must admit that this method is not a favorite of every programmer, and can be hated, since you will have to use multiple return in the same block of code.</p>\n<p>In my opinion, adding multiple returns shorten the code, reduce the <a href=\"https://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">arrow code</a>, make shorter stack traces (by leaving the method faster, you get fewer lines) and block invalid states before they reach your code (<a href=\"https://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"nofollow noreferrer\">guard clauses</a>).</p>\n<p>Examples:</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int get(int key) {\n int value = -1;\n\n Node node = cache.get(key);\n if (node != null) {\n remove(node);\n append(node);\n value = node.value;\n }\n\n return value;\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int get(int key) {\n Node node = cache.get(key);\n\n if (node == null) {\n return -1;\n }\n\n remove(node);\n append(node);\n\n return node.value;\n}\n</code></pre>\n<h2>Extract some of the logic to methods.</h2>\n<p>To reduce the size of your methods, you can extract the logic blocks in methods.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public void put(int key, int value) {\n Node currentNode = cache.get(key);\n\n if (currentNode != null) {\n remove(currentNode);\n currentNode.value = value;\n append(currentNode);\n } else {\n if (cache.size() == capacity) {\n cache.remove(tail.prev.key);\n remove(tail.prev);\n }\n\n Node node = new Node(key, value);\n append(node);\n cache.put(key, node);\n }\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public void put(int key, int value) {\n Node currentNode = cache.get(key);\n\n if (currentNode != null) {\n updateNodeValue(value, currentNode);\n } else {\n createNewNode(key, value);\n }\n}\n\nprivate void createNewNode(int key, int value) {\n if (cache.size() == capacity) {\n cache.remove(tail.prev.key);\n remove(tail.prev);\n }\n\n Node node = new Node(key, value);\n append(node);\n cache.put(key, node);\n}\n\nprivate void updateNodeValue(int value, Node currentNode) {\n remove(currentNode);\n currentNode.value = value;\n append(currentNode);\n}\n</code></pre>\n<h1>Refactored code</h1>\n<pre class=\"lang-java prettyprint-override\"><code>public class LRUCache {\n private final Node head = new Node(0, 0);\n private final Node tail = new Node(0, 0);\n private final Map<Integer, Node> cache;\n private final int capacity;\n\n public LRUCache(int capacity) {\n this.capacity = capacity;\n cache = new HashMap<>(capacity);\n head.next = tail;\n tail.prev = head;\n }\n\n public int get(int key) {\n Node node = cache.get(key);\n\n if (node == null) {\n return -1;\n }\n\n remove(node);\n append(node);\n\n return node.value;\n }\n\n public void put(int key, int value) {\n Node currentNode = cache.get(key);\n\n if (currentNode != null) {\n updateNodeValue(value, currentNode);\n } else {\n createNewNode(key, value);\n }\n }\n\n private void createNewNode(int key, int value) {\n if (cache.size() == capacity) {\n cache.remove(tail.prev.key);\n remove(tail.prev);\n }\n\n Node node = new Node(key, value);\n append(node);\n cache.put(key, node);\n }\n\n private void updateNodeValue(int value, Node currentNode) {\n remove(currentNode);\n currentNode.value = value;\n append(currentNode);\n }\n\n private void remove(Node node) {\n node.prev.next = node.next;\n node.next.prev = node.prev;\n }\n\n private void append(Node node) {\n Node headNext = head.next;\n head.next = node;\n headNext.prev = node;\n node.prev = head;\n node.next = headNext;\n }\n\n private class Node {\n Node prev, next;\n int key, value;\n\n Node(int key, int value) {\n this.key = key;\n this.value = value;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T01:01:08.923",
"Id": "244297",
"ParentId": "244286",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244297",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T21:11:20.030",
"Id": "244286",
"Score": "2",
"Tags": [
"java",
"performance",
"beginner",
"algorithm",
"programming-challenge"
],
"Title": "LeetCode 146: LRU Cache III"
}
|
244286
|
<p>I'm looking for a code review and code improvement for my own small server.
The server accepts the requests:
User Join,User Leave,User Text Notify Group Join, Group Leave, Group Notify Request Time.
The syntax for User Join/Left Group Join/Left:
**</p>
<pre class="lang-none prettyprint-override"><code>DSLP-3.0
User Join
NameOfUser
DSLP-Body
</code></pre>
<p>**
The syntax for Group Notify:
**</p>
<pre class="lang-none prettyprint-override"><code>DSLP-3.0
Group Notify
NameOfGroup
1(<--number of lines you want to send)
DSLP-Body
LineYouWantSend
</code></pre>
<p>**
The syntax for User Text Notify:
**</p>
<pre class="lang-none prettyprint-override"><code>DSLP-3.0
User Text Notify
User1
User2
1(<---number of lines you want to send)
DSLP-Body
LineYouWantSend
</code></pre>
<p>**</p>
<p>The syntax for Request Time:</p>
<pre class="lang-none prettyprint-override"><code>DSLP-3.0
Request Time
DSLP-Body
</code></pre>
<p>This is the code:</p>
<pre><code>import socket
from socket import *
from threading import Thread
from datetime import datetime
host="localhost"
port=44444
s = socket(AF_INET, SOCK_STREAM)
SOCK_STREAM
s.bind((host, port))
s.listen(5)
trash=[]
user=["foobar"]
group=["foobar"]
def clientHandler():
platz=""
conn, addr = s.accept()
print ("Connected with", addr)
while True:
data = conn.recv(4096)
#error
if repr(data)!="b'dslp-3.0'":
print(error_firstline())
else:
while True:
data = conn.recv(4096)
platz+=repr(data)
platz+="\r\n"
trash.append(platz)
if len(trash)==2 and platz.count("\r\n")==2:
if "b'dslp-3.0'" in platz:
continue
else:
print(error_search_2nd_line(platz))
if len(trash)>4 and "b'dslp-3.0'" in platz:
pp=platz.rsplit("b'dslp-3.0'\r\n")
trash.clear()
print(error_search_2nd_line(pp[1]))
if len(trash)>6:
trash.clear()
if "request time" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
print(response_time())
platz=""
if len(platz)>31:
print(error_forthline())
if "group join" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'group join'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>33:
print(error_forthline())
platz=""
else:
print(group_join(platz))
platz=""
if "group leave" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'group leave'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>34:
print(error_forthline())
platz=""
else:
print(group_leave(platz))
platz=""
if "user join" in platz:
if len(trash)>4:
trash.clear()
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'user join'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>32:
print(error_forthline())
platz=""
else:
print(user_join(platz))
platz=""
if "user leave" in platz:
if "dslp-body" in platz:
platz=check_dslp(platz)
so=platz.split(("b'user leave'"))
soo=so[1].split(("\r\nb'dslp-body'\r\n"))
sooo=soo[0].split(("\r\nb'"))
zahl=len(platz)-len(sooo[1])
if zahl>33:
print(error_forthline())
platz=""
else:
print(user_leave(platz))
platz=""
if "group notify" in platz:
platz=check_dslp(platz)
for i in range(5):
if str(i) in platz:
if i==1:
if platz.count("\r\n")==5:
print(group_notify(platz))
platz=""
if i==2:
if platz.count("\r\n")==6:
print(group_notify(platz))
platz=""
if i==3:
if platz.count("\r\n")==7:
print(group_notify(platz))
platz=""
if i==4:
if platz.count("\r\n")==8:
print(group_notify(platz))
platz=""
if i==5:
if platz.count("\r\n")==9:
print(group_notify(platz))
platz=""
if "user text notify" in platz:
platz=check_dslp(platz)
for i in range(5):
if str(i) in platz:
if i==1:
if platz.count("\r\n")==6:
print(user_notify(platz))
platz=""
if i==2:
if platz.count("\r\n")==7:
print(user_notify(platz))
platz=""
if i==3:
if platz.count("\r\n")==8:
print(user_notify(platz))
platz=""
if i==4:
if platz.count("\r\n")==9:
print(user_notify(platz))
platz=""
if i==5:
if platz.count("\r\n")==10:
print(user_notify(platz))
platz=""
if "user list" in platz:
if "dslp-body" in platz:
print(user_list())
platz=""
if "group list" in platz:
if "dslp-body" in platz:
print(group_list())
platz=""
for i in range(5):
Thread(target=clientHandler).start()
s.close()
def error_search_2nd_line(platzhalter):
bb=platzhalter.rsplit("b'")
b=bb[1].rsplit("'\r\n")
platzhalter=b[0]
print (platzhalter)
liste=["group join", "group leave", "user join", "user leave", "group notify", "user text notify","user list","group list"]
bedingung=""
for x in range(len(liste)):
bedingung+=liste[x]
if x+1==len(liste):
if platzhalter not in bedingung:
trash.clear()
print(error_secondline())
else:
trash.clear()
def error_firstline():
print("dslp-3.0\r\nerror\r\n1\r\ndslp-body\r\nReceived unexpected text as first line.\r\nConnection closed by foreign host.")
def error_secondline():
print("error")
print("1")
print("dslp-body")
print("Received unexpected message type in second line.")
print("Connection closed by foreign host.")
def error_forthline():
print("dslp-3.0")
print("error")
print("1")
print("dslp-body")
print("Unexpected state while analyzing line 4.")
print("Connection closed by foreign host.")
def group_error():
print("Group is unknown.")
def user_error():
print("Source user is unknown.")
def check_dslp(platz):
if "b'dslp-3.0'\r\n" in platz:
pp=platz.rsplit("b'dslp-3.0'\r\n")
platz=pp[1]
return platz
else:
return platz
def group_join(platzhalter):
print("dslp-3.0")
print("group join ack")
y=platzhalter.split("b'group join'\r\nb'")
y=y[1].split("'")
group.append(y[0])
print(y[0])
print("dslp-body")
def group_notify(platzhalter):
if len(group)==1:
print(group_error())
for x in group:
if x in platzhalter:
pp=platzhalter.rsplit("dslp-body'\r\nb'")
ppp=pp[1].rsplit("'\r\n")
for i in ppp:
print (i)
break
if x=="foobar":
continue
elif x not in platzhalter:
print(group_error())
def group_leave(platzhalter):
y=platzhalter.split("b'group leave'\r\nb'")
y=y[1].split("'")
for x in group:
if y[0] in group:
print("dslp-3.0")
print("group leave ack")
print(y[0])
print("dslp-body")
group.remove(y[0])
break
else:
print(group_error())
def group_list():
print("Groups: ")
for i in group:
print(i)
def user_join(platzhalter):
if "b'dslp-3.0'\r\n" in platzhalter:
z=platzhalter.split("b'dslp-3.0'\r\n")
y=z[1]
y=platzhalter.split("b'user join'\r\nb'")
y=y[1].split("\r\nb'dslp-body'\r\n")
y=y[0].split("'")
user.append(y[0])
print("dslp-3.0")
print("user join ack")
print(y[0])
print("dslp-body")
else:
y=platzhalter.split("b'user join'\r\nb'")
y=y[1].split("\r\nb'dslp-body'\r\n")
y=y[0].split("'")
user.append(y[0])
print("dslp-3.0")
print("user join ack")
print(y[0])
print("dslp-body")
def user_notify(platzhalter):
if len(user)==1:
print(user_error())
for x in user:
if x in platzhalter:
pp=platzhalter.rsplit("dslp-body'\r\nb'")
ppp=pp[1].rsplit("'\r\n")
for i in ppp:
print(i)
break
if x not in platzhalter:
print(user_error())
def user_leave(platzhalter):
y=platzhalter.split("b'user leave'\r\nb'")
y=y[1].split("\r\nb'dslp-body'\r\n")
y=y[0].split("'")
user.remove(y[0])
print("dslp-3.0")
print("user leave ack")
print(y[0])
print("dslp-body")
def user_list():
print("Users are: ")
for i in user:
print(i)
</code></pre>
|
[] |
[
{
"body": "<h2>Packet fragmentation</h2>\n<pre><code> data = conn.recv(4096)\n\n #error\n if repr(data)!="b'dslp-3.0'":\n</code></pre>\n<p>To quote the documentation for <a href=\"https://docs.python.org/3/library/socket.html#socket.socket.recv\" rel=\"nofollow noreferrer\"><code>recv</code></a>,</p>\n<blockquote>\n<p>The <strong>maximum</strong> amount of data to be received at once is specified by bufsize.</p>\n</blockquote>\n<p>Emphasis mine. This is a common pitfall that beginners encounter when attempting low-level socket programming. The socket library gives you no guarantee that you will actually get 4096 bytes, or even a complete message. You need to iterate until you think you have enough bytes or a valid message, however you define that.</p>\n<p>Put another way, it would be trivially easy to write a client that sends fragmented data to your server that <em>should</em> be valid but will in fact be erroneously rejected.</p>\n<p>Though I haven't tried it, <a href=\"https://docs.python.org/3/library/socketserver.html#socketserver.StreamRequestHandler\" rel=\"nofollow noreferrer\"><code>socketserver</code></a> seems like its <code>rfile</code> should be able to abstract this away for you since it handles buffering. In other words, you don't need to worry about packets or buffer sizes; you can ask for <code>rfile.readline()</code>, which is what you actually want given your protocol.</p>\n<p>If you do not want the abstraction of <code>socketserver</code>, you can also use <a href=\"https://docs.python.org/3/library/socket.html#socket.socket.makefile\" rel=\"nofollow noreferrer\"><code>makefile</code></a> - which is called by <code>socketserver</code> anyway.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T22:02:37.753",
"Id": "244291",
"ParentId": "244289",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T21:28:48.183",
"Id": "244289",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"multithreading",
"socket",
"server"
],
"Title": "Server in Python"
}
|
244289
|
<p>This is an interview question to generate the below pattern of numbers in a sequence, which is: 12.34, 23.45, 45.67, 78.910, 1112.1314, 1617.1819, 2223.2425, 2930.3132, 3738.3940, 4647.4849, 5657.5859, 6768.6970, 7980.8182, 9293.9495, 106107.108109, 121122.123124 We can use starting seed number as 12 and have to generate all the 16 numbers programmatically without using strings. We can use only arrays but no other built-in collection classes or data structures.</p>
<pre><code>public static void GenerateSequence()
{
int j = 1;
ArrayList sequenceList = new ArrayList();
for (int count = 0; count < 16; count++)
{
j = j + count;
int quotent = getValue(j, j + 1);
int reminder = getValue(j + 2, j + 3);
int length = getLength(reminder);
double result = Convert.ToUInt32(quotent) * getLength(reminder) + reminder;
sequenceList.Add(result / length);
}
Console.WriteLine(sequenceList.ToString());
}
static int getValue(int a, int b)
{
return a * getLength(b) + b;
}
static int getLength(int value)
{
int length = (int)(Math.Log10(value) + 1);
int formattedValue = 10;
for (int i = 1; i < length; i++)
formattedValue = formattedValue * 10;
return formattedValue;
}
</code></pre>
<p>I've arrived with above solution but this looks complex and less efficient. Looking for an alternate approach with better time/space complexity.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T23:49:42.860",
"Id": "479605",
"Score": "0",
"body": "_12.34, 23.45, 45.67, 78.910_ - how is this even a consistent sequence? Wouldn't this go 12.34, 23.45, 34.56, 45.67?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T00:01:28.763",
"Id": "479606",
"Score": "0",
"body": "@Reinderien the sequence is adding 1 to each digit, then 2, then 3... not adding 1 at each step."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T00:04:28.893",
"Id": "479607",
"Score": "1",
"body": "That seems underspecified. It isn't just adding to each digit - it's _substituting_ each digit with all of the digits of the resulting sum. You should spell this out in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T06:54:41.510",
"Id": "479614",
"Score": "0",
"body": "If it is an interview question then they are interested about your solution (skills) not others."
}
] |
[
{
"body": "<p>In the question it says</p>\n<blockquote>\n<p>We can use starting seed number as 12 and have to generate all the 16\nnumbers programmatically without using strings</p>\n</blockquote>\n<p>Was the seed value part of the requirements for the problem? If so, then one test of a solution would be to feed in another seed, say 13, and see if the output matches the expected results for that seed. The current solution is hard-coded to always produce the same outputs.</p>\n<p>Although not an explicit requirement, passing in the count of values to be produced as a parameter would be a nice touch (or <a href=\"https://en.wikipedia.org/wiki/Feature_creep\" rel=\"nofollow noreferrer\">feeping creaturism</a>, depending upon one's viewpoint).</p>\n<p><strong>Testability:</strong><br/>\nAs written, the only way to test the value generation is to run it and sight check the results. Another approach would be to create a function to return the values and the function could then be unit tested, quickly and reliably (sight checking 16 numbers for possibly small differences is doable. If it was 100 numbers it would become a lot more onerous)</p>\n<p><strong>Silly(ish):</strong><br/>\nIf the examiners are being picky on an applicant's ability to understand and follow instructions then using the <strong>ArrayList</strong> breaks the prohibition</p>\n<blockquote>\n<p>use only arrays but no other built-in collection classes or\ndata structures.</p>\n</blockquote>\n<p>It is a very picky point (but interviewers can be picky at times) and it may also hint that they are looking for something along the lines of</p>\n<pre><code>public static IEnumerable<double> GetSequence(int seed, int count)\n{\n // do count times\n // calc value\n yield value; \n}\n</code></pre>\n<p>If we are going to use a collection to hold the values, why use an <strong>ArrayList</strong>. A generic <strong>List<double></strong> would be better (<a href=\"https://stackoverflow.com/questions/17238764/whats-so-bad-about-arraylists\">Why not to use ArrayList in C#</a>).<br/>\nIf we are to follow the collection prohibition, then using a <strong>double[]</strong> and setting the values by index rather than adding them would work (though I would still push for a function returning an <strong>IEnumerable<double></strong>)</p>\n<pre><code>public static void GenerateSequence()\n{\n int j = 1;\n var sequence = new double[16];\n\n for (int count = 0; count < 16; count++)\n {\n j = j + count;\n int quotent = getValue(j, j + 1);\n int reminder = getValue(j + 2, j + 3);\n int length = getLength(reminder);\n double result = Convert.ToUInt32(quotent) * getLength(reminder) + reminder;\n sequence[count] = (result / length);\n }\n Console.WriteLine(string.Join(Environment.NewLine, sequence.Select(v => v.ToString())));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T08:40:22.903",
"Id": "263770",
"ParentId": "244290",
"Score": "1"
}
},
{
"body": "<h3>Variable name j</h3>\n<p>Why j? Probably you could use something of these: number, value, current_value, current, pivot.\nAlso, <code>j = j + count</code> is better written as <code>j += count</code>.</p>\n<h3>getValue</h3>\n<p>That's a poor name - it concatenates two numbers into one, not "gets value"; moreover, it does so only with consecutive numbers (arguments always differ by 1). Probably</p>\n<pre><code>int concatWithNext(int n)\n{\n return n * getLength(n+1) + n + 1;\n}\n</code></pre>\n<p>will do better.</p>\n<h3>"Magic" number 16</h3>\n<p>Why 16? That's the most obvious thing that can change. Make it an argument of GenerateSequence function. You can even make 16 the default value for that argument.</p>\n<h3>GenerateSequence should return a value, not output it</h3>\n<p>Usually, calculations and input/output should reside in different methods.</p>\n<h3>getLength(reminder) is calculated twice</h3>\n<p>You can reuse the result of first calculation</p>\n<h3>Convert.ToUInt32</h3>\n<p>Why? You want to raise an exception on an overflow? Better do it in getValue method.</p>\n<h3>Calculation formula</h3>\n<p>Probably it is better not to multiply and then divide, but divide at once to avoid overflow:</p>\n<pre><code>sequenceList.Add( Convert.ToDouble(quotent) + Convert.ToDouble(reminder)/Convert.ToDouble(length);\n</code></pre>\n<h3>getLength</h3>\n<p>I think it should be Math.Log10 and Math.Pow or division by 10 and multiplication by 10, but not together. Division and multiplication are usually slightly faster, but you still need to benchmark it. And the name... it actually doesn't get the length, so it should be roundToPowerOfTen or something.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T09:07:59.410",
"Id": "263771",
"ParentId": "244290",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-21T21:55:36.340",
"Id": "244290",
"Score": "5",
"Tags": [
"c#",
"array",
"interview-questions"
],
"Title": "c# Efficient solution: Sequence generator for a pattern"
}
|
244290
|
<p>I am implementing a binary search algorithm and my code is as shown bellow:</p>
<pre><code>def binary_search(a, x):
left, right = 0, len(a)
if right == 0: return -1
if x < a[0] or x > a[-1]:
return -1
elif x == a[0]:
return 0
elif x == a[-1]:
return right - 1
mid = right // 2
a_mid = a[mid]
if x == a_mid:
return mid
elif x < a_mid:
return binary_search(a[left:mid], x)
elif x > a_mid:
idx = binary_search(a[mid+1:right], x)
if idx == -1:
return -1
else:
return mid + 1 + idx
</code></pre>
<p>I tested it and cannot find any way to improve it by complexity. Someone suggested that I may "have used an incorrect base condition to terminate your loop" but I still cannot figure out where the problem lies.</p>
<p>Could anyone please help? Thanks in advance.</p>
|
[] |
[
{
"body": "<p>I can see the problem with your code. Why This "mid = right // 2 " ?</p>\n<p>You can try below code</p>\n<pre><code>def binarySearch(arr, low, high, key): \n if high >= low: \n mid = (high + low) // 2\n if arr[mid] == key: \n return mid \n elif arr[mid] > key: \n return binarySearch(arr, low, mid - 1, key)\n else: \n return binarySearch(arr, mid + 1, high, key)\n else:\n return -1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T22:34:46.607",
"Id": "479798",
"Score": "0",
"body": "It's because `left` is always 0, actually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T04:43:40.273",
"Id": "479815",
"Score": "1",
"body": "@Lnz sublist ooeration in python is not $ O(1) \\ it \\ is \\ O(n) $ and you are doing sub list in each iteration, this is the reason of slowness ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T04:44:38.493",
"Id": "479816",
"Score": "0",
"body": "https://stackoverflow.com/questions/39338520/time-complexity-for-a-sublist-in-python"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T00:56:50.347",
"Id": "479940",
"Score": "0",
"body": "I read [this](https://stackoverflow.com/a/13203617/3552975) and find that you are right. But the first two lines are in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-26T05:29:50.680",
"Id": "480081",
"Score": "0",
"body": "I think you are right. I can call your function in that function."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:32:30.377",
"Id": "244379",
"ParentId": "244295",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244379",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T00:24:46.593",
"Id": "244295",
"Score": "1",
"Tags": [
"python",
"complexity",
"binary-search"
],
"Title": "Faster binary search to find the index in Python?"
}
|
244295
|
<p>it's the second object oriented program i've worked on,
more details on <a href="https://hyperskill.org/projects/96?goal=391" rel="noreferrer">https://hyperskill.org/projects/96?goal=391</a>.</p>
<p>I've added as much documentation as needed, as a first time, to explain each component.</p>
<pre class="lang-py prettyprint-override"><code>class Matrix:
def __init__(self, dimension, elements=None):
"""
Use:
Matrix([num_of_rows, num_of_columns], [2D array or 1D array or None/blank])
self.dimension is a list with two values, refering to the number of rows and columns of the matrix, Ex: [3, 3] is a 3x3 matrix
self.matrix refers to the matrix in terms of 2D Arrays,
if elements is not given as an argument, then it will create a matrix of 0s with the dimensions provided
if elements is given as a certain list/matrix, it will store it as a matrix in it
self.transposition_type is a dictionary storing the possible transpositions functions of a matrix, if asked for
Input Types:
Matrix([3, 3]) or Matrix([3, 3], []) : creates a 3x3 matrix with only 0s
Matrix([3, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]]): creates a 3x3 matrix with a 2D array as elements
Matrix([3, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9]) : creates a 3x3 matrix with a 1D array, elements are filled left to right, top to bottom in matrix
"""
self.dimension = dimension
self.transposition_type = {'main_diagonal': self.transposition_along_main_diagonal,
'side_diagonal': self.transposition_along_side_diagonal,
'horizontal' : self.transposition_along_horizontal ,
'vertical' : self.transposition_along_vertical }
self.matrix = self.default_matrix() if elements == None else self.check_elements(elements)
def __add__(self, other):
"""
Add two matrices
Matrix + Matrix
Rules:
1) Matrixes should have the same dimensions
2) Matrixes cannot be added by other data types
"""
assert type(other) == Matrix, f"Matrix cannot be added by {type(other)}"
assert self.dimension == other.dimension, "Dimensions should be same"
return Matrix(self.dimension, [ [self.matrix[row][column] + other.matrix[row][column] for column in range(self.dimension[1])] for row in range(self.dimension[0])])
def __sub__(self, other):
"""
Subtract two matrices
Matrix - Matrix
Rules:
1) Matrixes should have the same dimensions
2) Matrixes cannot be added by other data types
"""
assert type(other) == Matrix, f"Matrix cannot be subtracted by {type(other)}"
assert self.dimension == other.dimension, "Dimensions should be same"
return Matrix(self.dimension, [ [self.matrix[row][column] - other.matrix[row][column] for column in range(self.dimension[1])] for row in range(self.dimension[0])])
def __mul__(self, other):
"""
multiples a matrix with an integer/float or another matrix
Multiplication process is different for a constant and another matrixes, so they go to different processes, depending on the type of other
Matrix * constant | constant * Matrix
Matrix * Matrix
"""
if isinstance(other, (int, float)): # int/float * matrix
return self.constant_multiplication(other)
elif isinstance(other, Matrix):
return self.matrix_multiplication(other)
raise Exception(f"Matrixes cannot be multiplied by {type(other)}")
def __rmul__(self, other):
"""
Does the same thing as the __mul__ method, just instead of matrix * number, it also supports number * matrix
"""
return self.__mul__(other)
def __str__(self):
"""
Displays Matrixes in a format
Ex:
Matrix( [3, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9]) or Matrix( [3, 3], [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
1 2 3
4 5 6
7 8 9
"""
return "\n".join(" ".join(str(value) for value in row) for row in self.matrix)
def check_elements(self, elements):
"""
Checks if the elements provided on instantiation is a 2D array or a 1D array, or None of them
if its a 1D array, it calls the method self.set_matrix_elements_by_array(elements)
if its a 2D array, it can be directly set to the self.matrix attribute directly
if its an empty list [], then it will make a default matrix with 0s only
"""
if elements:
if all(map(lambda x: type(x) == list, elements)):
if all(map(lambda x: type(x) == float or type(x) == int, elements[0])):
return elements
elif all(map(lambda x: type(x) == float or type(x) == int, elements)):
return self.set_matrix_elements_by_array(elements)
raise Exception('Invalid Input Type')
else:
return self.default_matrix()
def default_matrix(self, dimensions=None):
"""
Makes a 0 element only matrix with the dimensions provided
Dimensions cant be (0, 0)
"""
dimension = self.dimension if dimensions == None else dimensions
assert dimension[0] != 0 and dimension[1] != 0, "Dimensions cannot be (0, 0)"
return [dimension[1] * [0] for _ in range(dimension[0])]
def set_matrix_elements_by_array(self, elements):
"""
creates and returns a matrix (2D array) using a 1D array, given dimensions
where the number of elements in the array must be equal to the product of the number of rows and columns
"""
assert len(elements) == (self.dimension[0] * self.dimension[1]), "Number of elements is not equal"
j = 0
matrix = []
for i in range(self.dimension[1], self.dimension[1]*self.dimension[0]+1, self.dimension[1]):
matrix.append(elements[j:i])
j = i
return matrix
def constant_multiplication(self, constant, matrix=None):
"""
multiples a matrix with a constant and returns a new matrix
"""
matrix = self.matrix if matrix is None else matrix
return Matrix(self.dimension, [ [round(matrix[row][column] * constant, 2) for column in range(self.dimension[1])] for row in range(self.dimension[0])])
def matrix_multiplication(self, other):
"""
multiples a matrix with another matrix and returns a new matrix
creates a 0 element only 2D array with the appropriate dimensions, depending on the two matrixes multiplied
then changes the 2D array in place, and creates and returns a matrix using that 2D array
"""
assert self.dimension[1] == other.dimension[0], "The number of columns of the first matrix must equal the number of rows of the second matrix"
matrix_array = self.default_matrix([self.dimension[0], other.dimension[1]])
for i in range(self.dimension[0]):
for j in range(other.dimension[1]):
for k in range(other.dimension[0]):
matrix_array[i][j] += self.matrix[i][k] * other.matrix[k][j]
return Matrix([self.dimension[0], other.dimension[1]], matrix_array)
def transposition_along_main_diagonal(self, matrix=None):
"""
performs transposition along the main diagonal from left to right
- just switch the position of row and columns for each elements: element[row][column] = element[column][row]
Ex:
the diagonal is represented by 1 5 6
1 1 1 1 2 3
2 2 2 ---> 1 2 3
3 3 3 1 2 3
"""
matrix = self.matrix if matrix is None else matrix
return list(map(list, zip(*matrix)))
def transposition_along_side_diagonal(self):
"""
performs transposition along the side diagonal from right to left
- just perform a transposition along the main diagonal, then reverse the position of each row, and then reverse the elements in each row
Ex:
the diagonal is represented by -1 2 3
1 1 -1 transpos 1 2 3 reverse_pos -1 -2 -3 reverse_rows -3 -2 -1
2 2 -2 ---------> 1 2 3 ---------> 1 2 3 ------------> 3 2 1
3 3 -3 -1 -2 -3 1 2 3 3 2 1
"""
return [row[::-1] for row in self.transposition_along_main_diagonal()[::-1]]
def transposition_along_horizontal(self):
"""
performs transposition along the horizontal
- just simply reverse the position of rows
Ex:
the horizontal is represented by 4 5 6
1 2 3 reverse 7 8 9
4 5 6 --------> 4 5 6
7 8 9 1 2 3
"""
return [row for row in self.matrix[::-1]]
def transposition_along_vertical(self):
"""
performs transposition along the vertical
- just simply reverse the elements of each row
Ex:
the vertical is represented by 2 5 8
1 2 3 rev elems 3 2 1
4 5 6 ---------> 6 5 4
7 8 9 9 8 7
"""
return [row[::-1] for row in self.matrix]
def matrix_transposition(self, choice):
"""
returns the transposition of a matrix as a Matrix object, using switch case like dictionaries, with the dimensions swapped
"""
return Matrix([self.dimension[1], self.dimension[0]], self.transposition_type[choice]())
def get_minor(self, matrix, i, j):
"""
acquires the minor/submatrix of a matrix, with dimensions (n-1, n-1), with n being the current dimensions of the matrix, based on the ith row and jth column given, which is submatrix formed by all the other elements that dont have the row i and column j
Ex:
the minor of element (5) at i=1 j=1, cancels 2 and 8, because they are in the jth column and cancels 4 and 6 because they are in the ith row
| 1 2 3 | | 1 3 |
| 4 5 6 | ---> | 7 9 |
| 7 8 9 |
"""
return [row[:j] + row[j+1:] for row in (matrix[:i]+matrix[i+1:])]
def determinant_helper(self, matrix):
"""
recursively finds the determinant of a matrix, given as an argument, by finding the minor of every matrix using cofactors till it reaches the base cases
basecase 1: matrix 1x1, determinant is the element left in the matrix
Ex:
| 17 | has a determinant of 17
basecase 2: matrix 2x2, determinant is the difference between the product of diagonals
Ex:
| a b |
| c d | has a determinant of a*d-b*c
"""
# base case for a 2x2 matrix
if len(matrix) == 2:
return (matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0])*1.0
# base case for a 1x1 matrix
if len(matrix) == 1 and len(matrix[0]) == 1:
return matrix[0][0]*1.0
determinant = 0
for c in range(len(matrix)):
determinant += ((-1.0)**c) * matrix[0][c] * self.determinant_helper(self.get_minor(matrix, 0, c))
return determinant
def determinant(self):
"""
finds the determinant by using the helper function to supply the current matrix of the object
changes integer floats to integers, and so on
"""
det = self.determinant_helper(self.matrix)
return int(det) if det.is_integer() else det
def inverse(self):
"""
acquires the inverse form of a matrix by using laplace's expansion
which is A^-1 (inverse matrix) = 1/determinant * C^T (transposed matrix of all cofactors of all elements in matrix along main diagonal)
"""
determinant = self.determinant()
matrix = self.matrix
#assert determinant != 0, "Matrix does not have an inverse form"
# base case, for 2x2 matrix
if len(matrix) == 2:
return Matrix(self.dimension, [ [matrix[1][1]/determinant, -1*matrix[0][1]/determinant],
[-1*matrix[1][0]/determinant, matrix[0][0]/determinant] ])
# find matrix of cofactors
cofactors = []
for row in range(len(matrix)):
cofactor_row = []
for column in range(len(matrix)):
minor = self.get_minor(matrix, row, column)
cofactor_row.append( round(((-1)**(row+column)) * self.determinant_helper(minor) / determinant, 2) )
cofactors.append(cofactor_row)
cofactors = self.transposition_along_main_diagonal(cofactors)
return Matrix(self.dimension, cofactors)
class MatrixCalculator:
def __init__(self):
"""
self.matrices : holds a list of matrices for operations to be performed on.
self.count : represents the current prompt number to be displayed for an operation, and determines what is shown next, acts as an index in a list for self.prompts
self.choices : holds the possible operations for the menu.
self.prompts : holds the appropriate prompts for depending on whether 1 or 2 matrices should be inputted, and they are accessed using self.count, which is reset after each operation to 0.
self.transposition_choice : holds the possible transpositions for the menu in transpositions, represents which user input, will call what type of transposition
self.main : starts the program
"""
self.matrices = []
self.count = 0
self.choices = {1: self.addition, 2: self.constant_multiplication, 3: self.matrix_multiplication, 4: self.transpose_matrix, 5: self.get_determinant, 6: self.get_inverse, 0: exit}
self.prompts = {1: ['Enter size of matrix: ', 'Enter matrix: '],
2: ['Enter size of first matrix: ', 'Enter size of second matrix: ', 'Enter first matrix: ', 'Enter second matrix: ']}
self.transposition_choice = {1: 'main_diagonal', 2: 'side_diagonal', 3: 'vertical', 4: 'horizontal'}
self.main()
def clear_matrices_and_count(self):
"""
clears the matrices in memory and resets the prompt count after each operation
"""
self.matrices = []
self.count = 0
def display_choices_and_input(self):
"""
displays the menu, and the possible operations, and asks for a response to which operation to perform
self.choices key is located in __init__
"""
print("1. Add matrices\n2. Multiply matrix by a constant\n3. Multiply matrices\n4. Transpose matrix\n5. Calculate a determinant\n6. Inverse matrix\n0. Exit")
self.choices[int(input('Your choice: '))]()
def input_matrix(self, matrix, n):
"""
inputs a matrix using a specific format in command line, and the appropriate response based on the operation
self.prompts refers to the prompts performed based on n which refers to the number of matrices to be inputted
self.count refers to the prompt in this iteration of the program
Ex:
Enter Matrix:
> 1 2 3
> 4 5 6
> 7 8 9
"""
print(self.prompts[n][n + self.count])
for row in range(len(matrix.matrix)):
inp = input().split()
try:
matrix.matrix[row] = list(map(int, inp))
except:
matrix.matrix[row] = list(map(float, inp))
self.count += 1
def input_matrix_n_times(self, n):
"""
allows the inputting of a matrice multiple times with a value of n which refer to the number of matrices to be inputted
n refers to the number of matrices to be inputted and acts as a constant to output specific prompts for each operation
"""
for i in range(n):
self.matrices.append(Matrix(list(map(int, input(self.prompts[n][i]).split()))))
assert len(self.matrices[i].dimension) == 2, "Dimension is a list with two values, rows and columns only"
self.input_matrix(self.matrices[i], n)
def addition(self):
"""
uses the matrix class to add two matrices
Ex:
1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
0. Exit
Your choice: 1
Enter size of first matrix: 3 3
Enter first matrix:
1 2 3
4 5 6
7 8 9
Enter size of second matrix: 3 3
Enter second matrix:
1 1 1
1 1 1
1 1 1
The result is:
2 3 4
5 6 7
8 9 10
"""
self.input_matrix_n_times(2)
print('The result is: ')
print(self.matrices[0] + self.matrices[1], "", sep='\n')
self.clear_matrices_and_count()
def constant_multiplication(self):
"""
uses the matrix class to multiply a matrix by a constant
Ex:
1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
0. Exit
Your choice: 2
Enter size of matrix: 3 3
Enter matrix:
1 1 1
1 1 1
1 1 1
Enter constant: 1.5
The result is:
1.5 1.5 1.5
1.5 1.5 1.5
1.5 1.5 1.5
"""
self.input_matrix_n_times(1)
constant = input('Enter constant: ')
try:
constant = int(constant)
except:
constant = float(constant)
print('The result is: ')
print(constant * self.matrices[0], "", sep='\n')
self.clear_matrices_and_count()
def matrix_multiplication(self):
"""
uses the matrix class to multiply two matrices together
Ex:
1. Add matrices
2. Multiply matrix by a constant
3. Multiply matrices
0. Exit
Your choice: 3
Enter size of first matrix: 3 3
Enter first matrix:
2 2 2
2 2 2
2 2 2
Enter size of second matrix: 3 3
Enter second matrix:
2 2 2
2 2 2
2 2 2
The result is:
12 12 12
12 12 12
12 12 12
"""
self.input_matrix_n_times(2)
if self.matrices[0].dimension[1] != self.matrices[1].dimension[0]:
print('The operation cannot be performed.', "", sep='\n')
return
print('The result is: ')
print(self.matrices[0] * self.matrices[1], "", sep='\n')
self.clear_matrices_and_count()
def transpose_matrix(self):
"""
Holds the menu for transposing matrices in 4 different ways,
the types of transpositions are stored as a switch case in a dictionary, which is called depending on the user's input of 1-4
Performs transposition and returns the specified transposition requested for.
"""
print("\n1. Main diagonal\n2. Side diagonal\n3. Vertical line\n4. Horizontal line")
transposition_type = self.transposition_choice[int(input('Your choice: '))]
self.input_matrix_n_times(1)
print('The result is: ')
print(self.matrices[0].matrix_transposition(transposition_type), '', sep='\n')
self.clear_matrices_and_count()
def get_determinant(self):
"""
acquires and returns the determinant of an nxn matrix
matrix must have the same number of rows and columns
"""
self.input_matrix_n_times(1)
print('The result is: ')
print(self.matrices[0].determinant(), '', sep='\n')
self.clear_matrices_and_count()
def get_inverse(self):
"""
Acquires the inverse of the matrix, using cofactors and minors
if determinant is 0, then the matrix doesn't have an inverse form
"""
self.input_matrix_n_times(1)
if self.matrices[0].determinant() == 0:
print("This matrix doesn't have an inverse.", '', sep='\n')
return
print('The result is: ')
print(self.matrices[0].inverse(), '', sep='\n')
def main(self):
"""
program runs indefinitely until the exit operation by entering '0' is performed
"""
while True:
self.display_choices_and_input()
MatrixCalculator()
</code></pre>
|
[] |
[
{
"body": "<p>The real power of OOP is not that you can use classes as namespaces to bundle functions that belong together. The main power is polymorphism, meaning that you can inherit from classes and use subclasses interchangeably with their parent classes. This means that you want to be able to do something like this:</p>\n<pre><code>class UnitaryMatrix(Matrix):\n ...\n\na = Matrix(...)\nu = UnitaryMatrix(...)\na + u\n</code></pre>\n<p>However, this is currently not possible with your class, because you are using a too restrictive check for the type of classes in your operators. Instead of</p>\n<pre><code>assert type(other) == Matrix, f"Matrix cannot be added by {type(other)}"\n</code></pre>\n<p>simply use</p>\n<pre><code>assert isinstance(other, Matrix), f"Matrix cannot be added by {type(other)}"\n</code></pre>\n<p><code>isinstance</code> returns true as long as the object is of that type, or a type derived from it. In other words, a <code>UnitaryMatrix</code> is also a <code>Matrix</code> and can be used wherever a <code>Matrix</code> is expected.</p>\n<hr />\n<p>I would re-think how you construct your matrix. You want to make the default usecase as simple as possible. I would want to use your class like this:</p>\n<pre><code>m = Matrix([[1, 2], [3, 4]])\n</code></pre>\n<p>Without having to specify the dimensions, since they are obvious from the input. Other ways to construct the matrix should be <a href=\"https://www.geeksforgeeks.org/classmethod-in-python/\" rel=\"nofollow noreferrer\">class methods</a>:</p>\n<pre><code>m2 = Matrix.from_flattened([1, 2, 3, 4], shape=(2, 2))\nm3 = Matrix.zeros(2, 2)\n</code></pre>\n<p>Which you can implement like this:</p>\n<pre><code>class Matrix:\n def __init__(self, elements):\n self.matrix = elements\n self.shape = len(elements), len(elements[0])\n ...\n\n @classmethod\n def from_flattened(self, elements, shape):\n assert len(shape) == 2\n assert len(elements) == shape[0] * shape[1]\n return Matrix([elements[i*shape[0]:(i+1)*shape[0]]\n for i in range(shape[0])])\n\n @classmethod\n def zeros(self, *shape):\n assert len(shape) == 2\n return Matrix([[0] * shape[1] for _ in range(shape[0])])\n</code></pre>\n<p>Note that I renamed <code>dimension</code> to <code>shape</code>, which is what e.g. <code>numpy</code> uses. For me, <code>dimension</code> should be <code>len(shape)</code>, i.e always two in the case of a matrix.</p>\n<p>Depending on your usecases, defining a <code>filled</code> and a <code>ones</code> classmethod might also make sense:</p>\n<pre><code> @classmethod\n def filled(self, value, *shape):\n assert len(shape) == 2\n return Matrix([[value] * shape[1] for _ in range(shape[0])])\n\n @classmethod\n def zeros(self, *shape):\n return Matrix.filled(0, *shape)\n\n @classmethod\n def ones(self, *shape):\n return Matrix.filled(1, *shape)\n</code></pre>\n<p>Using class methods also allows you to define other special matrices, like the identity matrix:</p>\n<pre><code> @classmethod\n def identity(self, *shape):\n m = Matrix.zeros(*shape)\n for i in range(m.shape[0]):\n m.matrix[i][i] = 1\n return m\n</code></pre>\n\n<pre><code>>>> Matrix.identity(3, 3)\nMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n</code></pre>\n<hr />\n<p>Using <code>elements == None</code> is not the right way to do it. Use <code>elements is None</code>, as recommended by Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>.</p>\n<hr />\n<p>To ease using your class in an interactive terminal, you should also implement <code>__repr__</code>, which is used as a representation. By convention, the output should be able to construct your class again, i.e. <code>eval(repr(m)) == m</code>. In this case this is rather easy:</p>\n<pre><code>class Matrix:\n ...\n\n def __repr__(self):\n return f"Matrix({self.matrix!r})"\n</code></pre>\n\n<pre><code>>>> Matrix.zeros(2, 2)\nMatrix([[0, 0], [0, 0]])\n</code></pre>\n<hr />\n<p>Instead of using <code>*</code> both for scalar and matrix multiplication, you could implement the (normally unused) operator <code>@</code>, which is called matrix multiplication. In order to do so, simply implement the dunder method <code>__matmul__</code>. Even if you want <code>*</code> to do both things, I would implement <code>__matmul__</code> anyway and just use <code>self @ other</code> in the definition of <code>__mul__</code>.</p>\n<hr />\n<p>Use the built-in <code>sum</code> if you sum up things in a loop:</p>\n<pre><code>determinant = sum((-1)**c * matrix[0][c] * self.determinant_helper(self.get_minor(matrix, 0, c))\n for c in range(len(matrix)))\n</code></pre>\n<p>You can also iterate over the entries and indices at the same time using <code>enumerate</code>:</p>\n<pre><code>determinant = sum((-1)**i * m_0i * self.determinant_helper(self.get_minor(matrix, 0, i))\n for i, m_0i in enumerate(matrix[0]))\n</code></pre>\n<hr />\n<p>I would consider making the <code>determinant</code> method a property. This allows you to easily make it cached in the future:</p>\n<pre><code>class Matrix:\n ...\n\n @property\n def determinant(self):\n """\n finds the determinant by using the helper function to supply the current matrix of the object\n changes integer floats to integers, and so on\n """\n det = self.determinant_helper(self.matrix)\n return int(det) if det.is_integer() else det\n\n def inverse(self):\n """\n acquires the inverse form of a matrix by using laplace's expansion\n which is A^-1 (inverse matrix) = 1/determinant * C^T (transposed matrix of all cofactors of all elements in matrix along main diagonal)\n """\n determinant = self.determinant\n ...\n</code></pre>\n<p>In order to cache the result, you just need to use a <a href=\"https://docs.python.org/dev/library/functools.html?highlight=s#functools.cached_property\" rel=\"nofollow noreferrer\">different decorator</a> (Python 3.8+):</p>\n<pre><code>from functools import cached_property\n\n...\n\nclass Matrix:\n ...\n\n @cached_property\n def determinant(self):\n ...\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T07:26:21.357",
"Id": "244308",
"ParentId": "244299",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244308",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T01:43:43.370",
"Id": "244299",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"matrix",
"mathematics"
],
"Title": "Python - A Numeric Matrix Calculator/Processor"
}
|
244299
|
<p>I have made a script that syncs one folder to another. So if, for example, you saved some changes in a file in directory <code>A</code>, then that file would have the same contents om directory <code>B</code> if you set it up.</p>
<p>It runs on Python 3 and the <a href="https://pypi.org/project/watchdog/" rel="noreferrer"><code>watchdog</code></a> module. If you are wishing to try it out (and please do), make sure to install <code>watchdog</code> with <code>pip install watchdog</code>.</p>
<p>Here is the code:</p>
<pre><code>import logging
import pathlib
from watchdog.observers import Observer # pip install watchdog
from watchdog.events import FileSystemEventHandler # PyPI: https://pypi.org/project/watchdog/
import time
# Thanks @Tarik and @joelhed on Stack Overflow
# https://stackoverflow.com/questions/62501333/
# Set logging level
logging.basicConfig(level=logging.INFO,
format="%(asctime)s - %(levelname)s:\t%(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
# List of files to sync to
# Example: [["move", [path (string), path]],
# ["create", path],
# ["delete", path],
# ["modify", path]]
changes = []
# Define the main application code
class FolderSyncer(object):
def __init__(self, src, dst):
# Define paths
self.source_path = src
self.destination_path = dst
logging.debug(f"\nSource path:\t\t{self.source_path}\n"
f"Destination path:\t{self.destination_path}")
# Make a file system observer
self.observer = Observer()
# Schedule it with our EventHandler(), the path, and recursive
self.observer.schedule(EventHandler(), str(self.source_path), recursive=True)
# If we are completely synced
self.synced = False
def __enter__(self):
logging.debug("Entered the Folder Syncer")
# Start the observer
self.observer.start()
# Must return self for context managers
return self
def run(self):
while True:
if len(changes) > 0:
# Remove first change from queue
change = changes.pop(0)
# We are still handling changes, so we are not synced
self.synced = False
logging.debug(f"Handling {change[0]} from {change[1]}")
# Handle change here, pretend to do something
if change[0] == "move":
(self.destination_path / change[1][0].replace(str(self.source_path), "")).replace(
self.destination_path / change[1][1].replace(str(self.source_path), "")
)
elif change[0] == "create":
# If it's a file
if pathlib.Path(change[1]).is_file():
# Write the file's contents
(self.destination_path / change[1].replace(str(self.source_path), "")).write_bytes(
pathlib.Path(change[1]).read_bytes()
)
# Else, it's a directory
else:
(self.destination_path / change[1].replace(str(self.source_path), "")).mkdir(exist_ok=True)
elif change[0] == "delete":
try:
# Try to remove as file
(self.destination_path / change[1].replace(str(self.source_path), "")).unlink()
except PermissionError:
# It's a directory, so remove it as a directory
(self.destination_path / change[1].replace(str(self.source_path), "")).rmdir()
elif change[0] == "modify":
try:
(self.destination_path / change[1].replace(str(self.source_path), "")).write_bytes(
pathlib.Path(change[1]).read_bytes()
)
except PermissionError:
pass
logging.info(f"Finished handling {change[0]} from {change[1]}, {len(changes)} changes left!")
else:
if not self.synced:
self.synced = True
logging.info("You are all completely synced!")
time.sleep(1)
def __exit__(self, exc_type, exc_value, traceback):
logging.warning("Exited the Folder Syncer")
# Stop the observer
self.observer.stop()
# Join the observer to the current thread
self.observer.join()
# Define an event handler
class EventHandler(FileSystemEventHandler):
def on_moved(self, event):
super(EventHandler, self).on_moved(event)
what = "directory" if event.is_directory else "file"
logging.debug(f"Moved {what}: from {event.src_path} to {event.dest_path}")
changes.append(["move", [event.src_path, event.dest_path]])
def on_created(self, event):
super(EventHandler, self).on_created(event)
what = "directory" if event.is_directory else "file"
logging.debug(f"Created {what}: {event.src_path}")
changes.append(["create", event.src_path])
def on_deleted(self, event):
super(EventHandler, self).on_deleted(event)
what = "directory" if event.is_directory else "file"
logging.debug(f"Deleted {what}: {event.src_path}")
changes.append(["delete", event.src_path])
def on_modified(self, event):
super(EventHandler, self).on_modified(event)
what = "directory" if event.is_directory else "file"
logging.debug(f"Modified {what}: {event.src_path}")
changes.append(["modify", event.src_path])
with FolderSyncer(pathlib.Path(r"U:"), pathlib.Path(r"F:\USB 64GB sync")) as folder_syncer:
folder_syncer.run()
</code></pre>
<p>You will most likely want to change the directory you want to sync and the location. To do that, scroll down to the bottom and change the parameters in the <code>pathlib.Path()</code> objects. For example, if you want to change the directory you want to sync <code>D:</code> to <code>E:</code>, than you would change:</p>
<pre><code>with FolderSyncer(pathlib.Path(r"U:"), pathlib.Path(r"F:\USB 64GB sync")) as folder_syncer:
folder_syncer.run()
</code></pre>
<p>to</p>
<pre><code>with FolderSyncer(pathlib.Path(r"D:"), pathlib.Path(r"E:")) as folder_syncer:
folder_syncer.run()
</code></pre>
<p>I would appreciate any code optimizations, bug-squashing, clean-ups (It's quite messy, even with classes), and some security fixes are good too. Performance is a plus, but I would like to keep it readable too.</p>
<p>Thanks in advance!</p>
<p>(̶O̶h̶,̶ ̶a̶n̶d̶ ̶B̶T̶W̶,̶ ̶w̶h̶y̶ ̶i̶s̶ ̶<code>̶f̶o̶l̶d̶e̶r̶</code>̶ ̶n̶o̶t̶ ̶a̶ ̶t̶a̶g̶?̶)̶ Totally didn't forget that folder means directory*. Thanks Reinderien</p>
<p>*sarcasm</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T02:56:17.183",
"Id": "479610",
"Score": "0",
"body": "_why is folder not a tag?_ - Folder is a colloquial alias for directory; `file-system` captures it well enough."
}
] |
[
{
"body": "<h2>Python 3 classes</h2>\n<p>You should omit <code>(object)</code> as the base class for classes in Python 3.</p>\n<h2>Re-entrance</h2>\n<p><code>changes</code> is a global that's mutated by <code>FolderSyncer</code>, so immediately this is neither re-entrant nor thread-safe. Maybe move the changes list to a member of <code>FolderSyncer</code>.</p>\n<h2>Anonymous tuples</h2>\n<p>Your <code>changes</code> has a few other issues:</p>\n<ul>\n<li>The inner lists should be tuples, because - though the outer list changes - the inner items do not.</li>\n<li>The inner lists have implied positional significance - item 0 is assumed to be an operation string and item 1 is assumed to be a path. This should be replaced with a class (maybe a <code>@dataclass</code>) with operation and path members.</li>\n<li>The operation, being stringly-typed, has no guarantees about constraint to valid values. It should be replaced with an <code>Enum</code>.</li>\n</ul>\n<h2>Pathlib</h2>\n<p>There's a lot to unpack here:</p>\n<pre><code> (self.destination_path / change[1][0].replace(str(self.source_path), "")).replace(\n self.destination_path / change[1][1].replace(str(self.source_path), "")\n )\n</code></pre>\n<p>Let's first reformat it so that it's legible by humans:</p>\n<pre><code>source_path, dest_path = change[1]\n\n(\n self.destination_path\n / (\n source_path\n .replace(str(self.source_path), "")\n )\n).replace(\n self.destination_path\n / (\n dest_path \n .replace(str(self.source_path), "")\n )\n)\n</code></pre>\n<p>I can only be half-sure that I got that right. That one-liner should be unpacked into probably at least five separate statements, with well-named temporary variables. Otherwise, this is madness.</p>\n<p>Further, you're doing a mix of <code>pathlib</code> (good) and string manipulation (not good). Attempt to avoid <code>str()</code> and <code>replace()</code>, and use the path manipulation functions from <code>pathlib</code> to extract what you need.</p>\n<h2>Imports</h2>\n<p>Rather than writing <code>pathlib.Path</code> all the time, consider just <code>from pathlib import Path</code>.</p>\n<h2>Sleep?</h2>\n<p>If you're doing this:</p>\n<pre><code>time.sleep(1)\n</code></pre>\n<p>because the console window will disappear if you don't, then there are better solutions that don't pollute your code and hang the program for your user. The reason I'm guessing this is why you sleep is that you have Windows-style example paths.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T03:34:20.187",
"Id": "479611",
"Score": "1",
"body": "Thank you for your answer! I will work on this tommorow (If I have time). The only reason I have a `time.sleep(1)` is that to reduce CPU usage. If it doesn't have a big impact, I'll remove it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T03:13:41.250",
"Id": "244301",
"ParentId": "244300",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244301",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T02:00:09.900",
"Id": "244300",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"file-system",
"sync"
],
"Title": "Folder Syncer in Python"
}
|
244300
|
<p>I am developing a statistics library in .net. I have developed a <code>Set<T></code> data structure. Now, I want to derive a data structure named <code>DescriptiveStatisticalSet<T></code>, and I want this set to be able to operate only on integer and double types.</p>
<p><strong>Problem:</strong></p>
<blockquote>
<p>I want to implement a generic type that is able to work with integer
and double data types only.</p>
<p>Say, I have the following interfaces and classes:</p>
<pre><code>public interface IIntegerDataType
{
int Data { get; set; }
int Add(int other);
}
public interface IDoubleDataType
{
double Data { get; set; }
double Add(double other);
}
public class IntegerDataType : IIntegerDataType
{
public int Data { get; set; }
public int Add(int other)
{
return Data + other;
}
}
public class DoubleDataType : IDoubleDataType
{
public double Data { get; set; }
public double Add(double other)
{
return Data + other;
}
}
</code></pre>
<p>Is it possible to create a generic type <code>DataType<T></code> so that both
(and only) <code>IntegerDataType</code> and <code>DoubleDataType</code> could be accessed
through that generic type?</p>
</blockquote>
<p><strong>Solution:</strong></p>
<p>I have devised <a href="https://dotnetfiddle.net/qJGsAK" rel="noreferrer">the following solution</a>:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataTypeNamespace
{
public interface IDataType
{
object Add(object other);
void SetVal(object other);
}
public interface IDataType<T> where T : IDataType, new()
{
T Add(T other);
}
class IntegerDataType : IDataType
{
public int Data { get; set; }
public object Add(object other)
{
int o = ((IntegerDataType)other).Data;
return Data + o;
}
public void SetVal(object other)
{
Data = (int)other;
}
}
class DoubleDataType : IDataType
{
public double Data { get; set; }
public object Add(object other)
{
double o = ((DoubleDataType)other).Data;
return Data + o;
}
public void SetVal(object other)
{
Data = (double)other;
}
}
public class DataType<T> : IDataType<T> where T : IDataType, new()//https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-constraint
{
IDataType _item;
public DataType(IDataType item)
{
_item = item;
}
public T Add(T other)
{
object o = _item.Add(other);
T t = new T();
t.SetVal(o);
return t;
}
}
public class MainClass
{
public static void Main(string[] args)
{
//IntegerDataType item1 = new IntegerDataType();
//item1.Data = 10;
//IntegerDataType item2 = new IntegerDataType();
//item2.Data = 20;
//DataType<IntegerDataType> l1 = new DataType<IntegerDataType>(item1);
//IntegerDataType sum1 = l1.Add(item2);
DoubleDataType item3 = new DoubleDataType();
item3.Data = 10.5;
DoubleDataType item4 = new DoubleDataType();
item4.Data = 20.5;
DataType<DoubleDataType> l2 = new DataType<DoubleDataType>(item3);
DoubleDataType sum2 = l2.Add(item4);
}
}
}
</code></pre>
<p>Can someone review this? Or, maybe help me to improve?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T06:55:41.380",
"Id": "479615",
"Score": "0",
"body": "I like your namespace naming :D `IDataTypeeeeeeeeeee`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T07:03:23.917",
"Id": "479618",
"Score": "3",
"body": "This boxing and boxing (i.e.: `object other`) introduces a lot of unnecessary memory pressure (allocating a value type on a heap). Generics would be a much more preferable approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T08:29:17.807",
"Id": "479622",
"Score": "2",
"body": "Links rot. Don't point to another site for explanation of your problem, include the relevant text here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:18:17.090",
"Id": "479867",
"Score": "0",
"body": "@BCdotWEB I think it's been fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:29:43.450",
"Id": "479873",
"Score": "1",
"body": "I'm not sure that the effort you're going through is worth any benefit you get from it. Why would any implicitly convertable type be unacceptable? If you can write code that generically handles both ints and doubles, why could it then not handle other numeric types? Maybe try to answer the [5 whys](https://www.isixsigma.com/tools-templates/cause-effect/determine-root-cause-5-whys) on why you want/need this? I.e. why do you need this? [in response to that answer] Why is that? [and repeat]."
}
] |
[
{
"body": "<p>As has been said in the comments, it's unclear why you feel you need this behaviour to restrict the types used. There's an interesting discussion around constraining types <a href=\"https://stackoverflow.com/a/34186/592182\">here</a>, which includes a link to example code.</p>\n<p>So, there's a couple of questions. Why do you need to restrict it to <code>double</code> / <code>integer</code> types? Is it really that you want to do is restrict it to types that support certain operations? What is the actual downside to using it for <code>Decimal</code> / <code>float</code>?</p>\n<p>You've presented an example of <code>IDataType</code>, however suggested that really your goal is to put these items into a set. So this begs the question, are you planning on creating <code>DescriptiveStatisticalSet<IntegerDataType></code> or <code>DescriptiveStatisticalSet<IDataType></code>? If it's <code>IntegerDataType</code>, what are you gaining over <code>Int32</code> for example? If it's <code>IDataType</code>, then are you expecting to have both <code>IntegerDataType</code> and <code>DoubleDataType</code> both present in the same set? If so, what are you planning on doing if an Integer has the same value as a Double? Do you keep both because they are different types, or keep whichever one was there first, or keep the Double because it's more flexible, or the Integer because it's faster?</p>\n<p>Looking at your actual code, there's some aspects which are worth mentioning.</p>\n<blockquote>\n<pre><code>object Add(object other);\n</code></pre>\n</blockquote>\n<p>If we look at <code>IntegerDataType</code>, this method takes in an other of type <code>IntegerDataType</code>, but returns an <code>int</code>. This it not at all obvious from the method signature. You are working around this to an extent in your <code>DataType</code> class, which does some recasting by creating a new instance of the returned object, however this seems unnecessarily complex. Particularly since the implementation of <code>Add</code> relies on casting <code>other</code> to the correct type. Calling <code>Add</code> with a <code>DoubleDataType</code> for example throws a cast exception.</p>\n<blockquote>\n<pre><code>public int Data { get; set; }\n</code></pre>\n</blockquote>\n<p>Both your <code>Integer</code> and <code>Double</code> data types declare a <code>Data</code> property that has both public getter and setter. Since you're implementing an interface to <code>setVal</code>, does it really make sense to declare this public setter? It feels like it would be better for the <code>set</code> to be private, in order to encourage the client to use the interface method, in case you decide you need to do additional checking in the future.</p>\n<p>Your <code>DataType</code> class seems to exist purely to create a new item from the <code>object</code> version of <code>Add</code>. This seems to add unnecessary complexity over just having the initial <code>Add</code> return the correct datatype. So, it's a bit unclear to me what advantage your current approach has over simply doing this:</p>\n<pre><code>public interface IOtherDataType<T>\n{\n T Data { get;}\n\n IOtherDataType<T> Add(IOtherDataType<T> other);\n void SetVal(T other);\n}\n\npublic class IntType : IOtherDataType<int>\n{\n public IntType(int data)\n {\n Data = data;\n }\n\n public int Data { get; private set; }\n\n public IOtherDataType<int> Add(IOtherDataType<int> other)\n {\n return new IntType(Data + other.Data);\n }\n\n public void SetVal(int other)\n {\n Data = other;\n }\n}\n</code></pre>\n<p>Which can be used in a similar way...</p>\n<pre><code>IntType five = new IntType(5);\nIOtherDataType<int> eleven = five.Add(new IntType(6));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T13:10:55.777",
"Id": "244830",
"ParentId": "244304",
"Score": "1"
}
},
{
"body": "<p>I may be wrong, but I think you're trying to solve an XY-problem. If I understand the term "<code>DescriptiveStatisticalSet</code>", you want to provide a data set class, that exposes some significant statistical properties and therefore the generic type parameter of the set must be a numeric type of some kind (int, double, ??). To fix that, you try to develop a certain <code>int</code> and <code>double</code> data type, that you can constraint the <code>DescriptiveStatisticalSet<T></code>'s type parameter with. I think you'll get tired of that design rather quickly, because you'll have to convert to/from this "intermediate" type constantly, whenever you'll want to use the set.</p>\n<p>I think I would go in another direction by only allow the creation of <code>DescriptiveStatisticalSet<T></code> for certain data types, which can be done in the following way:</p>\n<pre><code> // For this illustration, I've just implemented the Set<T> as a generic list sub class. Yours is surely more sophisticated.\n public class Set<T> : List<T>\n {\n public Set()\n {\n\n }\n\n public Set(IEnumerable<T> data) : base(data)\n {\n\n }\n }\n\n\n public abstract class DescriptiveStatisticalSet<T> : Set<T>\n {\n protected DescriptiveStatisticalSet(IEnumerable<T> data) : base(data)\n {\n\n }\n\n public virtual T Average => default;\n public virtual T Median => default;\n public virtual T StdDev => default;\n // TODO public other key values...\n }\n\n public static class DescriptiveStatisticalSet\n {\n private class IntDescriptiveStatisticalSet : DescriptiveStatisticalSet<int>\n {\n public IntDescriptiveStatisticalSet(IEnumerable<int> data) : base(data)\n {\n\n }\n\n public override int Median\n {\n get\n {\n var ordered = this.OrderBy(v => v).ToArray();\n if (Count % 2 == 0) return (ordered[Count / 2] + ordered[Count / 2 + 1]) / 2;\n return ordered[Count / 2];\n }\n }\n }\n\n private class DoubleDescriptiveStatisticalSet : DescriptiveStatisticalSet<double>\n {\n public DoubleDescriptiveStatisticalSet(IEnumerable<double> data) : base(data)\n {\n\n }\n\n public override double Median\n {\n get\n {\n var ordered = this.OrderBy(v => v).ToArray();\n if (Count % 2 == 0) return (ordered[Count / 2] + ordered[Count / 2 + 1]) / 2.0;\n return ordered[Count / 2];\n }\n }\n\n }\n\n public static DescriptiveStatisticalSet<int> Create(IEnumerable<int> data)\n {\n return new IntDescriptiveStatisticalSet(data);\n }\n\n public static DescriptiveStatisticalSet<double> Create(IEnumerable<double> data)\n {\n return new DoubleDescriptiveStatisticalSet(data);\n }\n\n }\n</code></pre>\n<hr />\n<p>Used as:</p>\n<pre><code> var doubleStatSet = DescriptiveStatisticalSet.Create(new[] { 1.2, 3.4, 5.6 });\n Console.WriteLine(doubleStatSet.GetType().Name);\n Console.WriteLine(doubleStatSet.Median);\n var intStatSet = DescriptiveStatisticalSet.Create(new[] { 1, 2, 3, 4, 5 });\n Console.WriteLine(intStatSet.GetType().Name);\n Console.WriteLine(intStatSet.Median);\n\n var decimalStatSet = DescriptiveStatisticalSet.Create(new[] { 1.2m, 3.4m, 5.6m }); // ERROR wont compile\n</code></pre>\n<hr />\n<p>A simpler construct that builds on the same principles is to always operate on <code>double</code> in <code>DescriptiveStatisticalSet</code> and then only provide two constructors: one that takes a <code>double</code> data set and another taking an <code>int</code> data set:</p>\n<pre><code> public class DescriptiveStatisticalSet : Set<double>\n {\n public DescriptiveStatisticalSet(IEnumerable<double> data) : base(data)\n {\n }\n\n public DescriptiveStatisticalSet(IEnumerable<int> data) : this(data.Cast<double>())\n {\n\n }\n\n public double Average => ((IEnumerable<double>)this).Average();\n public double Median => default;\n public double StdDev => default;\n // TODO public other key values...\n\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-01T17:12:11.897",
"Id": "244840",
"ParentId": "244304",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244840",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T04:55:25.657",
"Id": "244304",
"Score": "4",
"Tags": [
"c#",
"generics"
],
"Title": "Solution of class design issue of generic of restricted type"
}
|
244304
|
<p>I have a form on my page. I am using jQuery validation for client-side and PHP for server-side validation. I am using PDO. I don't have any issues with client-side and server-side validation. My form is working. I want to know that is this code is the best code with serverside validation with logic?</p>
<p><strong>Client-side validation</strong></p>
<pre><code><script type = "text/javascript" >
$("#userregister").validate({
rules: {
user_name: {
required: true,
minlength: 3
},
user_profile_pic: {
required: true,
extension: "jpg,jpeg,png",
filesize: 1000000, // <- 1 MB
},
user_email: {
required: true,
email: true,
emailExt: true
},
user_mobileno: {
required: true,
minlength: 10,
maxlength: 10,
number: true,
mobileValidation: true
},
user_city: {
required: true,
minlength: 3
},
terms: {
required: true
},
},
messages: {
user_profile_pic: {
filesize: "File size must be less than 1MB.",
extension: "Sorry, only jpg, jpeg & png files are allowed."
}
},
submitHandler: function(form) {
// alert('hello');
var formData = new FormData(form);
$.ajax({
url: "process.php",
type: "POST",
dataType: "json",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(response) {
// alert("success");
if (response.error_no === '1') {
$('#formerros').html(response.error);
} else if (response.error_no === '2') {
$('#erroremail').html(response.error);
} else if (response.error_no === '3') {
$('#errorphone').html(response.error);
} else if (response.error_no === '4') {
$('#errorfile').html(response.error);
} else {
window.location = "success";
}
},
}); // AJAX Get Jquery statment
}
});
</code></pre>
<p><strong>Server-side validation with logic</strong></p>
<pre><code>function userregister($pdo){
$rv_user_name=validate_data($_POST['user_name']);
$rv_user_email=validate_data($_POST['user_email']);
$rv_user_mobileno=validate_data($_POST['user_mobileno']);
$rv_user_city=validate_data($_POST['user_city']);
$terms=validate_data($_POST['terms']);
$user_profile_pic =" ";
$target_dir = "assets/images/uploads/user_profile_pic/";
$filename = basename($_FILES['user_profile_pic']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new1 = mt_rand();// random number
$new_img_name = $new1.'.'.$extension;
$target_file = $target_dir . $new_img_name;
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);
$filename = pathinfo($target_file,PATHINFO_FILENAME);
if(($rv_user_name =="") || ($rv_user_name =="") || ($rv_user_email =="") || ($rv_user_mobileno =="") || ($rv_user_city =="") ) {
$errorMsg[]= "All fields must be completed before you submit the form.";
$code= "1" ;
}
elseif(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $rv_user_email)){
$errorMsg[]= "You did not enter a valid email.";
$code="2";
}
elseif($rv_user_mobileno == "") {
$errorMsg[]="Please enter mobile number.";
$code= "3" ;
}
elseif(is_numeric(trim($rv_user_mobileno)) == false){
$errorMsg[]="Please enter numeric value.";
$code= "3" ;
}elseif(strlen($rv_user_mobileno)<10){
$errorMsg[]="Number should be 10 digits.";
$code= "3" ;
}
else if ($_FILES['reviewer_user_profile_pic']['name'] == ""){
$errorMsg[]="Please upload profile pic.";
$code="4";
}
else if($FileType != "jpg" && $FileType != "jpeg" && $FileType != "png" ) {
$errorMsg[]="Sorry, only jpg, jpeg & png files are allowed.";
$code="4";
$uploadOk = 0;
}
else if ($_FILES["reviewer_user_profile_pic"]["size"] > 1000000) {
$errorMsg[]="Sorry, your file is too large.";
$code="4";
$uploadOk = 0;
}
else{
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$errorMsg[]="Sorry, your file was not uploaded.";
$code="4";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["reviewer_user_profile_pic"]["tmp_name"], $target_file)) {
$imagename= $new_img_name;
} else {
$errorMsg[]="Sorry, there was an error uploading your file.";
$code="4";
}
}
try{
$arrayname=array(
'pd_name'=>$rv_user_name,
'pd_pic'=>$imagename,
'pd_email'=>$rv_user_email,
'pd_contact'=>$rv_user_mobileno,
'pd_city'=>$rv_user_city,
'terms'=>$terms
);
$sql="INSERT INTO `tbl_details`(`pd_name`, `pd_pic`, `pd_email`, `pd_contact`, `pd_city`, `pb_name`,`terms`)VALUES (:pd_name,:pd_pic,:pd_email,:pd_contact,:pd_city,:pb_name,:terms)";
$stmt= $pdo->prepare($sql);
$stmt->execute($arrayname);
$code =5;
$errorMsg= "Success";
$response['error'] = "true";
}
catch(PDOExecption $e) {
$dbh->rollback();
print "Error!: " . $e->getMessage() . "</br>";
$response['error'] = "false";
}
}//else
echo json_encode($response);
}
function validate_data($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = strip_tags($data);
$data = htmlspecialchars($data);
return $data;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T20:06:04.517",
"Id": "479694",
"Score": "2",
"body": "Welcome to Code Review. While it's great that a review enabled you to improve your code, 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, as it unfortunately invalidates the existing review(s). This is not a forum where you should keep the most updated version in your question, so I rolled your changes back to the previous version. Please see see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)* for ways to announce your new code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T21:21:44.093",
"Id": "479702",
"Score": "0",
"body": "@Zeta, Noted. Thanks for the information."
}
] |
[
{
"body": "<ul>\n<li><p>Client-side validation can improve the UX and clarify the expected field values for well-behaved users, but the naughty folks that want to interact with your application will have no trouble bypassing these barriers to submission.\nAll of the restrictions that you impose in the jquery <code>validate()</code> call must be duplicated in the php script if you want to truly filter submission data.</p>\n</li>\n<li><p>I don't see any reason to call <code>validate_data()</code> (honestly, the function should be named <code>sanitize_data()</code>) on <code>$_POST['user_email']</code>, a valid email will not allow any of the things that you are sanitizing. If you want to sanitize the other values, okay.</p>\n</li>\n<li><p>You are using a battery of <code>if-elseif-else</code> statements (by the way, use <code>elseif</code> versus <code>else if</code> in php -- they are technically different but not meaningfully so), so it is impossible to collection more than one error in a submission. For this reason, an array is an inappropriate data type. Just save the error message as a string.</p>\n</li>\n<li><p>Use consistent spacing on either side of the assigment operator when declaring variables. Use 4-spaces or tabs (depending on your preference) so that your script is easier to read and maintain.</p>\n</li>\n<li><p>Remove the redundant check for emptiness on <code>$rv_user_name</code> (specifically <code>($rv_user_name =="") || ($rv_user_name =="")</code>. You also don't need to wrap any of the individual conditions in parentheses to maintain the disqualifying logic.</p>\n</li>\n<li><p>Pass a consistent set of response data back to your ajax call. It needn't be anything more than</p>\n<pre><code>$response = ['target' => 'formerros', 'message' => 'All fields must be completed before you submit the form.'];\n</code></pre>\n<p>or</p>\n<pre><code>$response = ['target' => '', 'message' => 'Success'];\n</code></pre>\n<p>This way there are no magical <code>error_no</code> numbers to translate and you can simply check if <code>!response.target</code> (which means Success), otherwise show the <code>response.message</code> string at the targeted field by its id.</p>\n</li>\n<li><p>Don't use regex to validate an email, the more accurate it is the more convoluted it looks. Just use <code>filter_var()</code> <a href=\"https://stackoverflow.com/a/5855853/2943403\">How to validate an Email in PHP?</a>.</p>\n</li>\n<li><p>Any place where you are making a loose comparison on an empty string, you might as well just use <code>!</code> for example: <code>!$rv_user_mobileno</code>.</p>\n</li>\n<li><p>Condense your file extension check by using <code>in_array()</code> with an array of whitelisted extensions.</p>\n</li>\n<li><p>Don't bother with the <code>try-catch</code> block once you get this into production, you are going to want those errors to go to the logs. Read this advice: <a href=\"https://codereview.stackexchange.com/a/243749/141885\">https://codereview.stackexchange.com/a/243749/141885</a> Definitely don't pass back the generated <code>$e->getMessage()</code> string.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T08:46:44.270",
"Id": "479625",
"Score": "0",
"body": "Give me some time to understand your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:54:21.130",
"Id": "479632",
"Score": "0",
"body": "I'm happy to explain anything that is unclear -- that is my responsibility as a reviewer. If you don't understand something then I have failed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:58:36.567",
"Id": "479633",
"Score": "0",
"body": "Yes, I'll update you here. Please allow me some hours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T20:13:24.867",
"Id": "479696",
"Score": "0",
"body": "I appreciate your help and support. This is great information for me to improve my skills. I have some doubts. Point no 6 and Point no 10-> Do you have any link where i can check the example and learn? Point no 8->It's confused me. Some of the correcton I done in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T08:39:35.893",
"Id": "479748",
"Score": "0",
"body": "Regarding #6, I am trying to streamline the information that php is sending back to javascript. Your javascript response handling code wants to know 1. If there was success, or if any errors then 2. What needs to be said and 3. where should the message be written on the html document. By having php pass back an array containing two pieces of data as a json encoded string, the exhaustive condition block can be avoided in the javascript. If the `target` value is empty, then the php script was successful, otherwise `$('#' + response.target).html(response.message);`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T08:43:35.190",
"Id": "479750",
"Score": "0",
"body": "#10 is a much deeper concept. The link to YourCommonSense's advice may be a little advanced. Generally, you don't need to worry about catching exceptions with your script because as long as you have written the correct table and column names, your sql is never going to break."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T08:49:59.573",
"Id": "479752",
"Score": "0",
"body": "Regarding #8 here's some reading: https://www.php.net/manual/en/types.comparisons.php and https://stackoverflow.com/q/6693876/2943403"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T09:40:53.150",
"Id": "479754",
"Score": "0",
"body": "\"you have written the correct table and column names, your SQL is never going to break\" This statement gives me a smile on my face that I am on the correct path. I'll implement your feedback with my code and then I'll ask one more question after implementation. Thank you so much for your valuable feedback. Upvote from my side."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T08:16:53.097",
"Id": "244310",
"ParentId": "244305",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244310",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T06:49:41.923",
"Id": "244305",
"Score": "2",
"Tags": [
"php",
"jquery",
"validation",
"pdo"
],
"Title": "What is the best way to use serverside validation in PHP PDO?"
}
|
244305
|
<p>I create <a href="https://github.com/storenth/react-redux-todo" rel="nofollow noreferrer">https://github.com/storenth/react-redux-todo</a> and ask to review my Todo-react-app for programming pattern: dividing components into presentational components and container components.</p>
<p>Here’s the basic idea behind it: if a component has to have state, make calculations based on props, or manage any other complex logic, then that component shouldn’t also have to render HTML-like JSX.</p>
<p>Instead of rendering HTML-like JSX, the component should render another component. It should be that component’s job to render HTML-like JSX.</p>
<p>So, my question about the <code>/containers/TodosContainer</code> that contains <code>/components/Todos</code> and <code>/components/AddForm</code>. Does it match the pattern? I didn't get where to place the <code>AddForm</code>, inside <code>/components/Todos</code> (to complex I guess)?</p>
<pre><code>import React, { Component, Fragment } from 'react';
import { Todos } from "../components/Todos";
import { AddForm } from "../components/AddForm";
export class TodosContainer extends Component {
constructor(props) {
super(props);
this.state = { items: [], text: '' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.removeItem = this.removeItem.bind(this);
}
handleChange = (e) => {
this.setState({
text: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault();
if (this.state.text.length === 0) {
return;
}
const newItem = {
text: this.state.text,
id: Date.now()
};
this.setState({
items: this.state.items.concat(newItem),
text: ''
})
}
removeItem = (id) => {
const items = this.state.items.filter(item => {
return item.id !== id;
})
this.setState({
items
})
console.log(this.state);
}
render() {
return (
<>
<Todos items={this.state.items} removeItem={this.removeItem} />
<AddForm items={this.state} onSubmit={this.handleSubmit} onChange={this.handleChange} />
</>
)
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T08:34:49.517",
"Id": "479745",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T11:14:01.237",
"Id": "479757",
"Score": "0",
"body": "@BCdotWEB will be very helpful you start to editing my post."
}
] |
[
{
"body": "<p>I'd say, if it's the <a href=\"https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0\" rel=\"nofollow noreferrer\">Presentation and Container Components</a> pattern as described by Dan Abramov, then yes, you've pretty effectively nailed it. (<em>Though Dan no longer advocates this pattern!!</em>)</p>\n<h1>Suggestions/Review</h1>\n<h2>AddForm</h2>\n<p><code>items</code> prop is really the <code>text</code> state in the parent component, it doesn't need the entire state object. (If it does then name it more accurately!) What's used is <em>just</em> the input value, so <code>value</code> is a better descriptor.</p>\n<pre><code>export const AddForm = ({ value, onSubmit, onChange }) => {\n console.log(value);\n return (\n <div className="add-item-form">\n <form onSubmit={e => onSubmit(e)}>\n <label htmlFor="name">Add new todo:</label>\n <input\n type="text"\n id="name"\n onChange={e => onChange(e)}\n value={value}\n />\n <button\n className="btn waves-effect waves-light"\n type="submit"\n name="action"\n >\n Add item\n </button>\n </form>\n </div>\n );\n};\n</code></pre>\n<p>Usage: <code><AddForm value={this.state.text} ... /></code></p>\n<h2>TodosContainer</h2>\n<p>The handlers are all arrow functions, they already have the <code>this</code> of the class bound to them, so there isn't need to bind them in a constructor. In fact, if all the constructor is doing is setting the initial state, then you don't really need the constructor either as you can simply set initial state with a state instance variable.</p>\n<p>Instead of</p>\n<pre><code>constructor(props) {\n super(props);\n this.state = { items: [], text: '' };\n this.handleChange = this.handleChange.bind(this);\n this.handleSubmit = this.handleSubmit.bind(this);\n this.removeItem = this.removeItem.bind(this);\n}\n</code></pre>\n<p>Simply</p>\n<pre><code>state = { items: [], text: '' };\n</code></pre>\n<h3>State updates</h3>\n<p>When <em>any</em> next state depends upon current state, like incrementing counters, or adding values to arrays, you should get into the habit of using functional state updates, and also not referencing <code>this.state</code> within the state update.</p>\n<p><a href=\"https://reactjs.org/docs/state-and-lifecycle.html\" rel=\"nofollow noreferrer\">State and Lifecycle</a>\n<a href=\"https://reactjs.org/docs/react-component.html#setstate\" rel=\"nofollow noreferrer\">setState</a></p>\n<p><code>handleSubmit</code> can be improved</p>\n<pre><code>handleSubmit = (e) => {\n e.preventDefault();\n const newItem = {\n text: this.state.text,\n id: Date.now(),\n };\n if (this.state.text) { // <-- if text is truthy, i.e. non-empty string\n this.setState(prevState => ({\n items: prevState.items.concat(newItem), \n }));\n }\n}\n</code></pre>\n<p>State updates are also asynchronous, so don't try to console.log it after requesting the state update. Use a component lifecycle like <code>componentDidUpdate</code> to log state after the update (or for class-based components, you <em>can</em> use the setState 2nd parameter callback function, but for simplicity sake stick to the lifecycle functions.).</p>\n<p><code>removeItem</code> handler can be improved</p>\n<pre><code>removeItem = (id) => {\n this.setState(prevState => ({\n items: prevState.items.filter(item => item.id !== id),\n }));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T05:38:37.927",
"Id": "480191",
"Score": "0",
"body": "I will review your answer more closely in a while, thank you. And, yes, in 2019 update, Dan Abramov told us use pattern without dogmatic fervor."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T06:56:20.207",
"Id": "244362",
"ParentId": "244306",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T07:03:59.090",
"Id": "244306",
"Score": "2",
"Tags": [
"javascript",
"design-patterns",
"react.js"
],
"Title": "React programming pattern"
}
|
244306
|
<p>This Q&A was iteration 1. Now there is<br />
<a href="https://codereview.stackexchange.com/questions/244571/iter-2-reusable-robust-c-stdhashmpz-class-for-gmps-big-integer-type">Iter 2: Reusable, robust c++ std::hash<mpz_class> for GMP's big integer type</a></p>
<p><strong>1. Goal</strong></p>
<p>My intention is to provide a fast hashing algorithm to hash <a href="https://gmplib.org/" rel="nofollow noreferrer">GMP</a>'s big integer type <code>mpz_class</code> and <code>mpz_t</code> so I can use these types as keys for an <code>unordered_map</code>. The code shall be reusable for others.</p>
<p>cf. <a href="https://stackoverflow.com/questions/62452712/how-to-write-and-call-stdhash-for-gmps-mpz-class-and-mpz-t">my stackoverflow question about this topic</a></p>
<p><strong>2. My Approach</strong></p>
<p>I've written the C++ glue code to use <a href="https://en.wikipedia.org/wiki/MurmurHash#MurmurHash3" rel="nofollow noreferrer">MurmurHash3</a> to hash a GMP big integer.
The questions about the code are at the bottom of this post.</p>
<p><strong>3. Code</strong></p>
<p>File <strong><code>hash_mpz.h</code></strong>:</p>
<pre><code>#ifndef HASH_MPZ_H_
#define HASH_MPZ_H_
#include <gmpxx.h>
namespace std {
template<> struct hash<mpz_srcptr> {
size_t operator()(const mpz_srcptr x) const;
};
template<> struct hash<mpz_t> {
size_t operator()(const mpz_t &x) const;
};
template<> struct hash<mpz_class> {
size_t operator()(const mpz_class &x) const;
};
}
#endif /* HASH_MPZ_H_ */
</code></pre>
<p>File <strong><code>hash_mpz.cpp</code></strong>:</p>
<pre><code>#include "hash_mpz.h"
#include "MurmurHash3.h"
size_t MurmurHash3_size_t(const void *key, int len, uint32_t seed) {
#if SIZE_MAX==0xffffffff
size_t result;
MurmurHash3_x86_32(key, len, seed, &result);
return result;
#elif SIZE_MAX==0xffffffffffffffff
size_t result[2];
MurmurHash3_x64_128(key, len, seed, &result);
return result[0] ^ result[1];
#else
#error cannot determine correct version of MurmurHash3, because SIZE_MAX is neither 0xffffffff nor 0xffffffffffffffff
#endif
}
namespace std {
size_t hash<mpz_srcptr>::operator()(const mpz_srcptr x) const {
// found 1846872219 by randomly typing digits on my keyboard
return MurmurHash3_size_t(x->_mp_d, x->_mp_size * sizeof(mp_limb_t),
1846872219);
}
size_t hash<mpz_t>::operator()(const mpz_t &x) const {
return hash<mpz_srcptr> { }((mpz_srcptr) x);
}
size_t hash<mpz_class>::operator()(const mpz_class &x) const {
return hash<mpz_srcptr> { }(x.get_mpz_t());
}
}
</code></pre>
<p>File <strong><code>main.cpp</code></strong>:</p>
<pre><code>#include <iostream>
#include <gmpxx.h>
#include <unordered_map>
#include "hash_mpz.h"
using namespace std;
int main() {
mpz_class a;
mpz_ui_pow_ui(a.get_mpz_t(), 168, 16);
cout << "a : " << a << endl;
cout << "hash(a): " << (hash<mpz_class> { }(a)) << endl;
unordered_map<mpz_class, int> map;
map[a] = 2;
cout << "map[a] : " << map[a] << endl;
return 0;
}
</code></pre>
<p>(<a href="https://github.com/jrslepak/murmur3/blob/master/MurmurHash3.h" rel="nofollow noreferrer">click to view MurmurHash3.h</a>)</p>
<p><strong>4. Questions</strong></p>
<p>4.1. In <code>MurmurHash3_size_t()</code>, I check <code>SIZE_MAX</code> to tell whether I'm on a 32 bit system or a 64 bit system. Does this check make sense, are there alternatives which are better?</p>
<p>4.2. Near the end of the file <code>hash_mpz.cpp</code>, I have the statement <code>return hash<mpz_srcptr> { }(x.get_mpz_t());</code>. Does this create an object of type <code>hash<mpz_srcptr></code> for every calculated hash value?</p>
<p>4.3. I'm not sure whether I'm using the references <code>const mpz_class &x</code> and <code>const mpz_t &x</code> in the most efficient way. This is partly due to GMP being a C library, <code>mpz_t</code> is a 1 element array with element type <code>__mpz_struct</code> and <code>mpz_class</code> being something rather obscure to me.</p>
<p>Excerpt from <strong><code>gmp.h</code></strong>:</p>
<pre><code>typedef struct
{
int _mp_alloc; /* Number of *limbs* allocated and pointed
to by the _mp_d field. */
int _mp_size; /* abs(_mp_size) is the number of limbs the
last field points to. If _mp_size is
negative this is a negative number. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpz_struct;
//...
typedef __mpz_struct mpz_t[1];
</code></pre>
<p>Excerpt from <strong><code>gmpxx.h</code></strong>:</p>
<pre><code>typedef __gmp_expr<mpz_t, mpz_t> mpz_class;
</code></pre>
<p>4.4. Last but not least, do you see anything else which can be improved?</p>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>In <code>MurmurHash3_size_t()</code>, I check <code>SIZE_MAX</code> to tell whether I'm on a 32 bit system or a 64 bit system. Does this check make sense, are there alternatives which are better?</p>\n</blockquote>\n<p>I think it's not worth it to write a generic version of this that avoids checking <code>SIZE_MAX</code>, even though that is possible. Machines with a different size_t size than 32 or 64 bits are uncommon, unless you're talking about 8 and 16 bit machines, but I'm assuming you are not interested in using bigints on those.</p>\n<p>But don't forget to <code>#include <cstdint></code>, otherwise <code>SIZE_MAX</code> might not be defined! Alternatively, use <code>sizeof(size_t) == 4</code> and <code>== 8</code>, in combination with <code>if constexpr (...)</code> instead of <code>#if ...</code>.</p>\n<blockquote>\n<p>Near the end of the file hash_mpz.cpp, I have the statement return hash<mpz_srcptr> { }(x.get_mpz_t());. Does this create an object of type hash<mpz_srcptr> for every calculated hash value?</p>\n</blockquote>\n<p>Technically, yet. But those objects don't have any member variables, just a member function <code>operator()</code>, which is resolved at compile-time, so there is no need to worry about inefficiencies here.</p>\n<blockquote>\n<p>I'm not sure whether I'm using the references const mpz_class &x and const mpz_t &x in the most efficient way. This is partly due to GMP being a C library, mpz_t is a 1 element array with element type __mpz_struct and mpz_class being something rather obscure to me.</p>\n</blockquote>\n<p>Using const references to the objects is perfectly fine.</p>\n<blockquote>\n<p>Last but not least, do you see anything else which can be improved?</p>\n</blockquote>\n<p>Yes, see below.</p>\n<h1>Your functions don't handle negative bigints correctly</h1>\n<p>As it mentions in the excerpt from <code>gmp.h</code> you posted, <code>_mp_size</code> will be negative for negative bigints. You need to handle this. One way would just be to write:</p>\n<pre><code>return MurmurHash3_size_t(..., abs(x->_mp_size) * sizeof(mp_limb_t), ...);\n</code></pre>\n<p>However, this means that for a given positive number, that number and its negative will get the same hash value. It may or may not be an issue for your application. One possible solution is to use a different seed value for negative numbers.</p>\n<h1>Consider using <code>std::hash</code> to calculate the hash</h1>\n<p>Yes, you can use <code>std::hash</code> instead of implementing your own. Of course, you need to pick an appropriate existing specialization <code>std::hash</code>. You could iterate over the limbs in the bignum, which are either 32 or 64 bit integers, so you could <code>std::hash</code> those individually, but then the questions is how to combine them. Just adding or XORing them might not result in a good final hash value if there are any patterns in the input. But in C++17, there is a specialization of <code>std::hash</code> for <code>std::string_view</code>. So you can create a view for the limb array, and hash that:</p>\n<pre><code>size_t hash<mpz_srcptr>::operator()(const mpz_srcptr x) const {\n std::string_view view{reinterpret_cast<char *>(x->_mp_d), abs(x->_mp_size) * sizeof(mp_limb_t)};\n return std::hash<std::string_view>{}(view);\n}\n</code></pre>\n<p>There is a good chance that the standard library's hash function for strings is a variant of MurmurHash, see for example <a href=\"https://stackoverflow.com/questions/19411742/what-is-the-default-hash-function-used-in-c-stdunordered-map\">this question</a>.</p>\n<h1>Use the appropriate cast operator instead of C-style casts</h1>\n<p>You should use <code>static_cast<>()</code> if possible to cast similar types, so the compiler will be able to generate an error if you are doing incorrect casts. For example:</p>\n<pre><code>size_t hash<mpz_t>::operator()(const mpz_t x) const {\n return hash<mpz_srcptr>{}(static_cast<mpz_srcptr>(x));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T12:58:26.223",
"Id": "479850",
"Score": "2",
"body": "It's always a pleasure when an experienced wizard takes the effort to explain his magic spells and you have the opportunity to listen. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T15:00:13.837",
"Id": "244325",
"ParentId": "244307",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244325",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T07:11:20.443",
"Id": "244307",
"Score": "5",
"Tags": [
"c++",
"hashcode",
"gmp"
],
"Title": "Iter 1: Reusable, robust c++ std::hash<mpz_class> for GMP's big integer type"
}
|
244307
|
<p>As you can see these functions differ only in <code>keys []int</code> and <code>keys []*int</code> (and in name).</p>
<pre class="lang-golang prettyprint-override"><code>func (db *myDB) QueryWithKeys(keys []int) ([]*models.Player) {
var players = make([]*models.Player, len(keys))
_ := db.Model(&players).Where("id in (?)", pg.In(keys)).Select()
// several other equal code here
return players
}
func (db *myDB) QueryWithPointerKeys(keys []*int) ([]*models.Player) {
var players = make([]*models.Player, len(keys))
_ := db.Model(&players).Where("id in (?)", pg.In(keys)).Select()
// several other equal code here
return players
}
</code></pre>
<p><strong>Is there a way to avoid this code duplication?</strong></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T07:48:04.160",
"Id": "244309",
"Score": "1",
"Tags": [
"go"
],
"Title": "Avoid code duplication if what changes is one argument type only"
}
|
244309
|
<p>The problem was using single <code>Stream</code> from the HTTP response in multiple consumers simultaneously. For example: while data is loading, I want write it to the some cache file and deserealize it at the same time.</p>
<p>This code will not work for an obvious reason. But it represents some desired things.</p>
<pre class="lang-csharp prettyprint-override"><code>private readonly HttpClient _client = new HttpClient();
// BAD CODE!!!
private async Task<T> HttpAPIRequest<T>(string url, string path)
{
using HttpResponseMessage response = await _client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
using Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
using FileStream fileStream = File.Create(path);
ValueTask<T> jsonTask = JsonSerializer.DeserializeAsync<T>(responseStream);
await responseStream.CopyToAsync(fileStream);
return await jsonTask;
}
</code></pre>
<hr />
<h2>The solution</h2>
<p>After few days of hard search for the solution I've ended up with the following one consisting of two classes:</p>
<pre class="lang-csharp prettyprint-override"><code>public sealed class ConcurrentStreamReader : IDisposable
{
private readonly Stream _inputStream;
private readonly MemoryStream _memoryStream;
private readonly int _bufferSize;
private readonly IProgress<long> _progress;
public ConcurrentStreamReader(Stream inputStream) : this(inputStream, null) { }
public ConcurrentStreamReader(Stream inputStream, IProgress<long> progress) : this(inputStream, 81920, 0, progress) { }
public ConcurrentStreamReader(Stream inputStream, int bufferSize, int capacity, IProgress<long> progress)
{
_memoryStream = new MemoryStream(capacity);
_inputStream = inputStream;
_bufferSize = bufferSize;
_progress = progress;
}
public Stream CreateNewStream() => new BlockingStream(ReadStream().GetEnumerator(), _memoryStream);
public async Task CopyToAsync(Stream outputStream)
{
foreach (ReadOnlyMemory<byte> buffer in ReadStream())
{
await outputStream.WriteAsync(buffer);
}
}
private IEnumerable<ReadOnlyMemory<byte>> ReadStream()
{
long position = 0;
byte[] buffer = new byte[_bufferSize];
int bytesRead;
while (true)
{
if (position == _memoryStream.Length)
{
lock (_inputStream)
{
if (position < _memoryStream.Length) continue;
bytesRead = _inputStream.Read(buffer, 0, _bufferSize);
if (bytesRead == 0) break;
lock (_memoryStream)
{
_memoryStream.Position = _memoryStream.Length;
_memoryStream.Write(buffer, 0, bytesRead);
}
}
_progress?.Report(_memoryStream.Length);
}
else
{
lock (_memoryStream)
{
_memoryStream.Position = position;
bytesRead = _memoryStream.Read(buffer, 0, _bufferSize);
}
}
position += bytesRead;
yield return new ReadOnlyMemory<byte>(buffer, 0, bytesRead);
}
}
private bool _disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
_memoryStream.Dispose();
}
}
_disposed = true;
}
~ConcurrentStreamReader() => Dispose(false);
}
public sealed class BlockingStream : Stream
{
private readonly IEnumerator<ReadOnlyMemory<byte>> _sourceEnumerator;
private readonly MemoryStream _stream;
private long _position;
private BlockingStream() { }
public BlockingStream(IEnumerator<ReadOnlyMemory<byte>> sourceEnumerator, MemoryStream stream)
{
_stream = stream;
_sourceEnumerator = sourceEnumerator;
_position = 0;
}
public override int Read(byte[] buffer, int offset, int count)
{
long tail = _position + offset + count;
while (tail >= _stream.Length && _sourceEnumerator.MoveNext()) { }
int bytesRead;
lock (_stream)
{
_stream.Position = _position;
bytesRead = _stream.Read(buffer, offset, count);
}
_position += bytesRead;
return bytesRead;
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override void Flush() => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
</code></pre>
<p>Additionally I've included to the solution the download Progress reporting (that I will not use in the usage example below).</p>
<p>And the usage</p>
<pre class="lang-csharp prettyprint-override"><code>private async Task<T> HttpAPIRequest<T>(string url, string path)
{
using HttpResponseMessage response = await _client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
using Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
using ConcurrentStreamReader reader = new ConcurrentStreamReader(responseStream);
using FileStream fileStream = File.Create(path);
using Stream deserealizerStream = reader.CreateNewStream();
ValueTask<T> jsonTask = JsonSerializer.DeserializeAsync<T>(deserealizerStream);
await reader.CopyToAsync(fileStream);
return await jsonTask;
}
</code></pre>
<p><strong>Environment:</strong> x64 WPF app / .NET Core 3.1</p>
<p>The code works correctly but it's pretty complicated for me especially near <code>lock()</code> statements. I'm not sure of that part and performed some code changes as random fixes while I was testing it. Suggestions are appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:28:38.207",
"Id": "479656",
"Score": "1",
"body": "Have you considered to use `SynchronizedStream` via `Stream.Synchronized`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T14:43:13.887",
"Id": "479657",
"Score": "1",
"body": "@PeterCsala No, but good point. Thank you very much! Will learn something about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T19:56:46.213",
"Id": "479693",
"Score": "0",
"body": "@PeterCsala I've read a lot about [`SynchronizedStream`](https://github.com/dotnet/runtime/blob/master/src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs#L1072) wrapper and it will not help to avoid lock() or make less locks in the code. Thus it's useless for me here. Thanks anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T21:37:31.367",
"Id": "479794",
"Score": "0",
"body": "Welcome to Code Review! 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 should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T23:00:17.783",
"Id": "479803",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Thanks for the warning. I did not update any things that may affect existing answers or comments. Otherwise I'll notify the members of updates. I just solved some bad optimization problems in the code that were not reported neither above nor below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T09:35:27.620",
"Id": "479838",
"Score": "1",
"body": "@aepot Minor but important observation: You are using `lock` statements on those objects on which you are working on. Your `_inputStream `is locked even though it is received as input. Please use separate lock objects for these. Here you can find some valuable resources about this topic: [1](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/lock-statement), [2](https://www.pluralsight.com/guides/lock-statement-best-practices), [3](https://www.tomfosdick.com/archives/90525)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T10:10:29.527",
"Id": "479840",
"Score": "1",
"body": "@PeterCsala You're right but I'm aware of it and was cereful in using locks. I know that it's violates some programming culture and will consider fixing it. Thank you again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T06:37:29.467",
"Id": "480562",
"Score": "1",
"body": "@aepot I've jut forgot to ask you about memory optimization. Is it a concern for you? Because fortunately there are plenty of good techniques to reduce the memory footprint. Like instead of directly allocating a `byte[]` you could use [ArrayPool](https://adamsitnik.com/Array-Pool/). Instead of directly allocating a `MemoryStream` you could use [RecycableMemoryStream](https://github.com/microsoft/Microsoft.IO.RecyclableMemoryStream). You could also take advantage of the `PipeReader` \\ `SequenceReader` [1](https://www.stevejgordon.co.uk/an-introduction-to-sequencereader)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-30T07:05:03.540",
"Id": "480567",
"Score": "1",
"body": "@PeterCsala Yet another Thank you! For now the code looks well-optimized for me. It allocates one `MemoryStream` and not so many `byte[]`s per API request. Another good thing that it doesn't consume more memory for new consumers because `BlockingStream` has no own storage. But I'll definetly look at all listed above classes."
}
] |
[
{
"body": "<p>If you do not need report progress then the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.loadintobufferasync?view=netcore-3.1\" rel=\"nofollow noreferrer\">LoadIntoBuffer</a> <a href=\"https://github.com/microsoft/referencesource/blob/aaca53b025f41ab638466b1efe569df314f689ea/System/net/System/Net/Http/HttpContent.cs#L276\" rel=\"nofollow noreferrer\">source code</a> + <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent.copytoasync?view=netcore-3.1\" rel=\"nofollow noreferrer\">CopyToAsync</a> <a href=\"https://github.com/microsoft/referencesource/blob/aaca53b025f41ab638466b1efe569df314f689ea/System/net/System/Net/Http/HttpContent.cs#L276\" rel=\"nofollow noreferrer\">source code</a> combo could be handy.</p>\n<p>All you need to prevent the concurrent call of the <code>LoadIntoBuffer</code> method. (You can call it n times it does not matter, because the <code>IsBuffered</code> flag will short-cut the method.) This can be done by using a <code>Monitor</code> or a <code>Semaphore</code> for mutual exclusion. Or you can simply use signalling primitives as well, like <code>AutoResetEvent</code>, <code>CountdownEvent</code>.</p>\n<p>With <code>CopyToAsync</code> each thread can have its own copy of the stream, so there won't be a shared resource.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:23:33.017",
"Id": "479767",
"Score": "1",
"body": "Thank you! Unfortunately progress reporting is required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-27T13:14:11.807",
"Id": "480208",
"Score": "1",
"body": "Great thanks for the suggestions! I have no more questions related to my code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T10:51:20.620",
"Id": "244372",
"ParentId": "244314",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244372",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:22:55.553",
"Id": "244314",
"Score": "8",
"Tags": [
"c#",
"concurrency",
"async-await",
"stream",
".net-core"
],
"Title": "Reading one source Stream by multiple consumers asynchronously"
}
|
244314
|
<p>I have the following class:</p>
<pre><code>public class UpdateData {
public static boolean updateHasMessage(Update update) {
return update.hasMessage() && update.getMessage().hasText();
}
public static boolean updateHasCallbackQuery(Update update) {
return update.hasCallbackQuery() && (update.getCallbackQuery().getData()!= null);
}
public static Long getChatId(Update update) {
if (updateHasMessage(update)) {
return update.getMessage().getChatId();
}
else if (updateHasCallbackQuery(update)) {
return update.getCallbackQuery().getMessage().getChatId();
}
else {
return null;
}
}
public static String getUserName(Update update) {
if (updateHasMessage(update)) {
return update.getMessage().getFrom().getUserName();
}
else if (updateHasCallbackQuery(update)){
return update.getCallbackQuery().getFrom().getUserName();
}
else {
return null;
}
}
public static String getInputUserData(Update update) {
if (updateHasMessage(update)) {
return update.getMessage().getText();
}
else if (updateHasCallbackQuery(update)){
return update.getCallbackQuery().getData();
}
else {
return null;
}
}
public static String getCallBackId(Update update) {
return update.getCallbackQuery().getId();
}
public static Integer getMessageId(Update update) {
if (updateHasMessage(update)) {
return update.getMessage().getMessageId();
}
else if (updateHasCallbackQuery(update)){
return update.getCallbackQuery().getMessage().getMessageId();
}
else {
return null;
}
}
public static String getCallBackData(Update update) {
return update.getCallbackQuery().getData();
}
}
</code></pre>
<p>As you can see I have similar block code in most methods:</p>
<pre><code>if (updateHasMessage(update)) {
...
}
else if (updateHasCallbackQuery(update)) {
...
}
else {}
</code></pre>
<p>They return unique information and have various stuff inside, but this is very similar to code duplication.
Do I need to rewrite this or just stay with it? If need to rewrite, then how?</p>
<p><strong>UPDATE</strong></p>
<p>Update is a Telegram API object.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:00:38.760",
"Id": "479634",
"Score": "2",
"body": "Can I see your update-class, or if it is from Telegram, could you tell so? This could give me a lot better understanding of the code. (eg. does `update` and `update.getCallbackQuery()` have the same interface)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:05:52.927",
"Id": "479635",
"Score": "1",
"body": "Yup, Update comes from Telegram API. I dont want to write update.getMessage().getChatId() etc in every handler. And decided to create \"API above API\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T21:47:24.550",
"Id": "479796",
"Score": "2",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>Keep it like that. It is perfectly readable, easy to understand, everything is fine.</p>\n<p>Naturally you <em>could</em> do some lambda trickery along the lines of:</p>\n<pre><code>public static String extractFromMessageOrQuery(\n Update update,\n Function<Update, String> messageExtractor,\n Function<Update, String> queryExtractor,\n String defaultValue) {\n if (updateHasMessage)\n return messageExtractor.apply(update);\n else if (updateHashCallbackQuery(update))\n return queryExtractor.apply(update);\n return defaultValue;\n}\n\npublic static String getInputUserData(Update update) {\n return extractFromMessageOrQuery(\n upd -> upd.getMessage().getText(),\n upd -> upd.getCallbackQuery().getData(),\n null\n );\n}\n</code></pre>\n<p>But: would that make the code</p>\n<ul>\n<li>easier to understand? No</li>\n<li>easier to extend? No</li>\n<li>easier to maintain? No</li>\n</ul>\n<p>Thus: take note that these possibilities exist, and keep the code as-is.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:02:04.233",
"Id": "244317",
"ParentId": "244316",
"Score": "15"
}
},
{
"body": "<p>Assuming <code>Update#getMessage()</code> is of type <code>Message</code> and <code>Update#getCallbackQuery()</code> is of type <code>CallbackQuery</code>:</p>\n<p>You can make a function <code>getUpdateAttribute</code> that receives higher-order functions as handlers for the situation where your update has a message or callback query as follows.</p>\n<pre><code>private static <T> T getUpdateAttribute(Update update,\n Function<Message, T> messageFunc,\n Function<CallbackQuery, T> callbackQueryFunc) {\n if (updateHasMessage(update)) {\n return messageFunc.apply(update.getMessage());\n }\n if (updateHasCallbackQuery(update)) {\n return callbackQueryFunc.apply(update.getCallbackQuery());\n }\n\n return null;\n}\n</code></pre>\n<p>I simplified the <code>if/else</code> code flow to take advantage of early returns. <code>getUpdateAttribute</code> is also generic over <code>T</code> because your attributes can be various types, like <code>Integer</code> and <code>String</code>. Finally, I made it private so your <code>public</code> attribute fetchers are the only interface exposed. Those attribute fetchers then become:</p>\n<pre><code>public static Long getChatId(Update update) {\n return getUpdateAttribute(\n update,\n Message::getChatId,\n callbackQuery -> callbackQuery.getMessage().getChatId()\n );\n}\n\npublic static String getUserName(Update update) {\n return getUpdateAttribute(\n update,\n message -> message.getFrom().getUserName(),\n callbackQuery -> callbackQuery.getFrom().getUserName()\n );\n}\n\npublic static String getInputUserData(Update update) {\n return getUpdateAttribute(\n update,\n Message::getText,\n CallbackQuery::getData\n );\n}\n\npublic static Integer getMessageId(Update update) {\n return getUpdateAttribute(\n update,\n Message::getMessageId,\n callbackQuery -> callbackQuery.getMessage().getMessageId()\n );\n}\n</code></pre>\n<p>Apart from this de-duplication, there is something else you can potentially improve. I'm not familiar with the Telegram API, but if it is possible that a message may have neither a message nor a callback query, then returning <code>null</code> seems like a valid response, in which case you may want to return <code>Optional<T></code> from <code>getUpdateAttribute</code> (and all the other attribute fetchers), as that would signal your intent better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:32:07.160",
"Id": "479639",
"Score": "0",
"body": "Thanks for this interesting solution, tried to use it, but compiler said \"Update is not a functional interface\" on Method Reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:34:46.557",
"Id": "479640",
"Score": "1",
"body": "@hsadik My bad, forgot to pass in `update` itself. See if the edited version works for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:37:46.900",
"Id": "479641",
"Score": "1",
"body": "Yup, after a little thought, I understood that I had to return 3 parametrs and fixed by myself, anyway thanks for fix."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T11:20:01.370",
"Id": "244318",
"ParentId": "244316",
"Score": "10"
}
},
{
"body": "<p>The other solutions gave an answer which is perfect for two classes.<br />\nIf you get to much functions//classes beside CallBack and Message, the code below might give you a better solution.</p>\n<h1>Wrapper</h1>\n<p>I personally would create a wrapper with a common interface.<br />\nThe reason is that this is not very extendable (adding a new class requires rewriting all the common functions.)</p>\n<pre><code>class UpdateDataFactory{\n public UpdateData createUpdateData(Update update){\n if(isMessageUpdateData(update)){\n return new MessageUpdateData(update.getMessage());\n } else if(isCallBackUpdateData()){\n return new CallBackUpdateData(update.getCallBackQuery());\n } else return EmptyUpdateData.getInstance();\n }\n private boolean isMessageUpdateData(Update update){\n return update.hasMessage() && update.getMessage().hasText();\n }\n private boolean isCallBackUpdateData(){\n return update.hasCallbackQuery() \n && (update.getCallbackQuery().getData()!= null);\n }\n}\n\ninterface UpdateData{\n public User getFrom();\n public String getInputUserData();\n public Message getMessage();\n}\npublic class MessageUpdateData implements UpdateData{...}\npublic class CallBackUpdateData implements UpdateData{...}\npublic class EmptyUpdateData implements UpdateData{\n static UpdateData getInstance(){...}\n}\n</code></pre>\n<p>The one problem with this approach is that it requires you to create a new class for each object.</p>\n<h1>Extractors</h1>\n<p>Instead of creating a wrapper for an object, you could also create extractors for a type.</p>\n<pre><code>interface UpdateDataExtractor{\n public boolean canExtract(Update update);\n public User getFrom(Update update);\n public String getInputUserData(Update update);\n public Message getMessage(Update update);\n}\n\n class MessageUpdateDataExtractor implements UpdateDataExtractor{\n public static MessageUpdateDataExtractor getInstance(){...}\n public boolean canExtract(Update update){\n return update.hasMessage() && update.getMessage().hasText();\n }\n ...\n }\n class CallBackUpdateData implements UpdateDataExtractor{\n public static CallBackUpdateDataExtractor getInstance(){...}\n public boolean canExtract(Update update){\n return update.hasMessage() && update.getMessage().hasText();\n }\n ...\n }\n\n class UpdateDataFactory{\n List<UpdateDataExtractor> extractors = new List<UpdateDataExtractor>();\n public UpdateDataExtractor createUpdateData(Update update){\n for(Extractor extractor : extractors)\n if(extractor.canExtract(update)) return extractor;\n return EmptyExtractor.getInstance();\n }\n }\n</code></pre>\n<p>If you don't like the canExtract and just want to store it in separate fields, you could use generics as parameters and make the code more typeSafe.</p>\n<h1>remaining functions</h1>\n<p>I don't exactly know how you should implement the following functions:</p>\n<pre><code>public static String getCallBackId(Update update) {\n return update.getCallbackQuery().getId();\n}\n\npublic static String getCallBackData(Update update) {\n return update.getCallbackQuery().getData();\n}\n</code></pre>\n<p>You could either implement them as all the other functions, or you could only implement them only in <code>CallBackUpdateExtractor</code> or <code>CallBackUpdateData</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T21:58:43.527",
"Id": "485864",
"Score": "0",
"body": "`getCallBackId()` and `getCallBackData()` could be implemented either in an abstract common parent of `UpdateData` called `UpdateDataBase` or something similar, or alternatively right inside the `UpdateData` interface as default methods."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T12:16:09.823",
"Id": "244321",
"ParentId": "244316",
"Score": "5"
}
},
{
"body": "<p>I suspect the root of your problem is that <strong>you're working at the wrong abstraction level.</strong></p>\n<p>Specifically, looking at the Telegram Bot API documentation, it seems that an <a href=\"https://core.telegram.org/bots/api#update\" rel=\"nofollow noreferrer\">Update</a> is just a wrapper for one of several unrelated objects that describe different kinds of events that your application might want to react to. Trying to treat all of these events as if they were the same thing makes no sense — but that's what you're effectively doing in your code, with methods that take an Update object and try to return some property of whatever random event the update might contain. Some of those events, for example, might not even <em>have</em> an associated chat ID or a user name; and even if they do, the way that chat ID or user name is related to the event might not be the same.</p>\n<p>Basically, the <em>only</em> part of your code that should be dealing with Update objects is the low-level code that receives then (from WebHooks or from getUpdates), possibly does reordering and/or de-duplication using the update IDs and then dispatches the event object contained in the Update wrapper to an appropriate handler for that kind of event.</p>\n<p>That is to say, your code for handling updates should look something like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private void handleUpdate(Update update) {\n if (update.hasMessage()) {\n handleNewMessage(update.getMessage());\n } else if (update.hasCallbackQuery()) {\n handleCallbackQuery(update.getCallbackQuery());\n } else if (/* ... */) {\n // ...\n } else {\n // Either we received a truly empty update, or we don't know how to\n // handle its contents. Ignore it and maybe log a warning.\n }\n}\n</code></pre>\n<p>…and then your <code>handleNewMessage(Message message)</code> and <code>handleCallbackQuery(CallbackQuery query)</code> methods (which will <em>not</em> have to deal with Update objects) should handle the messages or callback queries or whatever else they receive appropriately, using the methods provided by the objects they receive as their parameters.</p>\n<p>If you want, you <em>can</em> of course have the different handlers share some code. For example, since a <a href=\"https://core.telegram.org/bots/api#callbackquery\" rel=\"nofollow noreferrer\">CallbackQuery</a> can contain an optional Message, you might want to have your <code>handleCallbackQuery()</code> method internally call <code>handleNewMessage()</code> to deal with the message embedded in the query, if there is one — or, perhaps more practically, have both handler methods call other methods that implement the shared message-processing parts common to both of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T16:57:48.020",
"Id": "479775",
"Score": "0",
"body": "The main reason to write this \"API above API\" is convenience. I have about 15 additional handlers, and I don't want to write `update.getMessage().getFrom().getUsername()` or `update.getCallbackQuery().getMessage().getData()` every time, it's stupid. chatId and messageId always same for both handlers (callback and message), but you need to get them from different objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T16:59:59.460",
"Id": "479777",
"Score": "0",
"body": "@hsadik: My point is that your code should have exactly one call to (e.g.) `update.getMessage()`, and it should be in the method I posted above (or something equivalent to it). All the code the needs to access properties of the message should be working with a Message object, not with an Update. And similarly, you should have only one call to `update.getCallbackQuery()`, like in my example code above, and all code that deals with callback queries should be working with CallbackQuery objects, not with Updates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T17:03:34.403",
"Id": "479778",
"Score": "0",
"body": "… The abstraction level provided by the Update class is only good for one thing, and that thing is finding out what kind of an object is wrapped inside the update you just received and passing it to a handler written specifically for handling those objects. (If you do find that e.g. your Message and CallbackQuery handlers end up doing similar things, then you should certainly split those things into reusable methods that both handlers can call. But those methods still shouldn't be dealing with Update objects; they should be dealing with e.g. Messages and Chats and Strings and integers.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:31:54.100",
"Id": "244377",
"ParentId": "244316",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244318",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T10:42:20.207",
"Id": "244316",
"Score": "7",
"Tags": [
"java",
"object-oriented",
"api"
],
"Title": "If/else produce code duplication"
}
|
244316
|
<p>As a beginner coder in js, I'd like to hear about further improvements of the following code, but nothing too advanced, please.</p>
<p>The program is meant to work the following way:</p>
<ol>
<li>A user inputs a color array like this one: <code>["blue", "green"]</code></li>
<li>The code checks if those words are valid inputs (they should be found in a reference array of COLORS). This is done with <code>catchInvalid</code> function</li>
<li>If they are valid inputs, and so they are found in COLORS array, it gets the index of it. This is done in the <code>decodedValue</code> function</li>
</ol>
<p><strong>Example1:</strong></p>
<pre><code>COLORS= ["blue", "yellow", "red"]
User input: userColors=["yellow"]
returns index of yellow in COLORS i.e 1.
</code></pre>
<p><strong>Example2:</strong></p>
<pre><code>COLORS= ["blue", "yellow", "red"]
User input: userColors=["yellow", "red"]
returns index 12 (index of yellow in colors*10 + index of red in colors (2)).
</code></pre>
<p>That's all. It's now working fine, but I wonder if you'd give any suggestions for improving the code.</p>
<pre><code> const COLORS = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"];
//this will be the reference array
const catchInvalid = (color, COLORS) =>{
//checks if color is in COLORS (which is COLORS)
if(COLORS.indexOf(color)==-1){
return `not a ${color} in ${COLORS}`
}
else { }
}
const decodedValue = (colorArray) => {
//if previous 'color' is in the reference array, get the index of the color in COLORS.
let CODES=[];
if (colorArray.length==0){
return "Input a color value"
}
else if (colorArray.length==1){
catchInvalid(colorArray[0], COLORS)
return COLORS.indexOf(colorArray[0])
}
else {
for(let i=0; i<2;i++){
//only for the first 2 items in the array.
catchInvalid(colorArray[i], COLORS)
CODES.push(COLORS.indexOf(colorArray[i]))
}
return CODES[0]*10 + CODES[1];
}
}
console.log(decodedValue(["blue"]), decodedValue(["nothing"]), decodedValue(["blue", "green"]))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T13:46:30.480",
"Id": "479646",
"Score": "0",
"body": "Welcome to CodeReview"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:05:24.923",
"Id": "479710",
"Score": "0",
"body": "thx again :-) @konijn"
}
] |
[
{
"body": "<p>From a short review, considering you are a beginner;</p>\n<ul>\n<li>keep your variables in lowerCamelCase so\n<ul>\n<li>COLORS -> colors</li>\n<li>CODES -> codes</li>\n</ul>\n</li>\n<li>on the whole, avoid to have data type in the variable name\n<ul>\n<li>colorArray -> colors</li>\n</ul>\n</li>\n<li>your commenting is quite good</li>\n<li>Your indenting is inconsistent, it easier to read your code when code is properly indented</li>\n<li><code>catchInvalid</code> probably should return a boolean</li>\n<li>I would have called <code>catchInvalid</code> -> <code>isInvalidColor</code> it gives more detail</li>\n<li><code>catchInvalid</code> should either use the global, or know the colors locally</li>\n<li>I would use <code>COLORS.includes()</code> over <code>COLORS.indexOf</code></li>\n<li>There is way to calculate the return code without making a distinction between 1 or 2 elements</li>\n</ul>\n<p>Per the comment, a bit more explicit</p>\n<pre><code> function decodeColorValues(colors){\n //These are all the possible colors\n const knownColors = ["black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white"]; \n\n //Functions should return a consistent datatypes, so I return -1 instead of a message\n //If the caller did not provide an aray but say "orange", then this will return -1 as well\n if(!colors.length){\n return -1;\n }\n \n //Filter out unknown colors\n colors = colors.filter(color => knownColors.includes(color));\n\n //If all colors were unknown then return -1\n //You could change this so that if 1 color is unknown it returns -1\n if(!colors.length){\n return -1;\n } \n \n //We only deal with the first 2 entries (why?)\n colors = colors.slice(0,2);\n let value=0;\n \n //Abuse the fact that 10 times zero is still zero\n for(const color of colors){\n value = value * 10 + knownColors.indexOf(color);\n }\n \n return value;\n }\n\n\n console.log(decodeColorValues(["blue"]),\n decodeColorValues(["nothing"]),\n decodeColorValues(["blue", "green"]),\n decodeColorValues(["blue", "nothing"])\n );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:20:05.853",
"Id": "479672",
"Score": "0",
"body": "I agree with everything you've stated here, but I don't agree with stating to a newcomer (or anyone, ever, in fact) that something _should_ be done _this_ way, simply _because I said so_. This doesn't help the person understand what makes one way of doing something better than another, and learning effectively only comes through understanding. I'll pre-empt a possible response that some would cite _\"good coding practice\"_ as the reason, which is not a reason, but a name given to a collection of guidelines that often don't come with an explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T19:32:29.637",
"Id": "479692",
"Score": "0",
"body": "@CJK You must be new to CodeReview, welcome!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:03:55.940",
"Id": "479709",
"Score": "0",
"body": "thanks both :-) @CJK"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:57:50.907",
"Id": "479718",
"Score": "0",
"body": "Would you be more explicit in the last bullet point, please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T08:39:25.400",
"Id": "479831",
"Score": "0",
"body": "@misternobody Done!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T13:55:41.343",
"Id": "244322",
"ParentId": "244320",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244322",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T12:07:14.490",
"Id": "244320",
"Score": "3",
"Tags": [
"javascript",
"beginner"
],
"Title": "Javascript array-matching beginner"
}
|
244320
|
<p>I have implementing a simple version of Dijkstra's algorithm in C#. Could this be made more efficient? Does it need to be modified?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace dijkstra
{
class Program
{
static void Main(string[] args)
{
int n = 5; //nodes
int m = 100; //size of square
int mm = 999; //maximum cost
double t = m / 0.75; //distance
float[] x, y; //x and y coordinates
x = new float[n + 1];
y = new float[n + 1];
float[,] c; //cost matrix
c = new float[n + 1, n + 1];
int[,] a; //adjacency matrix
a = new int[n + 1, n + 1];
//distance array
float[] d;
d = new float[n + 1];
//span array
int[] sa;
sa = new int[n + 1];
Random r = new Random();
//randomise coordinates
for (int i = 1; i <= n; i++)
{
x[i] = m * (float)r.NextDouble();
y[i] = m * (float)r.NextDouble();
d[i] = mm;
sa[i] = 0;
}
//coordinates
Console.WriteLine("Coordinates");
for (int i = 1; i <= n; i++)
Console.WriteLine(i + ": (" + x[i].ToString("0.00") + " , " + y[i].ToString("0.00") + " )");
Console.WriteLine();
//span array
Console.WriteLine("Spanne array");
for (int i = 1; i <= n; i++)
Console.Write(i + ": " + sa[i] + " ");
Console.WriteLine();
Console.WriteLine();
//calculate distance costs
for (int i = 1; i <= n; i++)
for (int j = i + 1; j <= n; j++)
{
c[i, j] = (float)Math.Sqrt((x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]));
if (c[i, j] > t)
c[i, j] = mm;
a[i, j] = 0;
}
Console.WriteLine("Starting values: ");
Console.WriteLine();
// distances
Console.WriteLine("Cost matrix");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
if ((i >= j) || (c[i, j] > t)) //if i is greater than j or is the 999 distance then
Console.Write(" -- ");
else
Console.Write(" " + c[i, j].ToString("00.00"));
Console.WriteLine();
}
Console.WriteLine();
//adjaceny matrics
Console.WriteLine("Adjancency matrix");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
if (i >= j)
Console.Write(" -");
else
Console.Write(" " + a[i, j]);
Console.WriteLine();
}
Console.WriteLine();
Console.ReadLine();
// starting node
int start = r.Next(1, n + 1);
Console.WriteLine("Start at node " + start + " ...");
Console.WriteLine();
sa[start] = 1;
d[start] = 0;
Console.WriteLine("Span array");
for (int i = 1; i <= n; i++)
Console.Write(i + ": " + sa[i] + " ");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Distance array");
for (int i = 1; i <= n; i++)
Console.Write(i + ": " + d[i].ToString("0.00") + " ");
Console.WriteLine();
Console.WriteLine();
Console.ReadLine();
for (int k = 1; k < n; k++)
{
float shortestDistance = mm;
int iShortest = 0, jShortest = 0, spannedShortest = 0, unspannedShortest = 0;
for (int i = 1; i < n; i++)
for (int j = i + 1; j <= n; j++)
if ((sa[i] == 1) && (sa[j] == 0))
{
if (d[i] + c[i, j] < shortestDistance)
{
shortestDistance = d[i] + c[i, j];
iShortest = i;
jShortest = j;
spannedShortest = i;
unspannedShortest = j;
}
}
else if ((sa[i] == 0) && (sa[j] == 1))
{
if (d[j] + c[i, j] < shortestDistance)
{
shortestDistance = d[j] + c[i, j];
iShortest = i;
jShortest = j;
spannedShortest = j;
unspannedShortest = i;
}
}
a[iShortest, jShortest] = 1;
Console.WriteLine("Joining " + iShortest + " and " + jShortest);
sa[unspannedShortest] = 1;
d[unspannedShortest] = d[spannedShortest] + c[iShortest, jShortest];
Console.WriteLine("Distance to " + unspannedShortest + " is " + d[unspannedShortest].ToString("00.00"));
Console.ReadLine();
}
Console.WriteLine("Spanned array");
for (int i = 1; i <= n; i++)
Console.Write(i + ": " + sa[i] + " ");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Adjancey array");
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
if (i >= j)
Console.Write(" -");
else
Console.Write(" " + a[i, j]);
Console.WriteLine();
}
Console.WriteLine();
// look at the distance array
Console.WriteLine("Distance array");
for (int i = 1; i <= n; i++)
Console.Write(i + ": " + d[i].ToString("0.00") + " ");
Console.WriteLine();
Console.WriteLine();
Console.ReadLine();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-29T11:13:41.893",
"Id": "483637",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-30T21:50:15.380",
"Id": "483890",
"Score": "1",
"body": "(There are spelling errors in the prompts.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-30T21:52:43.743",
"Id": "483891",
"Score": "2",
"body": "Hm. What *square*, what *span*s?"
}
] |
[
{
"body": "<p><strong>Symbolic Constants</strong><br />\nIt is good that you named these numeric constants, but they are constants so rather than declare them as variables, declare them as constants.</p>\n<pre><code> static void Main(string[] args)\n {\n const int n = 5; //nodes\n const int m = 100; //size of square\n const int mm = 999; //maximum cost\n const double t = m / 0.75; //distance\n</code></pre>\n<p><strong>DRY Code</strong><br />\nThere is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n<p>This code is almost repeating and can be encapsulated in a function.</p>\n<pre><code> {\n shortestDistance = d[i] + c[i, j];\n iShortest = i;\n jShortest = j;\n spannedShortest = i;\n unspannedShortest = j;\n }\n</code></pre>\n<p>Other code that could be put into a function is the code that prints out the arrays.</p>\n<p><strong>Use Functions to Break Up the Code</strong><br />\nWhen designing and writing software the best problem solving method is to decompose the problem into smaller and smaller parts. This makes coding much easier and limits the complexity of the code. One example is the code above that is reusable. Smaller blocks of code are easier to read, write, debug and maintain.</p>\n<p><strong>Format the Output</strong><br />\nThere are ways to <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.console.writeline?view=netcore-3.1#System_Console_WriteLine_System_String_System_Object_System_Object_\" rel=\"noreferrer\">format</a> <code>Console.Write()</code> and <code>Console.WriteLine()</code>:</p>\n<pre><code> Console.WriteLine("Coordinates");\n for (int i = 1; i <= n; i++)\n {\n Console.WriteLine("{0:D}: ({1:F}, {2:F})", i, x[i].ToString("0.00"), y[i].ToString("0.00"));\n }\n Console.WriteLine();\n</code></pre>\n<p>Rather than using <code>Console.WriteLine();</code> use <code>Console.WriteLine("\\n");</code> or <code>Console.Write("\\n\\n");</code> to insert blank lines.</p>\n<p>This is a beginning and I'm out of time. After you have made functions you might want to post a second question with a link to this one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:11:27.060",
"Id": "244333",
"ParentId": "244326",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T15:06:12.833",
"Id": "244326",
"Score": "7",
"Tags": [
"c#",
"beginner",
"algorithm",
"graph",
"dijkstra"
],
"Title": "Dijkstra algorithm C#"
}
|
244326
|
<p>The challenge can be found <a href="https://acm.timus.ru/problem.aspx?space=1&num=1456&locale=en" rel="nofollow noreferrer">here</a>.
In short we have a recursive function, and we need to find when <span class="math-container">\$z_i\$</span> is equal to one.</p>
<p><span class="math-container">$$
\begin{align}
z_1 &= 1\\
z_i &= z_{i-1} * a\ \%\ n\\
\text{find}\ z_i &= 1
\end{align}
$$</span></p>
<p>Input range:</p>
<p><span class="math-container">$$ 2 \le a \lt n \le 10^9 $$</span></p>
<p>I have written the following. It is simple, but too slow.</p>
<pre><code>import math
def solution(a, n):
if math.gcd(a, n) > 1:
return 0
z = 1
i = 1
while True:
z = z * a % n
if z == 1:
return i
i += 1
l = map(int, input().split(' '))
print(solution(*l))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T20:17:14.533",
"Id": "479697",
"Score": "0",
"body": "I wonder, try (4, 20), this should return 0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T20:37:58.110",
"Id": "479699",
"Score": "0",
"body": "@konijn It does indeed"
}
] |
[
{
"body": "<h1>Code Review</h1>\n<p>Your code is a little hard to read.</p>\n<p>You should have a blank line after the <code>solution</code> body, to separate it from the mainline code.</p>\n<p>This code is hard to describe, document, and debug:</p>\n<pre><code>l = map(int, input().split(' '))\nprint(solution(*l))\n</code></pre>\n<p>What is <code>l</code>? How many arguments are there? If the wrong number of arguments are given as input, the problem doesn't occur immediately in the first statement but rather when attempting to execute the second.</p>\n<p>It would be significantly clearer to write:</p>\n<pre><code>a, n = map(int, input().split())\nprint(solution(a, n))\n</code></pre>\n<p>Now we can see we expect two arguments to be given, and we have names for the arguments. If too many or too few arguments are given, the first line will raise the exception, which should mean it will be easier to debug.</p>\n<p>Note: I'm using <code>.split()</code> instead of <code>.split(' ')</code> so that it will split the string on any white space character, including tabs, and multiple white-space characters will be considered a single delimiter. It is slightly friendlier.</p>\n<p>Adding type hints and a docstring would be useful. Also, a main guard should be used.</p>\n<p>Improved code:</p>\n<pre><code>import math\n\ndef solution(a: int, n: int) -> int:\n """\n Jedi Challenge:\n\n Return the smallest positive integer such that\n a^i = 1 (mod n)\n Returns 0 if there is no such number\n\n Constraints:\n 2 <= a < n <= 10^9\n """\n\n if math.gcd(a, n) > 1:\n return 0\n\n z = 1\n i = 1\n while True:\n z = z * a % n\n if z == 1:\n return i\n i += 1\n\nif __name__ == '__main__':\n a, n = map(int, input().split())\n print(solution(a, n))\n</code></pre>\n<h1>Performance</h1>\n<p>This is not really a programming challenge; it is a math challenge.</p>\n<p>First, due to the modulo operation, <code>z = z * a % n</code> will only ever produce a value between <code>0</code> and <code>n-1</code>. This means there are only <code>n</code> possible results at each iteration step. However, if <code>0</code> is produced, each iteration step afterwards will only ever produce <code>0</code>, leaving <code>n-1</code> non-trivial results.</p>\n<p>If the k-th iteration produces <code>1</code>, the code yields the result <code>k</code>. But if iteration continued, since it has reached its initial starting point, it would produce the same sequence of values in a never ending cycle.</p>\n<p>If you chose a different starting value, that did not appear in the above cycle, it would must have one of 3 fates. It would either terminate at zero, create its own loop of unique values, or possibly merge into the existing sequence.</p>\n<p>You have already determined that if <code>gcd(a, n) != 1</code> then the iteration sequence would eventually reach zero, without finding a solution.</p>\n<p>In fact, if <code>n</code> is prime, then <span class=\"math-container\">\\$a^{n-1} \\equiv 1 \\mod n\\$</span>, and therefore the iteration will produce the <code>1</code> after <code>n-1</code> iterations, and must have produced all of the possible values between <code>1</code> and <code>n-1</code>.</p>\n<p>So, as one optimization, if you can determine <code>n</code> is prime, you could immediately output the answer <code>n-1</code>. If not, then you could revert to doing the iterative calculations.</p>\n<p>If <code>n</code> is not prime, you might want to look at the prime factorization of <code>n</code>, and see if you can determine a relation between it and the result. (Hint: there is.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T21:41:22.873",
"Id": "479703",
"Score": "0",
"body": "\"the first line will raise the exception, which should mean it will be easier to debug.\" Seems a bit odd, neither seem better than the other here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:03:20.467",
"Id": "479708",
"Score": "0",
"body": "@Peilonrayz If there were 3 input lines, `l = ...`, `m = ...`, `n = ...`, and the line `solve(*l, *m, *n)` raises the exception \"incorrect number of arguments\", which list was the problem? We can't tell. If the lists were being immediately unpacked, it becomes crystal clear. Moreover, instead of a list of arguments, we get **named** arguments, which is way more self documenting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T08:54:51.033",
"Id": "479753",
"Score": "0",
"body": "Yeah. If the code were completely different then there can be completely different problems..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T21:32:21.480",
"Id": "244349",
"ParentId": "244328",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T15:37:15.910",
"Id": "244328",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "\"Jedi's riddle\" challenge"
}
|
244328
|
<p>I am using below code to rename and delete video.</p>
<p>Need review for the following:</p>
<ol>
<li><p>Code optimization</p>
</li>
<li><p>Performance</p>
</li>
<li><p>Overall code review</p>
</li>
</ol>
<pre><code>renameVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int index = filePath.lastIndexOf('.');
String selectedVideoTitleForRename;
if (index > 0) {
selectedVideoTitleForRename = filePath.substring(filePath.lastIndexOf("/") + 1, index);
} else {
selectedVideoTitleForRename = filePath.substring(filePath.lastIndexOf("/") + 1);
}
renameFile(PreviewActivity.this, selectedVideoTitleForRename, filePath, tvInstruction);
}
});
deleteVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
deleteFile(PreviewActivity.this, filePath);
}
});
private void renameFile(final Context context, final String selectedVideoTitleForRename, final String selectedVideoRenamePath,
final TextView tvInstruction) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
LayoutInflater li = LayoutInflater.from(context);
View renameVideoView = li.inflate(R.layout.rename_video, null);
final EditText input = (EditText) renameVideoView.findViewById(R.id.rename_edit_text);
input.setText(selectedVideoTitleForRename);
alert.setView(renameVideoView);
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File fileToRename = new File(selectedVideoRenamePath);
File fileNameNew = new File(selectedVideoRenamePath.replace(
selectedVideoTitleForRename, input.getText().toString()));
if (fileNameNew.exists()) {
Toast.makeText(context,
context.getResources().getString(R.string.same_title_exists), Toast.LENGTH_LONG).show();
} else {
boolean isRename = fileToRename.renameTo(fileNameNew);
if (isRename) {
String newFilePath = fileNameNew.toString();
tvInstruction.setText(context.getResources().getString(R.string.videoStoredPath, newFilePath));
try {
MediaScannerConnection.scanFile(context,
new String[]{fileToRename.toString(), newFilePath},
null,
null);
} catch (Exception e) {
FirebaseDatabase.getInstance().getReference("exception").push().setValue(e.toString());
Crashlytics.logException(e);
}
filePath = newFilePath;
Toast.makeText(context,
context.getResources().getString(R.string.rename_success), Toast.LENGTH_LONG).show();
}
}
}
});
alert.show();
}
private void deleteFile(final Context context, final String selectedVideoDelete) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Confirm Delete...");
alertDialog.setMessage("Are you sure you want to Delete:\n\n" + selectedVideoDelete);
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File fileToDelete = new File(selectedVideoDelete);
boolean deletedSuccessfully = fileToDelete.delete();
if (deletedSuccessfully) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
MediaScannerConnection.scanFile(context,
new String[]{selectedVideoDelete}, null, null);
} else {
context.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
}
Toast.makeText(context,
context.getResources().getString(R.string.delete_success), Toast.LENGTH_LONG).show();
((Activity) context).finish();
}
}
});
alertDialog.show();
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Code Structuring</strong></p>\n<p>All Android tutorial code packs event listeners into anonymous inner classes, because the examples are usually short and it is convenient, from distribution point of view, to pack all code into the same file. It is however not the correct way to implement production code, as it creates large and messy compilation units that contain many many responsibilities, making them impossible targets for unit tests.</p>\n<p>My personal rule of thumb is that if your <code>OnClickListener</code> or any other event listener contains anything more than one method call, it must be put it into a separate class. Otherwise a lambda is used.</p>\n<p>I prefer strict adherence to <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a> even in Android apps. I have used Guava EventBus in my hobby projects to send messages between different components and to avoid the "initialization spaghetti" where references between components are shared to connect them together. It works but you have to design the event mechanism throughly. There are several dependency injection libraries too, but I haven't had the time to look at those yet.</p>\n<p><strong>Code Optimization</strong></p>\n<p>We are dealing with an operation invoked by the user, which involves a confirmation dialog. What kind of problems have you noticed and what kind of preceivable optimization results are you looking for? To me this looks like premature optimization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:22:03.957",
"Id": "479734",
"Score": "0",
"body": "Thanks for your answer..What u mean here by 'premature optimization'.Does this mean that code is already optimized?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:37:22.330",
"Id": "479740",
"Score": "1",
"body": "It means that optimization should not be performed on code before it has been identified as being a bottle neck. The code in question is not run in a tight loop so any optimization would likely return minimal reward compared to the effort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:40:26.287",
"Id": "479742",
"Score": "0",
"body": "Sorry still not getting.. please explain in simpler language.what u mean by 'run in tight loop' and 'bottleneck' here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T20:20:57.643",
"Id": "479791",
"Score": "1",
"body": "It means, don't optimize the performance of a piece of code before knowing for sure that piece of code is contributing significantly to slow performance. It is time consuming for you to optimize code, and optimization often makes code less readable and maintainable. Don't spend ten minutes of your life making your users wait 1ms less for your dialog box. They won't be able to tell the difference."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:13:04.683",
"Id": "244364",
"ParentId": "244331",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244364",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:00:07.500",
"Id": "244331",
"Score": "1",
"Tags": [
"java",
"performance",
"android",
"file",
"video"
],
"Title": "Renaming and deleting video file"
}
|
244331
|
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p>
<h2>Problem</h2>
<blockquote>
<p>Given a 2d grid map of '1's (land) and '0's (water), count the number
of islands. An island is surrounded by water and is formed by
connecting adjacent lands horizontally or vertically. You may assume
all four edges of the grid are all surrounded by water.</p>
<h3>Example 1:</h3>
<pre><code>Input:
11110
11010
11000
00000
Output: 1
</code></pre>
<h3>Example 2:</h3>
<pre><code>Input:
11000
11000
00100
00011
Output: 3
</code></pre>
</blockquote>
<h3>Code</h3>
<pre><code>#include <vector>
class Solution {
public:
std::size_t numIslands(std::vector<std::vector<char>>& grid) {
std::size_t row_length = grid.size();
if (!row_length) {
return 0;
}
std::size_t col_length = grid[0].size();
std::size_t islands = 0;
// Runs depth first search for every cell
for (std::size_t row = 0; row < row_length; row++) {
for (std::size_t col = 0; col < col_length; col++) {
if (grid[row][col] == '1') {
islands++;
depth_first_search(grid, row, col, row_length, col_length);
}
}
}
return islands;
}
private:
void depth_first_search(std::vector<std::vector<char>>& grid, const std::size_t row, const std::size_t col, const std::size_t row_length, const std::size_t col_length) {
// Checks for grid boundaries and '0' cells
if (row < 0 || row >= row_length || col < 0 || col >= col_length || grid[row][col] == '0') {
return;
}
grid[row][col] = '0';
// Recurse in 4 directions of grid
depth_first_search(grid, row + 1, col, row_length, col_length);
depth_first_search(grid, row - 1, col, row_length, col_length);
depth_first_search(grid, row, col + 1, row_length, col_length);
depth_first_search(grid, row, col - 1, row_length, col_length);
}
};
</code></pre>
<h3>LeetCode's Solution (Not for review)</h3>
<pre><code>class Solution {
private:
void dfs(vector<vector<char>>& grid, int r, int c) {
int nr = grid.size();
int nc = grid[0].size();
grid[r][c] = '0';
if (r - 1 >= 0 && grid[r-1][c] == '1') dfs(grid, r - 1, c);
if (r + 1 < nr && grid[r+1][c] == '1') dfs(grid, r + 1, c);
if (c - 1 >= 0 && grid[r][c-1] == '1') dfs(grid, r, c - 1);
if (c + 1 < nc && grid[r][c+1] == '1') dfs(grid, r, c + 1);
}
public:
int numIslands(vector<vector<char>>& grid) {
int nr = grid.size();
if (!nr) return 0;
int nc = grid[0].size();
int num_islands = 0;
for (int r = 0; r < nr; ++r) {
for (int c = 0; c < nc; ++c) {
if (grid[r][c] == '1') {
++num_islands;
dfs(grid, r, c);
}
}
}
return num_islands;
}
};
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/number-of-islands/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/number-of-islands/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Offload more functionality into <code>depth_first_search()</code></h1>\n<p>One improvement your solution has over LeetCode's is that you move the grid boundary check into <code>depth_first_search()</code>. However, you can do more, by having it return whether you are starting on an island or in the ocean:</p>\n<pre><code>bool depth_first_search(...) {\n // Checks for grid boundaries and '0' cells\n if (...)\n return false;\n\n // We are on an island, recurse\n ...\n\n return true;\n}\n</code></pre>\n<p>Then, the loop inside <code>numIslands()</code> can be simplified:</p>\n<pre><code>for (std::size_t row = 0; row < row_length; row++)\n for (std::size_t col = 0; col < col_length; col++)\n islands += depth_first_search(grid, row, col, row_length, col_length);\n</code></pre>\n<h1>Naming things</h1>\n<p>While <code>depth_first_search()</code> does iterate in a depth-first fashion, it is not search for anything. Rather, it is implementing a <a href=\"https://en.wikipedia.org/wiki/Flood_fill\" rel=\"nofollow noreferrer\">flood fill</a> algorithm. But here we use it to remove an island. If it also performs a check to see if there is an island at the given position, I would name it <code>check_and_remove_island()</code>. As Emily L. mentions, a function name that reads like <code>foo_and_bar()</code> is usually a hint that it should be split into a <code>foo()</code> and <code>bar()</code>. If you want to go that way, I suggest you make it so you can write the following code:</p>\n<pre><code>if (is_island(grid, row, col)) {\n islands++;\n remove_island(grid, row, col);\n}\n</code></pre>\n<h1>Get rid of the size variables</h1>\n<p>I don't think it's that useful to store the sizes into separate variables, and to pass them explicitly to <code>depth_first_search()</code>. This information can always easily be gotten from the variable <code>grid</code>. This also gets rid of the check for an empty grid:</p>\n<pre><code>std::size_t numIslands(std::vector<std::vector<char>>& grid) {\n size_t islands{};\n\n for(std::size_t row = 0; row < grid.size(); row++)\n for (std::size_t col = 0; col < grid[row].size(); col++)\n islands += check_and_remove_island(grid, row, col);\n\n return islands;\n}\n</code></pre>\n<p>You have to modify <code>depth_first_search()</code> to match of course.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T08:58:27.027",
"Id": "487497",
"Score": "1",
"body": "I disagree with moving the island check into the DFS routine. Although clever and more compact, it conflates responsibilities. The method should then be called check_island_and_remove() and that's a smell to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T08:59:40.837",
"Id": "487499",
"Score": "1",
"body": "In fact the name DFS is also wrong, it's not a search as much as a flood fill implemented with depth first recursion. But I digress..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T09:05:03.607",
"Id": "487500",
"Score": "1",
"body": "@EmilyL. Separating responsibilities is usually a good thing, but I think that here conflating them does make the code nicer overall. But I totally agree about `depth_first_search()` needing a different name!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T11:07:00.557",
"Id": "487510",
"Score": "0",
"body": "Perhaps `flood`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T08:29:05.247",
"Id": "248802",
"ParentId": "244334",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248802",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:13:51.483",
"Id": "244334",
"Score": "1",
"Tags": [
"c++",
"beginner",
"programming-challenge",
"comparative-review",
"c++17"
],
"Title": "LeetCode 200: Number of Islands"
}
|
244334
|
<p>I'm posting my C++ code for LeetCode's Guess Number Higher or Lower II. If you have time and would like to review, please do so.</p>
<h2>Problem</h2>
<blockquote>
<p>We are playing the Guess Game. The game is as follows:</p>
<ul>
<li><p>I pick a number from 1 to n. You have to guess which number I picked.</p>
</li>
<li><p>Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.</p>
</li>
<li><p>However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code>
First round: You guess 5, I tell you that it's higher. You pay $5.
Second round: You guess 7, I tell you that it's higher. You pay $7.
Third round: You guess 9, I tell you that it's lower. You pay $9.
Game over. 8 is the number I picked.
</code></pre>
<ul>
<li><p>You end up paying $5 + $7 + $9 = $21.</p>
</li>
<li><p>Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.</p>
</li>
</ul>
</blockquote>
<h3>Accepted C++</h3>
<pre><code>#include <vector>
class Solution {
public:
std::size_t getMoneyAmount(const std::size_t num) {
std::vector<std::vector<std::size_t>> dp(num + 1, std::vector<std::size_t>(num + 1, 0));
return get_dp(1, num, dp);
}
private:
std::size_t get_dp(const std::size_t head, const std::size_t tail, std::vector<std::vector<std::size_t>>& dp) {
if (head >= tail) {
return 0;
}
if (dp[head][tail] != 0) {
return dp[head][tail];
}
std::size_t guesses = INT_MAX;
for (std::size_t guess = head; guess < tail; guess++) {
std::size_t max_guess = guess + max(get_dp(head, guess - 1, dp), get_dp(guess + 1, tail, dp));
guesses = min(guesses, max_guess);
}
dp[head][tail] = guesses;
return dp[head][tail];
}
};
</code></pre>
<h3>LeetCode's Java Solution (Not for review)</h3>
<pre><code>public class Solution {
public int getMoneyAmount(int n) {
int[][] dp = new int[n + 1][n + 1];
for (int len = 2; len <= n; len++) {
for (int start = 1; start <= n - len + 1; start++) {
int minres = Integer.MAX_VALUE;
for (int piv = start + (len - 1) / 2; piv < start + len - 1; piv++) {
int res = piv + Math.max(dp[start][piv - 1], dp[piv + 1][start + len - 1]);
minres = Math.min(res, minres);
}
dp[start][start + len - 1] = minres;
}
}
return dp[1][n];
}
}
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/guess-number-higher-or-lower-ii/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/guess-number-higher-or-lower-ii/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Your code is difficult to read, there are no comments to explain what the code is doing, or how it’s doing it.</p>\n<p>Using typedefs would also add explanations to the purpose of the code.</p>\n<p>More verbose variable names would also help, dp doesn’t mean anything.</p>\n<p>To me it looks like you have ported the code without understanding what it is doing, which has its place, but if you don’t understand it then how is anyone else meant to?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T20:44:20.323",
"Id": "244467",
"ParentId": "244337",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244467",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T17:24:05.673",
"Id": "244337",
"Score": "-1",
"Tags": [
"c++",
"beginner",
"programming-challenge",
"c++17",
"dynamic-programming"
],
"Title": "LeetCode 375: Guess Number Higher or Lower II"
}
|
244337
|
<p>I'm running MicroPython on an ESP32 relaying sensor data to my MQTT server for Home Assistant. I only want it to emit a message when state has changed and a motion detected state to hold for a minute before returning to a clear state. I see a lot of examples using sleep, but I don't like the blocking nature of sleep as I will be adding more sensors. Instead I've been using <strong>ticks_ms()</strong> and <strong>ticks_diff()</strong> to keep the state from fluttering on/off too much, but I can't help but think there's a better/more elegant way to do this that I'm not seeing.</p>
<p>There's some repetition and nesting that sticks out to me</p>
<pre><code>from umqtt.robust import MQTTClient
from machine import Pin, unique_id
from time import ticks_diff, ticks_ms
from ubinascii import hexlify
#Config
MQTT_SERVER = "X.X.X.X"
MQTT_PORT = 1883
MQTT_USER = b"USER"
MQTT_PASSWORD = b"PASSWORD"
MQTT_CLIENT_ID = hexlify(unique_id())
MQTT_TOPIC = b"esp/motion"
mqtt = MQTTClient(MQTT_CLIENT_ID, MQTT_SERVER, MQTT_PORT, MQTT_USER, MQTT_PASSWORD)
ledPin = Pin(2, Pin.OUT)
motPin = Pin(15, Pin.IN)
previousState = 0
delay_ms = 60000
clock = ticks_ms()
def main():
global clock, previousState, delay_ms
try:
mqtt.connect()
while True:
state = motPin.value()
if state == 1:
ledPin.on()
if previousState == 0:
if ticks_diff(ticks_ms(), clock) >= 0:
print('motion_start')
mqtt.publish(MQTT_TOPIC, 'motion_start')
clock = ticks_ms() + delay_ms
previousState = state
else:
clock = ticks_ms() + delay_ms
else:
ledPin.off()
if previousState == 1:
if ticks_diff(ticks_ms(), clock) >= 0:
print('motion_stop')
mqtt.publish(MQTT_TOPIC, 'motion_stop')
previousState = state
finally:
ledPin.off()
mqtt.publish(MQTT_TOPIC, 'motion_stop')
mqtt.disconnect()
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<h2>Fluttering</h2>\n<pre><code> if previousState == 0:\n if ticks_diff(ticks_ms(), clock) >= 0:\n</code></pre>\n<p>This is called a soft debounce. It may or may not be adequate. My usual recommendation is to do hard debounce instead (or maybe in addition) via a first-order RC lowpass filter followed by hysteresis in a Schmitt trigger. If none of that makes sense to you, then that's a question for <a href=\"https://electronics.stackexchange.com/\">https://electronics.stackexchange.com/</a> .</p>\n<h2>Truthiness</h2>\n<p>I would sooner write</p>\n<pre><code>if state:\n</code></pre>\n<p>rather than</p>\n<pre><code>if state == 1:\n</code></pre>\n<h2>snake_case</h2>\n<p>Per PEP8, <code>previousState</code> should be <code>previous_state</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T18:36:56.220",
"Id": "479689",
"Score": "0",
"body": "What I'm aiming for isn't necessarily debouncing as the sensor has digital signal processing; multiple motion events all within a minute just tend to present issues with home automation.\n\nAgreed on the state boolean - I had that initially, but thought that might obfuscate sensor value too much - but it is indeed cleaner."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T18:16:02.387",
"Id": "244340",
"ParentId": "244339",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "244340",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T18:06:47.877",
"Id": "244339",
"Score": "4",
"Tags": [
"python"
],
"Title": "Reduce Sensor Messaging Noise to MQTT"
}
|
244339
|
<p>How can I simplify this functioning JQuery validation process:</p>
<pre><code>class UserEdit {
addUser(uobj) {
if(uobj.adduser == "" && uobj.addfullname == "" && uobj.addemail == "" && uobj.addlevel == "")
{
$('#adduserError').show();
$('#addfullnameError').show();
$('#addemailError').show();
$('#adduserlevelError').show();
return false;
}
if(uobj.adduser == "")
{
$('#adduserError').show();
return false;
}
if(uobj.addfullname == "")
{
$('#addfullnameError').show();
return false;
}
if(uobj.addemail == "" || (uobj.addemail.indexOf("@",0)) == -1 || (uobj.addemail.indexOf(".",0)) == -1 || uobj.addemail.length < 6)
{
$('#addemailError').show();
return false;
}
else
{
$('#loadingDiv').show();
$.post('process/editUser.php', {uobj:uobj}, function(data)
{
var modal = "#addUserModal";
$('#loadingDiv').hide();
dataCheck(data, modal);
});
}
}
}
</code></pre>
<p>All of the above works as it should. I just know there must be a way to simplify it.</p>
<p>Note (because I believe someone will ask): I use the <em>dataCheck</em> function to check the data returned from the PHP process, and then close the modal if the process was successful. There are a couple of other modules within the class that use the same dataCheck function. That was my initial attempt to at least simplify how to handle the return data in each module.</p>
<p>Now I want to try to simply the code above. Any help is appreciated.</p>
|
[] |
[
{
"body": "<p>I see you removed the calls to <code>$('#loadingDiv').show();</code> from the many conditional blocks and moved that before the call to the AJAX call - I was going to suggest that.</p>\n<p>I see the <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like the Class syntax are used, so other ES-6 features could be used - like the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015\" rel=\"nofollow noreferrer\">object initializer shorthand notation</a> - i.e. on this line:</p>\n<blockquote>\n<pre><code> $.post('process/editUser.php', {uobj:uobj}, function(data)\n</code></pre>\n</blockquote>\n<p>The second argument can be simplified:</p>\n<pre><code>$.post('process/editUser.php', {uobj}, function(data)\n</code></pre>\n<p>There is no need to use the <code>else</code> keyword since all previous conditional blocks have a <code>return</code> statement.</p>\n<p>The callback to the AJAX call has a variable <code>modal</code>:</p>\n<blockquote>\n<pre><code>var modal = "#addUserModal";\n</code></pre>\n</blockquote>\n<p>The variable is only used one time so the value can be used in the call to <code>dataCheck</code> and the variable eliminated. Additionally, unless there is a good reason like needing a global variable, don't use <code>var</code>. Use <code>const</code> and then if you determine re-assignment is necessary use <code>let</code>.</p>\n<p>Instead of using <code>.indexOf()</code> to determine if a string does or does not contain a substring, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\" rel=\"nofollow noreferrer\">String.prototype.includes()</a> could be used unless <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes#Browser_compatibility\" rel=\"nofollow noreferrer\">browser compatibility is an issue</a>.</p>\n<p>I know that the PHP PSRs recommend having opening braces on a new line but this is less common in JavaScript.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T21:52:14.987",
"Id": "479705",
"Score": "0",
"body": "I appreciate the suggestions. I am having an issue with indexOf on a separate page. I will utilize the reference you provided. I was hoping to be able to reduce the amount of if/else statements. In the method I used above, would you say that the if/else statements I used is a good way to validate all of the parameters passed by the user?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T21:19:23.993",
"Id": "244348",
"ParentId": "244341",
"Score": "1"
}
},
{
"body": "<h1>Return Value</h1>\n<p>The method <code>addUser</code> returns <code>false</code> for all negative cases. Below it is possible to see that it does not return <code>true</code> for the positive case.. instead it returns nothing which leads to an <code>undefined</code>:</p>\n<blockquote>\n<pre><code>else\n{\n $('#loadingDiv').show();\n $.post('process/editUser.php', {uobj:uobj}, function(data)\n {\n var modal = "#addUserModal";\n $('#loadingDiv').hide();\n dataCheck(data, modal);\n });\n}\n</code></pre>\n</blockquote>\n<p>This makes the method hard to understand when working with it without knowing the implementation.</p>\n<hr />\n<h1>Concerns</h1>\n<p>The class <code>UserEdit</code> handles multiple concerns. There are two principles which can be named to emphasize the importance for separation:</p>\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Separation of Concerns (SoC)</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle (SRP)</a></li>\n</ul>\n<p>The concerns are</p>\n<ul>\n<li>validating (<code>uobj.adduser == ""</code>)</li>\n<li>presenting (<code>$('#adduserError').show();</code>)</li>\n<li>sending data (<code>$.post(...)</code>)</li>\n</ul>\n<p>When we separate the concerns we could accomplish something like</p>\n<pre><code>class UserEdit {\n constructor(validator, presenter, repository) {/* ... */}\n\n addUser(user) {\n const validation = validator.validate(user);\n presener.present(validation);\n \n if (validation.isValid())\n repository.update(user);\n\n return validation.isValid();\n }\n}\n</code></pre>\n<p>This has multiple advantages. Beside the descriptive and shorter method body we can accomplish through the dependency injection via the constructor a better way to test the class. Additionally the modification and the exchange of the modules is easier.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T09:02:58.273",
"Id": "244433",
"ParentId": "244341",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244348",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T18:33:41.967",
"Id": "244341",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"jquery",
"ecmascript-6",
"classes"
],
"Title": "How can I simplify this JQuery validation process?"
}
|
244341
|
<p>I'm posting my C++ code for LeetCode's 1320. If you have time and would like to review, please do so. Thank you!</p>
<h2>Problem</h2>
<blockquote>
<p><a href="https://i.stack.imgur.com/eHgrn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eHgrn.png" alt="enter image description here" /></a></p>
<ul>
<li><p>You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for
example, the letter <span class="math-container">\$A\$</span> is located at coordinate <span class="math-container">\$(0,0)\$</span>, the letter
<span class="math-container">\$B\$</span> is located at coordinate <span class="math-container">\$(0,1)\$</span>, the letter <span class="math-container">\$P\$</span> is located at
coordinate <span class="math-container">\$(2,3)\$</span> and the letter <span class="math-container">\$Z\$</span> is located at coordinate
<span class="math-container">\$(4,1)\$</span>.</p>
</li>
<li><p>Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates
<span class="math-container">\$(x_1,y_1)\$</span> and <span class="math-container">\$(x_2,y_2)\$</span> is <span class="math-container">\$|x_1 - x_2| + |y_1 - y_2|\$</span>.</p>
</li>
<li><p>Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers
do not have to start at the first letter or the first two letters.</p>
</li>
</ul>
<h3>Example 1:</h3>
<p>Input: word = "CAKE" Output: 3</p>
<h3>Explanation:</h3>
<p>Using two fingers, one optimal way to type "CAKE" is:</p>
<ul>
<li>Finger 1 on letter 'C' -> cost = 0</li>
<li>Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2</li>
<li>Finger 2 on letter 'K' -> cost = 0</li>
<li>Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1</li>
</ul>
<h3>Total distance = 3</h3>
<h3>Constraints:</h3>
<ul>
<li><span class="math-container">\$2 \le \text{word.length} \le 300\$</span></li>
<li>Each <code>word[i]</code> is an English uppercase letter.</li>
</ul>
</blockquote>
<h3>Accepted C++</h3>
<pre><code>#include <vector>
#include <string>
#include <algorithm>
class Solution {
const unsigned short int ALPHABET_LEN = 26;
const unsigned short int WIDTH = 6;
const unsigned char A_LETTER = 'A';
public:
std::size_t minimumDistance(const std::string word) {
const std::size_t length = word.size();
std::vector<int> dp(ALPHABET_LEN);
int max_decrease = 0;
int total_distance = 0;
for (std::size_t index = 0; index < length - 1; index++) {
const int second = word[index] - A_LETTER;
const int third = word[index + 1] - A_LETTER;
for (std::size_t first = 0; first < ALPHABET_LEN; first++) {
dp[second] = std::max(dp[second], dp[first] + coordinates(second, third) - coordinates(first, third));
}
max_decrease = std::max(max_decrease, dp[second]);
total_distance += coordinates(second, third);
}
return total_distance - max_decrease;
}
private:
unsigned short coordinates(unsigned short left, unsigned short right) {
return std::abs(left / WIDTH - right / 6) + std::abs(left % WIDTH - right % WIDTH);
}
};
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T22:45:00.720",
"Id": "479801",
"Score": "1",
"body": "Nice use of the default private region to declare your constants."
}
] |
[
{
"body": "<h1>Ensure you match the given API</h1>\n<p>Using <code>size_t</code> for sizes is a good thing to do, however the LeetCode problem specifies the API, and you should not change it. <code>minimumDistance()</code> should return <code>int</code>.</p>\n<h1>Use <code>static constexpr</code> for compile-time constants</h1>\n<p>Use <code>static constexpr</code> instead of <code>const</code> for the constants. This allows the compiler to make more optimizations, and they can then also be used in other places where a compile-time constant is required, for example:</p>\n<h1>Use a <code>std::array</code></h1>\n<p>Since <code>dp</code> has a compile-time constant size, you can make it a <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a>:</p>\n<pre><code>std::array<int, ALPHABET_LEN> dp;\n</code></pre>\n<h1>Avoid using small types unnecessarily</h1>\n<p>Here you have a problem where you know the maximum distance between two letters is 25. I see you have decided to make <code>coordinates()</code> return an <code>unsigned short</code>. I would not do this. While it might seem more optimal, it is not: on many 32-bit and 64-bit platforms, 16-bit integers are often less efficient than 32-bit integers, since they are smaller than the natural register size, and thus the compiler might need to add instructions to ensure all but the lower 16 bits are zeroed. There might also be a penalty because it has to convert it back to a regular <code>int</code> when adding it the result to <code>total_distance</code>.</p>\n<p>The right time to use <code>short</code>s or even <code>char</code>s to hold integer values is when you have large arrays of them, since then it might reduce memory usage and memory bandwidth.</p>\n<h1>Proper naming</h1>\n<p>The function <code>coordinates()</code>, contrary to what the name implies, does not return coordinates. Instead, it returns a distance. So name it <code>distance()</code>.</p>\n<p>I would also not name the arguments <code>left</code> and <code>right</code>, but just <code>a</code> and <code>b</code>. Left and right sounds confusing here since you might think it gets the character under the left and right fingers as inputs.</p>\n<p>Also, what does <code>dp</code> stand for? It seems like this vector holds the maximum distance traveled given a starting position. Try to find a more descriptive name for it. If there is no good one, then at least add a comment explaining what <code>dp</code> is.</p>\n<p>The names <code>second</code> and <code>third</code> are slightly misleading for <code>index > 0</code>. Maybe it would be better to name them <code>from</code> and <code>to</code>.</p>\n<h1>Use <code>WIDTH</code> consistently</h1>\n<p>You still use one literal <code>6</code> in <code>coordinates()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T06:35:54.400",
"Id": "479729",
"Score": "1",
"body": "The new version looks fine!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:08:20.763",
"Id": "244353",
"ParentId": "244343",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244353",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T19:16:45.757",
"Id": "244343",
"Score": "1",
"Tags": [
"c++",
"beginner",
"programming-challenge",
"c++17",
"dynamic-programming"
],
"Title": "LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers I"
}
|
244343
|
<p>I'm trying to create a component that receives an array, this component is going to show a list with props data</p>
<pre><code>const Mesas = [{
id: 1,
valor: 500,
produtos:['COCA COLA', 'FANTA']
},{
id: 2,
valor: 100,
produtos:['PRATO1', 'PRATO2']
}]
const App = () => {
return (<ListaMesas mesas = {{...Mesas}} />)
}
</code></pre>
<p>The component:</p>
<pre><code>class mesas extends Component {
render(){
const mesas = [this.props.mesas]
mesas.map(function(item){
return(
<div key ={item.id}>
<text>{item.id}</text>
</div>
)
})
return(
<div>
{mesas}
</div>
)
}
}
</code></pre>
<p>What is the best way to do this list?</p>
|
[] |
[
{
"body": "<p>I think the best way to refactor your problem is to use React programming pattern: a stateful, parent component passes down a prop to a stateless, child component. So, you don't ever need to declare <code>mesas</code> as a class, it is just a functional component because we dividing components into presentational components and container components.\nBut, I didn't get about the App's state, if you plan to use external storage fine, but if you need to manage the local state, just insert the <code>mesas</code> in your <code>App</code> under constructor. However, abstracting, based on your code, my refactoring:</p>\n<pre><code>// App.js\nimport React from 'react';\n\nconst mesas = [{\n id: 1,\n valor: 500,\n produtos:['COCA COLA', 'FANTA']\n },{\n id: 2,\n valor: 100,\n produtos:['PRATO1', 'PRATO2']\n }]\nconst App = () => {\n return (<ListaMesas mesas = {mesas} />)\n}\n</code></pre>\n<pre><code>// Mesas.js\nimport React from 'react';\n\nexport const mesas = ({ mesas }) => {\n const mesasList = mesas.map((mesa) => {\n <div key={mesa.id}>\n <text>{mesa.id}</text>\n </div>\n })\n return (\n <div>\n {mesasList}\n </div>\n )\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T15:50:49.443",
"Id": "479774",
"Score": "1",
"body": "Thanks for the explanation, this will be very useful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T04:06:51.157",
"Id": "244357",
"ParentId": "244344",
"Score": "2"
}
},
{
"body": "<p>You don't <em>really</em> need to destructure at all, you can simply use props directly if you like</p>\n<pre><code>this.props.mesas.map(item => ...\n</code></pre>\n<p>example</p>\n<pre><code>class Mesas extends Component {\n render() {\n return (\n <div>\n {this.props.mesas.map(function(item) {\n return (\n <div key={item.id}>\n <text>{item.id}</text>\n </div>\n );\n })}\n </div>\n );\n }\n}\n</code></pre>\n<p><em><strong>but</strong></em> if you did want/need to destructure your props, then the correct pattern is</p>\n<pre><code>const { mesas } = this.props;\n</code></pre>\n<p>example</p>\n<pre><code>class Mesas extends Component {\n render() {\n const { mesas } = this.props;\n return (\n <div>\n {mesas.map(function(item) {\n return (\n <div key={item.id}>\n <text>{item.id}</text>\n </div>\n );\n })}\n </div>\n );\n }\n}\n</code></pre>\n<p>At this point though there isn't much use in using a class-based component; no component lifecycle functions are used, no constructor, etc... a simpler functional component will do the job <em><strong>and</strong></em> allow you to destructure the props right in the function signature (you can even do this with the array::map callback).</p>\n<pre><code>const Mesas = ({ mesas }) => (\n <div>\n {mesas.map(({ id }) => (\n <div key={id}>\n <text>{id}</text>\n </div>\n })}\n </div>\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T15:49:50.483",
"Id": "479773",
"Score": "0",
"body": "Thank you very much for the explanation, it helped me a lot"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:44:54.710",
"Id": "244365",
"ParentId": "244344",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244365",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T19:52:39.767",
"Id": "244344",
"Score": "1",
"Tags": [
"react.js",
"reactive-programming"
],
"Title": "how to destructure this.props react js"
}
|
244344
|
<p>The code below iterates through the nodes of an XML file and updates values based on a Regex expression in the <code>rule</code> child node from an XPath expression. XML is included at the bottom.</p>
<p>Are there better alternatives to this approach? Would using LINQ be a good approach?</p>
<pre><code>using System;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.XPath;
namespace XMLParser
{
class Program
{
static void Main()
{
string ocrString = "";
string rule = "";
string output = "";
string dataNodeIDValue = "";
string dataNodeIDName = "";
string xpathStr = "";
Match match;
int groupInt = 0;
string filename = "C:\\Users\\name\\train\\dev\\offer\\TestParsing.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlElement root = xmlDoc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//offer/data");
XPathNavigator xnav = xmlDoc.CreateNavigator();
// Read in all 'data' nodes and perform functions
foreach (XmlNode node in nodes)
{
// Set to 0 so regex matches first match unless otherwise specified
groupInt = 0;
// Cycle through inner nodes of main node and pull in values
foreach (XmlNode xmlNode in node.ChildNodes)
{
switch (xmlNode.Name)
{
case "ocrstring":
ocrString = xmlNode.InnerText;
break;
case "rule":
rule = xmlNode.InnerText;
break;
case "group":
//groupInt = xmlNode.InnerText;
if (Int32.TryParse(xmlNode.InnerText, out groupInt)) { groupInt = Int32.Parse(xmlNode.InnerText); }
break;
}
}
// No rule given because ocr works effectively
if (rule.Length < 2) { continue; }
// If ocrstring is empty try finding text in pdf
if (String.IsNullOrEmpty(ocrString) | String.IsNullOrWhiteSpace(ocrString)) // This is to iterate through pdf
{
// TODO: Implement over full text doc <- ignore for now
}
else // This is to use XML string
{
var regex = new Regex(rule);
match = regex.Match(ocrString);
}
//if (match.Groups.Count > 0) { };
if (groupInt > 0 & match.Groups.Count > 0)
{
output = match.Groups[groupInt].Value.ToString();
}
else
{
output = match.Value.ToString().Trim();
}
dataNodeIDValue = node.Attributes[0].Value;
dataNodeIDName = node.Attributes[0].Name;
xpathStr = "//offer/data[@" + dataNodeIDName + "='" + dataNodeIDValue + "']/output";
if (String.IsNullOrEmpty(output))
{
root.SelectSingleNode(xpathStr).InnerText = "NA";
}
else
{
root.SelectSingleNode(xpathStr).InnerText = output;
}
xmlDoc.Save(filename); // Save XML session back to file
}
Console.WriteLine("Exiting...");
}
}
}
</code></pre>
<p>XML Data</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<offer>
<data id="Salary">
<ocrstring>which is equal to $40,000.00 if working 40 hours per week</ocrstring>
<rule>.*(([+-]?\$[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}))</rule>
<group>1</group>
<output></output>
</data>
<data id="DefaultWeeklyHours">
<ocrstring></ocrstring>
<rule><![CDATA["(?<=working).*?(?=hours)"]]></rule>
<output></output>
</data>
<data id="RelocationAttachment">
<ocrstring>LongWindingRoad222</ocrstring>
<rule>Regex2</rule>
<output></output>
</data>
</offer>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T06:16:53.637",
"Id": "479728",
"Score": "1",
"body": "Linq2XML (or XLINQ in short) would shift your code from imperative to more declarative. Is it a better approach? It depends. It might reduce the line of code by being more concise. This can increase (or decrease) readability depending on the reader's skills and Linq expression's complexity. Will it be more performant? It depends. It might be faster and it might be easier to move it into the world of parallelism. What you are really looking for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T11:32:33.927",
"Id": "479758",
"Score": "0",
"body": "@PeterCsala just suggestions and to hear what is more performant, your response answers my inquiry."
}
] |
[
{
"body": "<p>If you would define a model like this:</p>\n<pre><code>public class Data\n{\n public string Id { get; set; }\n public string OCR { get; set; }\n public string Rule {get; set; }\n public string Output {get; set; }\n}\n</code></pre>\n<p>then you could easily separate your <strong>ETL</strong> job's different stages.</p>\n<p>For example the <em>Extract</em> phase would look like this:</p>\n<pre><code>Document doc = XDocument.Parse(xml);\nvar parsedData = from data in doc.Descendants("Data")\n select new Data()\n {\n Id = (string)data.Attribute("id"),\n OCR = (string)data.Element("ocrstring"),\n Rule = (string)data.Element("rule")\n };\n</code></pre>\n<p>In your <em>Transform</em> phase you could perform the regex based transformations. The biggest gain here is that it is free from any input or output format. It is just pure business logic.</p>\n<p>And finally in your <em>Load</em> phase you could simply serialize the whole (modified) data collection. Or if it is too large, then create logic to find the appropriate element (based on the <code>Id</code> property) and overwrite only the <code>output</code> child element.</p>\n<hr />\n<p>What you have gained here is a pretty nice separation of concerns.</p>\n<ul>\n<li>Your read logic is not mixed with the processing logic.</li>\n<li>Because of the separation it is easier to spot where is the bottleneck of\nthe application (if any).</li>\n<li>Input format can be changed without affecting processing logic.</li>\n<li>Pipeline like processing can be introduced to improve performance by invoking processing right after a <code>Data</code> object has been populated from the source.</li>\n<li>Many other advantages. :)</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T13:33:43.860",
"Id": "244374",
"ParentId": "244345",
"Score": "4"
}
},
{
"body": "<p>I find using <code>XDocument</code> to be a lot simpler:</p>\n<pre><code>var fileName = @"C:\\Users\\name\\train\\dev\\offer\\TestParsing.xml";\nvar document = XDocument.Load(fileName);\nvar offerData = document.Descendants("offer").Descendants("data");\n\nforeach (var d in offerData)\n{ \n var rule = (string)d.Element("rule");\n if(rule.Length < 2)\n {\n continue;\n }\n\n var ocrString = (string)d.Element("ocrstring");\n if(string.IsNullOrWhiteSpace(ocrString))\n {\n continue;\n }\n \n var match = Regex.Match(ocrString, rule);\n var result = "NA";\n if (match.Success)\n {\n var group = (int?)d.Element("group");\n result = match.Groups[group.GetValueOrDefault(0)].Value;\n }\n \n d.SetElementValue("output", result);\n}\n\ndocument.Save(fileName);\n</code></pre>\n<p>The logic is no longer obscured by the XML-parsing and can be descerned more easily.\nAll the parsing is done by just casting the elements to the desired type.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T13:51:19.653",
"Id": "244375",
"ParentId": "244345",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244374",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T19:58:17.570",
"Id": "244345",
"Score": "2",
"Tags": [
"c#",
"xml"
],
"Title": "Parse XML data and update values of each node's children"
}
|
244345
|
<p>I'm posting my Python code for LeetCode's 1320. If you have time and would like to review, please do so.</p>
<h2>Problem</h2>
<blockquote>
<p><a href="https://i.stack.imgur.com/eHgrn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eHgrn.png" alt="enter image description here" /></a></p>
<ul>
<li><p>You have a keyboard layout as shown above in the XY plane, where each English uppercase letter is located at some coordinate, for
example, the letter <span class="math-container">\$A\$</span> is located at coordinate <span class="math-container">\$(0,0)\$</span>, the letter
<span class="math-container">\$B\$</span> is located at coordinate <span class="math-container">\$(0,1)\$</span>, the letter <span class="math-container">\$P\$</span> is located at
coordinate <span class="math-container">\$(2,3)\$</span> and the letter <span class="math-container">\$Z\$</span> is located at coordinate
<span class="math-container">\$(4,1)\$</span>.</p>
</li>
<li><p>Given the string word, return the minimum total distance to type such string using only two fingers. The distance between coordinates
<span class="math-container">\$(x_1,y_1)\$</span> and <span class="math-container">\$(x_2,y_2)\$</span> is <span class="math-container">\$|x_1 - x_2| + |y_1 - y_2|\$</span>.</p>
</li>
<li><p>Note that the initial positions of your two fingers are considered free so don't count towards your total distance, also your two fingers
do not have to start at the first letter or the first two letters.</p>
</li>
</ul>
<h3>Example 1:</h3>
<p>Input: word = "CAKE" Output: 3</p>
<h3>Explanation:</h3>
<p>Using two fingers, one optimal way to type "CAKE" is:</p>
<ul>
<li>Finger 1 on letter 'C' -> cost = 0</li>
<li>Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2</li>
<li>Finger 2 on letter 'K' -> cost = 0</li>
<li>Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1</li>
</ul>
<h3>Total distance = 3</h3>
<h3>Constraints:</h3>
<ul>
<li><span class="math-container">\$2 \le \text{word.length} \le 300\$</span></li>
<li>Each <code>word[i]</code> is an English uppercase letter.</li>
</ul>
</blockquote>
<h3>Accepted Python</h3>
<pre><code>import string
import functools
class Solution:
def minimumDistance(self, word: str) -> int:
WIDTH = 6
A_DECIMAL = 65
def get_coordinates(left: int, right: int) -> int:
if not left or not right:
return 0
x_left, y_left = indices[left]
x_right, y_right = indices[right]
return abs(x_left - x_right) + abs(y_left - y_right)
@functools.lru_cache(None)
def get_dp(index, word_a: str = None, word_b: str = None) -> None:
if index == len(chars):
return 0
dist_a = get_coordinates(word_a, chars[index]) + get_dp(index + 1, chars[index], word_b)
dist_b = get_coordinates(word_b, chars[index]) + get_dp(index + 1, word_a, chars[index])
return min(dist_a, dist_b)
chars = ''.join(a for a, b in zip(word, word[1:] + ' ') if a != b)
indices = {char: divmod((ord(char) - A_DECIMAL), WIDTH) for char in string.ascii_uppercase}
return get_dp(0)
</code></pre>
<h3>Reference</h3>
<p>On LeetCode, there is a class usually named <code>Solution</code> with one or more <code>public</code> functions which we are not allowed to rename.</p>
<ul>
<li><p><a href="https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Some remarks</p>\n<h1>A_DECIMAL and it's use</h1>\n<pre><code>A_DECIMAL = 65\n# [...]\nindices = {char: divmod((ord(char) - A_DECIMAL), WIDTH) for char in string.ascii_uppercase}\n</code></pre>\n<p>there is nothing wrong with</p>\n<pre><code>ord('A')\n</code></pre>\n<p>which you can use inline without defining a global (which it is not in the required Solution context).\nYou can even get rid of the <code>ord</code> math by enumerating.</p>\n<pre><code>indices = {char: divmod(idx, WIDTH) for idx, char in enumerate(string.ascii_uppercase)}\n</code></pre>\n<h1>Names</h1>\n<pre><code>def get_coordinates(left: int, right: int) -> int:\n if not left or not right:\n return 0\n\n x_left, y_left = indices[left]\n x_right, y_right = indices[right]\n\n return abs(x_left - x_right) + abs(y_left - y_right)\n</code></pre>\n<p>does in no way return coordinates, it returns a distance.\nAlso <code>left</code> and <code>right</code> was misleading me, I thought of the two finger positions.\nAlso you claim the parameters are ints. Actually you pass characters. That is sloppy.</p>\n<pre><code>dist_a = get_coordinates(word_a, chars[index]) + get_dp(index + 1, chars[index], word_b)\n</code></pre>\n<p>is near to obfuscation. <code>get_coordinates</code> delivers a distance, <code>word_a</code> is not a word but a character where one finger is on, and what <code>get_dp</code> delivers cannot be guessed from the name nor is a docstring existing.</p>\n<h1>Algorithm</h1>\n<p>You use depth first search (DFS) while for finding the shortest path typically breadth first (BFS) is the better approach. With DFS you have to search the whole tree. By introducing an lru cache you found a nice trick to shortcut some branches. Still you cannot find the shortest path early but have to check the whole tree.</p>\n<p>While the fingers are exchangeable you handle them as if they could not be swapped. So you find two optimal paths, one starting with the left finger, one starting with the right. Identical sequence, only the fingers are swapped. Also the cache does not match swapped fingers.</p>\n<h1>Cache</h1>\n<p>As already said, your cache does not match swapped fingers. By sorting the fingers you could match them. You do the lru cache on a function in a function. As the inner function is only existing while the outer is running also your cache is working for a single word only. Another call with the same word cannot be served from cache. If you pull the function on class level and change the signature to hold the remaining word instead of the index you could reuse cached "endgames".</p>\n<p>A function that would greatly benefit from a lru cache is <code>get_coordinates</code> (read <code>get_distance</code>)</p>\n<h1>Hostile test cases</h1>\n<p>You should implement a BFS with priority queue. Then you do some logging and timing on tests like <code>"FY"*150</code>. While the minimum distance is 0, your DFS evaluates branches at a distance of near 2700. A BFS would register nodes at a max distance of 9 but would never follow them.</p>\n<h1>Other</h1>\n<p>The line</p>\n<pre><code>chars = ''.join(a for a, b in zip(word, word[1:] + ' ') if a != b)\n</code></pre>\n<p>would deserve an explanatory comment or a nice function name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T00:12:16.990",
"Id": "244415",
"ParentId": "244346",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244415",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T20:36:07.203",
"Id": "244346",
"Score": "0",
"Tags": [
"python",
"beginner",
"algorithm",
"programming-challenge",
"dynamic-programming"
],
"Title": "LeetCode 1320: Minimum Distance to Type a Word Using Two Fingers II"
}
|
244346
|
<p>I am a Math tutor and I found the site <a href="https://www.yksityisopetus.fi/" rel="nofollow noreferrer">https://www.yksityisopetus.fi/</a> where one can search pupils. I made a Python parser to find pupils that want Math teaching with at least 25 €/hour. Are there any improvements for this code?</p>
<pre><code>import requests
import tkinter as tk
link = "https://www.yksityisopetus.fi/opiskelijat/matematiikka/min-25-per-tunti/uusin-ensin"
f = requests.get(link)
lista = f.text.split('\n')
ilmot = []
for i in range(len(lista)):
if "<a href=\"/" in lista[i] and "<a href=\"/opettajat" not in lista[i] and "<a href=\"/contact" not in lista[i]:
if lista[i] not in ilmot:
ilmot.append(lista[i])
parsittu = []
for i in range(len(ilmot)):
ilmo = "https://www.yksityisopetus.fi"+ilmot[i].split('"')[1]
f = requests.get(link)
f = f.text.split(">")
for j in range(len(f)):
if f[j] == '\n<br /':
parsittu.append(f[j+1])
s = ""
parsilmot = []
for i in range(len(parsittu)):
if parsittu[i].endswith('</div'):
parsilmot.append(parsittu[i][0:len(parsittu[i])-5])
p = list(set(parsilmot))
quote = ""
for i in p:
quote += i+"\n"
root = tk.Tk()
S = tk.Scrollbar(root)
T = tk.Text(root, height=4, width=100)
S.pack(side=tk.RIGHT, fill=tk.Y)
T.pack(side=tk.LEFT, fill=tk.Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
T.insert(tk.END, quote)
tk.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T20:54:47.433",
"Id": "479700",
"Score": "2",
"body": "I think you can drastically reduce the size of this code. But I don't want to misread anything. Can you provide a short example input and output and explain a little bit of what's going on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T00:11:25.557",
"Id": "479721",
"Score": "2",
"body": "Rather than using text searching, it would be much cleaner to use [`BeautifulSoup`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) to parse the HTML."
}
] |
[
{
"body": "<h2>Move your code into functions</h2>\n<p>Functions are easier to test, and make it easier to modify your code over time.</p>\n<p>For example, <em>I think</em> the first block requests information from a server and creates a list of links. <em>I think</em> the second block processes that list of links and generates some other sort of list. <em>I think</em> the third block iterates over the list from the second block and generates yet another list.</p>\n<p>If these blocks were in functions, then the main logic would be self explanatory. For example, your code could look like:</p>\n<pre><code>...\nilmot = get_students(link)\nparsittu = some_other_function(ilmot)\nparsilmot = another_function(parsittu)\nquote = create_quote(parsilmot)\n...\n</code></pre>\n<p>If those functions all had reasonable names, the code would be very easy to understand, and it would be easy to test each function in isolation.</p>\n<p>Not only that, but you can more easily move all of that code into a function so that you can implement a "refresh" feature into the UI so that you don't have to restart the script every time you want to update the data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:52:31.623",
"Id": "244354",
"ParentId": "244347",
"Score": "5"
}
},
{
"body": "<h2>English</h2>\n<p>For better or worse, <a href=\"https://en.wikipedia.org/wiki/English_in_computing#Programming_language\" rel=\"nofollow noreferrer\">English is the lingua franca of programming</a>. It is completely fine for user-facing content to be localised to Finnish, but the code should not be (e.g. <code>lista</code>, <code>parsittu</code>), for a handful of reasons. Python itself uses English words in its syntax, so doing otherwise in the rest of the code is inconsistent.</p>\n<h2>Parsing HTML</h2>\n<p>It is very risky to do this manually as you are:</p>\n<pre><code>if "<a href=\\"/" in lista[i]\n</code></pre>\n<p>it's fragile and prone to failure. Use BeautifulSoup instead.</p>\n<h2>Checking requests calls</h2>\n<p>After this:</p>\n<pre><code>f = requests.get(link)\n</code></pre>\n<p>call</p>\n<pre><code>f.raise_for_status()\n</code></pre>\n<p>Otherwise, failures will be non-obvious.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T15:00:41.877",
"Id": "244384",
"ParentId": "244347",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244354",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T20:48:02.400",
"Id": "244347",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"parsing",
"tkinter"
],
"Title": "Finding pupils to tutor"
}
|
244347
|
<p>Looking for any feedback to improve practices on the following logic, and I have removed large chunks of documentation to reduce noise. I feel the areas that could expect heavy criticism are the win/tie condition checking.</p>
<p>Main.cpp</p>
<pre><code>#include "Board.h"
int main() {
//initialize board
Board gameboard;
for (int i = 0; i < gameboard.GetBoardSize(); i++) {
gameboard.PlayTurn();
gameboard.SetTurn(gameboard.GetTurn() + 1);
if (gameboard.CheckWin()) {
std::cout << gameboard.GetWin() << " wins!" << std::endl;
break;
}
if (gameboard.CheckTie()) {
std::cout << "Cat's Game!" << std::endl;
break;
}
if (i == 8) {
std::cout << "Cat's Game!" << std::endl;
break;
}
}
return 0;
}
</code></pre>
<p>Board.h</p>
<pre><code>#pragma once
#include <iostream>
#include <string>
#include <vector>
class Board
{
private:
std::vector<std::string> tiles;
int turn;
public:
//constructors
Board();
//getters
std::string GetTile(int);
int GetTurn();
int GetBoardSize();
//setters
void SetTile(std::string, int);
void SetTurn(int);
//other methods
void Display();
void PlayTurn();
bool CheckPlayedTile(int);
bool CheckWin();
bool CheckTie();
std::string GetWin();
};
</code></pre>
<p>Board.cpp</p>
<pre><code>#include "Board.h"
//constructors
Board::Board() {
for (int i = 0; i < 9; i++)
tiles.push_back(std::to_string(i));
turn = 0;
Display();
}
//getters
std::string Board::GetTile(int pos) {
return tiles[pos];
}
int Board::GetTurn() {
return turn;
}
int Board::GetBoardSize() {
return tiles.size();
}
//setters
void Board::SetTile(std::string letter, int pos) {
tiles[pos] = letter;
}
void Board::SetTurn(int newTurn) {
turn = newTurn;
}
//other methods
void Board::Display() {
std::cout << std::endl;
if (turn == 0)
std::cout << "Turn " << turn << std::endl;
for (int i = 0; i < tiles.size(); i++) {
if (i % 3 == 0 && i > 0)
std::cout << std::endl << "---------" << std::endl;
else if (i % 3 != 0 && i > 0)
std::cout << " | ";
std::cout << tiles[i];
}
std::cout << std::endl << std::endl;
}
void Board::PlayTurn() {
int uiTile;
if (turn % 2 == 0) {
std::cout << "Turn " << turn << std::endl;
std::cout << "Player X, please select a square: ";
std::cin >> uiTile;
if (!CheckPlayedTile(uiTile))
tiles[uiTile] = "X";
else {
std::cout << uiTile << " has already been played, please select another" << std::endl;
PlayTurn();
}
}
else {
std::cout << "Turn " << turn << std::endl;
std::cout << "Player O, please select a square: ";
std::cin >> uiTile;
if (!CheckPlayedTile(uiTile))
tiles[uiTile] = "O";
else {
std::cout << uiTile << " has already been played, please select another" << std::endl;
PlayTurn();
}
}
Display();
}
bool Board::CheckPlayedTile(int pos) {
if (tiles[pos] == "X" || tiles[pos] == "O")
return true;
return false;
}
bool Board::CheckWin() {
if (tiles[0] == tiles[1] && tiles[0] == tiles[2])
return true;//tiles[0];
else if (tiles[0] == tiles[3] && tiles[0] == tiles[6])
return true;//tiles[0];
else if (tiles[0] == tiles[4] && tiles[0] == tiles[8])
return true;//tiles[0];
else if (tiles[1] == tiles[4] && tiles[1] == tiles[7])
return true;//tiles[1];
else if (tiles[2] == tiles[5] && tiles[2] == tiles[8])
return true;//tiles[2];
else if (tiles[2] == tiles[4] && tiles[2] == tiles[6])
return true;//tiles[2];
else if (tiles[3] == tiles[4] && tiles[3] == tiles[5])
return true;//tiles[3];
else if (tiles[6] == tiles[7] && tiles[6] == tiles[8])
return true;//tiles[6];
return false;
}
bool Board::CheckTie() {
for (int i = 0; i < tiles.size(); i++) {
if (tiles[i] == "X" || tiles[i] == "O")
return false;
}
return true;
}
std::string Board::GetWin() {
if (tiles[0] == tiles[1] && tiles[0] == tiles[2])
return tiles[0];
else if (tiles[0] == tiles[3] && tiles[0] == tiles[6])
return tiles[0];
else if (tiles[0] == tiles[4] && tiles[0] == tiles[8])
return tiles[0];
else if (tiles[1] == tiles[4] && tiles[1] == tiles[7])
return tiles[1];
else if (tiles[2] == tiles[5] && tiles[2] == tiles[8])
return tiles[2];
else if (tiles[2] == tiles[4] && tiles[2] == tiles[6])
return tiles[2];
else if (tiles[3] == tiles[4] && tiles[3] == tiles[5])
return tiles[3];
else if (tiles[6] == tiles[7] && tiles[6] == tiles[8])
return tiles[6];
return "";
}
</code></pre>
|
[] |
[
{
"body": "<h2>The interface</h2>\n<p>When I call <code>PlayTurn</code>, I expect the turn counter to automatically increment.</p>\n<pre><code>gameboard.PlayTurn();\n//gameboard.SetTurn(gameboard.GetTurn() + 1);\n</code></pre>\n<hr />\n<p>Rather than having the end-user do all the logic for the game's end, have a game-over check function. Try something like</p>\n<pre><code>bool Board::IsGameOver()\nstd::string Board::GameOverMessage()\n</code></pre>\n<p>so that the code will look like</p>\n<pre><code>if (gameboard.IsGameOver())\n std::cout << gameboard.GameOverMessage();\n</code></pre>\n<p>but I still suggest leaving in some of the interface you have, such as the "get winner" and other information state getters if the end-user wants to customize how the information is displayed.</p>\n<hr />\n<h2>Internal functions</h2>\n<p>Generally, you don't need to expose state-modifying functions publicly. For example, move functions like <code>SetTurn</code> to protected. This way, if the user ever decides to extend tic-tac-toe, he/she can still access the important state-modifying functions without the direct underlying members to mess things up.</p>\n<hr />\n<h2>Naming</h2>\n<p>Try to keep naming consistent. In some places, you use Hungarian notation and name variables <code>uiTurn</code>, and in others you do lower/UpperCamelCase. Pick something and stick to it.</p>\n<hr />\n<h2>Logic</h2>\n<p>Prefer member initialization over member assignment</p>\n<pre><code>Board::Board(): turn( 0 )\n{\n for (int i = 0; i < 9; i++)\n tiles.push_back(std::to_string(i));\n Display();\n}\n</code></pre>\n<hr />\n<p>Use an array over a vector if you don't need dynamic allocation.</p>\n<pre><code>std::array<std::string, 9> tiles;\n</code></pre>\n<pre><code>for (int i = 0; i < tiles.size(); i++)\n tiles[i] = std::to_string(i);\n</code></pre>\n<hr />\n<p><code>CheckWin</code> and <code>GetWin</code> can be cleaned up by implementing a new function.</p>\n<pre><code>int WinningRows[8][3]{\n{0,1,2}, // horizontal wins\n{3,4,5},\n{6,7,8},\n{0,3,6}, // vertical wins\n{1,4,7},\n{2,5,8},\n{0,4,8}, // diagonal wins\n{2,4,6}\n};\n\n\nbool Board::WinningRow(int * rows)\n{\n return tiles[rows[0]] == tiles[rows[1]]\n && tiles[rows[0]] == tiles[rows[2]];\n}\n\nstd::string Board::GetWin() {\n for (int i = 0; i < 8; ++i)\n if (WinningRow(WinningRows[i]))\n return GetTile(WinningRows[i][0]);\n return "";\n}\n\nbool Board::CheckWin() {\n for (int i = 0; i < 8; ++i)\n if (WinningRow(WinningRows[i]))\n return true;\n return false;\n}\n</code></pre>\n<hr />\n<p>Interface functions should abstract implementation details. Rather than numbering each square 0-8 because you have a continuous array, make it take two arguments: x and y.</p>\n<pre><code>std::string Board::GetTile(int x, int y) {\n return tiles[3*y + x];\n}\n</code></pre>\n<hr />\n<p><code>CheckTie</code> does not make sense to me based on the name -- it looks as though it checks if the board is empty. What does your documentation say? What is its purpose? I'll, for now, assume it is correct.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T19:26:08.667",
"Id": "479899",
"Score": "0",
"body": "I appreciate the feedback! As for `CheckTie`, it looks like I forgot to revisit that logic. My original intent was to check every possible square, and if all of them have been played without a win condition, it would result in a tie condition."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T06:29:32.447",
"Id": "244426",
"ParentId": "244351",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "244426",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T21:43:03.387",
"Id": "244351",
"Score": "2",
"Tags": [
"c++",
"tic-tac-toe"
],
"Title": "OOP Based TicTacToe - Logic Improvement/Best Practices"
}
|
244351
|
<p>I was playing around with sorting methods, brushing up on my algorithms. I have made the following implementation of quicksort:</p>
<pre><code>def quicksort(l):
def inner_qs(list_, start, end):
if end - start > 1:
piv = list_[end - 1]
aux_index = start
for i in range(start, end):
if list_[i] < piv or i == end - 1:
list_[aux_index], list_[i] = list_[i], list_[aux_index]
aux_index += 1
pivot_position = aux_index - 1
# left
inner_qs(list_, start=start, end=pivot_position)
# right
inner_qs(list_, start=pivot_position + 1, end=end)
l = l[:]
inner_qs(l, 0, len(l))
return l
</code></pre>
<p>Please, take a look at it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:07:26.027",
"Id": "479711",
"Score": "1",
"body": "I thought it was more suitable here, since I was asking for a code review ;-) But okay."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:16:39.113",
"Id": "479713",
"Score": "1",
"body": "I have edited the post title and body. Could you please take a look at my post now? Thanks for your time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T05:34:26.003",
"Id": "479723",
"Score": "1",
"body": "You tested this and it throws a recursion error. This means it's not ready for review. Please take a look at the [help/on-topic] and feel free to come back once it works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:13:44.313",
"Id": "479731",
"Score": "1",
"body": "Like every straightforward recursive implementation, yours needs recursion depth of n for an n element ordered input."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T22:01:24.573",
"Id": "244352",
"Score": "2",
"Tags": [
"python",
"algorithm",
"sorting",
"quick-sort"
],
"Title": "Python's quicksort algorithm"
}
|
244352
|
<p>This code unzips the downloaded subtitle files and maps them to their corresponding video file. Currently, after pairing video files with their corresponding subtitle files, it links them by renaming the subtitle file to the same file name as that of its corresponding video file.</p>
<pre><code>#!/usr/bin/env python3
import os, os.path
import shutil
from glob import glob
from PTN import parse
from zipfile import ZipFile
class Subtitles:
"""
Class to perform subtitle-related operations.
"""
def __init__(self, subtitleDir, targetDir, tempStorageDir):
"""
Function to get file paths.
subtitleDir: Path to source directory for subtitles.
targetDir: Path to directory which contains files
to which subtitles need to be mapped.
tempStorageDir: Path to directory to be used as storage
for saving files temporarily.
"""
self.subtitleDir = subtitleDir
self.targetDir = targetDir
self.tempStorageDir = tempStorageDir
self._videoFileFormats = ['3gp', 'avi', 'mkv', 'mp4', 'webm']
def getTargetFileNames(self):
"""
Function to get a list a file names which are to be
mapped to corresponding subtitle file.
"""
currentWorkingDir = os.getcwd()
os.chdir(self.targetDir)
targetFileNames = list()
for ext in self._videoFileFormats:
targetFileNames.extend(glob(f'*.{ext}'))
os.chdir(currentWorkingDir)
return targetFileNames
def getZipFileNames(self):
"""
Function to get a list of zip files present in subtitles
directory.
"""
zipFileNames = glob(os.path.join(self.subtitleDir, '*.zip'))
return zipFileNames
def unzipSubtitles(self, zipFilePath):
"""
Function to unzip a file, extract all subtitles from it
to temporary storage directory and return list of
subtitle filenames.
"""
with ZipFile(zipFilePath, 'r') as zipObj:
listOfFileNames = zipObj.namelist()
listOfSubtitleFileNames = list()
for fileName in listOfFileNames:
if fileName.endswith('.srt'):
listOfSubtitleFileNames.append(fileName)
zipObj.extract(fileName, self.tempStorageDir)
return listOfSubtitleFileNames
def genFileMetadataSummary(self, metadata):
"""
Function to generate summary of metadata in the format
<title>.S<season>E<episode>.<quality> and return it.
"""
fileMetadataSummary = metadata['title'] + '.S' \
+ str(metadata['season']) + 'E' \
+ str(metadata['episode']) + '.' \
+ metadata['quality']
return fileMetadataSummary
def cacheFileMetadata(self, listOfFileNames):
"""
Function to build a dictionary containing metadata
about each of the files and return it.
"""
fileMetadata = dict()
for fileName in listOfFileNames:
metadata = parse(fileName)
metadata['filename'] = fileName[:-4]
fileMetadataSummary = self.genFileMetadataSummary(metadata)
fileMetadata[fileMetadataSummary] = metadata
return fileMetadata
def cleanTempStorageDir(self, listOfFileNames):
"""
Function to remove a list of files from a temporary
storage directory.
"""
for fileName in listOfFileNames:
try:
os.remove(os.path.join(self.tempStorageDir, fileName))
except FileNotFoundError:
pass
def mapSubtitlesToFiles(self):
"""
Function to map a subtitle to corresponding file.
"""
targetFileNames = self.getTargetFileNames()
subtitleFileNames = list()
zipFileNames = self.getZipFileNames()
for zipFileName in zipFileNames:
subtitleFileNames.extend(self.unzipSubtitles(zipFileName))
subtitleMetadata = self.cacheFileMetadata(subtitleFileNames)
targetMetadata = self.cacheFileMetadata(targetFileNames)
for targetFileMetadataSummary in targetMetadata:
try:
sourceFileName = subtitleMetadata[targetFileMetadataSummary]['filename']+'.srt'
print(f'Subtitle for \'{targetFileMetadataSummary}\' successfully mapped.')
except KeyError:
print(f'>> ERROR: Subtitle for \'{targetFileMetadataSummary}\' not found!')
targetFileName = targetMetadata[targetFileMetadataSummary]['filename']+'.srt'
shutil.move(os.path.join(self.tempStorageDir, sourceFileName), \
os.path.join(self.targetDir, targetFileName))
self.cleanTempStorageDir(subtitleFileNames)
if __name__ == '__main__':
subtitleOp = Subtitles(
'/Users/st/Downloads',
'/Volumes/Untitled/Game of Thrones/Season 2',
'/tmp')
subtitleOp.mapSubtitlesToFiles()
</code></pre>
|
[] |
[
{
"body": "<h2>snake_case</h2>\n<p>The PEP8 standard is for these:</p>\n<pre><code>getTargetFileNames\ncurrentWorkingDir \n</code></pre>\n<p>to be</p>\n<pre><code>get_target_filenames\ncurrent_working_dir\n</code></pre>\n<p>and so on for your other functions and variable names.</p>\n<h2>Fail-safe directory reversion</h2>\n<pre><code> os.chdir(currentWorkingDir)\n</code></pre>\n<p>should be in a <code>finally</code>, with the <code>try</code> after the first <code>chdir</code>. That said, you shouldn't be changing the working directory at all. Nothing in <code>getTargetFileNames</code> requires it.</p>\n<h2><code>pathlib</code></h2>\n<p>Use of <code>pathlib.Path</code> in nearly all of your directory and filesystem operations rather than <code>os</code> will make for a much cleaner program.</p>\n<h2>Generators</h2>\n<pre><code> listOfSubtitleFileNames = list()\n for fileName in listOfFileNames:\n if fileName.endswith('.srt'):\n listOfSubtitleFileNames.append(fileName)\n zipObj.extract(fileName, self.tempStorageDir)\n return listOfSubtitleFileNames\n</code></pre>\n<p>first of all, "list of" can usually be dropped from variable names for legibility; <code>subtitle_filenames</code> is enough to know that it's an iterable. Second, <code>list()</code> can be replaced with <code>[]</code>. It would be even simpler as a list comprehension:</p>\n<pre><code>subtitle_filenames = [\n fn for fn in filenames if fn.endswith('.srt')\n]\nfor fn in subtitle_filenames:\n zip_obj.extract(fn, self.temp_storage_dir)\nreturn subtitle_filenames\n</code></pre>\n<h2>String interpolation</h2>\n<pre><code> fileMetadataSummary = metadata['title'] + '.S' \\\n + str(metadata['season']) + 'E' \\\n + str(metadata['episode']) + '.' \\\n + metadata['quality']\n</code></pre>\n<p>First, avoid <code>\\</code> line continuation whenever possible. The way to avoid that here is parentheses. Also, this is well-suited to string interpolation:</p>\n<pre><code>file_metadata_summary = (\n metadata['title'] +\n f'S{metadata["season"]}'\n f'E{metadata["episode"]}'\n f'.{metadata["quality"]}'\n)\n</code></pre>\n<h2>Hard-coded paths</h2>\n<pre><code> '/Users/st/Downloads',\n '/Volumes/Untitled/Game of Thrones/Season 2',\n '/tmp'\n</code></pre>\n<p>should not be hard-coded. It should be parametric, perhaps as a command-line parameter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:00:03.690",
"Id": "479860",
"Score": "0",
"body": "First of all thanks a lot for your code review. I've made the indicated changes and the code looks much cleaner now. However, I have a question. After making changes according to the GENERATORS section of your answer, my code runs slightly faster. Why using two for loops (1 list comprehension loop and 1 regular loop) is faster than a for loop with an if statement inside it? My intuition says the latter should run faster. It would be a great help if you could explain this to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-24T14:04:13.403",
"Id": "479863",
"Score": "0",
"body": "It's tough to say, and the only concrete answer is going to come from profiling."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T14:31:54.597",
"Id": "244378",
"ParentId": "244355",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244378",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T01:29:27.737",
"Id": "244355",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"complexity"
],
"Title": "Link downloaded subtitle files and video files"
}
|
244355
|
<p>I need to identify the different markdown files I have so I can create a unique url structure for them. I can already identify "notes" files, and want to create a second type called "projects".</p>
<p>My gatsby-node.js file looks like this right now</p>
<pre><code>const path = require('path');
const { createFilePath } = require('gatsby-source-filesystem');
// Look at every node when it is created
exports.onCreateNode = ({node, getNode, actions}) => {
// Check for markdown nodes
const { createNodeField } = actions;
if(node.internal.type === 'MarkdownRemark') {
// Create a slug out of the markdown filepath name
const slug = createFilePath({
node,
getNode,
basePath: 'notes'
});
// Add the newly created slug to the node itself
createNodeField({
node,
name: 'slug',
value: `/note${slug}`
});
}
};
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
return new Promise((resolve, reject) => {
graphql(`
{
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
}
}
`).then(result => {
result.data.allMarkdownRemark.edges.forEach(({ node }) => {
createPage({
path: node.fields.slug,
component: path.resolve(`./src/templates/note.js`),
context: {
// Data passed to context is available in page queries as GraphQL variables.
slug: node.fields.slug,
},
})
})
resolve()
})
})
};
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T03:24:59.767",
"Id": "244356",
"Score": "1",
"Tags": [
"javascript",
"graphql"
],
"Title": "Creating two different posts types on my Gatsby site - rewriting my gatsby-node.js"
}
|
244356
|
<p>Submitting for expert review.</p>
<p>I am trying to create a Chart - Crosshair cursor in excel chart sheet. Chart - Crosshair cursor lines are two lines (one horizontal and other vertical) moving along with the cursor/pointer/mousemove on the chart. Most of the stock market online charts have such interactive tool. I have referred to many webpages such as <a href="https://stackoverflow.com/questions/26426358/calculating-datapoint-position-with-chart-mouseover-event">Calculating datapoint position with chart mouseover event</a></p>
<p>Everyone concerned faced the same problem as I did - Calulation of exact cursor position coordinates as the chart is measured in points and cursor position (windows item) is measured in pixels. Somehow, I could calculate it with formula. (Very Close)</p>
<p>I understood cursor position coordinates are determined by following factors.</p>
<ol>
<li>Windows Zoom set by "Make everything bigger" option in control panel/ settings. In Excel this can be determined using (ActiveWindow.Width)</li>
<li>Page Size of the Chartsheet (ActiveChart.PageSetup.PaperSize)</li>
<li>Page Orientation of the Chartsheet(ActiveChart.PageSetup.Orientation )</li>
<li>Zoom percent of the chartsheet (ActiveWindow.Zoom)</li>
<li>Chart area size (ChartArea.Width and ChartArea.Height)</li>
</ol>
<p>for reference <a href="https://www.youtube.com/watch?v=V0f-WGwd0_s" rel="nofollow noreferrer">YouTube video</a>. Please note that page margins are set to zero</p>
<p><a href="https://i.stack.imgur.com/oLpHm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oLpHm.png" alt="enter image description here" /></a></p>
<p>Paste this code in excel VBE Chart(Sheet) object.</p>
<pre><code>Option Explicit
Private xPoint As Variant, yPoint As Variant, XMax As Variant, YMax As Variant, DispScale As Variant
Private shp As Shape, ChartPaperSize, PgWidPXL, PgHgtPXL, ChtAreaWid, ChtAreaHgt, ActWinZoom
Private shpHL As Variant, shpVL As Variant
'--------------------------------------------------------------------------------
Private Sub Chart_MouseMove(ByVal Button As Long, ByVal Shift As Long, ByVal A As Long, ByVal B As Long)
'Dim xPoint As Variant, yPoint As Variant, XMax As Variant, YMax As Variant, DispScale As Variant
'Dim shp As Shape, ChartPaperSize, PgWidPXL, PgHgtPXL, ChtAreaWid, ChtAreaHgt, ActWinZoom
'This macro is suitable for following 4 paper sizes only
'--------------------------------------------------------------------------------
ChartPaperSize = ActiveChart.PageSetup.PaperSize
Select Case ChartPaperSize
' I couldnt find better way to convert paper size number to inches and therafter to pixels
' I dont know why multiplying by 0.9745 or 0.9725 keeps the x, y coordinates more close to the diplayed cursor position
Case 5 '"xlPaperLegal"
If ActiveChart.PageSetup.Orientation = xlLandscape Then
PgWidPXL = 14 * 220 * 0.9745 '220 PPI
PgHgtPXL = 8.5 * 220 * 0.9725
Else
PgWidPXL = 8.5 * 220 * 0.9745
PgHgtPXL = 14 * 220 * 0.9725
End If
Case 1 '"xlPaperLetter"
If ActiveChart.PageSetup.Orientation = xlLandscape Then
PgWidPXL = 11 * 220 * 0.9745
PgHgtPXL = 8.5 * 220 * 0.9725
Else
PgWidPXL = 8.5 * 220 * 0.9745
PgHgtPXL = 11 * 220 * 0.9725
End If
Case 9 '"xlPaperA4"
If ActiveChart.PageSetup.Orientation = xlLandscape Then
PgWidPXL = 11.69 * 220 * 0.9745
PgHgtPXL = 8.27 * 220 * 0.9725
Else
PgWidPXL = 8.27 * 220 * 0.9745
PgHgtPXL = 11.69 * 220 * 0.9725
End If
Case 8 ' "xlPaperA3"
If ActiveChart.PageSetup.Orientation = xlLandscape Then
PgWidPXL = 16.54 * 220 * 0.9745
PgHgtPXL = 11.69 * 220 * 0.9725
Else
PgWidPXL = 11.69 * 220 * 0.9745
PgHgtPXL = 16.54 * 220 * 0.9725
End If
'Case Else
End Select
'Windows display recommended scale of 125% in my computer settings
XMax = PgWidPXL * (100 / 125) ' for A4 2503 for legal 2999 '2395 'Max mousepointer width on 100% chart sheet zoom
YMax = PgHgtPXL * (100 / 125) ' for A4 1764 for legal 1814 '1450 'Max mousepointer height on 100% chart sheet zoom
ChtAreaWid = ChartArea.Width
ChtAreaHgt = ChartArea.Height
DispScale = Round(1161 / ActiveWindow.Width, 2)
' 1161 is ActiveWindow.Width at Windows display recommended scale of 125% on my computer
ActWinZoom = ActiveWindow.Zoom
xPoint = (A * (ChtAreaWid * DispScale) / XMax) / (ActWinZoom / 100)
yPoint = (B * (ChtAreaHgt * DispScale) / YMax) / (ActWinZoom / 100)
'--------------------------------------------------------------------------------
'Delete lines
For Each shp In ActiveChart.Shapes
If shp.Type = msoLine Then
shp.Delete
End If
Next
'Add new lines
With ActiveChart.Shapes.AddLine(1, yPoint, ChartArea.Width, yPoint).Line 'horizontal line
.ForeColor.RGB = RGB(150, 150, 150)
.Weight = 5
End With
With ActiveChart.Shapes.AddLine(xPoint, 1, xPoint, ChartArea.Height).Line 'vertical line
.ForeColor.RGB = RGB(150, 150, 150)
.Weight = 5
End With
'--------------------------------------------------------------------------------
'Above deletion and addition of new lines could be avoided if two lines are already present
'Say, we manually insert line shapes named "Straight Connector 1" and "Straight Connector 2" then
'With ActiveChart.Shapes("Straight Connector 1") 'horizontal line
'.Left = 1
'.Top = yPoint
'.Width = ChartArea.Width
'.Height = 1
'End With
'With ActiveChart.Shapes("Straight Connector 2") 'vertical line
'.Left = xPoint
'.Top = 1
'.Width = 1
'.Height = ChartArea.Height
'End With
'--------------------------------------------------------------------------------
End Sub
</code></pre>
<p>Code works fine. I was wondering if we can avoid deletion and addition of lines with every mouse move. I tried adding lines on chart activate event and then allign those lines using module level variables. But the too procedures cannot work together as by the time chart activate is triggered mouse move already takes place. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:24:50.807",
"Id": "479736",
"Score": "1",
"body": "\"Refer YouTube video\" Links can rot. Please tell us the purpose of the code in the question itself, so the question is still valid without the link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:38:46.693",
"Id": "479741",
"Score": "0",
"body": "@Mast Added first paragraph. Please see. Thanks for guidance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T05:08:00.773",
"Id": "520160",
"Score": "0",
"body": "**Margins** in the above chart are set to **zero** .. Also, noticed [this OLD page](https://www.informit.com/articles/article.aspx?p=374498&seqNum=2) today :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-26T07:22:06.247",
"Id": "520161",
"Score": "0",
"body": "One can Use **MouseDown event** instead of MouseMove event to avoid continuous deletion and addition of lines with every mouse move."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T07:00:09.043",
"Id": "244363",
"Score": "4",
"Tags": [
"vba",
"excel"
],
"Title": "Excel Chart - Crosshair cursor lines with VBA"
}
|
244363
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.