body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm developing a class for connection to LCD (Liquid Crystal Display).
It can connect in two modes: 4-bit and 8-bit. And the number of modes may be increased. The mode can be configured in the constructor.
A lot of behavior depends on the mode. But! The mode can be changed in run-time, so I can't create the <code>Lcd</code> abstract class and two derivatives <code>FourBitLcd</code> and <code>EightBitLcd</code>.
Code:</p>
<pre><code>class Lcd {
public:
enum Mode {
Mode4bit,
Mode8bit,
};
explicit Lcd(Mode mode) : mode(mode) {}
public:
void Init() {
if (this->mode == Mode8bit) {
SendCommand(LCD_CMD_8_BIT_MODE);
}
else {
this->Reset();
SendCommand(LCD_CMD_4_BIT_MODE);
}
}
void SendCommand(uint8_t command_id) {
if (this->mode == Mode8bit) {
this->SendLowerNibble(command_id);
}
else {
this->SendHigherNibble(command_id);
this->SendCmdSignals();
command_id <<= 4;
}
this->SendHigherNibble(command_id);
this->SendCmdSignals();
}
void SendData(uint8_t data) {
if (this->mode == Mode8bit) {
this->SendLowerNibble(data);
}
else {
this->SendHigherNibble(data);
this->SendDataSignals();
data <<= 4;
}
this->SendHigherNibble(data);
this->SendDataSignals();
}
private:
void BusyCheck() {
// ...
if (this->mode == Mode4bit) {
en.Write(true);
_delay_us(10);
en.Write(false);
_delay_us(10);
}
// ...
}
void Reset();
void SendHigherNibble(uint8_t val);
void SendLowerNibble(uint8_t val);
void SendCmdSignals();
void SendDataSignals();
private:
Mode mode = Mode8bit;
};
</code></pre>
<p>In this case, I think I should use polymorphism instead of if/else. But then I have another problem. For example, I can create <code>ModeStrategy</code> abstract class and <code>FourBitModeStrategy</code> and <code>EightBitModeStrategy</code>. But derivative classes need the instance of the class <code>Lcd</code> because they need to use its methods such as <code>SendLowerNibble</code> and <code>SendHigherNibble</code>. But if I pass a pointer of <code>Lcd</code> to derivatives of <code>ModeStrategy</code> then it will be a bidirectional reference. As far as I know, it's not good. For example, code:</p>
<pre><code>class Lcd {
public:
class ModeStrategy {
public:
void InitLcdPtr(Lcd *lcd) {
this->lcd_ = lcd;
}
virtual void InitMode() = 0;
virtual void SendCommandPart(uint8_t &command_id) = 0;
virtual void SendDataPart(uint8_t &data) = 0;
virtual void BusyCheck() {}
protected:
Lcd *lcd_ = nullptr;
};
class FourBitModeStrategy : public ModeStrategy {
public:
void InitMode() override {
this->lcd_->Reset();
this->lcd_->SendCommand(LCD_CMD_4_BIT_MODE);
}
void SendCommandPart(uint8_t &command_id) override {
this->lcd_->SendHigherNibble(command_id);
this->lcd_->SendCmdSignals();
command_id <<= 4;
}
void SendDataPart(uint8_t &data) override {
this->lcd_->SendHigherNibble(data);
this->lcd_->SendDataSignals();
data <<= 4;
}
};
class EightBitModeStrategy : public ModeStrategy {
public:
void InitMode() override {
this->lcd_->SendCommand(LCD_CMD_8_BIT_MODE);
}
void SendCommandPart(uint8_t &command_id) override {
this->lcd_->SendLowerNibble(command_id);
}
void SendDataPart(uint8_t &data) override {
this->lcd_->SendLowerNibble(data);
}
};
friend FourBitModeStrategy;
public:
enum Mode {
Mode4bit,
Mode8bit,
};
explicit Lcd(ModeStrategy *mode_strategy) : mode_strategy(mode_strategy) {
// Bidirectional reference.
this->mode_strategy->InitLcdPtr(this);
}
public:
void Init() {
this->mode_strategy->InitMode();
}
void SendCommand(uint8_t command_id) {
this->mode_strategy->SendCommandPart(command_id);
this->SendHigherNibble(command_id);
this->SendCmdSignals();
}
void SendData(uint8_t data) {
this->mode_strategy->SendDataPart(data);
this->SendHigherNibble(data);
this->SendDataSignals();
}
private:
void BusyCheck() {
// ...
this->mode_strategy->BusyCheck();
// ...
}
void Reset();
void SendHigherNibble(uint8_t val);
void SendLowerNibble(uint8_t val);
void SendCmdSignals();
void SendDataSignals();
private:
ModeStrategy *mode_strategy = nullptr;
};
</code></pre>
<p>But as I said there is a bidirectional reference.
How to solve it?
Thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T12:16:04.760",
"Id": "501433",
"Score": "0",
"body": "You might want to learn about `protected` as well as `private` and public. Derivative classes can access `protected` functions."
}
] |
[
{
"body": "<h1>Avoid polymorphism in this case</h1>\n<p>You can avoid the circular reference by passing <code>Lcd *</code> to every member function of <code>ModeStrategy</code>, so the latter doesn't have to store that pointer. However,\ngiven the code you have posted, I don't think using polymorphism is a good idea at all in this case. It involves pointer dereferencing and indirect function calls, when all you need is a few <code>if (mode == ...)</code>.</p>\n<h1>Try to minimize the number of functions that need to know the <code>mode</code></h1>\n<p>Perhaps you can just have a single function that takes care of sending a full byte, whether it's a command or data byte? For example:</p>\n<pre><code>void SendByte(uint8_t data, bool command) {\n if (mode == Mode8bit) {\n // write data\n // write command or data signals\n } else {\n // write data\n // write command or data signals\n // write data << 4\n // write command or data signals\n } \n}\n</code></pre>\n<p>Then <code>SendCommand()</code> and <code>SendData()</code> and even <code>Init()</code> can call <code>SendByte()</code> without having to know the mode.</p>\n<h1>Unnecessary use of <code>this-></code></h1>\n<p>You almost never need to explicitly write <code>this-></code> in C++. You are not even doing it consistently anyway, for example in <code>Init()</code> in the non-polymorphic version you call <code>SendCommand()</code> without <code>this-></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T19:33:18.627",
"Id": "254233",
"ParentId": "254229",
"Score": "3"
}
},
{
"body": "<p>In addition to the existing review, a few other points may be helpful to you.</p>\n<h2>Rethink the interface</h2>\n<p>Chances are high that your software can't magically create hardware. In other words, you probably want an instance of your <code>LCD</code> class to access one particular LCD. Therefore you are unlikely to want copy or move constructors, so I would suggest they should be <code>delete</code>d. Further, there's unlikely to be much use in having a separate <code>BusyCheck</code> -- if I were using the code, I'd want the <code>LCD</code> class constructor to be tied to a particular physical LCD and to have functions that print to the LCD. I would expect the class itself to take care of initialization within the constructor and to manage contention.</p>\n<h2>Think about testing</h2>\n<p>You <em>do</em> test your code, right? One thing I've used for this is to create a virtual base object with all of the necessary methods, and then derive from that to create the actual object that write to the physical device. During test, I might prefer to have a simulated device, so I create a separate derived object for that purpose. All of the interfaces and interactions remain the same, but it gives you a way to test even in the absence of physical hardware.</p>\n<h2>Consider initialization and thread safety</h2>\n<p>Most embedded systems I work with these days are multithreaded. Your system may or may not be, but it's still good to think about. Consider a handheld device in which the top line shows GPS coordinates and time (from a GPS object running in its own thread) and a battery object showing the state of charge (from a Battery object running in a different thread). Both need asynchronous access to the LCD.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T16:43:12.667",
"Id": "254388",
"ParentId": "254229",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254233",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:04:26.090",
"Id": "254229",
"Score": "2",
"Tags": [
"c++",
"object-oriented"
],
"Title": "C++ switch-like code structure"
}
|
254229
|
<p>I've searched this site and find many similar questions, but not exactly the same as the one I'll post.</p>
<p>This attempts to solve <a href="https://leetcode.com/problems/sliding-window-maximum/" rel="nofollow noreferrer">Leetcode 239</a>:</p>
<blockquote>
<p>You are given an array of integers <code>nums</code>, there is a sliding window of size <code>k</code> which is moving from the very left of the array to the very right. You can only see the <code>k</code> numbers in the window. Each time the sliding window moves right by one position.</p>
<p>Return <em>the max sliding window</em>.</p>
</blockquote>
<p>The subject is - given an integer array, and positive integer k, denoting the sliding window size. Each time you can <em>only</em> slide from left to right one position, try to find each windows maximum number and output these maximum number into an output list. [Note - the given list could be very large ~ 1 Million (nums)]</p>
<p>For example: Given a nums array = [99, 74, 48, 27, 56, 88, 66, 77, 101]; k = 3
Output should be: [99, 74, 56, 88, 88, 88, 101]</p>
<p>I've tried to solve this in Python, and wonder if it could be further optimized and improved. Thanks in advance.</p>
<pre class="lang-py prettyprint-override"><code>def maxSliding(nums: List[int], k: int) -> List[int]:
if not k or not nums: return []
z = len(nums)
if z <= k: return [max(nums, default = 0)]
q = deque([])
res = []
for i, num in enumerate(nums):
if q and q[0] == i-k:
q.popleft()
while q and nums[q[-1]] < num:
q.pop()
q.append(i)
if i >= k-1: res.append(nums[q[0]])
return res
# Since every num. enters and leaves the queue at most once, the time
# complexity is O(len(A)), independent of the value of K.
if __name__ == '__main__':
B = [99, 74, 48, 27, 56, 88, 66, 77, 101]
print(maxSliding(B, 3))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:51:09.957",
"Id": "501367",
"Score": "0",
"body": "This is a job for Numpy. Is there a specific reason you aren't using it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:54:18.387",
"Id": "501368",
"Score": "0",
"body": "The req. asked not to use any 3rd party library. Only Python's lib. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:54:53.363",
"Id": "501369",
"Score": "0",
"body": "Is the request a homework request? If so, please tag the question as such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:55:37.123",
"Id": "501370",
"Score": "0",
"body": "No, no, no - it's for practice on the Web site - to prepare for interview. I've solved it and seek for comments if any room for improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:56:29.397",
"Id": "501371",
"Score": "0",
"body": "Is it a particular interview practice website? Adding a link to the original question would be helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:58:29.940",
"Id": "501373",
"Score": "0",
"body": "The question can be found here - https://leetcode.com/problems/sliding-window-maximum/ Thanks again for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T19:01:27.523",
"Id": "501374",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/117953/discussion-between-daniel-hao-and-reinderien)."
}
] |
[
{
"body": "<p>I don't see any obvious improvements to your algorithm.</p>\n<h3>Tests:</h3>\n<p>Your "main" section seems to be checking if the algorithm works, but you can make better use of the examples provided with the original prompt.</p>\n<h3>Constraints:</h3>\n<p>The original prompt makes certain promises about the inputs. It's reasonable to just take those as assumptions, or (maybe better, depending on stuff) to make them explicit assertions, but there's no need to <em>handle</em> violating cases.</p>\n<h3>Typing:</h3>\n<p>You've got type-hints in your function signature.<br />\nThat's great!<br />\nBut in python the idea of "types are comments that can't be wrong" only holds if you actually use a type-checker. Trying <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">mypy</a> on your code gives an error that it can't figure out the type of <code>q</code>. The easiest fix for this would be to use the <code>Deque</code> from <code>typing</code> (or upgrade to python 3.9) so you can write <code>q = Deque[int]()</code>.</p>\n<h3>Begging for microseconds:</h3>\n<p>You can save yourself some conditional checks by changing how you handle the first couple rounds: Start the loop with something in the deque, and slice off the head of the result-list at the end. On the other hand, trying to optimize at that level of granularity is easy to get wrong. I banged out an over-engineered version, but without benchmarking this is worthless.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List, Deque, Iterable, Tuple, Callable\nfrom itertools import islice\n\ndef _window_func(k: int, q: Deque[Tuple[int, int]]) -> Callable[[Tuple[int, int]], int]:\n def retval(pair):\n if q[0][0] == pair[0] - k:\n q.popleft()\n while q and q[-1][1] < pair[1]:\n q.pop()\n q.append(pair)\n return q[0][1]\n return retval\n\ndef maxSliding(nums: List[int], k: int) -> List[int]:\n assert nums\n assert 1 <= k <= len(nums)\n return list(islice(\n map(_window_func(k, Deque([(-1, nums[-1])])),\n enumerate(nums)),\n k - 1, None\n ))\n\ntests = [([99,74,48,27,56,88,66,77,101], 3, [99,74,56,88,88,88,101]),\n ([1,3,-1,-3,5,3,6,7], 3, [3,3,5,5,6,7]),\n ([1], 1, [1]),\n ([1,-1], 1, [1,-1]),\n ([9,11], 2, [11]),\n ([4,-2], 2, [4])]\n\nif __name__ == '__main__':\n for (l, k, result) in tests:\n try:\n actual = maxSliding(l, k)\n assert actual == result\n except:\n print(f'Offending test {(l, k, result)}, got {actual}')\n raise\n print("tests passed")\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T23:32:21.950",
"Id": "501404",
"Score": "0",
"body": "Hi, @ShapeOfMatter, thanks your review and feedback. I'll read and incorporate all the comments. Thank you again for effort. -Daniel"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T22:43:17.090",
"Id": "254249",
"ParentId": "254230",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254249",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T18:32:49.657",
"Id": "254230",
"Score": "3",
"Tags": [
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "Another Sliding Window - find each `k-size` window the maximum num. from an integer array/list"
}
|
254230
|
<p>In order to learn rust and concurrency , im trying to share a common hashmap between actix web server and a parallel thread</p>
<ul>
<li>Theres one thread which updates a hashmap with the current timestamp every 10 seconds</li>
<li>theres a GET API which returns the latest timestamp provided in the hashmap</li>
</ul>
<p>heres my code</p>
<pre><code>use actix_web::{web, App, HttpServer};
use std::collections::HashMap;
use chrono::prelude::*;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
async fn get_latest_timestamp(data: web::Data<Arc<Mutex<HashMap<String, String>>>>) -> String {
let wrapped_data = data.lock().unwrap();
match wrapped_data.get("time_now") {
Some(i) => String::from(i),
None => String::from("None")
}
}
fn update_timestamps(data: Arc<Mutex<HashMap<String, String>>>) -> () {
loop {
thread::sleep(Duration::from_secs(10));
println!("Updating time.... ");
let now: DateTime<Local> = Local::now();
let mut data = data.lock().unwrap();
data.insert(String::from("time_now"), now.to_rfc2822());
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let mut hash = HashMap::new();
hash.insert(String::from("time_now"), Local::now().to_rfc2822());
let data = Arc::new(Mutex::new(hash));
let hash_clone = Arc::clone(&data);
thread::spawn(move || {
update_timestamps(hash_clone)
});
HttpServer::new( move || {
App::new()
.data(data.clone())
.route("/", web::get().to(get_latest_timestamp))
})
.bind("127.0.0.1:8080")?
.run()
.await
}
</code></pre>
<p>Is there anything i could do handle better. A couple of questions i do have</p>
<ol>
<li><p>How does one generally handle errors that occur on the parallel thread? is the main thread notified in someway?</p>
</li>
<li><p>the code in <code>update_timestamps</code> runs in a continous loop - is there a better way to handle it so that it cleanly exits?</p>
</li>
</ol>
|
[] |
[
{
"body": "<p>Answering your questions:</p>\n<ol>\n<li>Depends on the nature of the error.</li>\n</ol>\n<p>Panics will make the thread exit. If the creator called <code>join</code> on the result of <code>thread::spawn</code>, the result of that <code>join</code> will be <code>Err(boxed_any)</code>. The boxed_any is the argument given to <code>panic!</code>. This is one common way to signal and handle an error.</p>\n<p>If the panic occurs while a mutex's lock is in scope, the mutex will be poisoned and therefore return <code>Err</code> for all locking attempts on all threads indefinitely.</p>\n<p>In case you'd like to notify another thread about an event, let's say, an occurence of a meaningful error, it's best to use channels. You can read more in "Using Message Passing to Transfer Data Between Threads": <a href=\"https://doc.rust-lang.org/book/ch16-02-message-passing.html\" rel=\"nofollow noreferrer\">https://doc.rust-lang.org/book/ch16-02-message-passing.html</a></p>\n<ol start=\"2\">\n<li>I'm not sure what you meant by exiting cleanly. You need the thread to run indefinitely. The thread will exit "cleanly" when the server is closed (and so when the main thread exits).</li>\n</ol>\n<p>Minor points:</p>\n<ul>\n<li>calls to <code>Arc::clone</code> can be simply <code>.clone()</code>. Quoting the docs:</li>\n</ul>\n<pre class=\"lang-rust prettyprint-override\"><code>// The two syntaxes below are equivalent.\nlet a = foo.clone();\nlet b = Arc::clone(&foo);\n</code></pre>\n<ul>\n<li>the second (and last) <code>data.clone()</code> is unnecessary. This is often seen in code. Just pass the value.</li>\n</ul>\n<p>You still have ownership of that original value. That original value can be spent by passing it to actix.</p>\n<ul>\n<li><code>-> ()</code> in a function signature is never meaningful; just cut it out.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-12T02:58:50.077",
"Id": "505096",
"Score": "2",
"body": "Personally, I prefer `Arc::clone` to `.clone()`, to stress the fact that we are calling a method of `Arc` and not going through `Deref`, and also for consistency with other associated functions of `Arc`, which aren't methods for the same reason."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T15:35:44.430",
"Id": "254605",
"ParentId": "254236",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T20:01:11.437",
"Id": "254236",
"Score": "1",
"Tags": [
"rust"
],
"Title": "Handling shared state between actix and a parallel thread"
}
|
254236
|
<p><a href="https://en.wikipedia.org/wiki/Set_cover_problem" rel="nofollow noreferrer">The set-cover problem is explained here.</a></p>
<p>I am using lists that are being treated as sets. As I found lists were easier to manipulate in python than sets.</p>
<p>The first part of the algorithm uses input validation.</p>
<pre><code>import json
from copy import deepcopy
import random
s = input("Input list of integers (no repeating elements) for S with commas (eg. 1,2,3,4...) : ").split(',')
c = input('enter list for C (eg. [[1,2,3],[4,5,6]]): ')
c = json.loads(c)
s = [int(a) for a in s]
random.seed()
miss = []
delete = []
remove = []
remove_t=[]
no = 0
def input_validation():
# checking for missing elements.
no = 0
for a in range(0, len(c)):
for b in range(0, len(c[a])):
miss.append(c[a][b])
for d in s:
if d not in miss:
print('False', d)
no = 1
break
if no == 1:
quit()
# Throw out unwanted orderings of sub-lists
for a in range(0, len(c)):
c[a] = sorted(c[a])
# Lists are treated as sets, so lists
# with repeating elements is thrown out
for rem in range(0, len(c)):
if len(c[rem]) != len(set(c[rem])):
remove.append(c[rem])
for rem_two in range(0, len(remove)):
if remove[rem_two] in c:
del c[c.index(remove[rem_two])]
# Throw out lists that have elements that do
# not exist in s.
for j in range(0, len(c)):
for jj in range(0, len(c[j])):
if any(elem not in s for elem in c[j]):
remove_t.append(c[j])
for rem_two in range(0, len(remove_t)):
if remove_t[rem_two] in c:
del c[c.index(remove_t[rem_two])]
</code></pre>
<p>The Second Part of the Algorithm uses a bijective mapping that will prepare it for the heart of the program. There is a function, I found on the internet that shuffles the list. I already know that Python has a shuffling function. But, I wasn't sure, if it would be able to generate all permutations of the list; if it ran forever in a while-loop. So far it suffices.</p>
<pre><code>s_copy = deepcopy(s)
input_validation()
# remove repeating lists
c = [c[x] for x in range(len(c)) if not(c[x] in c[:x])]
c_copy = deepcopy(c)
one_s = []
# See if there is sets
# with one element.
# and check them for a
# cover.
for a in c:
if len(a) == 1:
if a not in one_s:
one_s.append(a)
if len(one_s) == len(s):
print(one_s)
quit()
def bijective_mapp():
s_copy = deepcopy(s)
for a in range(0, len(s)):
s[a] = a+1
for b in range(0, len(c)):
for bb in range(0, len(c[b])):
c[b][bb] = s_copy.index(c[b][bb])+1
bijective_mapp()
c = [sorted(y) for y in c]
def shuff(c, n):
for i in range(n-1,0,-1):
j = random.randint(0,i)
c[i],c[j] = c[j],c[i]
c.append(sorted(c[len(c)-1]))
</code></pre>
<p>The third and final part of the program sorts the list <code>C</code> in a special-way where all <code>[1,x,x]'s</code> are grouped together. So are <code>[4,x,x]'s</code> with the other <code>[4,x,x,...]'s</code>. When the <code>reset</code> variable is met, the list C gets shuffled until the loop reaches <code>steps</code> iterations. After the loop ends, I will output the cover with the most sets found.</p>
<p>The variable <code>steps</code> are impractical; when the input is large enough. As I need, the largest amount of sets found without running in exponential-time. The reason for the constant shuffling (and sorting) is because it seems to find covers more easily.</p>
<pre><code>n = len(s)
steps = n*(2**2)*((n*(2**2))-1)*((n*(2**2))-2)//6
reset = 0
c_elem = set()
set_cover = []
partial = []
for a in range(0, steps + 1):
reset = reset + 1
if reset > len(c):
c_elem = set()
reset = 0
shuff(c, len(c))
c = sorted(c, key=lambda parameter: parameter[0])
set_cover = []
c.append(c[0])
del(c[0])
for l in c:
if not any(v in c_elem for v in l):
set_cover.append(l)
c_elem.update(l)
# if exact solution not found,
# then use partial solution
if set_cover not in partial:
partial.append(set_cover)
# get the largest set-cover found
list_of_partials = [len(r) for r in partial]
k = partial[list_of_partials.index(max(list_of_partials))]
# Reversing the Bijective mapping
# to the original input. But, its sorted.
for a in range(0, len(k)):
for b in range(0, len(k[a])):
l = s.index(k[a][b])
k[a][b] = s_copy[l]
# Outputs the largest amount of sets found
print(k)
</code></pre>
<p>What are some simple optimizations for the function <code>input_validation</code> that I could use?</p>
<p>Are there better ways, to improve the efficiency of the nested loops in the third part of the algorithm?</p>
<p>What variable names would you recommend using for the function <code>input_validation</code>?</p>
<p>Because, I am coding as a hobby, what is a more pythonic way to make this easier for you to read and understand?</p>
|
[] |
[
{
"body": "<h2>Validation</h2>\n<p>This:</p>\n<pre><code>c = input('enter list for C (eg. [[1,2,3],[4,5,6]]): ')\nc = json.loads(c)\n</code></pre>\n<p>may be fine for your purposes if this is a proof-of-concept script, but if you needed rigorous input validation, <code>loads</code> allows for too much variation. You also need to check that this is a list of lists of integers and nothing else. Otherwise, the user could provide a dictionary of dictionaries of lists of dictionaries of strings mapping to nulls, and your program would unceremoniously crash.</p>\n<h2>Shadowing</h2>\n<p>You have a big crazy mix of global code interleaved (with no empty lines) with function definitions. Among other things, you'll see strange effects from code like</p>\n<pre><code>no = 0\ndef input_validation():\n no = 0\n</code></pre>\n<p>Those two <code>no</code> variables do <em>not</em> refer to the same thing, the latter shadowing the former. Tear out your globals and pass them around via function parameters and return values, or make a class.</p>\n<h2>Range defaults</h2>\n<p>Drop <code>0, </code> from these:</p>\n<pre><code>for a in range(0, len(c)):\n for b in range(0, len(c[a])):\n</code></pre>\n<h2>Sets</h2>\n<blockquote>\n<p>I am using lists that are being treated as sets. As I found lists were easier to manipulate in python than sets.</p>\n</blockquote>\n<p>That's... ominous, and a little baffling? How could a <code>set()</code> be a worse representation of an actual set than a <code>list()</code>?</p>\n<p>Among the many consequences of this decision, this code:</p>\n<pre><code>if d not in miss\n</code></pre>\n<p>has been ballooned from O(1) to O(n) time. You should really invest the time into learning how to work with actual sets.</p>\n<p>A related block is</p>\n<pre><code>for rem in range(0, len(c)):\n if len(c[rem]) != len(set(c[rem])):\n remove.append(c[rem])\nfor rem_two in range(0, len(remove)):\n if remove[rem_two] in c:\n del c[c.index(remove[rem_two])]\n</code></pre>\n<p>which is stunning:</p>\n<ul>\n<li>Form a range over the indices of <code>c</code> instead of using a standard <code>for x in c</code></li>\n<li>Temporarily make a set, only to throw it out again</li>\n<li>Construct a list of values to remove, instead of a list of indices to remove</li>\n<li>Form another range over the indices of <code>remove</code> instead of using a standard <code>for x in remove</code></li>\n<li>Invoke <code>if in c</code>, which executes in linear time, within a loop that multiplies it to O(n^2)</li>\n<li>Invoke the linear-time <code>c.index</code> on the stored value, instead of just having remembered the index</li>\n</ul>\n<p>If all this does is validate input, I don't see why any of this needs to happen, and if it did need to happen it can be done in a vastly simpler way.</p>\n<p>If you wanted to keep this validation, a useful validation would apply a <code>Counter</code> to the input comprehension and raise a warning (or error) for any count over one. If you wanted to silently collapse lists with repeat elements to sets, this can be done in one line.</p>\n<p>Another stunning block is</p>\n<pre><code># Throw out lists that have elements that do\n# not exist in s.\nfor j in range(0, len(c)):\n for jj in range(0, len(c[j])):\n if any(elem not in s for elem in c[j]):\n remove_t.append(c[j])\n</code></pre>\n<p>This is a loop, containing a nested loop, containing an <code>any</code> generator, containing a linear <code>in s</code> check. I will leave it as an exercise to you what the computational complexity of this creature is, and how it could be reduced if you convert to real sets.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T21:59:20.053",
"Id": "501398",
"Score": "0",
"body": "Looking forward to this. Optimizing my code means, I am finally done with this hobby-project."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T21:43:46.073",
"Id": "254246",
"ParentId": "254242",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254246",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T20:42:04.073",
"Id": "254242",
"Score": "1",
"Tags": [
"python",
"heuristic"
],
"Title": "Set Cover Heuristic"
}
|
254242
|
<p>As I'm doing the MOOC Java course I decided to write a small program to count the word occurrences that accepts as the first (mandatory) input a path to a text file (extension not enforced) and as many words you want to check (optional). It prints out the results to the terminal. Checked with books in .txt format from Project Gutenberg.</p>
<p>This is my first ever Java program, thank you.</p>
<pre class="lang-java prettyprint-override"><code>package com.my.name;
public class Main {
public static void main(String[] args) {
if (args.length == 0) {
throw new IllegalArgumentException("Required file name");
}
Option option = new Option();
if (args.length > 1) {
for (int i = 1; i < args.length; i++) {
option.addWords(args[i]);
}
}
Stats stats = new Stats(option);
String fileName = args[0];
TextFileReader textReader = new TextFileReader(fileName, stats);
textReader.readTest();
stats.printOccurrences();
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.my.name;
import java.util.ArrayList;
import java.util.Locale;
public class Option {
private final ArrayList<String> words;
public Option() {
this.words = new ArrayList<>();
}
public void addWords(String word) {
this.words.add(word.toLowerCase(Locale.ROOT));
}
public boolean hasFilters() {
return !(this.words.size() == 0);
}
public boolean hasWord(String word) {
return this.words.contains(word);
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.my.name;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Locale;
import java.util.regex.Pattern;
public class TextFileReader {
private final String fileName;
private final Stats stats;
public TextFileReader(String fileName, Stats stats) {
this.fileName = fileName;
this.stats = stats;
}
public void readTest() {
try (BufferedReader reader = Files.newBufferedReader(Paths.get(this.fileName))) {
String line;
Pattern pattern = Pattern.compile("[^a-zA-Z]"); // @TODO if needed
while ((line = reader.readLine()) != null) {
String[] words = line.split(" ");
for (String word : words) {
word = pattern.matcher(word).replaceAll("").toLowerCase(Locale.ROOT);
if (word.isBlank()) continue;
this.stats.mapWordToCount(word);
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.my.name;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class Stats {
private final Map<String, Integer> wordCounts;
private final Option option;
private int numberOfWords;
public Stats(Option option) {
this.wordCounts = new HashMap<>();
this.option = option;
this.numberOfWords = 0;
}
public void mapWordToCount(String word) {
this.numberOfWords++;
this.wordCounts.merge(word, 1, Integer::sum);
}
public void printOccurrences() {
boolean hasFilters = option.hasFilters();
Map<String, Integer> topTen = this.wordCounts
.entrySet()
.stream()
.filter(w -> !hasFilters || option.hasWord(w.getKey()))
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(20L)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
for (String word : topTen.keySet()) {
System.out.println("Word " + " | " + "\u001B[31m" + word + "\u001B[0m" + " | " + " occurred " + wordCounts.get(word) + " times");
}
System.out.println("Total words: " + this.numberOfWords);
}
}
</code></pre>
<p>Thanks again</p>
|
[] |
[
{
"body": "<h1>Unnecessary conditional</h1>\n<pre><code> if (args.length > 1) {\n for (int i = 1; i < args.length; i++) {\n option.addWords(args[i]);\n }\n }\n</code></pre>\n<p>If <code>args.length</code> is not greater than one, then <code>for (int i=0; i < args.length; i++)</code> will execute zero times. There is no need to protect the <code>for</code> loop with an <code>if</code> statement. The following would work just as well:</p>\n<pre><code> for (int i = 1; i < args.length; i++) {\n option.addWords(args[i]);\n }\n</code></pre>\n<h1>Underhanded return</h1>\n<pre><code> TextFileReader textReader = new TextFileReader(fileName, stats);\n textReader.readTest();\n</code></pre>\n<p>The <code>TextFileReader</code> is only used once, immediately after construction. The above two statements could be simplified to:</p>\n<pre><code> new TextFileReader(fileName, stats).readTest();\n</code></pre>\n<p>Notice that nothing is returned from <code>readTest()</code>. It is stranger for a reader to not return what it reads. In fact, the "return value" structure (<code>stats</code>) is passed into the constructor.</p>\n<p>It would make more sense to pass the structure to be filled in into the function that does the reading. Then the class wouldn't need to store it as a member variable. Actually, the <code>fileName</code> is passed to the constructor, and only used int the <code>testRead</code> function as well. This could also be passed to the read function, making the <code>TextFileReader</code> <strong>object</strong> unnecessary; a <code>static</code> method could be used:</p>\n<pre><code>public class TextFileReader {\n public static void readTest(String fileName, Stats stats) {\n try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))) {\n String line;\n Pattern pattern = Pattern.compile("[^a-zA-Z]");\n while ((line = reader.readLine()) != null) {\n String[] words = line.split(" ");\n for (String word : words) {\n word = pattern.matcher(word).replaceAll("").toLowerCase(Locale.ROOT);\n if (word.isBlank()) continue;\n stats.mapWordToCount(word);\n }\n }\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n }\n}\n</code></pre>\n<p>It would be used with:</p>\n<pre><code> TextFileReader.readTest(fileName, stats);\n</code></pre>\n<h1>Naming</h1>\n<h2>Read Test</h2>\n<p>Why <code>readTest()</code>? Is it really a test? Should this not be <code>readText()</code>? Or <code>readStats()</code> or <code>readWordCounts()</code>?</p>\n<h2>Add Words</h2>\n<pre><code> public void addWords(String word) {\n this.words.add(word.toLowerCase(Locale.ROOT));\n }\n</code></pre>\n<p>Doesn't exactly look like it is adding words; at best it is adding a word. Maybe <code>addWord(String word)</code> would be better?</p>\n<h2>Option</h2>\n<p>The <code>Option</code> class, on the other hand, stores many words. Perhaps <code>Options</code> would be better, to indicated it holds more than one option.</p>\n<p>Does it hold options, though? Or does it store <code>Words</code>?</p>\n<h2>Top Ten</h2>\n<p>Why does the list of top 10 words by occurrence have 20 entries?</p>\n<h1>Efficiency</h1>\n<h2>Counts of all words</h2>\n<p>If you run this with a large tome - say "War & Peace", and you are counting the number of times the words "France" and "Russia" occur, you will build up a <code>Map<String, Integer> wordCounts</code> for every word that occurs in the text, most of which are never needed.</p>\n<p>You can't change which words are reported by <code>Stats</code>. So, why counts of all words which are encountered?</p>\n<pre><code> public void mapWordToCount(String word) {\n this.numberOfWords++;\n if (!option.hasFilters() || option.hasWord(word) {\n this.wordCounts.merge(word, 1, Integer::sum);\n }\n }\n</code></pre>\n<p>... and remove the <code>filter</code> from <code>printOccurences()</code>.</p>\n<h2>Filtering</h2>\n<p><code>Option.hasWord()</code> will go through the <code>ArrayList<String> words</code> one word at a time, searching for a match. Using a <code>Set<String></code> would be more efficient.</p>\n<h2>Filtering</h2>\n<p>Conditional filtering in the stream results in an unnecessary stage, and slower streaming. An <code>if(option.hasFilters()) { ... with filter ... } else { ... without filter }</code> construct would remove the <code>!hasFilters</code> test from every entry.</p>\n<p>Ok, while "War and Peace" has a half-million words, it only a few thousand unique words, so it may not be a serious performance issue here. Still, it isn't that hard to construct the stream conditionally:</p>\n<pre><code> var stream = this.wordCounts.entrySet().stream();\n\n // Only add the filter step if filtering is needed.\n if (hasFilters)\n stream = stream.filter(w -> option.hasWord(w.getKey()));\n\n Map<String, Integer> topTen = stream\n .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))\n .limit(20L)\n .collect(Collectors.toMap(Map.Entry::getKey,\n Map.Entry::getValue,\n (e1, e2) -> e1,\n LinkedHashMap::new));\n</code></pre>\n<p>If you're using Java 9 or earlier, you won't have the <code>var</code> keyword and you'll need to use the exact type:</p>\n<pre><code>Stream<Map.Entry<String, Integer>> stream = this.wordCounts.entrySet().stream();\n</code></pre>\n<h1>Organization</h1>\n<p>You should separate printing of the occurrences from determining the filtered, sorted list of top word occurrences.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T09:18:38.067",
"Id": "501566",
"Score": "0",
"body": "Thanks a lot for the review. Didn't know that you can create a stream with some options and then adding others and in the end consume it. Totally makes sense what you said about naming, (test/text I always type it wrong!). I chose the singular `Option` because I thought in Java classes should be singularly named?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T14:38:27.897",
"Id": "501584",
"Score": "1",
"body": "The [Stream](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/stream/Stream.html) class: \"_A stream pipeline consists of a source ..., zero or more intermediate operations (which transform a stream into another stream, such as filter(Predicate)), and a terminal operation ... . Streams are lazy; computation on the source data is only performed when the terminal operation is initiated, and source elements are consumed only as needed._\" Until the terminal operation, a stream is just an object that more intermediate operations can be applied to, creating new stream objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T14:50:43.057",
"Id": "501586",
"Score": "1",
"body": "Java classes are often named singular because they define one type of object, of which multiple instances may be created. Containers are singular because a bag is one object, even if you put multiple objects in it. But if you have a class where each instances represents multiple elements, using a plural name for the class scans better. Also, Java has several plural named classes. You even used one, `Collectors`, but there are others like `Collections`, `Arrays`, and `SocketOptions`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T18:33:47.990",
"Id": "254321",
"ParentId": "254243",
"Score": "5"
}
},
{
"body": "<p>When structuring your code to components (classes) you should think about what the application tries to accomplish and what steps it needs to do to achieve that. In this example, the steps are quite clear:</p>\n<ol>\n<li>Read lines</li>\n<li>Split line to words</li>\n<li>Normalize words to lower case</li>\n<li>Filter interesting words</li>\n<li>Gather statistics</li>\n<li>Print statistics</li>\n</ol>\n<p>These are the <em>responsibilities</em> of your application. Implementation of each one should go to it's own class. This is called <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a>.</p>\n<p>Reading lines provides a set of strings. This is all mundane stuff already provided by the JRE. The files can be big so this seems like a place where Streams would be handy, so use <code>BufferedReader.lines()</code>. What you missed in your code is handling the input text character set correctly. If you are from the US your program will most likely fail a bit if it encounters the Finnish epic <a href=\"http://www.gutenberg.org/ebooks/7000\" rel=\"noreferrer\">Kalevala</a>. When you work with text files you ALWAYS have to provide the character encoding. Relying on the system default will cause bugs at some point.</p>\n<p>Splitting a line into words provides a stream of words from a String. <code>Stream.flatMap()</code> should be used for this with a class implementing <code>Function<String, Stream<String>></code>.</p>\n<p>Then, if you want to, you can normalize the words to lower case using a <code>Function<String, String></code>. Again, you need to specify a locale that can handle the characters in the text.</p>\n<p>Once you have a stream of words, filtering becomes a trivial set of classes that implement <code>Predicate<String></code>.</p>\n<p>Counting the words that are left after the filtering is an operation where a <a href=\"https://stackoverflow.com/questions/23925315/count-int-occurrences-with-java8\">grouping collector</a> would come in handy.</p>\n<p>Printing statistics is an UI operation and should be separated from the statistics. It's a class or static method that accepts a Map<String, Integer> as a parameter and does whatever it needs with it.</p>\n<p>Once you have split te code to reasonably small parts you combine everything into a simple stream operation:</p>\n<pre><code>Map<String, Integer> occurrences = reader\n .lines()\n .flatMap(new LineTokenizer())\n .map(new WordNormalizer())\n .filter(...)\n .collect(...);\n</code></pre>\n<p>Note that your implementation breaks hyphenated words, like mother-in-law and none of the examples that process the input as lines can correctly handle hyphenated words that are broken to two lines without becoming overly complicated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T14:07:38.920",
"Id": "501955",
"Score": "0",
"body": "Thanks Torben. Didn't know about `BufferedReader.lines()`, I thought `reader.readLine()` is a stream as well. Better get back and experiment more. Cheers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T10:56:40.470",
"Id": "254413",
"ParentId": "254243",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254321",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T21:12:27.173",
"Id": "254243",
"Score": "5",
"Tags": [
"java",
"beginner"
],
"Title": "Counting words and word occurrences in a .txt file with optional filters"
}
|
254243
|
<p>I have some JavaScript code to manage a 2D map in a game. I have a function to create a new room in the map which is at <code>map[x][y]</code>. I need to create that property and also initialize the <code>monsters</code> property. The code I wrote looks like this, which works fine.</p>
<pre class="lang-js prettyprint-override"><code>'use strict';
let map = {};
function newRoom(x, y) {
if (map[x] === undefined)
map[x] = {};
map[x][y] = {};
map[x][y].monsters = {};
}
newRoom(0, 0);
</code></pre>
<p>Is there a more concise way to write code like this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T13:24:12.190",
"Id": "501436",
"Score": "0",
"body": "It's already a great question, but I would love to see a new question with more of this code."
}
] |
[
{
"body": "<p>Fundamentally, not really. When you need to <em>create</em> a nested structure, there are no built-in ways to get around explicitly testing if the intermediate object(s) exist, and creating them if they don't.</p>\n<p>(If you just wanted to <em>access</em> a possibly-existing nested element, you could use optional chaining to achieve it concisely, but nested <em>creation</em> is much more verbose)</p>\n<p>There are libraries that do nested creation for you, but they ultimately implement the same sort of logic under the hood:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Just for demonstration, I do not recommend using a library for this:\n\nlet map = {};\nfunction newRoom(x, y) {\n _.setWith(map, [x, y, 'monsters'], {}, Object);\n}\nnewRoom(0, 0);\nconsole.log(map);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>One shortcut you can make in your original code is to simply check <code>map[x]</code> instead of comparing against <code>undefined</code>. You can also declare the <code>monsters</code> object inline when assigning the room. You should also declare the map object with <code>const</code> unless you're reassigning it later.</p>\n<p>Now that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_nullish_assignment\" rel=\"nofollow noreferrer\">logical nullish assignment</a> exists, you could use it as well, though given how new it is, you (or others who may read the code) may not be comfortable with it, and it may look a bit confusing regardless:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const map = {};\n\nfunction newRoom(x, y) {\n map[x] ??= {};\n map[x][y] = {\n monsters: {}\n };\n}\n\n/*\nor\nfunction newRoom(x, y) {\n if (!map[x]) {\n map[x] = {};\n }\n map[x][y] = {\n monsters: {}\n };\n}\n*/\n\nnewRoom(0, 0);\nconsole.log(map);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I do recommend using brackets for your <code>if</code> blocks. They'll make it a bit easier to read and will keep you from accidentally writing on the wrong indentation level assuming that something is inside the <code>if</code> block, when it actually isn't.</p>\n<p>Note that both the above code and your original code will overwrite contents of the room if it already exists in the <code>map</code>. Hopefully that's desirable.</p>\n<p>There are a few alternative methods to achieve the same result that require fewer characters of code, that code golfers or minifiers could use, but they sacrifice readability and therefore aren't worth it IMO, eg:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const map = {};\n\nfunction newRoom(m,n){map[m]||(map[m]={}),map[m][n]={monsters:{}}}\n\nnewRoom(0, 0);\nconsole.log(map);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Another thing to consider - as of ES2015, <code>Map</code>s are more suited to dynamic properties than objects. <a href=\"https://stackoverflow.com/questions/65270531/memory-usage-of-javascript-objects-with-numeric-keys#comment115392196_65270531\">If you want a Map, use a Map</a> instead of an object.</p>\n<pre><code>function newRoom(x, y) {\n if (!map.has(x)) {\n map.set(x, new Map());\n }\n map.get(x).set('y', { monsters: {} });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T07:29:10.630",
"Id": "501424",
"Score": "1",
"body": "Good answer. I just wanted to add the fact that while there might be ways of achieving what OP asked, none of the above is as readable and easier to understand as OP’s"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:47:37.373",
"Id": "501445",
"Score": "0",
"body": "Not even the `or` section? I'm not sold on the `??=` either, but I think using just a truthy test for the `if`, using `const` instead of `let`, and declaring the `monsters` sub-object inline all to be improvements over the original?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:49:33.393",
"Id": "501446",
"Score": "0",
"body": "Don’t get me wrong, they’re all improvements definitely! I was strictly talking about the readability of the code :p"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T23:49:38.183",
"Id": "254253",
"ParentId": "254247",
"Score": "4"
}
},
{
"body": "<h3>TL;DR</h3>\n<p>This code snippet is rather taken out of context and is likely symptomatic of bigger issues in the codebase as a whole. You <em>may</em> have bigger problems than trying to improve these few lines of object initialization.</p>\n<hr />\n<h3>A few minor points...</h3>\n<p>For starters:</p>\n<pre><code>'use strict';\n</code></pre>\n<p>Good start!</p>\n<hr />\n<pre><code>let map = {};\n</code></pre>\n<p>Use <code>const</code>. Using <code>let</code> says "I'm going to re-assign this value later" which is almost never what you want to do except for loop counters.</p>\n<hr />\n<pre><code> if (map[x] === undefined)\n map[x] = {};\n</code></pre>\n<p>Always use block braces <code>{}</code> on conditions.</p>\n<p>If your "contract" behind <code>map</code> is that it only ever has two values, <code>undefined</code> and <code>{}</code> then <code>if (map[x])</code> seems clearest to me and robust to changes like swapping <code>undefined</code> out for <code>null</code>. This is a minor point--the <code>=== undefined</code> is not bad.</p>\n<hr />\n<h3>Respect scope and consider encapsulation</h3>\n<p><code>newRoom</code> has a serious problem: it breaks scope and relies on a hardcoded global, <code>map</code>. It can't be re-used with arbitrary maps. If you change the name of the global <code>map</code> to <code>bigMap</code> or something, the function breaks for no good reason. At best, a call to <code>newRoom</code> has no obvious connection to <code>map</code>.</p>\n<p>With this in mind, a better function header is <code>newRoom(map, x, y)</code>. This communicates explicitly which <code>map</code> is being initialized, it works on any <code>map</code>-type object we pass in and it won't break if you do something simple like change a variable name elsewhere in your application.</p>\n<p>Now, even if you pass <code>map</code> as a parameter, the function is still impure because it mutates the object. It's looking like C-style OOP with the object passed in as the first argument to the function. If you need to mutate a property on an object repeatedly like this or have many functions like <code>foo(map, ...)</code>, <code>bar(map, ...)</code>, <code>baz(map, ...)</code>, consider attaching a prototype function to it (or using the <code>class</code> syntactic sugar) so you can use <code>map.newRoom(x, y)</code>. A benefit is that the function <code>newRoom</code> "belongs" to the <code>map</code> object (or its prototype/class) rather than drifting out in the global scope with no obvious connection to anything. When <code>map.newRoom(x, y)</code> mutates data on <code>this</code>, it's easy to reason about what's going on because the state is encapsulated in an instance.</p>\n<p>Another approach is to allocate and return a totally new map with the added room, keeping the function entirely free of side effects. This is the safest option.</p>\n<p>Making this design call relies on context that isn't available here and I'm not advocating jumping straight to OOP or 100% pure programming without good motivation to do so.</p>\n<p>The important thing is to get <code>map</code> into <code>newRoom</code>'s scope.</p>\n<hr />\n<h3>More design thoughts</h3>\n<p>On a related note, why isn't <code>map</code> preallocated with empty objects for rooms? Checking <code>undefined</code> strikes me as a bit of a code smell--if the rest of the codebase has functions that repeatedly check for <code>undefined</code> before taking action on <code>map</code>, there's likely a better way to design this, given more context about the application.</p>\n<p>It's a bit odd that the function has to act as a coalescing operation to both initialize and re-initialize a room. It seems overburdened. It may be better to have a <code>newRoom</code> function that handles setting the <code>map[x] = {};</code> and an <code>initializeMonstersInRoom</code> function that sets <code>map[x][y] = {monsters: {}}</code>. This is still pretty unusual but at least there's no condition and the caller can use <code>newRoom</code> and <code>initializeMonstersInRoom</code> at separate points in the application rather than basically using a branch in <code>newRoom</code> to figure out what to do. If you're calling this function in a loop that initializes rooms for many <code>x</code> and <code>y</code> values, there may be a cleaner way to arrange that that solves the coalescing problem.</p>\n<hr />\n<h3>Prefer arrays for numeric, sequential indexes</h3>\n<p>It's a little surprising to me that <code>map</code> is a nested object with stringified integer keys and hash lookups. The only reason I'd do this is if the <code>x</code>/<code>y</code> coordinates are sparse or numbered non-sequentially.</p>\n<p>I also prefer using row-major order: <code>map[y][x]</code> rather than <code>map[x][y]</code>. The standard approach is to iterate rows, then columns. This is typically how memory is laid out and compilers often rearrange column-major matrix accesses to row-major to improve locality. I'm not sure if JS JIT compilers do this or not, but it's only icing on the cake of following standards. There are some notable exceptions like FORTRAN and R that use column-major, but these languages also use 1-indexing so neither has much credibility as a reference for writing modern code in a language like JS.</p>\n<hr />\n<h3>A rewrite suggestion taking the original at face value</h3>\n<p>As for the original logic, it isn't particularly terse or elegant and seems suggestive of larger design flaws, but on the other hand, there's nothing especially wrong with the function block logic in and of itself. Since the function is so small, there's no real readability problem here. Your attention might be oversensitive to a minor readability micro-optimization that would solve itself naturally with the correct design (such as prepopulating <code>map</code> indices).</p>\n<p>Having said that, I'd write it as</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nconst newRoom = (map, x, y) => {\n map[x] = map[x] || {};\n map[x][y] = {monsters: {}};\n};\n\nconst map = {};\nnewRoom(map, 0, 0);\nconsole.log(map);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Or, with arrays, assuming your rooms use sequential integers:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nconst newRoom = (map, x, y) => {\n map[x] = map[x] || [];\n map[x][y] = {monsters: {}};\n};\n\nconst map = [];\nnewRoom(map, 0, 0);\nconsole.log(map);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T00:31:56.427",
"Id": "254256",
"ParentId": "254247",
"Score": "4"
}
},
{
"body": "<h2>Intent</h2>\n<p>Reading only the code</p>\n<p>The code gives hints at some higher level use, but what that could be is unclear. I will use intent to fill the blanks</p>\n<p>Good code provides more than just an understanding of the logic, but conveys intent.</p>\n<p>The strongest guide to intent is naming, I find this more true for less experienced coders.</p>\n<h2>Deducing intent</h2>\n<p>From the naming <code>map</code>, <code>x</code>, <code>y</code>, <code>monsters</code>, <code>newRoom</code></p>\n<ul>\n<li><p><code>map</code> hints at spacial layout, though it is also common (and bad practice) to use it to represent key / value store. In this case I think you are building a geographic like map.</p>\n</li>\n<li><p><code>x</code>, <code>y</code> This further enforces that your intent is a geographic coordinate on the <code>map</code></p>\n</li>\n<li><p>'monsters' This is a term one would seldom use outside a game. Which is the clincher that make me sure that up are creating some type of level map. Adding a room at coordinates x, y that contains <code>monsters</code>. As <code>monsters</code> is plural it suggests many monsters</p>\n</li>\n<li><p><code>newRoom</code> this name does not match the logic of the code. The code is conditional creating a column on the map, then creates a room, directly added to the map, then adds <code>monsters</code> I suspect that your intent is more closely matched to the name <code>newRoom</code> That you are forced to add the column due to the fact that the map is incomplete.</p>\n</li>\n</ul>\n<p>On the assumption I just made</p>\n<h2>Use a 2D Array</h2>\n<p>With that I would suggest that map be a 2D array. To work effectively as an array it would be best that all items in an array be created before adding items at random indexes. This is to avoid the array being marked as sparse array (sparse arrays are slow)</p>\n<p>I will also suggest that you swap the coordinates, convention addresses coordinates, x then y, so it is best to maintain that when ever you access a coordinate. This will save you lots of head ache.</p>\n<p>To populate the array would require some information on the max size of the map.</p>\n<p>The next example is one method of creating a 2D array that is filled with <code>undefined</code> to ensure that indexing into the array is as fast as possible.</p>\n<p>The 2D array is an array of columns.</p>\n<pre><code>const WIDTH = 10;\nconst HEIGHT = 10;\nconst map = new Array(WIDTH).fill().map(()=>new Array(HEIGHT).fill());\n</code></pre>\n<h2>Create a room</h2>\n<p>A room is independent of a map location. I suggest that you create a room then add it to the map</p>\n<p>The <code>monsters</code> as a plural would also be better as an array, unless you give each monster a unique name. But I think you are not familiar with arrays and that you would name monsters 1, 2, 3</p>\n<p>Thus creating a room would be</p>\n<pre><code>const createRoom = (x, y) => ({monsters: [], x, y});\n</code></pre>\n<p><strong>Note</strong> that I added the coordinates of the room to the room. This is so code that deals with the room can easily know where the room is.</p>\n<h2>Adding a room to the map</h2>\n<p>As the room is now independently created the <code>newRoomToMap</code> function can get a better name. <code>addRoomToMap</code> that as the name implies adds a room to the map.</p>\n<p>Because the room holds its coordinates you need only pass the room to the function.</p>\n<p>I will also assume that your code knows the correct coordinates for each room and that there is no need to check if a room already exists</p>\n<pre><code>// with map already defined as 2D array\nconst addRoomToMap = (room, map) => { map[room.x][room.y] = room }\n</code></pre>\n<h2>Putting it all together.</h2>\n<p>Thus with all the assumptions you code is somewhat transformed to</p>\n<pre><code>"use strict";\nconst WIDTH = 10, HEIGHT = 10;\nconst map = new Array(WIDTH).fill().map(()=>new Array(HEIGHT).fill());\n\nconst createRoom = (x, y) => ({monsters: [], x, y});\nconst addRoomToMap = (room, map) => { map[room.x][room.y] = room }\n\naddRoomToMap(createRoom(5, 0), map); \n</code></pre>\n<h2>Assumptions.</h2>\n<p>I have based this answer on assumptions derived completely on your code alone. This is how I always approach a review, copy code to an IDE write the review, then read the question, and refine the review. The reason is that in the real world code is all we see, a description seldom comes with code, and when it does, it is not read at the same time or in the same document as the code.</p>\n<p>Reading the full question I see that your intent is truly embedded in the naming, but not well defined in the logic.</p>\n<h2>Arrays</h2>\n<p>If you are unfamiliar with arrays <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\">MDN Array</a> will get you started</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T11:43:40.960",
"Id": "254269",
"ParentId": "254247",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T22:30:19.040",
"Id": "254247",
"Score": "6",
"Tags": [
"javascript",
"array",
"game",
"json"
],
"Title": "JS function to initialize properties"
}
|
254247
|
<p>I'm making a Unity game with a "1-bit" color palette, a la <a href="https://store.steampowered.com/app/360740/Downwell/" rel="nofollow noreferrer">Downwell</a> - the vast majority of the screen will end up being in black and white, but unlike true 1-bit graphics, some highlights and visual effects will use additional colors. In my case, those effects will output values along a range of colors making up a single color ramp - all the colors between green and pink inclusive, by default. It's also a low resolution, large-pixel game, and uses the <a href="https://docs.unity3d.com/Packages/com.unity.2d.pixel-perfect@1.0/manual/index.html" rel="nofollow noreferrer">pixel perfect camera</a> package to enforce that.</p>
<p>I want to be able to switch out the exact black, white, and color ramp values that are used at runtime, the same way that Downwell does through the ability to unlock additional palettes. That seems like a good job for shaders, so I finally buckled down and wrote some shader code for this. Now I want to check for room for improvement in terms of potential performance bottlenecks or general shader style.</p>
<p>This component is attached to the main camera:</p>
<pre><code>using UnityEngine;
public class ColorPaletteApplier : MonoBehaviour
{
public Material Material;
void OnRenderImage (RenderTexture source, RenderTexture destination)
{
Graphics.Blit(source, destination, Material);
}
}
</code></pre>
<p>And this is the shader that I wrote:</p>
<pre><code>Shader "Color Palette"
{
Properties
{
[PerRendererData] _MainTex ("Texture", 2D) = "white" {}
_BlackColor ("Black Color", Color) = (0, 0, 0, 1)
_WhiteColor ("White Color", Color) = (1, 1, 1, 1)
_RampTex ("Ramp LUT", 2D) = "defaulttexture" {}
}
SubShader
{
// No culling or depth
Cull Off ZWrite Off ZTest Always
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float4 vertex : SV_POSITION;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = v.uv;
return o;
}
sampler2D _MainTex, _RampTex;
float4 _BlackColor, _WhiteColor;
inline fixed4 convertBlackAndWhite (fixed4 input)
{
bool closerToWhite = round(input.r);
return closerToWhite ? _WhiteColor : _BlackColor;
}
// input is assumed to be somewhere on a lerp between (0, 1, 0) and (1, 1, 0)
// these colors are chosen so that one channel goes from 0 to 1, the other two channels are always the same value, and all three channels are never equal
inline fixed4 convertEffectRamp (fixed4 input)
{
float i = input.r;
// for effect pixels that break the g or b assumptions, we can assume they occupy subpixel positions and that the pixel perfect camera averaged their true value with the background pixel. we'll fix that by making the effects override the background color
if (input.g == 0.5)
{
// undo average with black
i *= 2;
}
else if (input.b == 0.5)
{
// undo average with white
i = i * 2 - 1;
}
return tex2D(_RampTex, i);
}
fixed4 frag (v2f i) : SV_Target
{
fixed4 col = tex2D(_MainTex, i.uv);
return (col.r == col.g && col.g == col.b) ? convertBlackAndWhite(col) : convertEffectRamp(col);
}
ENDCG
}
}
}
</code></pre>
<p>I'm using a 128x1 PNG for the ramp lookup texture.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-02T23:31:33.230",
"Id": "254252",
"Score": "1",
"Tags": [
"unity3d",
"hlsl",
"shaders"
],
"Title": "Shader for 1-bit color palette + a VFX ramp"
}
|
254252
|
<p><em>I'm learning C# .NET 5 Intrinsics and interested in best practices. It's really hard now to find enough information about how SIMD instructions (logically/internally) work in .NET. In addition i'm not familiar with C++ and Assembly languages.</em></p>
<p>The purpose of the solution - apply <a href="https://en.wikipedia.org/wiki/Sobel_operator" rel="nofollow noreferrer">Sobel Operator</a> filter to the loaded image. For image operations i used <code>System.Drawing.Common</code> NuGet package. Thus the solution is Windows-only.</p>
<p>The <code>SobelOperator</code> class contains two Sobel Operator implementations:</p>
<ol>
<li><code>SobelOperatorScalar</code> - Scalar solution that can be used as a fallback if current CPU is not compartible with AVX2.</li>
<li><code>SobelOperatorSimd</code> - SIMD x86 solution for hardware acceleration. - <strong>review target</strong></li>
</ol>
<h3>Code for review</h3>
<pre class="lang-cs prettyprint-override"><code>public interface ISobelOperator
{
Bitmap Apply(Bitmap bmp);
}
public class SobelOperator : ISobelOperator
{
private static Color[] _grayPallette;
private readonly ISobelOperator _operator;
public bool IsHardwareAccelerated { get; }
public SobelOperator(bool hardwareAccelerated = true)
{
if (_grayPallette == null)
_grayPallette = Enumerable.Range(0, 256).Select(i => Color.FromArgb(i, i, i)).ToArray();
IsHardwareAccelerated = hardwareAccelerated && Avx2.IsSupported;
_operator = IsHardwareAccelerated ? new SobelOperatorSimd() : new SobelOperatorScalar();
}
public Bitmap Apply(Bitmap bmp)
=> _operator.Apply(bmp);
private class SobelOperatorSimd : ISobelOperator
{
private const byte m0 = 0b01001001;
private const byte m1 = 0b10010010;
private const byte m2 = 0b00100100;
//0.299R + 0.587G + 0.114B
private readonly Vector256<float> bWeight = Vector256.Create(0.114f);
private readonly Vector256<float> gWeight = Vector256.Create(0.587f);
private readonly Vector256<float> rWeight = Vector256.Create(0.299f);
private readonly Vector256<int> bMut = Vector256.Create(0, 3, 6, 1, 4, 7, 2, 5);
private readonly Vector256<int> gMut = Vector256.Create(1, 4, 7, 2, 5, 0, 3, 6);
private readonly Vector256<int> rMut = Vector256.Create(2, 5, 0, 3, 6, 1, 4, 7);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe Vector256<int> GetBrightness(byte* ptr)
{
Vector256<int> v0 = Avx2.ConvertToVector256Int32(ptr);
Vector256<int> v1 = Avx2.ConvertToVector256Int32(ptr + 8);
Vector256<int> v2 = Avx2.ConvertToVector256Int32(ptr + 16);
Vector256<int> vb = Avx2.Blend(Avx2.Blend(v0, v1, m1), v2, m2);
vb = Avx2.PermuteVar8x32(vb, bMut);
Vector256<int> vg = Avx2.Blend(Avx2.Blend(v0, v1, m2), v2, m0);
vg = Avx2.PermuteVar8x32(vg, gMut);
Vector256<int> vr = Avx2.Blend(Avx2.Blend(v0, v1, m0), v2, m1);
vr = Avx2.PermuteVar8x32(vr, rMut);
Vector256<float> vfb = Avx.Multiply(Avx.ConvertToVector256Single(vb), bWeight);
Vector256<float> vfg = Avx.Multiply(Avx.ConvertToVector256Single(vg), gWeight);
Vector256<float> vfr = Avx.Multiply(Avx.ConvertToVector256Single(vr), rWeight);
return Avx.ConvertToVector256Int32WithTruncation(Avx.Add(Avx.Add(vfb, vfg), vfr));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void ToGrayscale(byte* srcPtr, byte* dstPtr, int pixelsCount)
{
byte* tail = srcPtr + (pixelsCount & -16) * 3;
byte* srcEnd = srcPtr + pixelsCount * 3;
byte* dstEnd = dstPtr + pixelsCount;
while (true)
{
while (srcPtr < tail)
{
Vector256<int> vi0 = GetBrightness(srcPtr);
Vector256<int> vi1 = GetBrightness(srcPtr + 24);
Vector128<short> v0 = Sse2.PackSignedSaturate(Avx2.ExtractVector128(vi0, 0), Avx2.ExtractVector128(vi0, 1));
Vector128<short> v1 = Sse2.PackSignedSaturate(Avx2.ExtractVector128(vi1, 0), Avx2.ExtractVector128(vi1, 1));
Sse2.Store(dstPtr, Sse2.PackUnsignedSaturate(v0, v1));
srcPtr += 48;
dstPtr += 16;
}
if (srcPtr == srcEnd)
break;
tail = srcEnd;
srcPtr = srcEnd - 48;
dstPtr = dstEnd - 16;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe Vector128<byte> ApplySobelKernel(byte* srcPtr, int width)
{
Vector256<short> v00 = Avx2.ConvertToVector256Int16(srcPtr);
Vector256<short> v01 = Avx2.ConvertToVector256Int16(srcPtr + 1);
Vector256<short> v02 = Avx2.ConvertToVector256Int16(srcPtr + 2);
Vector256<short> v10 = Avx2.ConvertToVector256Int16(srcPtr + width);
Vector256<short> v12 = Avx2.ConvertToVector256Int16(srcPtr + width + 2);
Vector256<short> v20 = Avx2.ConvertToVector256Int16(srcPtr + width * 2);
Vector256<short> v21 = Avx2.ConvertToVector256Int16(srcPtr + width * 2 + 1);
Vector256<short> v22 = Avx2.ConvertToVector256Int16(srcPtr + width * 2 + 2);
Vector256<short> vgx = Avx2.Subtract(v02, v00);
vgx = Avx2.Subtract(vgx, Avx2.ShiftLeftLogical(v10, 1));
vgx = Avx2.Add(vgx, Avx2.ShiftLeftLogical(v12, 1));
vgx = Avx2.Subtract(vgx, v20);
vgx = Avx2.Add(vgx, v22);
Vector256<short> vgy = Avx2.Add(v00, Avx2.ShiftLeftLogical(v01, 1));
vgy = Avx2.Add(vgy, v02);
vgy = Avx2.Subtract(vgy, v20);
vgy = Avx2.Subtract(vgy, Avx2.ShiftLeftLogical(v21, 1));
vgy = Avx2.Subtract(vgy, v22);
// sqrt(vgx * vgx + vgy * vgy)
Vector256<short> vgp0 = Avx2.UnpackLow(vgx, vgy);
Vector256<short> vgp1 = Avx2.UnpackHigh(vgx, vgy);
Vector256<int> v0 = Avx2.MultiplyAddAdjacent(vgp0, vgp0);
Vector256<int> v1 = Avx2.MultiplyAddAdjacent(vgp1, vgp1);
Vector256<int> gt0 = Avx.ConvertToVector256Int32WithTruncation(Avx.Sqrt(Avx.ConvertToVector256Single(v0)));
Vector256<int> gt1 = Avx.ConvertToVector256Int32WithTruncation(Avx.Sqrt(Avx.ConvertToVector256Single(v1)));
Vector128<short> gts0 = Sse2.PackSignedSaturate(Avx2.ExtractVector128(gt0, 0), Avx2.ExtractVector128(gt1, 0));
Vector128<short> gts1 = Sse2.PackSignedSaturate(Avx2.ExtractVector128(gt0, 1), Avx2.ExtractVector128(gt1, 1));
return Sse2.PackUnsignedSaturate(gts0, gts1);
}
public Bitmap Apply(Bitmap bmp)
{
int width = bmp.Width;
int height = bmp.Height;
int pixelsCount = width * height;
byte[] buffer = new byte[pixelsCount];
Rectangle rect = new Rectangle(Point.Empty, bmp.Size);
Bitmap outBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
ColorPalette pal = outBmp.Palette;
for (int i = 0; i < 256; i++)
pal.Entries[i] = _grayPallette[i];
outBmp.Palette = pal;
unsafe
{
fixed (byte* bufPtr = buffer)
{
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
ToGrayscale((byte*)bmpData.Scan0.ToPointer(), bufPtr, pixelsCount);
bmp.UnlockBits(bmpData);
BitmapData outBmpData = outBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
byte* dstPtr = (byte*)outBmpData.Scan0.ToPointer();
int length = pixelsCount - width * 2 - 1;
byte* tail = bufPtr + (length & -16);
byte* srcPos = bufPtr;
byte* srcEnd = bufPtr + length;
byte* dstPos = dstPtr + width + 1;
byte* dstEnd = dstPos + length;
while (true)
{
while (srcPos < tail)
{
Sse2.Store(dstPos, ApplySobelKernel(srcPos, width));
srcPos += 16;
dstPos += 16;
}
if (srcPos == srcEnd)
break;
tail = srcEnd;
srcPos = srcEnd - 16;
dstPos = dstEnd - 16;
}
for (dstPos = dstPtr + width; dstPos <= dstPtr + pixelsCount - width; dstPos += width)
{
*dstPos-- = 0;
*dstPos++ = 0;
}
outBmp.UnlockBits(outBmpData);
}
}
return outBmp;
}
}
private class SobelOperatorScalar : ISobelOperator
{
public Bitmap Apply(Bitmap bmp)
{
BitmapData bmpData = bmp.LockBits(new Rectangle(Point.Empty, bmp.Size), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
int strideLength = bmpData.Stride * bmpData.Height;
byte[] buffer = new byte[Math.Abs(strideLength)];
Marshal.Copy(bmpData.Scan0, buffer, 0, strideLength);
bmp.UnlockBits(bmpData);
int width = bmp.Width;
int height = bmp.Height;
int pixelsCount = width * height;
byte[] pixelBuffer = new byte[pixelsCount];
byte[] resultBuffer = new byte[pixelsCount];
//0.299R + 0.587G + 0.114B
for (int i = 0; i < pixelsCount; i++)
{
int offset = i * 3;
byte brightness = (byte)(buffer[offset] * 0.114f + buffer[offset + 1] * 0.587f + buffer[offset + 2] * 0.299f);
pixelBuffer[i] = brightness;
}
for (int i = width + 1; i < pixelsCount - width - 1; i++)
{
if (i % width == width - 1)
i += 2;
int gx = -pixelBuffer[i - 1 - width] + pixelBuffer[i + 1 - width] - 2 * pixelBuffer[i - 1] +
2 * pixelBuffer[i + 1] - pixelBuffer[i - 1 + width] + pixelBuffer[i + 1 + width];
int gy = pixelBuffer[i - 1 - width] + 2 * pixelBuffer[i - width] + pixelBuffer[i + 1 - width] -
pixelBuffer[i - 1 + width] - 2 * pixelBuffer[i + width] - pixelBuffer[i + 1 + width];
int gt = (int)MathF.Sqrt(gx * gx + gy * gy);
if (gt > byte.MaxValue) gt = byte.MaxValue;
resultBuffer[i] = (byte)gt;
}
Bitmap outBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
BitmapData outBmpData = outBmp.LockBits(new Rectangle(Point.Empty, outBmp.Size), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
Marshal.Copy(resultBuffer, 0, outBmpData.Scan0, outBmpData.Stride * outBmpData.Height);
outBmp.UnlockBits(outBmpData);
ColorPalette pal = outBmp.Palette;
for (int i = 0; i < 256; i++)
pal.Entries[i] = _grayPallette[i];
outBmp.Palette = pal;
return outBmp;
}
}
}
</code></pre>
<h3>Output test</h3>
<p><strong>Test image</strong>
<a href="https://i.stack.imgur.com/zu7oc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zu7oc.jpg" alt="source image" /></a></p>
<p><strong>Program.cs</strong></p>
<pre class="lang-cs prettyprint-override"><code>static void Main(string[] args)
{
const string fileName = "image.jpg";
Bitmap bmp = new Bitmap(fileName);
SobelOperator sobelOperator = new SobelOperator();
Console.WriteLine($"SIMD accelerated: {(sobelOperator.IsHardwareAccelerated ? "Yes" : "No")}");
Bitmap result = sobelOperator.Apply(bmp);
result.Save("out.jpg", ImageFormat.Jpeg);
Console.WriteLine("Done.");
Console.ReadKey();
}
</code></pre>
<p><strong>Console output</strong></p>
<pre class="lang-none prettyprint-override"><code>SIMD accelerated: Yes
Done.
</code></pre>
<p><strong>Output Image</strong>
<a href="https://i.stack.imgur.com/fCZ9A.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fCZ9A.jpg" alt="enter image description here" /></a></p>
<p>Output images of Scalar and SIMD implementations are binary identical.</p>
<h3>Benchmark.NET</h3>
<pre class="lang-cs prettyprint-override"><code>[MemoryDiagnoser]
public class MyBenchmark
{
private readonly ISobelOperator _sobelOperator = new SobelOperator();
private readonly ISobelOperator _sobelOperatorSw = new SobelOperator(false);
private readonly Bitmap bmp = new Bitmap(@"C:\Source\image.jpg");
[Benchmark(Description = "SIMD Enabled")]
public Bitmap TestSimd()
{
return _sobelOperator.Apply(bmp);
}
[Benchmark(Description = "SIMD Disabled")]
public Bitmap TestScalar()
{
return _sobelOperatorSw.Apply(bmp);
}
}
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<MyBenchmark>();
Console.ReadKey();
}
</code></pre>
<pre class="lang-none prettyprint-override"><code>BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042
Intel Core i7-4700HQ CPU 2.40GHz (Haswell), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=5.0.101
[Host] : .NET Core 5.0.1 (CoreCLR 5.0.120.57516, CoreFX 5.0.120.57516), X64 RyuJIT
DefaultJob : .NET Core 5.0.1 (CoreCLR 5.0.120.57516, CoreFX 5.0.120.57516), X64 RyuJIT
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|---------------- |----------:|----------:|----------:|---------:|---------:|---------:|----------:|
| 'SIMD Enabled' | 7.285 ms | 0.1165 ms | 0.1089 ms | 992.1875 | 992.1875 | 992.1875 | 3.35 MB |
| 'SIMD Disabled' | 48.412 ms | 0.2312 ms | 0.2162 ms | 454.5455 | 454.5455 | 454.5455 | 16.61 MB |
</code></pre>
<p>Intrinsics solution is ~6.6x Times faster. And eating less memory in general because it's <code>unsafe</code> and doesn't use <code>Marshal.Copy</code> to load/save the <code>byte[]</code> buffers.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:19:12.023",
"Id": "501440",
"Score": "0",
"body": "Is the output being binary identical a requirement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:21:19.693",
"Id": "501441",
"Score": "0",
"body": "@harold probably not. It's just a fact."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T20:04:18.453",
"Id": "501473",
"Score": "2",
"body": "Please add a follow up question if you want to continue updating the question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) especially the part about `What should I not do`."
}
] |
[
{
"body": "<h1>Bugs for images of inconvenient width</h1>\n<p>This code:</p>\n<pre><code>Bitmap outBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);\nBitmapData outBmpData = outBmp.LockBits(new Rectangle(Point.Empty, outBmp.Size), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);\nMarshal.Copy(resultBuffer, 0, outBmpData.Scan0, outBmpData.Stride * outBmpData.Height);\n</code></pre>\n<p>Works great if the width of the image is a multiple of 4. But in other cases, it does not work. The problem is that bitmaps have a stride is a multiple of 4, if their "natural byte-width" is not a multiple of 4 then there will be padding at the end of every row. This code does not account for that, so for images that have padding it tries to copy more data from the result buffer than is actually in it, which causes an exception. Even if it had worked it still would have been wrong, resulting in every row of pixels "losing" some pixels to the padding, shearing the image.</p>\n<p>This issue also affects other places where a bitmap is locked with a pixel type that is not 4 bytes, but it affects them in different ways.</p>\n<p>Generally it means that we need to work with RGB and 8bit image data row-by-row, annoying as it is. ARGB is nicer in this regard, but locking an RGB image into ARGB format has a large cost - from a performance perspective it's much worse than being forced to work with RGB data (but the code we have to write to deal with RGB is really nasty..) Your code has some really nice loops, it's a shame that they have to be replaced by uglier ones, at least if you want images of various widths to work.</p>\n<p>An other small detail is that <em>very small widths</em> don't work with the "step back from the end"-trick to do the last iteration. In those cases you may as well fall back to the scalar implementation - there is no hope for SIMD and they're small images anyway.</p>\n<h1>Performance improvements that may change the result</h1>\n<p>For the benchmarks, I note that you're using an Intel Haswell, so I benchmarked on an Intel Haswell as well. That may matter: if code A is better than code B on Haswell, the situation may be reversed on Skylake or AMD Ryzen.</p>\n<p>The square root in the Sobel kernel can be replaced by <code>Avx.Multiply(Avx.ReciprocalSqrt(v0f), v0f)</code> where <code>v0f</code> is <code>v0</code> converted to floats. The reciprocal square root has about 11 to 12 bits of precision, and the result is converted to 8 bits per pixel anyway. On the test image, it didn't make any difference for the results, but made the kernel slightly faster. In general, I cannot guarantee that there is <em>never</em> a difference in result, especially when taking the square root of a perfect square (which sits right on the knife edge of being truncated the wrong way if the reciprocal square root is <em>only just</em> too low).</p>\n<p>The grayscale conversion can also be done slightly faster. The main idea there, based somewhat on <a href=\"https://github.com/komrad36/RGB2Y/blob/master/RGB2Y.h\" rel=\"nofollow noreferrer\">this code</a>, is to use <code>Avx2.MultiplyHigh</code> on a vector of <code>ushort</code> instead of floating point multiplication. Everything else happens in support of that. The way it works out though, is that vectors end up with "wasted bits" where the result of the computation is thrown away. Due to that, it still works out to 6 multiplication instructions per 16 bytes of output even though twice as many multiplications happen per instruction. So in terms of the number of multiplication instructions, it isn't any better than it used to be, and on top of that, on Haswell integer multiplication has half throughput compared to floating point multiplication.</p>\n<p>The rest of the function does not seem especially nice either, being extremely shuffle-heavy (Haswell can only do one shuffle per cycle, so the number of shuffles is important). So actually, I don't know <em>why</em> it's faster, I can only tell you that the benchmarks said so and that the difference was significant despite the relatively highly timing variance that I kept seeing. Hopefully a better approach is possible but I don't know what it is.</p>\n<pre><code>const ushort rw = 19595;\nconst ushort gw = 38470;\nconst ushort bw = 7471;\nVector256<ushort> rW = Vector256.Create(rw);\nVector256<ushort> gW = Vector256.Create(gw);\nVector256<ushort> bW = Vector256.Create(bw);\nconst byte _ = 0x80;\nVector256<byte> shuf0 = Vector256.Create(\n _, 0, _, 3, _, 6, _, 9, _, 12, _, _, _, _, _, _,\n _, 0, _, 3, _, 6, _, 9, _, 12, _, _, _, _, _, _);\nVector256<byte> shuf1 = Vector256.Create(\n _, 1, _, 4, _, 7, _, 10, _, 13, _, _, _, _, _, _,\n _, 1, _, 4, _, 7, _, 10, _, 13, _, _, _, _, _, _);\nVector256<byte> shuf2 = Vector256.Create(\n _, 2, _, 5, _, 8, _, 11, _, 14, _, _, _, _, _, _,\n _, 2, _, 5, _, 8, _, 11, _, 14, _, _, _, _, _, _);\nVector256<byte> shuf3 = Vector256.Create(\n 1, 3, 5, 7, 9, _, _, _, _, _, _, _, _, _, _, _,\n _, _, _, _, _, 1, 3, 5, 7, 9, _, _, _, _, _, _);\nVector256<byte> shuf4 = Vector256.Create(\n _, _, _, _, _, _, _, _, _, _, 9, _, _, _, _, _,\n _, _, _, _, _, _, _, _, _, _, _, 1, 3, 5, 7, 9);\nVector256<ushort> bias = Vector256.Create((ushort)0x02);\n\n[MethodImpl(MethodImplOptions.AggressiveInlining)]\nprivate unsafe Vector128<byte> GetBrightness16(byte* ptr)\n{\n var raw0 = Avx2.LoadVector128(ptr);\n var raw1 = Avx2.LoadVector128(ptr + 16);\n var raw2 = Avx2.LoadVector128(ptr + 32);\n var partA = Avx2.InsertVector128(raw0.ToVector256(), Avx2.AlignRight(raw1, raw0, 15), 1);\n var partB = Avx2.InsertVector128(Avx2.AlignRight(raw2, raw1, 1).ToVector256(), raw2, 1);\n partB = Avx2.AlignRight(partB, partB, 1);\n\n var b0 = Avx2.Shuffle(partA, shuf0).AsUInt16();\n var g0 = Avx2.Shuffle(partA, shuf1).AsUInt16();\n var r0 = Avx2.Shuffle(partA, shuf2).AsUInt16();\n var b1 = Avx2.Shuffle(partB, shuf0).AsUInt16();\n var g1 = Avx2.Shuffle(partB, shuf1).AsUInt16();\n var r1 = Avx2.Shuffle(partB, shuf2).AsUInt16();\n\n b0 = Avx2.MultiplyHigh(b0, bW);\n g0 = Avx2.MultiplyHigh(g0, gW);\n r0 = Avx2.MultiplyHigh(r0, rW);\n b1 = Avx2.MultiplyHigh(b1, bW);\n g1 = Avx2.MultiplyHigh(g1, gW);\n r1 = Avx2.MultiplyHigh(r1, rW);\n var sum0 = Avx2.AddSaturate(Avx2.AddSaturate(Avx2.Add(b0, g0), r0), bias);\n var shufsum0 = Avx2.Shuffle(sum0.AsByte(), shuf3);\n var sum1 = Avx2.AddSaturate(Avx2.AddSaturate(Avx2.Add(b1, g1), r1), bias);\n var shufsum1 = Avx2.Shuffle(sum1.AsByte(), shuf4);\n var shufsum = Avx2.Or(shufsum0, shufsum1);\n return Avx2.Or(Vector256.GetLower(shufsum), Vector256.GetUpper(shufsum));\n}\n</code></pre>\n<p>By the way, I chose the bias to minimize the difference with the original grayscale conversion. Normally I would use a bias of 0x80 to round evenly. The weights of the color channels are approximations of 65536 times their floating point weight, chosen so that they add up to 65536. MultiplyHigh implicitly divides by 65536, so effectively these scales work like their floating point counterparts. They don't <em>have</em> to add up to exactly 65536 by the way: thanks to the saturating additions (which are no extra cost compared to regular additions) nothing bad would happen if they added up to slightly more. You could use that property to tune them to more closely match the original conversion.</p>\n<p>Alternatively, it would be easy to adapt the scalar function to fixed-point arithmetic such that it gives the same results as this version of the SIMD grayscale converter.</p>\n<p>I tried using unaligned loads to replace the <code>Avx2.AlignRight</code> (aka <code>vpalignr</code>) instructions with, but the benchmark said that was marginally slower.</p>\n<p>It's possible to base a grayscale conversion on <code>vpmaddubsw</code> (<code>Avx2.MultiplyAddAdjacent</code> with vectors of byte and sbyte). For ARGB data that is very fast, though noticably less accurate. I have not worked that out for RGB data.</p>\n<h1>Small things</h1>\n<h3><code>ExtractVector128</code>-ing the low half of a vector</h3>\n<p>If you write <code>Avx2.ExtractVector128(gt0, 0)</code>, you get what you asked for, <code>VEXTRACTI128</code> with an index of zero. However, that's not the best instruction to use, the best instruction to use is .. nothing. No instruction is necessary. What should happen is that the next operation only uses the 128bit version of the same vector register. The way to tell C# to do that is with <code>Vector256.GetLower</code>.</p>\n<p>This is a contrast with eg C++, where compilers normally do that substitution on their own.</p>\n<p>The performance difference from this, if any, was negligible. Saving an explicit extraction instruction can only help though.</p>\n<h3>Unnecessary <code>intptr.ToPointer()</code></h3>\n<p>At various times, the code contains <code>(byte*)intptr.ToPointer()</code> or some variant. It's enough to cast to the pointer, calling <code>ToPointer()</code> doesn't add anything to that code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:42:22.237",
"Id": "501450",
"Score": "0",
"body": "`Even if it had worked it still would have been wrong` can't agree because `PixelFormat` is set explicitly `Format8bppIndexed` - that mean 1 byte per pixel. Logically there's no room for mistake or any exception. Respecting pixel row data alignment only makes sense if you writing BMP file format directly to file. It doesn't affect `BmpData.Scan0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:53:38.047",
"Id": "501454",
"Score": "1",
"body": "It doesn't affect Scan0, but it affects the end of every row, because Stride != Width in that case. For example an image with width 301 would have a stride of 304 if it is locked with an 8 bit/pixel format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:55:59.423",
"Id": "501493",
"Score": "0",
"body": "Thank you for the great review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T08:39:22.017",
"Id": "501564",
"Score": "1",
"body": "Jfyi `Hopefully a better approach is possible` Yes! Finally i came up with a lightning-fast grayscaling solution that is a sort of hybrid of my and your code (not shown below): load into 3x 256 Int16, Permute2x128 as 1-4 2-5 3-6, 3x Blend-Blend-(byte-Shuffle - lack of Int16 permute that available only in AVX512), 3x MultiplyHigh (only 3!), Add-Add-Add, one final byte-shuffle, return Or. Faster from yours by ~0,4ms on my test. Thanks again!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:32:11.420",
"Id": "254280",
"ParentId": "254255",
"Score": "4"
}
},
{
"body": "<h3>Reviewed Code</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>public interface ISobelOperator\n{\n Bitmap Apply(Bitmap bmp);\n}\n\npublic class SobelOperator : ISobelOperator\n{\n private static Color[] _grayPallette;\n private readonly ISobelOperator _operator;\n\n public bool IsHardwareAccelerated { get; }\n\n public SobelOperator(bool hardwareAccelerated = true)\n {\n if (_grayPallette == null)\n _grayPallette = Enumerable.Range(0, 256).Select(i => Color.FromArgb(i, i, i)).ToArray();\n\n IsHardwareAccelerated = hardwareAccelerated && Avx2.IsSupported;\n\n _operator = IsHardwareAccelerated ? new SobelOperatorSimd() : new SobelOperatorScalar();\n }\n\n public Bitmap Apply(Bitmap bmp)\n => _operator.Apply(bmp);\n\n private class SobelOperatorSimd : ISobelOperator\n {\n private readonly Vector256<ushort> rw = Vector256.Create((ushort)19595);\n private readonly Vector256<ushort> gw = Vector256.Create((ushort)38470);\n private readonly Vector256<ushort> bw = Vector256.Create((ushort)7471);\n private const byte _ = 0x80;\n private readonly Vector256<byte> mask0 = Vector256.Create(_, 0, _, 3, _, 6, _, 9, _, 12, _, _, _, _, _, _, _, 0, _, 3, _, 6, _, 9, _, 12, _, _, _, _, _, _);\n private readonly Vector256<byte> mask1 = Vector256.Create(_, 1, _, 4, _, 7, _, 10, _, 13, _, _, _, _, _, _, _, 1, _, 4, _, 7, _, 10, _, 13, _, _, _, _, _, _);\n private readonly Vector256<byte> mask2 = Vector256.Create(_, 2, _, 5, _, 8, _, 11, _, 14, _, _, _, _, _, _, _, 2, _, 5, _, 8, _, 11, _, 14, _, _, _, _, _, _);\n private readonly Vector256<byte> mask3 = Vector256.Create(1, 3, 5, 7, 9, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, 1, 3, 5, 7, 9, _, _, _, _, _, _);\n private readonly Vector256<byte> mask4 = Vector256.Create(_, _, _, _, _, _, _, _, _, _, 9, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, 1, 3, 5, 7, 9);\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private unsafe void ToGrayscale(byte* srcPtr, byte* dstPtr, int srcStride, int dstStride, int height)\n {\n for (int row = 0; row < height; row++)\n {\n byte* srcPos = srcPtr + row * srcStride;\n byte* dstPos = dstPtr + row * dstStride;\n byte* srcEnd = srcPos + srcStride;\n\n while (srcPos < srcEnd)\n {\n Vector128<byte> raw0 = Sse2.LoadVector128(srcPos);\n Vector128<byte> raw1 = Sse2.LoadVector128(srcPos + 16);\n Vector128<byte> raw2 = Sse2.LoadVector128(srcPos + 32);\n Vector256<byte> v0 = Avx2.InsertVector128(raw0.ToVector256(), Ssse3.AlignRight(raw1, raw0, 15), 1);\n Vector256<byte> v1 = Avx2.InsertVector128(Ssse3.AlignRight(raw2, raw1, 1).ToVector256(), raw2, 1);\n v1 = Avx2.AlignRight(v1, v1, 1);\n\n Vector256<ushort> b0 = Avx2.MultiplyHigh(Avx2.Shuffle(v0, mask0).AsUInt16(), bw);\n Vector256<ushort> g0 = Avx2.MultiplyHigh(Avx2.Shuffle(v0, mask1).AsUInt16(), gw);\n Vector256<ushort> r0 = Avx2.MultiplyHigh(Avx2.Shuffle(v0, mask2).AsUInt16(), rw);\n Vector256<ushort> b1 = Avx2.MultiplyHigh(Avx2.Shuffle(v1, mask0).AsUInt16(), bw);\n Vector256<ushort> g1 = Avx2.MultiplyHigh(Avx2.Shuffle(v1, mask1).AsUInt16(), gw);\n Vector256<ushort> r1 = Avx2.MultiplyHigh(Avx2.Shuffle(v1, mask2).AsUInt16(), rw);\n\n Vector256<byte> sum0 = Avx2.Shuffle(Avx2.AddSaturate(Avx2.Add(b0, g0), r0).AsByte(), mask3);\n Vector256<byte> sum1 = Avx2.Shuffle(Avx2.AddSaturate(Avx2.Add(b1, g1), r1).AsByte(), mask4);\n Vector256<byte> sum = Avx2.Or(sum0, sum1);\n Sse2.Store(dstPos, Sse2.Or(sum.GetLower(), sum.GetUpper()));\n srcPos += 48;\n dstPos += 16;\n }\n }\n }\n\n [MethodImpl(MethodImplOptions.AggressiveInlining)]\n private unsafe Vector128<byte> ApplySobelKernel(byte* srcPtr, int stride)\n {\n Vector256<short> v00 = Avx2.ConvertToVector256Int16(srcPtr);\n Vector256<short> v01 = Avx2.ConvertToVector256Int16(srcPtr + 1);\n Vector256<short> v02 = Avx2.ConvertToVector256Int16(srcPtr + 2);\n Vector256<short> v10 = Avx2.ConvertToVector256Int16(srcPtr + stride);\n Vector256<short> v12 = Avx2.ConvertToVector256Int16(srcPtr + stride + 2);\n Vector256<short> v20 = Avx2.ConvertToVector256Int16(srcPtr + stride * 2);\n Vector256<short> v21 = Avx2.ConvertToVector256Int16(srcPtr + stride * 2 + 1);\n Vector256<short> v22 = Avx2.ConvertToVector256Int16(srcPtr + stride * 2 + 2);\n\n Vector256<short> vgx = Avx2.Subtract(v02, v00);\n vgx = Avx2.Subtract(vgx, Avx2.ShiftLeftLogical(v10, 1));\n vgx = Avx2.Add(vgx, Avx2.ShiftLeftLogical(v12, 1));\n vgx = Avx2.Subtract(vgx, v20);\n vgx = Avx2.Add(vgx, v22);\n\n Vector256<short> vgy = Avx2.Add(v00, Avx2.ShiftLeftLogical(v01, 1));\n vgy = Avx2.Add(vgy, v02);\n vgy = Avx2.Subtract(vgy, v20);\n vgy = Avx2.Subtract(vgy, Avx2.ShiftLeftLogical(v21, 1));\n vgy = Avx2.Subtract(vgy, v22);\n\n // sqrt(vgx * vgx + vgy * vgy)\n Vector256<short> vgp0 = Avx2.UnpackLow(vgx, vgy);\n Vector256<short> vgp1 = Avx2.UnpackHigh(vgx, vgy);\n Vector256<int> v0 = Avx2.MultiplyAddAdjacent(vgp0, vgp0);\n Vector256<int> v1 = Avx2.MultiplyAddAdjacent(vgp1, vgp1);\n Vector256<float> vf0 = Avx.ConvertToVector256Single(v0);\n Vector256<float> vf1 = Avx.ConvertToVector256Single(v1);\n Vector256<int> gt0 = Avx.ConvertToVector256Int32WithTruncation(Avx.Multiply(Avx.ReciprocalSqrt(vf0), vf0));\n Vector256<int> gt1 = Avx.ConvertToVector256Int32WithTruncation(Avx.Multiply(Avx.ReciprocalSqrt(vf1), vf1));\n\n Vector128<short> gts0 = Sse2.PackSignedSaturate(gt0.GetLower(), gt1.GetLower());\n Vector128<short> gts1 = Sse2.PackSignedSaturate(gt0.GetUpper(), gt1.GetUpper());\n return Sse2.PackUnsignedSaturate(gts0, gts1);\n }\n\n\n public unsafe Bitmap Apply(Bitmap bmp)\n {\n int width = bmp.Width;\n int height = bmp.Height;\n\n Rectangle rect = new Rectangle(Point.Empty, bmp.Size);\n BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);\n int srcStride = bmpData.Stride;\n int srcLength = srcStride * height;\n\n Bitmap outBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);\n ColorPalette pal = outBmp.Palette;\n for (int i = 0; i < 256; i++)\n pal.Entries[i] = _grayPallette[i];\n outBmp.Palette = pal;\n\n BitmapData outBmpData = outBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);\n int dstStride = outBmpData.Stride;\n int dstLength = dstStride * height;\n\n byte[] buffer = new byte[dstLength];\n\n fixed (byte* bufPtr = buffer)\n {\n ToGrayscale((byte*)bmpData.Scan0, bufPtr, srcStride, dstStride, height);\n bmp.UnlockBits(bmpData);\n\n byte* dstPtr = (byte*)outBmpData.Scan0;\n\n int length = dstLength - dstStride * 2 - 1;\n byte* tail = bufPtr + (length & -16);\n byte* srcPos = bufPtr;\n byte* srcEnd = bufPtr + length;\n byte* dstPos = dstPtr + dstStride + 1;\n byte* dstEnd = dstPos + length;\n\n while (true)\n {\n while (srcPos < tail)\n {\n Sse2.Store(dstPos, ApplySobelKernel(srcPos, dstStride));\n srcPos += 16;\n dstPos += 16;\n }\n\n if (srcPos == srcEnd)\n break;\n tail = srcEnd;\n srcPos = srcEnd - 16;\n dstPos = dstEnd - 16;\n }\n\n int padding = dstStride - width + 1;\n for (dstPos = dstPtr + dstStride; dstPos <= dstPtr + dstLength - dstStride; dstPos += dstStride)\n {\n *dstPos = 0;\n *(dstPos - padding) = 0;\n }\n }\n outBmp.UnlockBits(outBmpData);\n return outBmp;\n }\n }\n\n private class SobelOperatorScalar : ISobelOperator\n {\n public Bitmap Apply(Bitmap bmp)\n {\n int width = bmp.Width;\n int height = bmp.Height;\n\n Rectangle rect = new Rectangle(Point.Empty, bmp.Size);\n BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);\n int inStride = Math.Abs(bmpData.Stride);\n int strideLength = bmpData.Stride * height;\n byte[] buffer = new byte[Math.Abs(strideLength)];\n Marshal.Copy(bmpData.Scan0, buffer, 0, strideLength);\n bmp.UnlockBits(bmpData);\n\n\n Bitmap outBmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);\n ColorPalette pal = outBmp.Palette;\n for (int i = 0; i < 256; i++)\n pal.Entries[i] = _grayPallette[i];\n outBmp.Palette = pal;\n\n BitmapData outBmpData = outBmp.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);\n int outStride = outBmpData.Stride;\n\n int outLength = outStride * height;\n byte[] pixelBuffer = new byte[outLength];\n byte[] resultBuffer = new byte[outLength];\n\n //0.299R + 0.587G + 0.114B\n for (int row = 0; row < height; row++)\n {\n int inRowOffset = inStride * row;\n int outRowOffset = outStride * row;\n for (int col = 0; col < width; col++)\n {\n int offset = inRowOffset + col * 3;\n byte brightness = (byte)(buffer[offset] * 0.114f + buffer[offset + 1] * 0.587f + buffer[offset + 2] * 0.299f);\n pixelBuffer[outRowOffset + col] = brightness;\n }\n }\n\n for (int row = 1; row < height - 1; row++)\n {\n int rowOffset = outStride * row;\n for (int col = 1; col < width - 1; col++)\n {\n int offset = rowOffset + col;\n\n int gx = -pixelBuffer[offset - 1 - outStride] + pixelBuffer[offset + 1 - outStride] - 2 * pixelBuffer[offset - 1] +\n 2 * pixelBuffer[offset + 1] - pixelBuffer[offset - 1 + outStride] + pixelBuffer[offset + 1 + outStride];\n\n int gy = pixelBuffer[offset - 1 - outStride] + 2 * pixelBuffer[offset - outStride] + pixelBuffer[offset + 1 - outStride] -\n pixelBuffer[offset - 1 + outStride] - 2 * pixelBuffer[offset + outStride] - pixelBuffer[offset + 1 + outStride];\n\n int g = (int)MathF.Sqrt(gx * gx + gy * gy);\n if (g > byte.MaxValue)\n g = byte.MaxValue;\n\n resultBuffer[offset] = (byte)g;\n }\n }\n Marshal.Copy(resultBuffer, 0, outBmpData.Scan0, outLength);\n outBmp.UnlockBits(outBmpData);\n return outBmp;\n }\n }\n}\n</code></pre>\n<h3>Benchmark.NET</h3>\n<pre class=\"lang-none prettyprint-override\"><code>| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |\n|---------------- |----------:|----------:|----------:|---------:|---------:|---------:|----------:|\n| 'SIMD Enabled' | 6.318 ms | 0.1190 ms | 0.1113 ms | 992.1875 | 992.1875 | 992.1875 | 3.35 MB |\n| 'SIMD Disabled' | 43.062 ms | 0.2253 ms | 0.2107 ms | 500.0000 | 500.0000 | 500.0000 | 16.61 MB |\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:39:17.220",
"Id": "254289",
"ParentId": "254255",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254280",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T00:18:00.000",
"Id": "254255",
"Score": "5",
"Tags": [
"c#",
"x86",
"simd",
".net-5"
],
"Title": "Sobel Operator - SIMD x86 Intrinsics Implementation"
}
|
254255
|
<p>I made a fork bomb virus in Assembly. Now, I want to make my code better.</p>
<p>Here is my code:</p>
<pre><code>section .text
global _start
_start:
mov eax, 2
int 0x80
jmp _start
</code></pre>
<p>Makefile:</p>
<pre><code>DIR=build
$(shell mkdir -p $(DIR))
$(shell nasm -f elf64 Program.asm -o Program.o)
$(shell ld Program.o -o build/ForkBomb)
$(shell rm Program.o)
$(shell echo "run.sh" > build/run.sh)
$(shell echo "./build/ForkBomb" > build/run.sh)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:10:45.640",
"Id": "501438",
"Score": "3",
"body": "It’s not a virus because it doesn’t replicate. It’s just a nuisance."
}
] |
[
{
"body": "<ul>\n<li><p><code>int 0x80</code> preserves <code>eax</code>. There is no need to reinitialize it in the loop.</p>\n</li>\n<li><p><code>Makefile</code> is not really a makefile. The purpose of a makefile is to avoid rebuilding stuff which is still up to date. Your makefile rebuilds the program even if nothing has been changed. Consider instead</p>\n<pre><code>build/ForkBomb: Program.o # tell that if Program.o changes, ForkBomb shall be remade...\n ld -o build/ForkBomb Program.o # ... using to this recipe\n\nProgram.o: Program.asm # tell that if Program.asm changes, Program.o shall be remade....\n nasm -f elf64 Program.asm -o Program.o # ... using this recipe\n</code></pre>\n<p>This is pretty much it. If you want a <code>build</code> directory to be created automagically, and without warnings, study <a href=\"https://www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html\" rel=\"noreferrer\">order-only prerequisites</a>.</p>\n</li>\n<li><p>If you want to use macros (like <code>DIR</code>), use them consistently.</p>\n</li>\n<li><p>There is no point to <code>echo "run.sh" > build/run.sh</code>. This will be overwritten immediately by <code>echo "./build/ForkBomb" > build/run.sh</code>.</p>\n<p>That said, I see no reason tor <code>run.sh</code> to exist.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T07:12:44.373",
"Id": "254264",
"ParentId": "254259",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254264",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T06:19:59.723",
"Id": "254259",
"Score": "-1",
"Tags": [
"assembly"
],
"Title": "Fork Bomb virus in Assembly"
}
|
254259
|
<p>Previous: <a href="https://codereview.stackexchange.com/q/254209/188857">Advent of Code 2020 - Day 1: finding 2 or 3 numbers that add up to 2020</a></p>
<p>Next: <a href="https://codereview.stackexchange.com/q/254832/188857">Advent of Code 2020 - Day 3: tobogganing down a slope</a></p>
<h1>Problem statement</h1>
<p>I decided to take a shot at <a href="https://adventofcode.com/2020" rel="nofollow noreferrer">Advent of Code 2020</a> to exercise my Rust knowledge. Here's the task for Day 2:</p>
<blockquote>
<h2>Day 2: Password Philosophy</h2>
<p>[...]</p>
<p>To try to debug the problem, they have created a list (your puzzle
input) of passwords (according to the corrupted database) and the
corporate policy when that password was set.</p>
<p>For example, suppose you have the following list:</p>
<pre><code>1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
</code></pre>
<p>Each line gives the password policy and then the password. <strong>The
password policy indicates the lowest and highest number of times a
given letter must appear for the password to be valid.</strong> For example,
<code>1-3 a</code> means that the password must contain <code>a</code> at least <code>1</code> time and
at most <code>3</code> times.</p>
<p>In the above example, <code>2</code> passwords are valid. The middle password,
<code>cdefg</code>, is not; it contains no instances of <code>b</code>, but needs at least
<code>1</code>. The first and third passwords are valid: they contain one <code>a</code> or
nine <code>c</code>, both within the limits of their respective policies.</p>
<p><strong>How many passwords are valid according to their policies?</strong></p>
<p>[...]</p>
<h3>Part Two</h3>
<p>While it appears you validated the passwords correctly, they don't
seem to be what the Official Toboggan Corporate Authentication System
is expecting.</p>
<p>The shopkeeper suddenly realizes that he just accidentally explained
the password policy rules from his old job at the sled rental place
down the street! The Official Toboggan Corporate Policy actually works
a little differently.</p>
<p><strong>Each policy actually describes two positions in the password, where <code>1</code> means the first character, <code>2</code> means the second character, and so
on.</strong> (Be careful; Toboggan Corporate Policies have no concept of
"index zero"!) <strong>Exactly one of these positions must contain the given
letter.</strong> Other occurrences of the letter are irrelevant for the
purposes of policy enforcement.</p>
<p>Given the same example list from above:</p>
<ul>
<li><code>1-3 a: abcde</code> is valid: position <code>1</code> contains <code>a</code> and position <code>3</code> does not.</li>
<li><code>1-3 b: cdefg</code> is invalid: neither position <code>1</code> nor position <code>3</code> contains <code>b</code>.</li>
<li><code>2-9 c: ccccccccc</code> is invalid: both position <code>2</code> and position <code>9</code> contain <code>c</code>.</li>
</ul>
<p><strong>How many passwords are valid according to the new interpretation of the policies?</strong></p>
</blockquote>
<p>The full story can be found on the <a href="https://adventofcode.com/2020/day/2" rel="nofollow noreferrer">website</a>.</p>
<h1>My solution</h1>
<p><strong>src/day_2.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>use {
anyhow::{anyhow, Result},
itertools::{self, Itertools},
std::str::FromStr,
};
pub const PATH: &str = "./data/day_2/input";
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Policy {
Old,
New,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Entry {
pub numbers: (usize, usize),
pub key: char,
pub password: String,
}
impl Entry {
pub fn is_valid(&self, policy: Policy) -> bool {
match policy {
Policy::Old => {
let (start, end) = self.numbers;
let frequency =
self.password.chars().filter(|&c| c == self.key).count();
(start..=end).contains(&frequency)
}
Policy::New => {
let (num_a, num_b) = self.numbers;
let pos_a = num_a - 1;
let pos_b = num_b - 1;
let char_a = match self.password.chars().nth(pos_a) {
Some(c) => c,
None => return false,
};
let char_b = match self.password.chars().nth(pos_b) {
Some(c) => c,
None => return false,
};
(char_a == self.key) ^ (char_b == self.key)
}
}
}
}
impl FromStr for Entry {
type Err = anyhow::Error;
fn from_str(text: &str) -> Result<Self> {
fn parse(text: &str) -> Option<Entry> {
let (policy, password) = text.split(": ").collect_tuple()?;
let (range, key) = policy.split(" ").collect_tuple()?;
let numbers = itertools::process_results(
range.split("-").map(str::parse),
|iter| iter.collect_tuple(),
)
.ok()??;
Some(Entry {
numbers,
key: key.parse().ok()?,
password: String::from(password),
})
}
parse(text).ok_or_else(|| anyhow!("invalid entry"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn entry_is_valid() {
let entries = [
Entry {
numbers: (1, 3),
key: 'a',
password: "abcde".to_owned(),
},
Entry {
numbers: (1, 3),
key: 'b',
password: "cdefg".to_owned(),
},
Entry {
numbers: (2, 9),
key: 'c',
password: "ccccccccc".to_owned(),
},
];
assert!(entries[0].is_valid(Policy::Old));
assert!(!entries[1].is_valid(Policy::Old));
assert!(entries[2].is_valid(Policy::Old));
assert!(entries[0].is_valid(Policy::New));
assert!(!entries[1].is_valid(Policy::New));
assert!(!entries[2].is_valid(Policy::New));
}
#[test]
fn entry_from_str() -> Result<()> {
let text = "1-3 a: abcde";
assert_eq!(
text.parse::<Entry>()?,
Entry {
numbers: (1, 3),
key: 'a',
password: "abcde".to_owned(),
},
);
Ok(())
}
}
</code></pre>
<p><strong>src/bin/day_2_1.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>use {
anyhow::Result,
aoc_2020::day_2::{self as lib, Entry, Policy},
std::{
fs::File,
io::{prelude::*, BufReader},
},
};
fn main() -> anyhow::Result<()> {
let file = BufReader::new(File::open(lib::PATH)?);
let valid_count = itertools::process_results(
file.lines()
.map(|line| -> Result<_> { Ok(line?.parse::<Entry>()?) }),
|entries| entries.filter(|entry| entry.is_valid(Policy::Old)).count(),
)?;
println!("{}", valid_count);
Ok(())
}
</code></pre>
<p><strong>src/bin/day_2_2.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>use {
anyhow::Result,
aoc_2020::day_2::{self as lib, Entry, Policy},
std::{
fs::File,
io::{prelude::*, BufReader},
},
};
fn main() -> anyhow::Result<()> {
let file = BufReader::new(File::open(lib::PATH)?);
let valid_count = itertools::process_results(
file.lines()
.map(|line| -> Result<_> { Ok(line?.parse::<Entry>()?) }),
|entries| entries.filter(|entry| entry.is_valid(Policy::New)).count(),
)?;
println!("{}", valid_count);
Ok(())
}
</code></pre>
<p>Crates used: <a href="https://docs.rs/anyhow/1.0.37/anyhow/" rel="nofollow noreferrer"><code>anyhow</code> 1.0.37</a> <a href="https://docs.rs/itertools/0.10.0/itertools/" rel="nofollow noreferrer"><code>itertools</code> 0.10.0</a></p>
<p><code>cargo fmt</code> and <code>cargo clippy</code> have been applied.</p>
|
[] |
[
{
"body": "<p>Instead of implementing <code>FromStr</code> on <code>Entry</code> on your own, you may use crates such as <a href=\"https://crates.io/crates/parse-display\" rel=\"nofollow noreferrer\"><code>parse-display</code></a>, <a href=\"https://crates.io/crates/reformation\" rel=\"nofollow noreferrer\"><code>reformation</code></a> or <a href=\"https://crates.io/crates/recap\" rel=\"nofollow noreferrer\"><code>recap</code></a>.</p>\n<p>Some of the derives on <code>Policy</code> and <code>Entry</code> seem unnecessary.</p>\n<p>Kudos for including tests. It makes the code easier to review.</p>\n<p>In tests, when running assertions, I tend to name one of the arguments <code>expected_foo</code>, so that the assertion is shorter. Also, this makes it clear which argument is expected and which is the actual result. In your code:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>assert_eq!(\n text.parse::<Entry>()?,\n Entry {\n numbers: (1, 3),\n key: 'a',\n password: "abcde".to_owned(),\n },\n);\n</code></pre>\n<p>I would change to:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let expected_entry = Entry {\n numbers: (1, 3),\n key: 'a',\n password: "abcde".to_owned(),\n};\n\nassert_eq!(text.parse::<Entry>()?, expected_entry);\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T05:52:33.330",
"Id": "502568",
"Score": "0",
"body": "The `expected_*` one is excellent - it makes the code significantly more readable. Speaking of unnecessary derives, can you name the particular derives that you deem unnecessary? I derived the `Eq` series for testing, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:02:42.067",
"Id": "502595",
"Score": "0",
"body": "@L.F. Glad it was helpful. After a cursory glance, the only needed ones are for testing: `Debug`, `Eq` + `PartialEq` on `Entry`. Other than that, derives can be removed: you dont hash Entry, you rarely use Policy, and you dont clone Entry. By the way, I would be curious how you'd solve day 19."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:11:24.967",
"Id": "502597",
"Score": "0",
"body": "I would generally derive `Clone` as long as it makes sense to clone the type. I'm curious to know if there are any downsides to this. As for day 19, I'm thinking of writing a build script or procedural macro to generate a [pest](https://pest.rs/) script. A little bit cheating, but we'll see :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:24:19.877",
"Id": "502598",
"Score": "1",
"body": "@L.F. I believe there are no downsides to deriving anything, except that a type may no longer support the derive in future versions. So backwards compatibility is the only concern. For clone, the situation is good as you rarely need to remove it.\n\nObviously your program is a binary, not a library, so you have an easier job here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:26:12.193",
"Id": "502599",
"Score": "0",
"body": "@L.F. Ah, it is the case that with many types and many dervives, the compilation takes longer. It used to be the case that for some derives, their compilation took O(n**2), but it was fixed."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T14:36:16.083",
"Id": "254604",
"ParentId": "254260",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254604",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T06:29:49.893",
"Id": "254260",
"Score": "0",
"Tags": [
"programming-challenge",
"validation",
"rust"
],
"Title": "Advent of Code 2020 - Day 2: validating passwords"
}
|
254260
|
<p>I've been tasked with writing a function that executes a passed function every interval, passed to the function by the user. Below is the code, and how to call it:</p>
<pre><code>import time
from typing import Callable
last_milliseconds: int = 0
def set_timer(interval: int, function: Callable) -> bool:
global last_milliseconds
milliseconds: int = int(round(time.time() * 1000))
done: bool = (milliseconds - last_milliseconds) >= interval
if done:
function()
last_milliseconds = milliseconds
</code></pre>
<p>Called by:</p>
<pre><code>p: Callable = lambda: print("set_timer called.")
while True:
set_timer(1000, p)
</code></pre>
<p>Is there a better way to go about this? I'm unsure with the use of the global variable, and the function must be called in an infinite loop structure in order to work. Any and all feedback is accepted and appreciated.</p>
|
[] |
[
{
"body": "<p>First of all, your function doesn't return anything and so you can remove <code>-> bool</code> since it only creates confusion. You can either use <code>-> None</code> or use nothing at all. Still related to type annotations, I find it kinda hard to read your code with annotations everywhere. This is subjective and it's just my personal preference but I usually tend to use type annotations only when dealing with function / class definitions and their arguments.</p>\n<p>For example, <code>milliseconds: int = int(round(time.time() * 1000))</code> it's obviously going to be an integer since we can see the cast to <code>int()</code>.\nMore, <code>round()</code> already returns an <code>int</code> in your case so that can be removed as well. The <code>done</code> variable can also be omitted and added directly to the condition itself:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def set_timer(interval: int, function: Callable) -> None:\n global last_milliseconds\n milliseconds = round(time.time() * 1000)\n \n if milliseconds - last_milliseconds >= interval:\n function()\n last_milliseconds = milliseconds\n</code></pre>\n<p>You can also remove the parentheses from your condition since <code>-</code> has a higher precedence than <code>>=</code>.</p>\n<hr />\n<p>Strictly speaking about the implementation, if you're not tied to using a function and want to get rid of the usage of <code>global</code>, I'd use a class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from time import time\nfrom typing import Callable\n\n\nclass Timer:\n def __init__(self):\n self.last_milliseconds = 0\n\n def set(self, interval: int, function: Callable) -> None:\n milliseconds = round(time() * 1000)\n\n if milliseconds - self.last_milliseconds >= interval:\n function()\n self.last_milliseconds = milliseconds\n</code></pre>\n<p>Which can be used like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n timer = Timer()\n while True:\n timer.set(1000, lambda: print("set_timer called."))\n\n\nmain()\n</code></pre>\n<p>Or, even better, you can have a static class if your workflow allows it:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class StaticTimer:\n last_milliseconds = 0\n\n @classmethod\n def set(cls, interval: int, function: Callable) -> None:\n milliseconds = round(time() * 1000)\n\n if milliseconds - cls.last_milliseconds >= interval:\n function()\n cls.last_milliseconds = milliseconds\n</code></pre>\n<p>Which you'd call like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n while True:\n StaticTimer.set(1000, lambda: print("set_timer called."))\n\n\nmain()\n</code></pre>\n<p>The difference between the two classes is that you can't have multiple of the latter because of the class attribute and <code>@classmethod</code>. So even if you made multiple instance of the class, they'd all share that value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:42:37.420",
"Id": "501451",
"Score": "3",
"body": "_You can either use -> None or use nothing at all_ - Kind of not really. Omitting a return type leaves it undefined and does not imply `None`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T20:24:24.130",
"Id": "501476",
"Score": "1",
"body": "@Reinderien that's a valid point. That's why I said it's a matter of preference on my side but I might've been a bit unclear ^_^ Thanks for pointing that out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T13:37:05.187",
"Id": "501684",
"Score": "0",
"body": "This is a bit over the top, taking into account the complexity of the task. This is all super solid advice in some situations, but in this instance it's beside the point in my opinion. OP can simply use `time.sleep()` and move the loop into a function."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T09:36:28.997",
"Id": "254266",
"ParentId": "254265",
"Score": "4"
}
},
{
"body": "<p>I would approach this a bit differently. Let's employ a bit of design to construct our function. What does the user of the function choose, versus us that write it? From your question we can gather that the user chooses a callable, the interval and maybe whether it is called indefinitely or stopped at some point. This becomes our starting point when we define a function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def repeat_call(func: Callable, interval_ms: int, n_times: int = None) -> None:\n ...\n</code></pre>\n<p>Now all that's left is defining the function body, which can be arbitrarily complicated. In this case it isn't, but there's a much better way of doing it. If you insert a print statement to your <code>while</code> loop, you can see that it runs a bunch of times without calling the function. This is quite wasteful. Instead, we can wait for a certain period of time and repeat. Depending on the final limit we either check for stopping or never stop.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def repeat_call(func: Callable, interval_ms: int, n_times: int = None) -> None:\n if n_times is not None:\n for i in range(n_times):\n func()\n time.sleep(interval_ms / 1000)\n else:\n while True:\n func()\n time.sleep(interval_ms / 1000)\n</code></pre>\n<p>We still have some work to do, since the function is basically doing the same thing in two different places. We can take advantage of the fact that integers cannot overflow in Python to construct a conditionally infinite loop.</p>\n<pre><code>def repeat_call(func: Callable, interval_ms: int, n_times: int = None) -> None:\n if n_times is None:\n n_times = -1\n\n while n_times != 0:\n func()\n n_times -= 1\n time.sleep(interval_ms / 1000)\n</code></pre>\n<p>And to check to see if it works:</p>\n<pre><code>repeat_call(p, 1000, 3)\nprint('Done, starting infinite:')\nrepeat_call(p, 1000)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T13:25:08.210",
"Id": "254381",
"ParentId": "254265",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254266",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T07:21:23.673",
"Id": "254265",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"timer"
],
"Title": "Timer with interval function"
}
|
254265
|
<p>I am trying to implement a monochromic image container with <code>std::unique_ptr</code>.</p>
<p><strong>The example usages</strong></p>
<p>The example usages is as below.</p>
<pre><code>int main()
{
auto test_data = std::make_unique<unsigned char[]>(100 * 100);
for (size_t i = 0; i < 100 * 100; i++)
{
test_data[i] = 3;
}
auto test = DigitalImageProcessing::MonoImage(DigitalImageProcessing::MyImageSize(100, 100), test_data);
auto test2 = test++;
std::cout << test.Sum() << std::endl;
std::cout << test2.Sum() << std::endl;
return 0;
}
</code></pre>
<p><strong>The experimental implementation</strong></p>
<p>The contents in <em>MyImageSize.h</em> file:</p>
<pre><code>#ifndef IMAGESIZE
#define IMAGESIZE
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <concepts>
#include <cstdbool>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <execution>
#include <exception>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
namespace DigitalImageProcessing
{
template<class T = unsigned int>
class MyImageSize
{
private:
T xsize;
T ysize;
public:
MyImageSize(T new_xsize, T new_ysize)
{
this->xsize = new_xsize;
this->ysize = new_ysize;
}
~MyImageSize()
{
}
T GetSizeX()
{
return this->xsize;
}
T GetSizeY()
{
return this->ysize;
}
void SetSizeX(T sizex)
{
this->xsize = sizex;
return;
}
void SetSizeY(T sizey)
{
this->ysize = sizey;
return;
}
};
}
#endif
</code></pre>
<p>The contents in <em>MyImageSize.cpp</em> file:</p>
<pre><code>#include "IMAGESIZE.h"
</code></pre>
<p>The contents in <em>MonoPixelOperation.h</em> file:</p>
<pre><code>#ifndef MONOPIXELOPERATION
#define MONOPIXELOPERATION
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <concepts>
#include <cstdbool>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <execution>
#include <exception>
#include <fstream>
#include <functional>
#include <future>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <omp.h>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <variant>
#include <vector>
namespace DigitalImageProcessing
{
class MonoPixelOperation
{
public:
MonoPixelOperation()
{
}
~MonoPixelOperation()
{
}
static void SetMonoPixelValue(unsigned char *input_pixel, unsigned char value);
static void SetMonoPixelValue(unsigned char *input_pixel, unsigned int value);
static void SetMonoPixelValue(unsigned char *input_pixel, signed int value);
static void SetMonoPixelValue(unsigned char *input_pixel, long double value);
static void SetMonoPixelValue(std::unique_ptr<unsigned char> input_pixel, unsigned char value);
static void SetMonoPixelValue(std::unique_ptr<unsigned char> input_pixel, long double value);
static void SetMonoPixelValue(std::shared_ptr<unsigned char> input_pixel, unsigned char value);
static unsigned char GetMonoPixelValue(unsigned char *input_pixel);
static void SetMonoPixelValueToZero(unsigned char *input_pixel);
private:
const static unsigned char PixelMAXValue = 255;
const static unsigned char PixelMINValue = 0;
template<class T>
static unsigned char TruncatePixelValue(T value)
{
if (value > PixelMAXValue)
{
return PixelMAXValue;
}
else if (value < PixelMINValue)
{
return PixelMINValue;
}
else
{
return static_cast<unsigned char>(value);
}
}
};
}
#endif // !MONOPIXELOPERATION
</code></pre>
<p>The contents in <em>MonoPixelOperation.cpp</em> file:</p>
<pre><code>#include "MonoPixelOperation.h"
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(unsigned char * input_pixel, unsigned char value)
{
*input_pixel = TruncatePixelValue(value);
return;
}
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(unsigned char * input_pixel, unsigned int value)
{
*input_pixel = TruncatePixelValue(value);
return;
}
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(unsigned char * input_pixel, signed int value)
{
*input_pixel = TruncatePixelValue(value);
return;
}
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(unsigned char * input_pixel, long double value)
{
*input_pixel = TruncatePixelValue(value);
return;
}
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(std::unique_ptr<unsigned char> input_pixel, unsigned char value)
{
*input_pixel = TruncatePixelValue(value);
return;
}
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(std::unique_ptr<unsigned char> input_pixel, long double value)
{
*input_pixel = TruncatePixelValue(value);
return;
}
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(std::shared_ptr<unsigned char> input_pixel, unsigned char value)
{
*input_pixel = TruncatePixelValue(value);
return;
}
unsigned char DigitalImageProcessing::MonoPixelOperation::GetMonoPixelValue(unsigned char * input_pixel)
{
return *input_pixel;
}
void DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValueToZero(unsigned char * input_pixel)
{
*input_pixel = 0;
return;
}
</code></pre>
<p>The contents in <em>MonoImage.h</em> file:</p>
<pre><code>#ifndef MONOIMAGE
#define MONOIMAGE
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cmath>
#include <complex>
#include <concepts>
#include <cstdbool>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <execution>
#include <exception>
#include <fstream>
#include <functional>
#include <future>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <numeric>
#include <omp.h>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
#include "ImageSize.h"
#include "MonoPixelOperation.h"
namespace DigitalImageProcessing
{
template<class SizeT = unsigned int>
class MonoImage
{
public:
MonoImage()
{
}
constexpr auto GetimageSizeX()
{
return image_size.xsize;
}
constexpr auto GetimageSizeY()
{
return this->image_size.ysize;
}
constexpr auto GetimageSize()
{
return this->image_size;
}
std::unique_ptr<unsigned char[]> GetImageData()
{
auto output = std::make_unique<unsigned char[]>(image_size.xsize * image_size.ysize);
if (image_data == NULL)
{
std::printf("Memory allocation error!");
throw std::logic_error("Memory allocation error!");
}
for (SizeT y = 0; y < image_size.ysize; y++)
{
for (SizeT x = 0; x < image_size.xsize; x++)
{
DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValue(&output[y * image_size.xsize + x],
DigitalImageProcessing::MonoPixelOperation::GetMonoPixelValue(&image_data[y * image_size.xsize + x]));
}
}
return output;
}
MonoImage& operator=(MonoImage const& input) // Copy Assign
{
this->image_size.xsize = input.image_size.xsize;
this->image_size.ysize = input.image_size.ysize;
this->image_data = std::make_unique<unsigned char[]>(image_size.xsize * image_size.ysize);
for (SizeT y = 0; y < image_size.ysize; y++)
{
for (SizeT x = 0; x < image_size.xsize; x++)
{
MonoPixelOperation::SetMonoPixelValue(&this->image_data[y * image_size.xsize + x],
MonoPixelOperation::GetMonoPixelValue(&input.image_data[y * image_size.xsize + x]));
}
}
return *this;
}
MonoImage& operator=(MonoImage&& other) // Move Assign
{
image_size = std::move(other.image_size);
image_data = std::move(other.image_data);
return *this;
}
MonoImage& operator+=(const MonoImage& rhs)
{
if (rhs.image_size.xsize == this->image_size.xsize &&
rhs.image_size.ysize == this->image_size.ysize)
{
auto output = MonoImage(rhs.image_size.xsize, rhs.image_size.ysize);
for (SizeT y = 0; y < image_size.ysize; y++)
{
for (SizeT x = 0; x < image_size.xsize; x++)
{
MonoPixelOperation::SetMonoPixelValue(&output.image_data[y* image_size.xsize + x],
MonoPixelOperation::GetMonoPixelValue(&image_data[(y)*(image_size.xsize) + (x)]) +
MonoPixelOperation::GetMonoPixelValue(&rhs.image_data[(y) * (image_size.xsize) + (x)])
);
}
}
return output;
}
}
MonoImage& operator++()
{
return *this;
}
/* This operator is used as
MonoImage MonoImage1(100, 100);
MonoImage MonoImage2(100, 100);
MonoImage2 = MonoImage1++;
*/
MonoImage operator++(int)
{
auto output = MonoImage(this->image_size.GetSizeX(), this->image_size.GetSizeY());
for (SizeT y = 0; y < image_size.GetSizeY(); y++)
{
for (SizeT x = 0; x < image_size.GetSizeX(); x++)
{
MonoPixelOperation::SetMonoPixelValue(&output.image_data[y* image_size.GetSizeX() + x],
MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y)*(image_size.GetSizeX()) + (x)])
);
}
}
for (SizeT y = 0; y< image_size.GetSizeY(); y++)
{
for (SizeT x = 0; x< image_size.GetSizeX(); x++)
{
MonoPixelOperation::SetMonoPixelValue(&this->image_data[y * image_size.GetSizeX() + x],
MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y) * (image_size.GetSizeX()) + (x)]) + 1
);
}
}
return output;
}
MonoImage& operator--()
{
return *this;
}
MonoImage operator--(int)
{
auto output = MonoImage(this->image_size.xsize, this->image_size.ysize);
for (SizeT y = 0; y< image_size.ysize; y++)
{
for (SizeT x = 0; x< image_size.xsize; x++)
{
MonoPixelOperation::SetMonoPixelValue(&output.image_data[y* image_size.xsize + x],
MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y)*(image_size.xsize) + (x)]) - 1
);
}
}
return output;
}
friend bool operator==(const MonoImage& input1, const MonoImage& input2)
{
if (input1.image_size != input2.image_size)
{
return false;
}
for (SizeT y = 0; y < input1.image_size.ysize; y++)
{
for (SizeT x = 0; x < input1.image_size.xsize; x++)
{
if (MonoPixelOperation::GetMonoPixelValue(&input1.image_data[y * input1.image_size.xsize + x]) -
MonoPixelOperation::GetMonoPixelValue(&input2.image_data[y * input2.image_size.xsize + x]) != 0)
{
return false;
};
}
}
return true;
}
friend bool operator!=(const MonoImage& input1, const MonoImage& input2)
{
return !(input1 == input2);
}
MonoImage Difference(const MonoImage& input)
{
auto output = MonoImage(this->image_size.xsize, this->image_size.ysize);
for (SizeT y = 0; y < image_size.ysize; y++)
{
for (SizeT x = 0; x < image_size.xsize; x++)
{
MonoPixelOperation::SetMonoPixelValue(&output.image_data[y * image_size.xsize + x],
std::abs(
MonoPixelOperation::GetMonoPixelValue(&input.image_data[(y) * (image_size.xsize) + (x)]) -
MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y) * (image_size.xsize) + (x)])
)
);
}
}
return output;
}
constexpr auto Subtract(const MonoImage& input)
{
auto output = MonoImage<SizeT>(this->image_size.GetSizeX(), this->image_size.GetSizeY());
for (SizeT y = 0; y < image_size.GetSizeY(); y++)
{
for (SizeT x = 0; x < image_size.GetSizeX(); x++)
{
MonoPixelOperation::SetMonoPixelValue(&output.image_data[y * image_size.GetSizeX() + x],
MonoPixelOperation::GetMonoPixelValue(&input.image_data[(y) * (image_size.GetSizeX()) + (x)]) -
MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y) * (image_size.GetSizeX()) + (x)])
);
}
}
return output;
}
constexpr auto Sum()
{
unsigned long long int ReturnValue = 0;
for (SizeT y = 0; y < image_size.GetSizeY(); y++)
{
for (SizeT x = 0; x < image_size.GetSizeX(); x++)
{
ReturnValue += MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y) * (image_size.GetSizeX()) + (x)]);
}
}
return ReturnValue;
}
MonoImage(const MonoImage<SizeT> &input)
: image_size(input.image_size)
{
if (input.image_size.xsize == 0 || input.image_size.ysize == 0)
{
return;
}
image_data = std::make_unique<unsigned char[]>(image_size.xsize * image_size.ysize);
for (SizeT y = 0; y < image_size.ysize; y++)
{
for (SizeT x = 0; x < image_size.xsize; x++)
{
MonoPixelOperation::SetMonoPixelValue(&image_data[y * image_size.xsize + x],
MonoPixelOperation::GetMonoPixelValue(&input.image_data[y * image_size.xsize + x]));
}
}
}
/* Move Constructor
*/
MonoImage(MonoImage &&input) : image_size(input.image_size), image_data(std::move(input.image_data))
{
}
MonoImage(DigitalImageProcessing::MyImageSize<SizeT> input_size)
: image_size(input_size)
{
this->image_data = std::make_unique<unsigned char[]>(this->image_size.GetSizeX() * this->image_size.GetSizeY());
if (this->image_data == NULL)
{
printf("Memory allocation error!");
throw std::logic_error("Memory allocation error!");
}
SetImageDataToBlack();
}
MonoImage(DigitalImageProcessing::MyImageSize<SizeT> input_size, const std::unique_ptr<unsigned char[]>& input_image_data)
: image_size(input_size)
{
this->image_data = std::make_unique<unsigned char[]>(this->image_size.GetSizeX() * this->image_size.GetSizeY());
if (this->image_data == NULL)
{
printf("Memory allocation error!");
throw std::logic_error("Memory allocation error!");
}
for (SizeT y = 0; y < input_size.GetSizeY(); y++)
{
for (SizeT x = 0; x < input_size.GetSizeX(); x++)
{
MonoPixelOperation::SetMonoPixelValue(&this->image_data[y * input_size.GetSizeX() + x],
MonoPixelOperation::GetMonoPixelValue(&input_image_data[y * input_size.GetSizeX() + x]));
}
}
}
template<class T1, class T2>
MonoImage(const T1& xsize, const T2& ysize)
: image_size(MyImageSize<SizeT>(static_cast<SizeT>(xsize), static_cast<SizeT>(ysize)))
{
this->image_data = std::make_unique<unsigned char[]>(xsize * ysize);
if (this->image_data == NULL)
{
std::printf("Memory allocation error!");
throw std::logic_error("Memory allocation error!");
}
SetImageDataToBlack();
}
template<class T1, class T2>
MonoImage(const SizeT& xsize, const SizeT& ysize, const std::unique_ptr<unsigned char[]>& input_image_data)
: image_size(MyImageSize<SizeT>(static_cast<SizeT>(xsize), static_cast<SizeT>(ysize)))
{
this->image_data = std::make_unique<unsigned char[]>(xsize * ysize);
if (this->image_data == NULL)
{
printf("Memory allocation error!");
throw std::logic_error("Memory allocation error!");
}
for (SizeT y = 0; y < ysize; y++)
{
for (SizeT x = 0; x < xsize; x++)
{
MonoPixelOperation::SetMonoPixelValue(&this->image_data[y * xsize + x],
MonoPixelOperation::GetMonoPixelValue(&input_image_data[y * xsize + x]));
}
}
}
~MonoImage()
{}
private:
MyImageSize<SizeT> image_size;
std::unique_ptr<unsigned char[]> image_data;
void SetImageDataToBlack()
{
for (SizeT y = 0; y < this->image_size.GetSizeY(); y++)
{
for (SizeT x = 0; x < this->image_size.GetSizeX(); x++)
{
DigitalImageProcessing::MonoPixelOperation::SetMonoPixelValueToZero(&image_data[y * image_size.GetSizeX() + x]);
}
}
}
void SetImageDataToWhite()
{
for (SizeT y = 0; y < image_size.GetSizeY(); y++)
{
for (SizeT x = 0; x < image_size.GetSizeX(); x++)
{
MonoPixelOperation::SetMonoPixelValue(&image_data[y * image_size.GetSizeX() + x], 255);
}
}
}
void SetImageDataToSpecificValue(const unsigned char input_value)
{
for (SizeT y = 0; y < image_size.GetSizeY(); y++)
{
for (SizeT x = 0; x < image_size.GetSizeX(); x++)
{
MonoPixelOperation::SetMonoPixelValue(&image_data[y * image_size.GetSizeX() + x], input_value);
}
}
}
};
}
#endif // !MONOIMAGE
</code></pre>
<p>The contents in <em>MonoImage.cpp</em> file:</p>
<pre><code>#include "MonoImage.h"
</code></pre>
<p><a href="https://godbolt.org/z/sWPMKo" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>If there is any possible improvement about:</p>
<ul>
<li><p>Performance: including data accessing/updating speed things</p>
</li>
<li><p>The naming and readability</p>
</li>
<li><p>Potential drawbacks of the implemented member functions</p>
</li>
</ul>
<p>, please let me know.</p>
|
[] |
[
{
"body": "<p><code>#include</code> only the headers you need where you need them. <code>MyImageSize.h</code> needs no includes. <code>MonoPixelOperation.h</code> needs only <code><memory></code>.</p>\n<hr />\n<pre><code>template<class T = unsigned int>\nclass MyImageSize\n{\nprivate:\n T xsize;\n T ysize;\n\npublic:\n\n MyImageSize(T new_xsize, T new_ysize)\n {\n this->xsize = new_xsize;\n this->ysize = new_ysize;\n }\n ~MyImageSize()\n {\n }\n\n T GetSizeX()\n {\n return this->xsize;\n }\n\n T GetSizeY()\n {\n return this->ysize;\n }\n\n void SetSizeX(T sizex)\n {\n this->xsize = sizex;\n return;\n }\n\n void SetSizeY(T sizey)\n {\n this->ysize = sizey;\n return;\n }\n};\n</code></pre>\n<p>We could replace this whole thing with:</p>\n<pre><code>template<class T = unsigned int>\nstruct MyImageSize\n{\n T xsize;\n T ysize;\n};\n</code></pre>\n<p>Only the constructor provides extra functionality (ensuring the variables are initialized), but that's arguably unnecessary too.</p>\n<hr />\n<pre><code> static void SetMonoPixelValue(unsigned char *input_pixel, unsigned char value);\n static void SetMonoPixelValue(unsigned char *input_pixel, unsigned int value);\n static void SetMonoPixelValue(unsigned char *input_pixel, signed int value);\n static void SetMonoPixelValue(unsigned char *input_pixel, long double value);\n \n static void SetMonoPixelValue(std::unique_ptr<unsigned char> input_pixel, unsigned char value);\n static void SetMonoPixelValue(std::unique_ptr<unsigned char> input_pixel, long double value);\n \n static void SetMonoPixelValue(std::shared_ptr<unsigned char> input_pixel, unsigned char value);\n \n static unsigned char GetMonoPixelValue(unsigned char *input_pixel);\n \n static void SetMonoPixelValueToZero(unsigned char *input_pixel);\n</code></pre>\n<p>This is kinda silly...</p>\n<ul>\n<li><code>input_pixel</code> is an output for most of these.</li>\n<li>We should use a reference instead of a pointer (a <code>nullptr</code> wouldn't work).</li>\n<li>We could define a single <code>Set</code> function that takes the correct type (the same as the pixel type)?</li>\n<li>We shouldn't hide clamping in a function called "Set".</li>\n<li>We may well want to set the values without clamping.</li>\n<li>We can use <code>std::clamp</code> for clamping.</li>\n</ul>\n<p>Compare:</p>\n<pre><code>pixel = std::clamp(value, min, max);\n</code></pre>\n<p>vs.</p>\n<pre><code>MonoPixelOperation::SetMonoPixelValue(&pixel, value);\n</code></pre>\n<hr />\n<p>I don't think there's much point in templating the <code>SizeT</code> of the image, rather than just using <code>std::size_t</code> for the index type.</p>\n<p>Consider templating the pixel type instead, so we don't need a separate <code>MonoImage</code> and <code>RGBImage</code>; we could use an <code>Image<unsigned char></code> or <code>Image<Vec3></code>.</p>\n<hr />\n<pre><code> MonoImage& operator+=(const MonoImage& rhs)\n {\n if (rhs.image_size.xsize == this->image_size.xsize &&\n rhs.image_size.ysize == this->image_size.ysize)\n {\n ...\n return output;\n }\n }\n</code></pre>\n<p>So if the sizes aren't the same, we... err... don't return anything? I'm surprised that compiles. If you aren't getting a compiler warning about that, you need to turn up the compiler warning level (and set warnings to errors).</p>\n<hr />\n<pre><code> MonoImage& operator++()\n {\n return *this;\n }\n</code></pre>\n<p><code>// TODO: implement me? ;)</code></p>\n<pre><code> MonoImage operator++(int)\n {\n auto output = MonoImage(this->image_size.GetSizeX(), this->image_size.GetSizeY());\n for (SizeT y = 0; y < image_size.GetSizeY(); y++)\n {\n for (SizeT x = 0; x < image_size.GetSizeX(); x++)\n {\n MonoPixelOperation::SetMonoPixelValue(&output.image_data[y* image_size.GetSizeX() + x],\n MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y)*(image_size.GetSizeX()) + (x)])\n );\n }\n }\n for (SizeT y = 0; y< image_size.GetSizeY(); y++)\n {\n for (SizeT x = 0; x< image_size.GetSizeX(); x++)\n {\n MonoPixelOperation::SetMonoPixelValue(&this->image_data[y * image_size.GetSizeX() + x],\n MonoPixelOperation::GetMonoPixelValue(&this->image_data[(y) * (image_size.GetSizeX()) + (x)]) + 1\n );\n }\n }\n return output;\n }\n</code></pre>\n<p>Or... we could just:</p>\n<pre><code>auto output = *this;\nfor (auto i = std::size_t{ 0 }; i != image_size.GetImageSize(); ++i)\n ++output.image_data[i];\n</code></pre>\n<hr />\n<p><code>std::vector<></code> provides a much cleaner and more useful interface than <code>std::unique_ptr<[]></code> for holding and manipulating the data.</p>\n<p>Consider:</p>\n<pre><code>struct ImageSize\n{\n std::size_t x, y;\n};\n\ntemplate<class PixelT>\nclass Image\n{\npublic:\n \n Image():\n m_size(0, 0),\n m_data() { }\n\n Image(std::size_t width, std::size_t height, PixelT value = PixelT()):\n m_size(width, height),\n m_data(GetSize(), value) { }\n\n // ... other std::vector-style constructors\n \n Image(Image const&) = default; // woo!\n Image& operator=(Image const&) = default; // yay!\n Image(Image&&) = default; // yaaaaaaaaas queen!\n Image& operator=(Image&&) = default; // it's so easy!\n \n std::vector<PixelT> CloneData() const { return m_data; } // copy the whole thing!\n \n Image& operator++()\n {\n for (auto& v : m_data) // easy peasy...\n ++v;\n \n return *this;\n }\n \n Image& operator+=(Image const& rhs)\n {\n if (m_size != rhs.m_size)\n throw std::runtime_error("unequal image sizes in operator+=");\n \n for (auto i = std::size_t{ 0 }; i != m_data.size(); ++i) // this is as hard as it gets\n m_data[i] += rhs.m_data[i];\n \n return *this;\n }\n \n // ...\n \nprivate:\n \n ImageSize m_size;\n std::vector<PixelT> m_data;\n};\n</code></pre>\n<hr />\n<p>For the interface I'd suggest to:</p>\n<ul>\n<li><p>Look at the <code>std::vector</code> interface: constructors, indexed pixel access, iterators, range-based for loops etc. would all be useful. We can simply write a wrapper around the <code>std::vector</code> implementations for this part of the interface (e.g. use <code>std::vector<T>::iterator</code>).</p>\n</li>\n<li><p>Look at the basic mathematical operators: +, -, /, *, %, and the assignment versions and unary operators would all be useful. We can mainly apply the built-in operations to every pixel in the image (with a bit of bounds checking).</p>\n</li>\n<li><p>Other operations (e.g. <code>Abs()</code>, <code>Difference()</code>, <code>Clamp()</code> etc.) can be implemented as free-functions instead of member functions. They can use the math / vector interfaces and should be a couple of lines of code each. e.g.:</p>\n<pre><code> template<class ImageT>\n void Clamp(ImageT& image, typename ImageT::PixelT min, typename ImageT::PixelT max)\n {\n for (auto& p : image)\n p = std::clamp(p, min, max);\n }\n</code></pre>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:27:10.297",
"Id": "254274",
"ParentId": "254267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254274",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T10:54:23.720",
"Id": "254267",
"Score": "2",
"Tags": [
"c++",
"performance",
"c++11",
"reinventing-the-wheel",
"classes"
],
"Title": "An Implementation of Two Dimensional Plane as Monochromic Image Container with std::unique_ptr in C++"
}
|
254267
|
<p>I have an old car that I use for long distance driving and have coded an onboard computer based on a Raspberry Pi 3 and a few other modules. It's my first project in Python and while I've already gotten some help, I now have a version of my project which works quite well.</p>
<p>I use a FONA 808 from Adafruit as the cellular modem (via serial), the Sparkfun NEO-M9N as a GPS sensor (i2c), an OLED display (i2c) and a small temperature sensor via 1-wire.
Here is a link to a picture of the computer in action, just so you have a better picture of it: <a href="https://www.instagram.com/p/CJO9HnNneg2/" rel="nofollow noreferrer">https://www.instagram.com/p/CJO9HnNneg2/</a></p>
<p>I'd appreciate getting some optimization tips to make it run smoothly. I'm especially unsure on how I've used threading and if I'm being really efficient with the GPS and the logging etc... Thanks!</p>
<p>(also, if the question is missing some information, don't downvote, comment and I'll correct it)</p>
<pre><code>import os
from threading import Thread
import glob
import serial
import subprocess
import urllib
import urllib.request
import urllib.parse
import array
import requests
from time import sleep
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import sh1106
from PIL import ImageFont, Image, ImageDraw
import time
import board
import busio
import subprocess
import pymysql
import RPi.GPIO as GPIO
from haversine import haversine, Unit
import csv
import pandas
import datetime
import pathlib
import json
import smbus
import logging
import pynmea2
################## config display ##################
device = sh1106(i2c(port=1, address=0x3c), rotate=0)
device.clear()
global pending_redraw
pending_redraw = False
### setup different fonts
FA_solid = ImageFont.truetype('/home/pi/Desktop/fonts/fa-solid-900.ttf', 12)
FA_solid_largest = ImageFont.truetype('/home/pi/Desktop/fonts/fa-solid-900.ttf', 40)
text_largest = ImageFont.truetype('/home/pi/Desktop/fonts/digital-7.ttf', 58)
text_medium = ImageFont.truetype('/home/pi/Desktop/fonts/digital-7.ttf', 24)
text_small = ImageFont.truetype('/home/pi/Desktop/fonts/digital-7.ttf', 18)
### Initialize drawing zone (aka entire screen)
output = Image.new("1", (128,64))
add_to_image = ImageDraw.Draw(output)
### coordinates always: padding-left, padding-top. the first pair of zone is always = start
# temp_ext
temp_zone = [(14,44), (36,64)]
temp_start = (14,44)
temp_icon_zone = [(0,48), (15,64)]
temp_icon_start = (3,48)
# alti
alti_zone = [(14,22), (69,40)]
alti_start = (14,22)
alti_icon_zone = [(0,24), (15,40)]
alti_icon_start = (0,26)
# distance
dist_zone = [(14,0), (69,21)]
dist_start = (14,0)
dist_icon_zone = [(0,4), (15,21)]
dist_icon_start = (0,4)
# speed
speed_zone = [(66,0), (128,45)]
speed_start = (66,0)
# GPRS status
gprs_zone = [(114,46), (128,64)]
gprs_start = (114,50)
# GPS status, incl. GPS startup icon
status_icon_zone = [(70,50), (88,64)]
status_icon_start = (70,50)
status_zone = [(86,46), (113,64)]
status_start_text = (86,46)
status_start = (86,50)
# usage
#add_to_image.rectangle(speed_zone, fill="black", outline = "black")
#add_to_image.text(speed_start, "\uf00c", font=FA_solid, fill="white")
#device.display(output)
################## upload data from GPS folder via FONA to MySQL ##################
def fix_nulls(s):
for line in s:
yield line.replace('\0','')
def upload_data():
while True:
sleep(20)
current_dir = "/home/pi/Desktop/data/gps"
archive_dir = "/home/pi/Desktop/data/gps/archive"
path, dirs, files = next(os.walk(current_dir))
file_count = len(files)
if file_count < 2:
print("Not enough GPS.csv files found so it's probably in use now or doesn't exist")
return
list_of_files = glob.glob(current_dir+"/*.csv")
oldest_file = min(list_of_files, key=os.path.getctime)
oldest_file_name = os.path.basename(oldest_file)
try:
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
add_to_image.text(gprs_start, "\uf0c2", font=FA_solid, fill="white")
global pending_redraw
pending_redraw = True
print("Opening remote db")
openPPPD()
print("Opening remote db: done")
db = pymysql.connect("XXX","XXX","XXX","XXX" )
cursor = db.cursor()
csv_data = csv.reader(fix_nulls(open(oldest_file)))
next(csv_data)
for row in csv_data:
if row:
cursor.execute('INSERT INTO gps_data_2 (gps_time, gps_lat, gps_long, gps_speed) VALUES (%s, %s, %s, %s)',row)
print("Commiting to db")
db.commit()
cursor.close()
closePPPD()
print("Successfully commited to db")
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
add_to_image.text(gprs_start, "\uf058", font=FA_solid, fill="white")
pending_redraw = True
os.rename(current_dir+"/"+oldest_file_name, archive_dir+"/archive_"+oldest_file_name)
sleep(60)
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
except Exception as e:
print("Database error:", e)
sleep(60)
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
return
sleep(300)
################## config and start GPS ##################
BUS = None
address = 0x42
gpsReadInterval = 1
reading_nr = 1
reading_nr_upload = 1
reading_nr_upload_nbrowsinlog = 0
total_km = 0
prev_lat = 0
prev_long = 0
def connectBus():
global BUS
BUS = smbus.SMBus(1)
def parseResponse(gpsLine):
gpsChars = ''.join(chr(c) for c in gpsLine)
local_pending_redraw = False
if "$GNGGA" in gpsChars:
if ",1," not in gpsChars:
print("Looking for fix... (GGA)")
add_to_image.rectangle(status_icon_zone, fill="black", outline = "black")
add_to_image.rectangle(status_zone, fill="black", outline = "black")
add_to_image.text(status_icon_start, "\uf124", font=FA_solid, fill="white")
add_to_image.text(status_start, "\uf128", font=FA_solid, fill="white")
local_pending_redraw = True
return False
try:
nmea = pynmea2.parse(gpsChars, check=True)
#print("GGA:", '%.6f'%(nmea.latitude), ",",'%.6f'%(nmea.longitude), ", sats:", nmea.num_sats, ", alt:", nmea.altitude) # GGA
if "0.0" in str(nmea.latitude):
return False
if "0.0" in str(nmea.longitude):
return False
## show fix + nb satellites
#num_sats = str(nmea.num_sats)
#num_sats = num_sats.lstrip("0")
#add_to_image.rectangle(status_icon_zone, fill="black", outline = "black")
#add_to_image.rectangle(status_zone, fill="black", outline = "black")
#add_to_image.text(status_icon_start, "\uf124", font=FA_solid, fill="white")
#add_to_image.text(status_start_text, num_sats, font=text_medium, fill="white")
## update altitude
add_to_image.text(alti_icon_start, "\uf077", font=FA_solid, fill="white")
add_to_image.rectangle(alti_zone, fill="black", outline = "black")
add_to_image.text(alti_start, str('%.0f'%(nmea.altitude)), font=text_medium, fill="white")
## update total distance
global reading_nr
global total_km
global prev_lat
global prev_long
dist = 0
if reading_nr != 1:
dist = haversine(((float(prev_lat)), (float(prev_long))), ((float(nmea.latitude)), (float(nmea.longitude))))
total_km = total_km+dist
add_to_image.text(dist_icon_start, "\uf1b9", font=FA_solid, fill="white")
add_to_image.rectangle(dist_zone, fill="black", outline = "black")
add_to_image.text(dist_start, "%0.1f" % total_km, font=text_medium, fill="white")
prev_lat = nmea.latitude
prev_long = nmea.longitude
local_pending_redraw = True
reading_nr +=1
except Exception as e:
print("GGA parse error:", e)
add_to_image.rectangle(status_zone, fill="black", outline = "black")
local_pending_redraw = True
pass
if "$GNRMC" in gpsChars:
if ",A," not in gpsChars: # 1 for GGA, A for RMC
print("Looking for fix... (RMC)")
add_to_image.rectangle(status_icon_zone, fill="black", outline = "black")
add_to_image.rectangle(status_zone, fill="black", outline = "black")
add_to_image.text(status_icon_start, "\uf124", font=FA_solid, fill="white")
add_to_image.text(status_start, "\uf128", font=FA_solid, fill="white")
local_pending_redraw = True
return False
try:
nmea = pynmea2.parse(gpsChars, check=True)
if "0.0" in str(nmea.latitude):
return False
if "0.0" in str(nmea.longitude):
return False
add_to_image.rectangle(status_zone, fill="black", outline = "black")
## update speed
add_to_image.rectangle(speed_zone, fill="black", outline = "black")
add_to_image.text(speed_start, str('%.0f'%(nmea.spd_over_grnd*1.852)), font=text_largest, fill="white")
local_pending_redraw = True
## log every 5th GPS coordinate in CSV file
global reading_nr_upload
global reading_nr_upload_nbrowsinlog
#print(reading_nr_upload)
if reading_nr_upload % 5 == 0:
t = datetime.datetime.combine(nmea.datestamp, nmea.timestamp).strftime("%s")
d = datetime.datetime.combine(nmea.datestamp, nmea.timestamp).strftime("%Y%m%d%H")
filename = '/home/pi/Desktop/data/gps/gps_' + d + '.csv'
with open(filename, 'a', newline='') as csvfile:
gps_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
gps_writer.writerow([t, nmea.latitude, nmea.longitude, nmea.spd_over_grnd*1.852])
reading_nr_upload_nbrowsinlog +=1
print("Added to log. Total in Log from this session is", reading_nr_upload_nbrowsinlog)
add_to_image.rectangle(status_icon_zone, fill="black", outline = "black")
add_to_image.rectangle(status_zone, fill="black", outline = "black")
add_to_image.text(status_icon_start, "\uf124", font=FA_solid, fill="white")
add_to_image.text(status_start, "\uf56f", font=FA_solid, fill="white")
reading_nr_upload +=1
#print("RMC: speed is", nmea.spd_over_grnd*1.852) # RMC
#print("RMC nmea.longitude:", nmea.longitude)
except Exception as e:
print("RMC parse error:", e)
add_to_image.rectangle(status_zone, fill="black", outline = "black")
local_pending_redraw = True
pass
if local_pending_redraw == True:
global pending_redraw
pending_redraw = True
def readGPS(gpsReadInterval=1):
c = None
response = []
try:
while True: # Newline, or bad char.
global BUS
c = BUS.read_byte(address)
if c == 255:
return False
elif c == 10:
break
else:
response.append(c)
parseResponse(response)
except IOError:
time.sleep(0.5)
connectBus()
connectBus()
def updateGPS(gpsReadInterval=1):
while True:
readGPS()
#sleep(gpsReadInterval)
################## config external thermometer ##################
def update_temp_ext(temp_signature='t=', update_interval=60):
sleep(10)
add_to_image.text(temp_icon_start, "\uf2c9", font=FA_solid, fill="white")
while True:
f = open('/sys/bus/w1/devices/28-012032ffbd96/w1_slave', 'r')
lines = f.readlines()
f.close()
equals_pos = lines[1].find(temp_signature)
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = round(float(temp_string) / 1000.0)
add_to_image.rectangle(temp_zone, fill="black", outline = "black")
add_to_image.text(temp_start, str(temp_c), font=text_medium, fill="white")
global pending_redraw
pending_redraw = True
#filename = 'data/temp_ext/tempext_' + datetime.datetime.now().strftime("%Y%m%d") + '.csv'
#with open(filename, 'a', newline='') as csvfile:
# temp_ext_writer = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
# temp_ext_writer.writerow([str(temp_c)])
time.sleep(update_interval)
################## update display ##################
def update_display():
while True:
# there is a potential race condition here, not critical
global pending_redraw
if pending_redraw:
pending_redraw = False
device.display(output)
time.sleep(0.1)
################## start cellular connection ##################
def openPPPD():
print("Opening PPPD")
subprocess.call("sudo pon fona", shell=True)
print("FONA on")
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
add_to_image.text(gprs_start, "\uf0c2", font=FA_solid, fill="white")
global pending_redraw
pending_redraw = True
sleep(20)
try:
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
add_to_image.text(gprs_start, "\uf0c2", font=FA_solid, fill="white")
pending_redraw = True
urllib.request.urlopen('http://google.com')
print("Connection is on")
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
add_to_image.text(gprs_start, "\uf382", font=FA_solid, fill="white")
pending_redraw = True
return True
except:
print("No connection")
add_to_image.rectangle(gprs_zone, fill="black", outline = "black")
add_to_image.text(gprs_start, "\uf127", font=FA_solid, fill="white")
pending_redraw = True
sleep(5)
return False
# Stop PPPD
def closePPPD():
print("turning off PPPD")
subprocess.call("sudo poff fona", shell=True)
print("turned off")
return True
################## threading and program execution ##################
if __name__ == '__main__':
temp_ext_thread = Thread(target = update_temp_ext)
display_thread = Thread(target=update_display)
gps_thread = Thread(target = updateGPS)
data_thread = Thread(target = upload_data)
display_thread.start()
gps_thread.start()
data_thread.start()
temp_ext_thread.start()
display_thread.join()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T12:01:26.543",
"Id": "501429",
"Score": "0",
"body": "Welcome to the Code Review Community where we review working code and provide suggestions for how to improve that code. The question is fairly good, but it is border line on working code. What makes it questionable is `but is not super super reliable.`. This is why I haven't voted it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:18:47.207",
"Id": "501439",
"Score": "1",
"body": "@pacmaninbw thx for your feedback! I meant to say something like \"it works, but I wouldn't trust it with my life\". It's working at the moment, I believe the only hiccups are when there's a loose contact on my breadboard - I have ordered a PCB to remedy that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:31:37.363",
"Id": "501444",
"Score": "2",
"body": "According to some people on this site, Duct tape or Duck tape fixes everything including breadboards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T21:11:22.237",
"Id": "501478",
"Score": "0",
"body": "While this isn't really about the code, I'm a little concerned about you directly connecting to a remote MySQL server, since that tends to be pretty insecure (your credentials are probably broadcasted to the nearest cell tower in plaintext unless you've set up TLS). I would definitely recommend using a HTTPS POST request instead, along with a PHP script on the server to commit the information to the DB upon receiving said request, possibly also with some authentication, even if HTTP basic auth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T12:46:50.623",
"Id": "501515",
"Score": "0",
"body": "Don't use `open` ... that might leak file descriptors, which are _rare earth materials_; You might run out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:55:15.953",
"Id": "501613",
"Score": "0",
"body": "@TR_SLimey I actually had that first, POSTing to a server with PHP handling the rest but have run into issues on how to add hundreds of lines at once and thus found adding directly into MySQL easier. Happy for suggestions on how to do it server-side tho"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:07:31.763",
"Id": "501614",
"Score": "0",
"body": "@DamienBourdonneau Assuming you have full access to your server (as opposed to it being a web host for instance), you could even simply write a Python server, and send the data along a socket using JSON or pickle, which should work just fine. Security-wise, you could just encrypt your traffic with AES using a pre-shared key since this is a project for you exclusively I assume. That would provide authentication also. If it is a webhost and you have to use PHP, you could still format the data as JSON and submit it as the POST body. The only issue with that I can think of is POST body size limit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:16:46.110",
"Id": "501617",
"Score": "0",
"body": "@TR_SLimey sadly, it is a shared host... I'll look into limitations of POST body size and try to think of something. The thing is that since it is mounted in a car, it has to cope with power being cut abruptly at random, which is why I like the approach of preparing then committing. I'm still struggling with Python, dont want to get into making my own servers on top of that :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:24:05.853",
"Id": "501621",
"Score": "1",
"body": "@DamienBourdonneau I see. With the prepare/commit issue, it should be fine since if it's formatted as JSON, the server needs the whole message to start working on it, so there won't be any malformed data, but you could also include a checksum to be sure. As for POST body size, it should be configurable on the server, assuming your host lets you do that. You may want to contact their support and ask, but it should be pretty big by default anyway. Good luck though if you do decide to try it! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:33:08.143",
"Id": "502012",
"Score": "0",
"body": "I've posted a new question with the updated code: https://codereview.stackexchange.com/questions/254555/car-computer-in-python-gps-tracking-version-2"
}
] |
[
{
"body": "<p>There's A LOT going on in your code but I'll try to give you some hints and some suggestions regarding the overall structure/workflow of the code.</p>\n<ul>\n<li>you have really abused the use of <code>global</code>s in your code. Some of them don't even make sense. I'd suggest you try and understand what the use of it is and stop using it unless really needed. For example, the use of <code>global</code> keyword outside a function has no effect (e.g. <code>pending_redraw</code>).</li>\n<li>for setting your fonts, you could easily create a function and a <code>dataclass</code> to stick to the DRY principle:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>FONTS_BASEDIR = '/home/pi/Desktop/fonts/'\n\n\ndef setup_font(font_filename, value):\n return ImageFont.truetype(\n os.path.join(FONTS_BASEDIR, font_filename),\n value\n )\n\n\n@dataclass\nclass Fonts:\n fa_solid = setup_font('fa-solid-900.ttf', 12)\n fa_solid_largest = setup_font('fa-solid-900.ttf', 40)\n text_largest = setup_font('digital-7.ttf', 58)\n text_medium = setup_font('fa-solid-900.ttf', 24)\n text_small = setup_font('fa-solid-900.ttf', 18)\n</code></pre>\n<ul>\n<li>remove the unused imports and try not to duplicate them.</li>\n<li>try to be as clear/accurate as possible in your comments. If I were to believe this: <code>coordinates always: padding-left, padding-top. the first pair of zone is always = start</code> which doesn't seem to be the case for <code>temp_icon_zone</code> and <code>temp_icon_start</code> (<code>(0, 48)</code> != <code>(3, 48)</code>).</li>\n<li>you have a lot of constants which look more like configuration variables. I'd suggest you create a config file to have easier access to all of these. Config variables should also be named using the <code>UPPER_CASE</code> notation. (e.g. <code>temp_zone</code> would be <code>TEMP_ZONE = [(14, 44), (36, 64)]</code> and <code>temp_start</code> would become: <code>TEMP_START = TEMP_ZONE[0]</code>)</li>\n<li>try using <code>os.path.join()</code> instead of <code>current_dir + "/" + oldest_file_name, archive_dir + "/archive_" + oldest_file_name</code> when joining together pieces of a path. (see my example from <code>setup_font</code> function)</li>\n<li>you misspelled <em>committed</em> and <em>committing</em></li>\n<li>here: <code>db = pymysql.connect("XXX", "XXX", "XXX", "XXX")</code> it looks like you're using clear-text credentials. <strong>That's bad practice</strong> and I'd suggest you stop doing that! There are multiple other ways of importing your credentials, one of which would be setting the password as an ENV Variable.</li>\n<li>this:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>if "0.0" in str(nmea.latitude):\n return False\nif "0.0" in str(nmea.longitude):\n return False\n</code></pre>\n<p>can be rewritten as this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if "0.0" in str(nmea.latitude) or "0.0" in str(nmea.longitude):\n return False\n</code></pre>\n<p>or even better:</p>\n<pre class=\"lang-py prettyprint-override\"><code>return "0.0" not in str(nmea.latitude) or "0.0" not in str(nmea.longitude)\n</code></pre>\n<ul>\n<li>here:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>f = open('/sys/bus/w1/devices/28-012032ffbd96/w1_slave', 'r')\nlines = f.readlines()\nf.close()\nequals_pos = lines[1].find(temp_signature)\n</code></pre>\n<p>you only seem to use whatever it's on the second line of that file, so why keep the whole file into memory? Try to break after you reached that very line:</p>\n<pre class=\"lang-py prettyprint-override\"><code>with open('/sys/bus/w1/devices/28-012032ffbd96/w1_slave') as f:\n for i, line in enumerate(f):\n if i == 1:\n equals_pos = line.find(...)\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:24:40.647",
"Id": "501442",
"Score": "0",
"body": "that's great, thanks for the feedback! I'll look into your comments (which all make sense from a first read), implement them and edit/comment when confused or successful!\nAlso, I'm not not sure about threading at the end and on which thread I join - does that look right to you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:27:00.427",
"Id": "501443",
"Score": "4",
"body": "Please don’t edit your code but rather ask a follow-up question instead with the new code to be reviewed. Also, it’s worth allowing 1-2 days until accepting an answer since there might be valuable input still coming from other reviewers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:55:21.560",
"Id": "501456",
"Score": "2",
"body": "`return \"0.0\" not in str(nmea.latitude) or \"0.0\" not in str(nmea.longitude)` does not have the same behavior as the first rewrite because it changes a conditional return to an unconditional return"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:52:19.667",
"Id": "501612",
"Score": "0",
"body": "@GrajdeanuAlex I'm implementing everything atm but I have a few questions: following your advice, I now have an .ini file with different config variables etc. Is that a safe(r) place to store the mysql info? Also, regarding ```TEMP_ZONE = [(14, 44), (36, 64)]```: I have added that to my ini file too but it seems that when I try to use it, it is not seen as a tuple but just some random string and thus the coordinates are not read correctly. Got any tips on that? Have been unsuccessful so far. The rest I've implemented as far as possible!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T20:06:33.707",
"Id": "501625",
"Score": "0",
"body": "\"_Is that a safe(r) place to store the mysql info?_\" -> not quite / it depends. It's usually a common practice to have a `.env` file where you can store these kind of things. You also have to make sure you don't add this `.env` file to git. The parsed configuration (from this env file) is used as a basis for adding environment variables. If you want to keep the data structures and use them in your code, you can use, at any point, any other data type format like a yaml file / json file or even a `config.py`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:33:14.220",
"Id": "502013",
"Score": "0",
"body": "I've posted a new question with the updated code: https://codereview.stackexchange.com/questions/254555/car-computer-in-python-gps-tracking-version-2"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T12:35:05.587",
"Id": "254271",
"ParentId": "254268",
"Score": "15"
}
},
{
"body": "<p>Other minor points:</p>\n<h2>Generators</h2>\n<p>Your generator -</p>\n<pre><code>for line in s:\n yield line.replace('\\0','')\n</code></pre>\n<p>can be simplified to</p>\n<pre><code>return (line.replace('\\0', '') for line in s)\n</code></pre>\n<p>To see what the difference is, we borrow from some techniques in a <a href=\"https://stackoverflow.com/a/39427083/313768\">different answer</a>:</p>\n<pre><code>>>> def f():\n... for c in 'a b':\n... yield c.replace(' ', '')\n\n>>> def g():\n... return (c.replace(' ', '') for c in 'a b')\n\n>>> from inspect import isgeneratorfunction\n>>> from dis import dis\n\n>>> isgeneratorfunction(f)\nTrue\n>>> isgeneratorfunction(g)\nFalse\n\n>>> dis(f)\n 2 0 LOAD_CONST 1 ('a b')\n 2 GET_ITER\n >> 4 FOR_ITER 18 (to 24)\n 6 STORE_FAST 0 (c)\n\n 3 8 LOAD_FAST 0 (c)\n 10 LOAD_METHOD 0 (replace)\n 12 LOAD_CONST 2 (' ')\n 14 LOAD_CONST 3 ('')\n 16 CALL_METHOD 2\n 18 YIELD_VALUE\n 20 POP_TOP\n 22 JUMP_ABSOLUTE 4\n >> 24 LOAD_CONST 0 (None)\n 26 RETURN_VALUE\n\n\n>>> dis(g)\n 2 0 LOAD_CONST 1 (<code object <genexpr> at 0x00000236289E7F50, file "<stdin>", line 2>)\n 2 LOAD_CONST 2 ('g.<locals>.<genexpr>')\n 4 MAKE_FUNCTION 0\n 6 LOAD_CONST 3 ('a b')\n 8 GET_ITER\n 10 CALL_FUNCTION 1\n 12 RETURN_VALUE\n\nDisassembly of <code object <genexpr> at 0x00000236289E7F50, file "<stdin>", line 2>:\n 2 0 LOAD_FAST 0 (.0)\n >> 2 FOR_ITER 18 (to 22)\n 4 STORE_FAST 1 (c)\n 6 LOAD_FAST 1 (c)\n 8 LOAD_METHOD 0 (replace)\n 10 LOAD_CONST 0 (' ')\n 12 LOAD_CONST 1 ('')\n 14 CALL_METHOD 2\n 16 YIELD_VALUE\n 18 POP_TOP\n 20 JUMP_ABSOLUTE 2\n >> 22 LOAD_CONST 2 (None)\n 24 RETURN_VALUE\n</code></pre>\n<p>This demonstrates that writing a <em>generator function</em> does not produce equivalent bytecode to writing a <em>function that returns a generator</em>. The generator function produces bytecode that is shorter, but the generator-returning function has code that's more terse; so in the end it's somewhat of a wash.</p>\n<h2>Paths</h2>\n<p>It's not a good idea to bake <code>/home/pi</code> into your data directory paths. This should be configurable, and/or auto-discovered based on the location of the source. Beyond that, storing your application in a subdirectory of a login user's desktop directory is not a good idea. Do some research on the standard Unix directory layout, which would see your fonts in <code>/usr/share/my_app</code>, your application in <code>/usr/bin</code>, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T18:29:59.420",
"Id": "501461",
"Score": "1",
"body": "How is converting from a generator to a generator expression any simpler? I don't see how moving the for loop from the line above to behind the expression could be called \"simplified\" when all you've done is rearrange the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T18:58:54.450",
"Id": "501465",
"Score": "0",
"body": "@Peilonrayz I don't understand your comment. Knowing how the interpreter differentiates between these two styles is educational."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T19:03:19.990",
"Id": "501467",
"Score": "0",
"body": "My original comment was actually just wrong, due to a typo in the example function. The `yield` style produces simpler bytecode, but the `return` style requires fewer lines of code. In the end it's a judgement call based on context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T06:08:54.330",
"Id": "501504",
"Score": "0",
"body": "@Reinderien is `yield from` best of both worlds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T14:45:03.363",
"Id": "501520",
"Score": "0",
"body": "@GavinS.Yancey It's a stylistic choice, and if performance matters profiling should be done before a decision is made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:44:50.063",
"Id": "501611",
"Score": "0",
"body": "@Reinderien I've tried to take up your feedback on paths but have run in an issue: the script is executed at start via ```systemctl``` and this seems to mess with ```os.getcwd()```. Any suggestion on the auto-discovery part? Can't really figure it out. It works fine when I launch it myself but not on autostart"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:20:13.240",
"Id": "501619",
"Score": "1",
"body": "Autodiscovery isn't strictly necessary if you choose sane paths for your data. You can omit `getcwd` and hard-code a base path for your fonts like `/usr/share/carcomp/fonts`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:33:19.390",
"Id": "502014",
"Score": "0",
"body": "I've posted a new question with the updated code: https://codereview.stackexchange.com/questions/254555/car-computer-in-python-gps-tracking-version-2"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:39:03.673",
"Id": "254281",
"ParentId": "254268",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "254271",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T11:35:12.533",
"Id": "254268",
"Score": "16",
"Tags": [
"python",
"python-3.x",
"raspberry-pi"
],
"Title": "Car computer in python / GPS tracking"
}
|
254268
|
<p>I needed a way to automatically update my IP forwarding rules on Google Domains for my home web server running behind my router. (I'm not paying for a static IP!). After writing a simple functional script for myself, I decided to refactor it to be object oriented and make it work for anyone.</p>
<p>I know you could write a simpler bash script to do something similar, but a) I love Python and wouldn't get past the shebang in bash without a lot of googling, lol, and b) I actually don't think it would be as effective.</p>
<p>It's pretty simple I guess, but I would welcome any feedback/criticism as I'm relatively new to all this.</p>
<pre><code>ipchecker.py
</code></pre>
<pre><code>import base64
import getopt
import logging
import os
import pickle
import smtplib
import sys
from email.errors import MessageError
from email.message import EmailMessage
from getpass import getpass
from itertools import cycle
from requests import get, post
from requests.exceptions import ConnectionError as ReqConError
def get_cwd():
"""Change &/ return working directory depending on OS: for absolute file paths
Cron jobs will have '/' as their working dir by default."""
if os.name == 'nt':
return os.path.dirname(os.path.realpath(__file__))
os.chdir(os.path.dirname(os.path.abspath(__file__)))
return os.getcwd()
FILE_PATH = get_cwd()
USER_PICKLE = '%s/.user' % FILE_PATH
LOG_FILE = '%s/ipchecker.log' % FILE_PATH
logger = logging.getLogger('')
logger.setLevel(logging.INFO)
fh = logging.FileHandler(LOG_FILE)
sh = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('[%(levelname)s]|%(asctime)s|%(message)s',
datefmt='%d %b %Y %H:%M:%S')
fh.setFormatter(formatter)
sh.setFormatter(formatter)
logger.addHandler(sh)
logger.addHandler(fh)
class User:
BASE_URL = '@domains.google.com/nic/update?hostname='
def __init__(self):
"""Create user instance and save it for future changes to API and for email notifications,
or load previous user profile"""
if os.path.isfile(USER_PICKLE):
self.__dict__.update(self.load_user().__dict__)
else:
self.notifications = 'Y'
self.domain, self.DNS_username, self.DNS_password, self.req_url = self.set_credentials()
self.gmail_address, self.gmail_password = self.set_email()
self.save_user()
logging.info('New user created. (See `python3 ipchecker.py --help` for help changing/removing the user)')
def set_credentials(self, update=False):
"""Set/return attributes for Google Domains credentials"""
self.domain = input("What's your domain? (example.com / subdomain.example.com): ")
self.DNS_username = input("What's your autogenerated DNS username?: ")
self.DNS_password = input("What's your autogenerated DNS password?: ")
self.req_url = f'https://{self.DNS_username}:{self.DNS_password}{self.BASE_URL}{self.domain}&myip='
if update:
self.save_user()
return self.domain, self.DNS_username, self.DNS_password, self.req_url
def set_email(self):
"""Set/return attributes for Gmail credentials if user enables notifications"""
self.notifications = input("Enable email notifications? [Y]all(default); [e]errors only; [n]no: ").lower()
if self.notifications != 'n':
self.gmail_address = input("What's your email address?: ")
self.gmail_password = base64.b64encode(getpass("What's your email password?: ").encode("utf-8"))
return self.gmail_address, self.gmail_password
else:
return None, None
def send_notification(self, ip, msg_type='success', error=None):
"""Notify user via email if IP change is made successfully or if API call fails."""
if self.notifications != 'n':
msg = EmailMessage()
if msg_type == 'success' and self.notifications not in ('n', 'e'):
msg.set_content(f'IP for {self.domain} has changed! New IP: {ip}')
msg['Subject'] = 'IP CHANGED SUCCESSFULLY!'
elif msg_type == 'error' and self.notifications != 'n':
msg.set_content(f'IP for {self.domain} has changed but the API call failed ({error})! New IP: {ip}')
msg['Subject'] = 'IP CHANGE FAILED!'
msg['From'] = self.gmail_address
msg['To'] = self.gmail_address
try:
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(self.gmail_address, base64.b64decode(self.gmail_password).decode('utf-8'))
server.send_message(msg)
server.close()
except (MessageError, ConnectionError) as e:
log_msg = 'Email notification not sent: %s' % e
logger.warning(log_msg)
def save_user(self):
with open(USER_PICKLE, 'wb') as pickle_file:
pickle.dump(self, pickle_file)
@staticmethod
def load_user(pickle_file=USER_PICKLE):
with open(pickle_file, 'rb') as user_pickle:
return pickle.load(user_pickle)
@staticmethod
def delete_user():
os.remove(USER_PICKLE)
class IPChanger:
def __init__(self, argv):
"""Check for command line arguments, load User instance,
check previous IP address against current external IP, and change if different."""
opts = []
try:
self.current_ip = get('https://api.ipify.org').text
opts, _args = getopt.getopt(argv,
'cdehnu:',
['credentials',
'delete_user',
'email',
'help',
'notifications',
'user_load='])
except getopt.GetoptError:
print('ipchecker.py -h --help')
sys.exit(2)
except ReqConError:
logger.warning('Connection Error')
sys.exit(5)
finally:
if opts:
for opt, arg in opts:
if opt in ('-h', '--help'):
print(
"""
ipChecker.py help manual (command line options):
``````````````````````````````````````````````````````````````````````````````````````````````````````````
ipchecker.py || -run the script normally without arguments
ipchecker.py -h --help || -show this help manual
ipchecker.py -c --credentials || -change API credentials
ipchecker.py -e --email || -email set up wizard > use to delete email credentials (choose 'n')
ipchecker.py -n --notifications || -toggle email notification settings > will not delete email address
ipchecker.py -d --delete_user || -delete current user profile
ipchecker.py -u path/to/user.file || (or `--user_load user.file`) -load user from file**
|| **this will overwrite any current user profile without warning!
|| **Backup "/.user" file to store multiple profiles.
"""
)
elif opt in ('-c', '--credentials'):
self.user = User()
self.user.set_credentials(update=True)
self.domains_api_call()
logger.info('***API credentials changed***')
elif opt in ('-d', '--delete'):
User.delete_user()
logger.info('***User deleted***')
print('>>>Run the script without options to create a new user, or '
'`ipchecker.py -u path/to/pickle` to load one from file')
elif opt in ('-e', '--email'):
self.user = User()
self.user.set_email()
self.user.save_user()
logger.info('***Notification settings changed***')
elif opt in ('-n', '--notifications'):
n_options = {'Y': '[all changes]', 'e': '[errors only]', 'n': '[none]'}
self.user = User()
options_iter = cycle(n_options.keys())
for option in options_iter:
if self.user.notifications == option:
break
self.user.notifications = next(options_iter)
self.user.save_user()
log_msg = '***Notification settings changed to %s***' % n_options[self.user.notifications]
logger.info(log_msg)
if self.user.notifications in ('Y', 'e') and not self.user.gmail_address:
logger.info('No email user set, running email set up wizard from beginning...')
self.user.set_email()
self.user.save_user()
elif opt in ('-u', '--user_load'):
try:
self.user = User.load_user(pickle_file=arg)
self.user.save_user()
logger.info('***User loaded***')
except FileNotFoundError as e:
logger.warning(e)
sys.exit(2)
sys.exit()
try:
self.user = User()
if self.user.previous_ip == self.current_ip:
log_msg = 'Current IP: %s (no change)' % self.user.previous_ip
logger.info(log_msg)
else:
self.user.previous_ip = self.current_ip
self.domains_api_call()
log_msg = 'Newly recorded IP: %s' % self.user.previous_ip
logger.info(log_msg)
self.user.save_user()
except AttributeError:
setattr(self.user, 'previous_ip', self.current_ip)
self.user.save_user()
self.domains_api_call()
finally:
sys.exit()
def domains_api_call(self):
"""Attempt to change the Dynamic DNS rules via the Google Domains API and handle response codes"""
try:
req = post(f'{self.user.req_url}{self.current_ip}')
response = req.content.decode('utf-8')
log_msg = 'Google Domains API response: %s' % response
logger.info(log_msg)
# Successful request:
if response[:4] == 'good' or response[:5] == 'nochg':
self.user.send_notification(self.current_ip)
# Unsuccessful requests:
elif response == 'nohost' or response == 'notfqdn':
msg = "The hostname does not exist, is not a fully qualified domain" \
" or does not have Dynamic DNS enabled. The script will not be " \
"able to run until you fix this. See https://support.google.com/domains/answer/6147083?hl=en-CA" \
" for API documentation"
logger.warning(msg)
if input("Recreate the API profile? (Y/n):").lower() != 'n':
self.user.set_credentials(update=True)
self.domains_api_call()
else:
self.user.send_notification(self.current_ip, 'error', msg)
else:
logger.warning("Could not authenticate with these credentials")
if input("Recreate the API profile? (Y/n):").lower() != 'n':
self.user.set_credentials(update=True)
self.domains_api_call()
else:
self.user.delete_user()
logger.warning('API authentication failed, user profile deleted')
sys.exit(1)
# Local connection related errors:
except ReqConError as e:
log_msg = 'Connection Error: %s' % e
logger.warning(log_msg)
self.user.send_notification(self.current_ip, 'error', e)
if __name__ == "__main__":
IPChanger(sys.argv[1:])
</code></pre>
<p>Thank you in advance!</p>
<p>The full repository is available <a href="https://github.com/nihilok/ipChecker" rel="nofollow noreferrer">here</a> with <a href="https://github.com/nihilok/ipChecker/blob/master/README.md" rel="nofollow noreferrer">readme</a>.</p>
<p>If you're interested, I also wrote a <a href="https://mjfullstack.medium.com/running-a-home-web-server-without-a-static-ip-using-google-domains-python-saves-the-day-246570b26d88" rel="nofollow noreferrer">blog post</a> on the process of writing the script: <em>spoiler-alert</em>: I tried semi-successfully to do the same thing with Selenium before I figured out the API!</p>
|
[] |
[
{
"body": "<h2>"Current" directory</h2>\n<p>Your <code>get_cwd</code> is problematic for a list of reasons:</p>\n<ul>\n<li>It does <em>not</em> get the current working directory; it <em>sets</em> the current working directory and returns that, which is a surprising side-effect given the method's name</li>\n<li>It's not the current directory you're after; it's the directory of the source code</li>\n<li>Spooky changes based on OS that try to make assumptions about what the current directory was before the method was called</li>\n</ul>\n<p>This needs a serious re-think. It's only being used to initialize <code>FILE_PATH</code>, which in turn is being used as the base directory for <code>USER_PICKLE</code> and <code>LOG_FILE</code>. That reveals another issue: you really should not be putting log and user files next to source code. In a Unix-like directory tree, logs should go in <code>/var/log</code>, and your <code>USER_PICKLE</code> perhaps in <code>/usr/share/my_app</code>. The same vaguely applies in Windows: if your source is in <code>Program Files</code>, log and user files could go in either <code>ProgramData</code> of the root volume or the <code>AppData</code> directory for the service user.</p>\n<p>Once you've chosen sane locations for your files, don't <code>%</code>-format in the base directories; use <code>pathlib</code> - particularly since you want to be portable, this will use the correct slashes.</p>\n<h2>Class caching</h2>\n<p>Reaching for <code>pickle</code> is a good decision. Mashing values into <code>__dict__</code> like this:</p>\n<pre><code> self.__dict__.update(self.load_user().__dict__)\n</code></pre>\n<p>perhaps less so. One consequence is that this will not be compatible with <code>__slots__</code> if you go that route. Consider changing your <code>__init__</code> to <em>always</em> construct a new instance, and keep your <code>load_user</code> as it is.</p>\n<h2>Finally exit?</h2>\n<p>Your <code>finally</code> clauses in <code>IPChanger.__init__</code> are questionable. If I read it correctly, after you <code>exit(5)</code>, you're still going to execute your <code>finally</code> block, which attempts a complete arg parse and application execution. The only thing stopping it would be that <code>opts</code> would have failed to populate.</p>\n<p>This second <code>finally</code>:</p>\n<pre><code> finally:\n sys.exit()\n</code></pre>\n<p>should just be deleted. The only thing I can imagine you intended here is to silence exceptions, but that's not a great idea.</p>\n<p>Delete this:</p>\n<pre><code> opts = []\n</code></pre>\n<p>and your first and second <code>finally</code>. Also consider moving your arg-parsing code into its own function since it's so lengthy.</p>\n<h2>Membership checks</h2>\n<p>Change these:</p>\n<pre><code> elif opt in ('-e', '--email'):\n</code></pre>\n<p>into set literal checks:</p>\n<pre><code> elif opt in {'-e', '--email'}:\n</code></pre>\n<p>Also, use this for response comparison:</p>\n<pre><code>if response in {'nohost', 'notfdqn'}:\n</code></pre>\n<h2>Response parsing</h2>\n<p>I wasn't all that successful in finding documentation on what a response format from this API looks like, but one example I found on a random post (that I don't consider authoritative enough to link to) compares the entire response to "good" / "nochg" instead of a prefix. As such, is the slicing here:</p>\n<pre><code> if response[:4] == 'good' or response[:5] == 'nochg':\n</code></pre>\n<p>actually necessary?</p>\n<p>There are other aspects of your Requests usage that should be improved. You construct this URL:</p>\n<pre><code>f'https://{self.DNS_username}:{self.DNS_password}{self.BASE_URL}{self.domain}&myip='\n \n</code></pre>\n<p>in a method <code>set_credentials</code> that shouldn't include the <code>update</code> feature. It should also not include the <code>&myip</code> suffix.</p>\n<p>Consider instead constructing this URL with <a href=\"https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urlunparse\" rel=\"nofollow noreferrer\"><code>urlunparse</code></a>, rather than string formatting; leaving out the <code>myip</code> parameter, and later passing this as a key in a <code>params</code> dictionary to go to <code>post</code>.</p>\n<p>Additionally, do not <code>response.content.decode</code> yourself, use <code>response.text</code>; and be sure you call <code>raise_for_status</code> to notice whether a call failed.</p>\n<h2>Security</h2>\n<p>This is a big no-no:</p>\n<pre><code>self.DNS_password = input("What's your autogenerated DNS password?: ")\n \n</code></pre>\n<p>It's vulnerable to over-the-shoulder password snooping. Use <a href=\"https://docs.python.org/3/library/getpass.html\" rel=\"nofollow noreferrer\">getpass</a> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T18:10:07.883",
"Id": "501458",
"Score": "0",
"body": "I remember `in` being faster for small hard-coded tuples than hard-coded sets. Not sure if this is still the case for the current version of Python, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T18:56:42.187",
"Id": "501463",
"Score": "0",
"body": "@Graipher AFAIK in Python > 3.2, if you use `set`s the peephole optimiser will replace that with a `frozenset()` object and membership tests against sets are O(1) constant operations. Testing against a tuple is O(n) worst case. Although testing against a set has to calculate the hash (higher constant cost, cached for immutable types), the cost for testing against a tuple other than the first element is always going to be higher. So on average, sets are easily faster even for small hard-coded tuples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T19:29:03.753",
"Id": "501470",
"Score": "1",
"body": "@GrajdeanuAlex Well, the reason I remember was that constructing a (small) tuple is so much faster than constructing a set that it made up for the slower `in`. I'll have to make some timings tomorrow to check if this is (still) the case..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T19:54:47.703",
"Id": "501472",
"Score": "2",
"body": "@Reinderien thank you so much for all this; it's more detailed/useful than I could have hoped for"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:21:03.233",
"Id": "254278",
"ParentId": "254272",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254278",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T13:15:08.250",
"Id": "254272",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"api",
"ip-address"
],
"Title": "Dynamic DNS IP Checker/Changer for Google Domains in Python"
}
|
254272
|
<p>I've been trying to build 3D rendering engine for some time. My main source of knowledge about OpenGL is amazing <a href="http://www.learnopengl.com" rel="nofollow noreferrer">www.learnopengl.com</a> so is my code design heavily inspired by Joe's examples. What I didn't like about his approach - I know educational code is different beast from enterprise solutions - is no connections between shader logic and its implementation.</p>
<p>In the rendering process there are used many shaders, each can differ from each other a lot. Phong shader and particle shader in its logic might have nothing in common. So in my design base class for all Shaders only takes care of OpenGL stuff and serves as utility class (e.x. reading source file for different stages)
ShaderProgram.h</p>
<pre><code>#ifndef ShaderProgram_h
#define ShaderProgram_h
#include "../debuging/Logger.h"
#include "../core/Enum.h"
#pragma warning(push, 0)
#include <glad/glad.h>
#include <glm/glm.hpp>
#pragma warning(pop)
#include <assert.h>
#include <vector>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <optional>
constexpr GLsizei infolog_max_length = 1024;
namespace zephyr::rendering {
class ICamera;
class ShaderProgram {
public:
ShaderProgram(const std::string& name, const std::string& vertex_code, const std::string& fragment_code, const std::string& geometry_code);
ShaderProgram(const ShaderProgram&) = delete;
ShaderProgram& operator=(const ShaderProgram&) = delete;
ShaderProgram(ShaderProgram&&) = delete;
ShaderProgram& operator=(ShaderProgram&&) = delete;
virtual ~ShaderProgram();
void Use() const;
GLuint ID() const { return m_ID.value(); }
const std::string& Name() const { return m_Name; }
virtual void Draw(const ICamera* camera) = 0;
void Uniform(const std::string &name, bool value) const;
void Uniform(const std::string &name, int value) const;
void Uniform(const std::string &name, float value) const;
void Uniform(const std::string &name, const glm::vec2 &vec) const;
void Uniform(const std::string &name, float x, float y) const;
void Uniform(const std::string &name, const glm::vec3 &vec) const;
void Uniform(const std::string &name, float x, float y, float z) const;
void Uniform(const std::string &name, const glm::vec4 &vec) const;
void Uniform(const std::string &name, float x, float y, float z, float w) const;
void Uniform(const std::string &name, const glm::mat2 &mat) const;
void Uniform(const std::string &name, const glm::mat3 &mat) const;
void Uniform(const std::string &name, const glm::mat4 &mat) const;
protected:
std::string ReadShaderFile(const std::string& path);
private:
std::optional<GLuint> m_ID;
std::string m_Name;
void LinkProgram();
std::optional<GLuint> CompileShader(const std::string& code, GLenum shader);
};
}
#endif
</code></pre>
<p>ShaderProgram.cpp</p>
<pre><code>#include "ShaderProgram.h"
zephyr::rendering::ShaderProgram::ShaderProgram(const std::string& name, const std::string& vertex_path, const std::string& fragment_path, const std::string& geometry_path)
: m_Name(name) {
m_ID = glCreateProgram();
auto vertex_shader = CompileShader(vertex_path, GL_VERTEX_SHADER);
auto fragment_shader = CompileShader(fragment_path, GL_FRAGMENT_SHADER);
auto geometry_shader = !geometry_path.empty() ? CompileShader(geometry_path, GL_GEOMETRY_SHADER) : std::nullopt;
assert(vertex_shader.has_value() && fragment_shader.has_value());
LinkProgram();
glDeleteShader(vertex_shader.value());
glDeleteShader(fragment_shader.value());
glDeleteShader(geometry_shader.value_or(0));
}
zephyr::rendering::ShaderProgram::~ShaderProgram() {
glDeleteProgram(m_ID.value());
}
void zephyr::rendering::ShaderProgram::Use() const {
glUseProgram(m_ID.value());
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, bool value) const {
glUniform1i(glGetUniformLocation(m_ID.value(), name.c_str()), (int)value);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, int value) const {
glUniform1i(glGetUniformLocation(m_ID.value(), name.c_str()), value);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, float value) const {
glUniform1f(glGetUniformLocation(m_ID.value(), name.c_str()), value);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, const glm::vec2 &vec) const {
glUniform2fv(glGetUniformLocation(m_ID.value(), name.c_str()), 1, &vec[0]);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, float x, float y) const {
glUniform2f(glGetUniformLocation(m_ID.value(), name.c_str()), x, y);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, const glm::vec3 &vec) const {
glUniform3fv(glGetUniformLocation(m_ID.value(), name.c_str()), 1, &vec[0]);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, float x, float y, float z) const {
glUniform3f(glGetUniformLocation(m_ID.value(), name.c_str()), x, y, z);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, const glm::vec4 &vec) const {
glUniform4fv(glGetUniformLocation(m_ID.value(), name.c_str()), 1, &vec[0]);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, float x, float y, float z, float w) const {
glUniform4f(glGetUniformLocation(m_ID.value(), name.c_str()), x, y, z, w);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, const glm::mat2 &mat) const {
glUniformMatrix2fv(glGetUniformLocation(m_ID.value(), name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, const glm::mat3 &mat) const {
glUniformMatrix3fv(glGetUniformLocation(m_ID.value(), name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
void zephyr::rendering::ShaderProgram::Uniform(const std::string &name, const glm::mat4 &mat) const {
glUniformMatrix4fv(glGetUniformLocation(m_ID.value(), name.c_str()), 1, GL_FALSE, &mat[0][0]);
}
std::string zephyr::rendering::ShaderProgram::ReadShaderFile(const std::string& path) {
std::fstream shader_file;
std::stringstream shader_stream;
shader_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
// Read file
try {
shader_file.open(path);
shader_stream << shader_file.rdbuf();
shader_file.close();
}
catch (const std::ifstream::failure & e) {
ERROR_LOG(Logger::ESender::Rendering, "Failed to read shader file %s:\n%s", path, e.what());
return "";
}
return shader_stream.str();
}
std::optional<GLuint> zephyr::rendering::ShaderProgram::CompileShader(const std::string& code, GLenum shader_type) {
// Compile shader
GLuint shader = glCreateShader(shader_type);
const GLchar* shader_code_ptr = code.c_str();
glShaderSource(shader, 1, &shader_code_ptr, nullptr);
glCompileShader(shader);
// Check compile errors
GLint success;
GLchar info_log[infolog_max_length];
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(shader, infolog_max_length, nullptr, info_log);
ERROR_LOG(Logger::ESender::Rendering, "Failed to compile shader %d:\n%s", shader_type, info_log);
return std::optional<GLuint>();
}
glAttachShader(m_ID.value(), shader);
return shader;
}
void zephyr::rendering::ShaderProgram::LinkProgram() {
glLinkProgram(m_ID.value());
// Check linking errors
GLint success;
GLchar info_log[infolog_max_length];
glGetProgramiv(m_ID.value(), GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(m_ID.value(), infolog_max_length, nullptr, info_log);
ERROR_LOG(Logger::ESender::Rendering, "Failed to link shader %d:\n%s", m_ID.value(), info_log);
}
}
</code></pre>
<p>I've mentioned Phong many times earlier because I think it's a good example of shader with advanced logic. Since this class represent rendering logic behind Phong's it's make sense for it to also define structures that it uses. The most important it's own implementation of Model/Mesh. I really don't like idea of general use Model class that can take any shader and any model data (vertices, normals end others).
Phong.h</p>
<pre><code>#ifndef Phong_h
#define Phong_h
#include "../ShaderProgram.h"
#include "../IDrawable.h"
#pragma warning(push, 0)
#include <glm/glm.hpp>
#pragma warning(pop)
#include <vector>
namespace zephyr::resources {
class Model;
class Mesh;
}
namespace zephyr::rendering {
class Texture;
class IRenderListener;
class Phong : public ShaderProgram {
struct DirectionalLight {
glm::vec3 Direction{ 0.0f };
glm::vec3 Ambient{ 0.0f };
glm::vec3 Diffuse{ 0.0f };
glm::vec3 Specular{ 0.0f };
};
public:
class StaticModel;
Phong();
Phong(const Phong&) = delete;
Phong& operator=(const Phong&) = delete;
Phong(Phong&&) = delete;
Phong& operator=(Phong&&) = delete;
~Phong() = default;
void Draw(const ICamera* camera) override;
void SetDirectionalLight(const glm::vec3& direction, const glm::vec3& ambient, const glm::vec3& diffuse, const glm::vec3& specular);
void Register(StaticModel* static_model);
void Unregister(StaticModel* static_mocel);
private:
std::vector<StaticModel*> m_Drawables;
DirectionalLight m_DirectionalLight;
};
class Phong::StaticModel : public IDrawable {
public:
class StaticMesh {
public:
explicit StaticMesh(const resources::Mesh& raw_StaticMesh);
StaticMesh() = delete;
StaticMesh(const StaticMesh&) = delete;
StaticMesh& operator=(const StaticMesh&) = delete;
StaticMesh(StaticMesh&& other) noexcept;
StaticMesh& operator=(StaticMesh&& other) noexcept;
~StaticMesh();
void Draw(const ShaderProgram& shader) const;
GLuint VAO() const { return m_VAO; }
GLuint VBO() const { return m_VBO; }
GLuint EBO() const { return m_EBO; }
GLsizei IndicesCount() const { return m_IndicesCount; }
const Texture* Diffuse() const { return m_Diffuse.get(); }
const Texture* Specular() const { return m_Specular.get(); }
float Shininess() const { return m_Shininess; }
private:
GLuint m_VAO;
GLuint m_VBO;
GLuint m_EBO;
GLsizei m_IndicesCount;
std::unique_ptr<Texture> m_Diffuse{ nullptr };
std::unique_ptr<Texture> m_Specular{ nullptr };
float m_Shininess;
};
explicit StaticModel(const resources::Model& raw_model);
StaticModel() = delete;
StaticModel(const StaticModel&) = delete;
StaticModel& operator=(const StaticModel&) = delete;
StaticModel(StaticModel&&) = default;
StaticModel& operator=(StaticModel&&) = default;
~StaticModel() = default;
void Draw(const ShaderProgram& shader) const override;
void ModelMatrix(const glm::mat4& matrix_model);
glm::mat4 ModelMatrix() const;
private:
std::vector<StaticModel::StaticMesh> m_StaticMeshes;
glm::mat4 m_Model{0.0f};
};
}
#endif
</code></pre>
<p>Phong.cpp</p>
<pre><code>#include "Phong.h"
#include "../ICamera.h"
#include "../IRenderListener.h"
#include "../Texture.h"
#include "../../resources/Model.h"
#include "../../resources/Mesh.h"
zephyr::rendering::Phong::StaticModel::StaticModel(const resources::Model& raw_model) {
m_StaticMeshes.reserve(raw_model.RawMeshes().size());
for (auto it = raw_model.RawMeshes().begin(); it != raw_model.RawMeshes().end(); it++) {
m_StaticMeshes.emplace_back(*it);
}
}
void zephyr::rendering::Phong::StaticModel::Draw(const ShaderProgram& shader) const {
shader.Uniform("model", m_Model);
for (auto it = m_StaticMeshes.begin(); it != m_StaticMeshes.end(); it++) {
it->Draw(shader);
}
}
void zephyr::rendering::Phong::StaticModel::ModelMatrix(const glm::mat4& matrix_model) {
m_Model = matrix_model;
}
glm::mat4 zephyr::rendering::Phong::StaticModel::ModelMatrix() const {
return m_Model;
}
zephyr::rendering::Phong::StaticModel::StaticMesh::StaticMesh(const resources::Mesh& raw_mesh)
: m_IndicesCount(raw_mesh.Indices().size())
, m_Shininess(static_cast<float>(raw_mesh.Shininess())) {
if (raw_mesh.Diffuse()) {
m_Diffuse = std::make_unique<Texture>(*raw_mesh.Diffuse(), Texture::EType::Diffuse);
}
if (raw_mesh.Specular()) {
m_Specular = std::make_unique<Texture>(*raw_mesh.Specular(), Texture::EType::Specular);
}
glGenVertexArrays(1, &m_VAO);
glGenBuffers(1, &m_VBO);
glGenBuffers(1, &m_EBO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, raw_mesh.Vertices().size() * sizeof(resources::Mesh::Vertex), &raw_mesh.Vertices()[0], GL_STATIC_DRAW);
// Position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(resources::Mesh::Vertex), (void*)0);
glEnableVertexAttribArray(0);
// Normal vectors
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(resources::Mesh::Vertex), (void*)offsetof(resources::Mesh::Vertex, resources::Mesh::Vertex::Normal));
glEnableVertexAttribArray(1);
// Image coords
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(resources::Mesh::Vertex), (void*)offsetof(resources::Mesh::Vertex, resources::Mesh::Vertex::TexCoords));
glEnableVertexAttribArray(2);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_IndicesCount * sizeof(unsigned int), &raw_mesh.Indices()[0], GL_STATIC_DRAW);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
zephyr::rendering::Phong::StaticModel::StaticMesh::StaticMesh(StaticMesh&& other) noexcept
: m_VAO(std::exchange(other.m_VAO, 0))
, m_VBO(std::exchange(other.m_VBO, 0))
, m_EBO(std::exchange(other.m_EBO, 0))
, m_Diffuse(std::move(other.m_Diffuse))
, m_Specular(std::move(other.m_Specular)) {
m_IndicesCount = other.m_IndicesCount;
m_Shininess = other.m_Shininess;
}
zephyr::rendering::Phong::StaticModel::StaticMesh& zephyr::rendering::Phong::StaticModel::StaticMesh::operator=(StaticMesh&& other) noexcept {
m_VAO = std::exchange(other.m_VAO, 0);
m_VBO = std::exchange(other.m_VBO, 0);
m_EBO = std::exchange(other.m_EBO, 0);
m_Diffuse = std::move(other.m_Diffuse);
m_Specular = std::move(other.m_Diffuse);
m_IndicesCount = other.m_IndicesCount;
m_Shininess = other.m_Shininess;
return *this;
}
zephyr::rendering::Phong::StaticModel::StaticMesh::~StaticMesh() {
glDeleteVertexArrays(1, &m_VAO);
glDeleteBuffers(1, &m_VBO);
glDeleteBuffers(1, &m_EBO);
}
void zephyr::rendering::Phong::StaticModel::StaticMesh::Draw(const ShaderProgram& shader) const {
if (m_Diffuse) {
glActiveTexture(GL_TEXTURE0);
shader.Uniform("material.diffuse", 0);
glBindTexture(GL_TEXTURE_2D, m_Diffuse->ID());
}
if (m_Specular) {
glActiveTexture(GL_TEXTURE1);
shader.Uniform("material.specular", 1);
glBindTexture(GL_TEXTURE_2D, m_Specular->ID());
}
shader.Uniform("material.shininess", m_Shininess);
glBindVertexArray(m_VAO);
glDrawElements(GL_TRIANGLES, m_IndicesCount, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
glActiveTexture(GL_TEXTURE0);
}
zephyr::rendering::Phong::Phong()
: ShaderProgram(
"Phong",
ReadShaderFile("../../include/Zephyr3D/rendering/shaders/PhongVert.glsl"),
ReadShaderFile("../../include/Zephyr3D/rendering/shaders/PhongFrag.glsl"),
"") { }
void zephyr::rendering::Phong::Draw(const ICamera* camera) {
glm::mat4 pv = camera->Projection() * camera->View();
Uniform("directionalLight.direction", m_DirectionalLight.Direction);
Uniform("directionalLight.ambient", m_DirectionalLight.Ambient);
Uniform("directionalLight.diffuse", m_DirectionalLight.Diffuse);
Uniform("directionalLight.specular", m_DirectionalLight.Specular);
Uniform("pv", pv);
Uniform("viewPosition", camera->LocalPosition());
for (auto& drawable : m_Drawables) {
auto user_pointer = static_cast<IRenderListener*>(drawable->UserPointer());
user_pointer->OnDrawObject();
drawable->Draw(*this);
}
}
void zephyr::rendering::Phong::SetDirectionalLight(const glm::vec3& direction, const glm::vec3& ambient, const glm::vec3& diffuse, const glm::vec3& specular) {
m_DirectionalLight.Direction = direction;
m_DirectionalLight.Ambient = ambient;
m_DirectionalLight.Diffuse = diffuse;
m_DirectionalLight.Specular = specular;
}
void zephyr::rendering::Phong::Register(StaticModel* static_model) {
assert(std::find(m_Drawables.begin(), m_Drawables.end(), static_model) == m_Drawables.end());
m_Drawables.push_back(static_model);
}
void zephyr::rendering::Phong::Unregister(StaticModel* static_mocel) {
auto to_erase = std::find(m_Drawables.begin(), m_Drawables.end(), static_mocel);
if (to_erase != m_Drawables.end()) {
m_Drawables.erase(to_erase);
}
}
</code></pre>
<p>I've cut some other code from it like PointLight struct as it's almost identical to DirectionalLight which should present design on it's own. And also didn't show some included class but theirs implementation is not important. So my question would be what do you think about architecture as this? I would love to hear your opinion, maybe pros and cons about this approach and possible pitfalls I don't see.</p>
|
[] |
[
{
"body": "<p>Some suggestions re. the <code>ShaderProgram</code> class:</p>\n<ul>\n<li><p>The code reading input from a file shouldn't be inside the <code>ShaderProgram</code> class. We should do that separately and pass in the actual source string.</p>\n</li>\n<li><p>OpenGL shaders programs don't always use one shader source file (or indeed one shader object) for each stage. We often want to use multiple fragment shader objects in a single program.</p>\n<p>(e.g. We might want a file with a bunch of utility constants, e.g. pi. Or for deferred lighting, we want a single fragment shader object to fetch data from the gbuffers, and use that one object in several different lighting-related shader programs.)</p>\n<ul>\n<li><p>... so we might want a constructor taking a <code>std::vector</code> of source strings (and shader types) or shader objects.</p>\n</li>\n<li><p>... and it might be better to write a separate <code>ShaderObject</code> class.</p>\n</li>\n</ul>\n</li>\n<li><p>OpenGL uses <code>0</code> for an invalid shader object / program ID. So we don't really need to use <code>std::optional</code> for the ID.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T15:03:49.757",
"Id": "254275",
"ParentId": "254273",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T14:20:09.873",
"Id": "254273",
"Score": "3",
"Tags": [
"c++"
],
"Title": "OpenGL statically typed shaders"
}
|
254273
|
<p>I have created helper class for configuration validation, the main purpose is to find any human "errors"
in the configuration for the app.</p>
<p>the case is that any type of "message" can be configured in more then one place, the application is ok with that and do no not limit this, in some very rare cases this is needed but for most this will cause problems.</p>
<p>with that said i still would like to prompt the warnings.</p>
<p>In the app config there can be unlimited amount of "managers" that each can hold list of "messages"
there are also two types of them but that is not so important.</p>
<p>This is my draft of the class so far, it works but i feel this is very slow and can be done better or at least i am sure there are places to "fix" a little.</p>
<pre><code>public static class ConfigurationValidator
{
public static void ValidateConfiguration(Configuration configuration)
{
if (configuration != null)
{
try
{
// Create Temp dictionary for validation.
Dictionary<string, List<string>> tempDictionary = new Dictionary<string, List<string>>();
Dictionary<string, List<string>> duplicatesList = new Dictionary<string, List<string>>();
// Fill the temp Dictionary for validation.
foreach (var player in configuration.PlayerManager.Players)
{
List<string> lst = new List<string>(); // list of messages.
for (int i = 0; i < player.Messages.Count; i++)
{
lst.Add(player.Messages[i].Type);
}
tempDictionary.Add(player.PlayerName, lst); // list name + list of messages.
}
FindDuplicates(tempDictionary, ref duplicatesList);
// clear for next set of validation.
tempDictionary.Clear();
foreach (var reciver in configuration.ReceiverManager.Receivers)
{
List<string> lst = new List<string>();
for (int i = 0; i < reciver.Messages.Count; i++)
{
lst.Add(reciver.Messages[i].Type);
}
tempDictionary.Add(reciver.ReceiverName, lst);
}
FindDuplicates(tempDictionary, ref duplicatesList);
PrintDuplicates(duplicatesList);
}
catch (Exception Ex)
{
Log.Instance.Error(Ex.Message, Ex);
}
}
else
{
Log.Instance.Warn($"Cannot validate empty configuration.");
}
}
private static void FindDuplicates(Dictionary<string, List<string>> data, ref Dictionary<string, List<string>> duplicatesList)
{
// find duplicates
var dupes = new HashSet<string>(
from list1 in data.Values
from list2 in data.Values
where list1 != list2
from item in list1.Intersect(list2)
select item);
foreach (var list in data.Values)
{
foreach (var message in dupes)
{
if (list.Contains(message))
{
var listName = data.FirstOrDefault(x => x.Value == list).Key;
List<string> value = (duplicatesList.TryGetValue(message, out List<string> index) ? duplicatesList[message] : null);
if (value == null)
{
duplicatesList.Add(message, new List<string>());
duplicatesList[message].Add(listName);
}
else
{
duplicatesList[message].Add(listName);
}
}
}
}
}
private static void PrintDuplicates(Dictionary<string, List<string>> duplicatesList)
{
if (duplicatesList == null || duplicatesList.Count <= 0)
{
Log.Instance.Info("Configuration validation was OK! no duplicates were found.");
return;
}
Log.Instance.Error($"Configuration validation found duplicate messages in configuration!!!");
Log.Instance.Warn($"This could lead to not accurate recording or playing please fix before using the DDS Recorder.");
foreach (var key in duplicatesList)
{
Log.Instance.Warn($"The Message: [{key.Key}] is duplicated in this lists: ");
foreach (var listName in key.Value)
{
Log.Instance.Warn($" Name: [{listName}]");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T21:49:14.677",
"Id": "501482",
"Score": "0",
"body": "Doesn't `intersect` return a collection of duplicates in a straight forward way? Most of the rest of the code seems superfluous in that case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T13:09:32.007",
"Id": "501516",
"Score": "0",
"body": "Yes you are correct the `intersect` does that and i am using it there but i also needed to know from what \"players\" the duplicate comes from and not only the duplicate itself."
}
] |
[
{
"body": "<p>I'm going to make some assumptions about your code that there is either an interface or base class or they are using the same class for players and receivers. If not I would create an interface so you don't have to duplicate so much code between players and receivers. I'd leave the printing alone with exception of changing parameter to <code>IDictionary<string, IEnumerable<string>></code>.</p>\n<p>Instead of having the ValidateConfiguration create a temp dictionary and then passing it down to use <code>intersect</code> we can do that entire set using Linq in the FindDuplicates and reduce the amount of code. If I'm reading the code correctly in the end you just want to show each "PlayerName" that has the same "Type" as another "PlayerName"</p>\n<pre><code>public static void ValidateConfiguration(Configuration configuration)\n{\n</code></pre>\n<p>// ... omitted code for logging and checking for null config.</p>\n<pre><code> var playerDups = FindDuplicates(configuration.PlayerManager.Players);\n PrintDuplicates(playerDups);\n \n // this assumes receivers and players share the same class. If not they should share a base class or interface \n var receiverDups = FindDuplicates(configuration.PlayerManager.Receiver);\n PrintDuplicates(receiverDups);\n}\n\n\n// todo the parameter should be the common class or base class or interface that is shared between Players and Receivers\nprivate static IDictionary<string, IEnumerable<string>> FindDuplicates(IEnumerable<Player> player)\n{\n // flattern out the messages to be the playername and type \n // Then group messages together\n // filter out the ones that only have one (old code was using intercept)\n // convert to dictionary for easier access (could do ILookup)\n return player.SelectMany(p => p.Messages.Select(m => new\n {\n Type = m.Type,\n PlayerName = p.PlayerName\n }))\n .GroupBy(x => x.Type, x => x.PlayerName)\n .Where(x => x.Count() > 1)\n .ToDictionary(x => x.Key, x => x.AsEnumerable());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T13:16:33.310",
"Id": "501517",
"Score": "0",
"body": "I will defiantly add base class for the player and receiver , it wasn't necessary until now as its only data holder witch is filed from json but with your suggestion its the right approach. also will give a try to the shorter LINQ. and you are very right about the end goal, print any \"player\" and type he has duplicated with another player, thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T04:24:15.313",
"Id": "254298",
"ParentId": "254277",
"Score": "1"
}
},
{
"body": "<p>Some quick remarks:</p>\n<ul>\n<li><p>Invert the <code>if (configuration != null)</code> logic and <code>return;</code> immediately <code>if (configuration == null)</code> (after logging this error). That way your code isn't indented as much and easier to read.</p>\n</li>\n<li><p>Comments should say why, not what. <code>// Create Temp dictionary for validation.</code> is something I should be able to instantly see in your code, if I need a comment to figure this out you need to rewrite your code, not write a comment.</p>\n</li>\n<li><p>Do not call things "List" etc. unless you absolutely need to. Case in point is your code: <code>duplicatesList</code> isn't a list, it is a dictionary. Simply call it <code>duplicates</code>, just like you would do in real life with collections.</p>\n</li>\n<li><p>Do not pointlessly abbreviate. <code>lst</code> isn't clear.</p>\n</li>\n<li><p>The whole <code>foreach (var player in configuration.PlayerManager.Players)</code> block can be expressed in a simple LINQ query, and most certainly the whole logic to construct <code>lst</code>.</p>\n</li>\n<li><p>Beware of spelling errors: <code>reciver</code>.</p>\n</li>\n<li><p>Why does a <code>Receiver</code> have a <code>ReceiverName</code> property? Why not simply <code>Name</code>? (Ditto for <code>Player</code> and <code>PlayerName</code>.)</p>\n</li>\n<li><p>Why is there a <code>try...catch</code> for Exceptions? I don't see anything in your code that could cause exceptions.</p>\n</li>\n<li><p>I'm baffled at <code>(duplicatesList.TryGetValue(message, out List<string> index) ? duplicatesList[message] : null);</code>. Please look up <code>TryGetValue</code> and how it works and how it should be used.</p>\n</li>\n<li><p>Do not "shout" at people, especially not by using multiple exclamation marks ("!!!"). The level of urgency is set by the type of log entry -- Error vs Warn vs Info vs Debug etc. "Configuration validation was OK!" is somehow even worse: this should be a simple statement of fact, not an exclamation of joy.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T13:23:34.533",
"Id": "501518",
"Score": "0",
"body": "While creating this i had some exceptions but you are correct this is not necessary for most part, the TryGetValue i honesty dont know why i did that, thank you for the rest of the comments i will fix the code accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T19:43:46.593",
"Id": "501543",
"Score": "1",
"body": "upvote. After this, the fundamental problem IMO is the (implied) classes' `Player`, `Message`, etc. elements ripped from their objects - such as `Type` - then being iterated to create excessively unnecessary collections that are in turn iterated. `Player.messages`, for example, is already a collection easily referenced where needed. Also for example, if the duplicate collections were of the originating types then I can see a `ToString()` override as more efficient, with temporary collections not required."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T08:36:29.600",
"Id": "254300",
"ParentId": "254277",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254298",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T16:32:45.003",
"Id": "254277",
"Score": "1",
"Tags": [
"c#",
"linq",
"hash-map"
],
"Title": "Finding duplicates in multiple lists for configuration validation"
}
|
254277
|
<p>I reinvented a c++ smart pointer, <code>shared_ptr</code> to be precise. It is meant for practice purpose and does not attempt to replace the standard implementation. To the best of my knowledge, the code works as expected. I decided to skip the custom deleter because I want to keep things simple for now. I would love feedbacks and constructive criticism.</p>
<p>Here is the implementation</p>
<h2>shared.hpp</h2>
<pre><code>#ifndef SHARED_PTR_H_
#define SHARED_PTR_H_
#include <cstddef>
namespace smp
{
template<typename T>
class shared_ptr
{
public:
explicit shared_ptr(T* ptr = nullptr);
~shared_ptr();
shared_ptr(shared_ptr& ptr);
shared_ptr operator=(shared_ptr& ptr);
shared_ptr(shared_ptr&& ptr) noexcept;
shared_ptr operator=(shared_ptr&& ptr) noexcept;
T operator*();
T* operator->() const;
size_t use_count() const;
void reset();
T* get();
bool unique() const;
operator bool() const;
private:
T* obj_ptr;
struct RefCount {
size_t use_count_;
T* object_;
}* ref_cnt;
};
template<typename T>
shared_ptr<T> make_shared(T object);
}
#endif /* SHARED_PTR_H_ */
</code></pre>
<h2>shared.cpp</h2>
<pre><code>#include "shared.hpp"
#include <algorithm>
#include <iostream>
namespace smp
{
template<typename T>
shared_ptr<T>::shared_ptr(T* ptr)
: obj_ptr{ptr}, ref_cnt{new RefCount()}
{
ref_cnt->object_ = ptr;
if(ptr)
++ref_cnt->use_count_;
}
template<typename T>
shared_ptr<T>::shared_ptr(shared_ptr& ptr)
: ref_cnt{new RefCount()}
{
obj_ptr = ptr.obj_ptr;
ref_cnt = ptr.ref_cnt;
++ref_cnt->use_count_;
}
template<typename T>
shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr)
{
obj_ptr = ptr.obj_ptr;
ref_cnt = ptr.ref_cnt;
++ref_cnt->use_count_;
return *this;
}
template<typename T>
shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept
: obj_ptr{nullptr}, ref_cnt{new RefCount()}
{
obj_ptr = std::move(ptr.obj_ptr);
ref_cnt = std::move(ptr.ref_cnt);
ptr.reset();
}
template<typename T>
shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept
{
if(obj_ptr)
reset();
obj_ptr = std::move(ptr.obj_ptr);
ref_cnt = std::move(ptr.ref_cnt);
ptr.obj_ptr = nullptr;
return *this;
}
template<typename T>
shared_ptr<T> make_shared(T object)
{
return shared_ptr<T>(new T{object});
}
template<typename T>
T shared_ptr<T>::operator*()
{
return *obj_ptr;
}
template<typename T>
T* shared_ptr<T>::operator->() const
{
return &*obj_ptr;
}
template<typename T>
size_t shared_ptr<T>::use_count() const
{
return ref_cnt->use_count_;
}
template<typename T>
void shared_ptr<T>::reset()
{
obj_ptr = nullptr;
if(ref_cnt)
--ref_cnt->use_count_;
if(ref_cnt->use_count_ == 0)
ref_cnt->object_->~T();
}
template<typename T>
T* shared_ptr<T>::get()
{
return obj_ptr;
}
template<typename T>
bool shared_ptr<T>::unique() const
{
return (ref_cnt->use_count_ == 1);
}
template<typename T>
shared_ptr<T>::operator bool() const
{
return (obj_ptr != nullptr);
}
template<typename T>
shared_ptr<T>::~shared_ptr()
{
if(obj_ptr)
reset();
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>I am not sure how it works at all as it shouldn't compile. Generic templates require the whole implementation in .hpp/.h files and nothing hidden in .cpp files aside from some possible instantiations.</p>\n</li>\n<li><p>You have a ton of memory leaking due to <code>ref_cnt{new RefCount()}</code> in lots of places.</p>\n</li>\n<li><p>Those are incorrect ways to write copy assignment/operator:</p>\n<pre><code> shared_ptr(shared_ptr& ptr);\n shared_ptr operator=(shared_ptr& ptr);\n</code></pre>\n<p>They should be</p>\n<pre><code> shared_ptr(const shared_ptr& ptr);\n shared_ptr operator=(const shared_ptr& ptr);\n</code></pre>\n</li>\n<li><p>Also, copy-assignment and move-assignment aren't safe for self assignment. E.g., <code>shared_ptr<T> x = ...; x = x;</code> results in a bug.</p>\n</li>\n<li><p><code>make_shared</code> is supposed to obtain a bunch of arguments and construct the object with the parameters. As it is, it can only construct copy-constructible objects and it isn't what people want with it. It supposed to go like this</p>\n<pre><code> template<typename T, typename... Args>\n shared_ptr<T> make_shared(Args&&... args)\n {\n return shared_ptr<T>(new T(std::forwat<Args>(args)...));\n }\n</code></pre>\n<p>also, <code>std::make_shared</code> saves on the extra allocation of the control block by creating the object and the reference counter together.</p>\n</li>\n<li><p>The reference counter class you use <code>RefCount</code> is not thread-safe. The counter is supposed to be atomic. You cannot use this smart pointer in a multi-thread environment safely which is the primary purpose of the <code>std::shared_ptr</code>.</p>\n</li>\n<li><p>I believe both <code>*</code> and <code>-></code> operators are supposed to return <code>T&</code> and not <code>T</code> or <code>T*</code>.</p>\n</li>\n<li><p><code>operator bool()</code> is ought to be <code>explicit</code> else you can made odd comparisons.</p>\n</li>\n<li><p>As it is written following line shouldn't compile <code>shared_ptr<int> x = {};</code> because it has no default constructor and instead it uses <code>explicit shared_ptr(T* ptr = nullptr);</code> which is explicit.</p>\n</li>\n<li><p>You should consider what to do when <code>T</code> is a const object. At times people want to pass <code>shared_ptr<const T></code> to some code because they want to make sure that the object isn't modified.</p>\n</li>\n<li><p>You need some more consideration to the object oriented scenario. Frequently people want to create a <code>Derived</code> class and return <code>shared_ptr<Base></code> and your class has no support for it. Also you have no support for dynamic casting.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T21:33:36.160",
"Id": "501480",
"Score": "1",
"body": "6. I doubt `std::shared_ptr` is primarily for concurrency. Though it is certainly used there too. 7. [Look it up.](//en.cppreference.com/w/cpp/memory/shared_ptr/operator*) He got op* wrong, you got op-> wrong. 9. Shouldn't and does or should but won't? 10. That's a minor aspect of the next point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:24:41.693",
"Id": "501488",
"Score": "0",
"body": "`std::shared_ptr` is not thread safe either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:41:40.607",
"Id": "501489",
"Score": "1",
"body": "@MartinYork `shared_ptr` is thread safe. Like, it doesn't do anything about thread safety of the variable it manages - but the control block is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:49:43.587",
"Id": "501490",
"Score": "0",
"body": "@Deduplicator 6. `shared_ptr` is a big overkill if it isn't used in multithreading environment. 9. Go test on your compiler. Don't have time for it and there is no tester supplied. 10/11. Dealing with class hierarchy is quite different from dealing with classifiers in template classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:50:05.933",
"Id": "501491",
"Score": "0",
"body": "@ALX23z: IS that new in the standard? Can you quote tell me the section in the standard, because I though I read otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:55:47.260",
"Id": "501492",
"Score": "0",
"body": "@MartinYork you wouldn't be able to use `shared_ptr` in multithreaded enviorenment at all if it's control block wasn't thread-safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:03:14.257",
"Id": "501494",
"Score": "0",
"body": "Well, `shared_ptr` is about shared ownership, which is nearly always overkill (often resulting from muddled thinking). Whether the ownership is shared across threads or not. That was a prompt to clarify your post, me knowing (or not?) is not really relevant. One can deal with the qualifiers without hauling out the big guns, but they will deal with the issue thoroughly too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:11:29.683",
"Id": "501496",
"Score": "0",
"body": "@Deduplicator that's the point that when dealing with multithreading it is never clearly known when object is meant to be destroyed. Thus, shared ownership is needed there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:14:25.943",
"Id": "501497",
"Score": "0",
"body": "@ALX23z so it should be easy to quote the standard then (as it is so important)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:31:51.453",
"Id": "501498",
"Score": "0",
"body": "@MartinYork that would be easy if I knew how to navigate standard. Well you can check cppreference on shared_ptr. In implementation notes they wrote a bit about proper atomic synchronisation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:42:30.263",
"Id": "501500",
"Score": "0",
"body": "The standard does not mention threads (I just re-read to check). So there are no guarantees provided by the standard. Specific implementations may provide extra guarantees over the standard (as long as they document them). Cppreferece talks about control blocks (this is a traditional way of implementing the shared pointer but not the only way (a ring of pointers can also be used)). **BUT** the standard does not mention a specific implementation technique (it never does). The standard talks in terms of pre and post conditions of the object. So nothing is mentioned about a control block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:49:47.077",
"Id": "501501",
"Score": "0",
"body": "@MartinYork can you link reference to standard?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T17:32:05.387",
"Id": "501533",
"Score": "0",
"body": "@ALX23z Find reference to standard here: [Where can I find the C++ standard](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents/4653479#4653479) You will find the definition of shared pointer in **20.11.3 Class template shared_ptr [util.smartptr.shared]**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T20:54:41.507",
"Id": "501546",
"Score": "0",
"body": "@MartinYork checked out one of drafts post C++11 for the `std::shared_ptr`. Honestly, it is poorly written as a technical document. But still it implicitly implies that the control block (or however it is implemented) needs to be thread-safe to satisfy the requirements of `std::shared_ptr`. Even if it not explicitly stated one needs to misunderstand and/or twist meaning and intention of the writer to claim otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T22:09:29.783",
"Id": "501547",
"Score": "0",
"body": "@ALX23z As I understand it no STD classes are thread safe (as this adds costs). (Though there are some specific notes on streams about it). C++ is all about not paying for what you don't need. So why should a single threaded application pay the cost (it will never need that security) just so a few users don't have to. It is up to the user of the shared pointer to make sure accesses is thread safe. If you found something that says otherwise I would love to read it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T06:59:26.353",
"Id": "501561",
"Score": "0",
"body": "@MartinYork the very definition implies it: `The shared_ptr class template stores a pointer, usually obtained via new. shared_ptr implements semantics\nof shared ownership; the last remaining owner of the pointer is responsible for destroying the object, or otherwise releasing the resources associated with the stored pointer.` It is not explicitly stated but one cannot even reason whether instance is unique or not without ensuring thread safety. The poor documentation part is lack of explicit definitions and vagueness, e.g., what is \"shared ownership\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T09:17:05.020",
"Id": "501565",
"Score": "0",
"body": "@ALX23z Completely disagree. Not even implied that it is thread safe in that statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T10:20:20.580",
"Id": "501567",
"Score": "0",
"body": "@MartinYork \"last remaining pointer is responsible...\" how would it know if it is last remaining pointer if it weren't thread safe?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T10:45:04.427",
"Id": "501569",
"Score": "0",
"body": "@MartinYork let me give a concrete trivial example. Say you have two threads each having an instance of a shared pointer. Those are the only instances of the shared pointer. When both threads go out of scope - in your opinion - does the definition implies that the pointer's destruction must be called exactly once?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T12:21:49.137",
"Id": "501574",
"Score": "0",
"body": "@MartinYork *the shared pointer instances manage the same pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:01:08.240",
"Id": "501600",
"Score": "0",
"body": "@ALX23z If shared_ptr was thread safe then it would talk about what would happen under **\"data race\"** conditions. It does not so there is no implication (explicit or implied) of it working in a multi threaded environment (just like all other std types (none are thread safe (except those specifically designed mutex/condition_variable/atomic etc...)). `std::shared_ptr` has undefined behavior if a \"Data Race\" happens it is your responsibility to make sure that such a data race does not happen by using the appropriate thread controls (mutex/atomic/condition_variables etc)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:02:30.203",
"Id": "501601",
"Score": "0",
"body": "**does the definition implies that the pointer's destruction must be called exactly once?** Nope. This is undefined behavior as you have let a \"Data Race\" happen. See: Section 6.9.2 Multi-threaded executions and data races [intro.multithread] paragraph 21 => **The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other, except for the special case for signal handlers described below. Any such data race results in undefined behavior.**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:20:33.273",
"Id": "501603",
"Score": "0",
"body": "@MartinYork but it clearly and explicitly states so - definition promises that the destructor is called once. Yet you claim the opposite. It doesn't help your case to state an unrelated part of the standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:22:00.227",
"Id": "501604",
"Score": "0",
"body": "**it gives promise that the destructor is called once** This only holds true if there is no undefined behavior. Rather than us discussing it in comments I have opend a question on SO: https://stackoverflow.com/questions/65584420/stdshared-ptr-thread-safe"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:23:31.057",
"Id": "501605",
"Score": "0",
"body": "@MartinYork but where is undefined behavior? You have two distinct instances of an object that go out of scope from two different threads. How is this undefined behaviour?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:24:06.003",
"Id": "501606",
"Score": "0",
"body": "@ALX23z Its undefined behavior because you have a \"Data Race\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:26:09.220",
"Id": "501607",
"Score": "0",
"body": "@MartinYork but there is no data race because definition of `std::shared_ptr` implies that the destructor is called once. There is nothing about multiple threads invalidating it in any manner. Also the `stdshared-ptr-thread-safe` is a duplicate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:28:13.883",
"Id": "501608",
"Score": "0",
"body": "@ALX23z Make your argument on the linked question. Lets see how many votes you get. The standard never implies things. They are either explicitly defined, undefined behavior or implementation specific."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:33:53.460",
"Id": "501609",
"Score": "0",
"body": "@MartinYork I believe you misunderstand where data races can potentially happen in the standard. They occur when two multiple threads operate on the same object - same memory. This is just the general rule. Of course if explicitly stated function/method can be thread safe. E.g., if same `shared_ptr`'s reference was forwarded to two threads then operating on it causes a data race. However, in the example two threads have different instances of `shared_ptr`. It is just that the instances happen to manage the same object. It is implementation responsibility to ensure safe destruction call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:35:12.190",
"Id": "501610",
"Score": "0",
"body": "@MartinYork and it is explicitly stated in the standard that the destruction call must be done once by the `shared_ptr`. Nothing says that multithreading invalidates it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T15:24:23.573",
"Id": "501694",
"Score": "0",
"body": "There are a lot of comments here, please make sure that if you have any information that should be added to the Answer that you do edit it in. Also please remember that Comments can be deleted at any time, so that anything left in them could be lost at any time."
}
],
"meta_data": {
"CommentCount": "31",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T20:48:38.963",
"Id": "254285",
"ParentId": "254279",
"Score": "4"
}
},
{
"body": "<h2>Overview</h2>\n<p>Templated classes "normally" should provide all the code at the point of usage. As a result you should probably not have a separate shared.cpp. Though some people put the definitions in a separate shared.tpp file that is included by the header file.</p>\n<h2>Code Review:</h2>\n<p>You are missing a constructor for <code>nullptr</code>.</p>\n<p>Though <code>nullptr</code> can be converted to any other type the compiler can not know what type you want in this situation so you would need to be explicit. But it would be nice to allow auto conversion from <code>nullptr</code> to the correct shared pointer type.</p>\n<pre><code> void myFunc(smp::shared_ptr<int>&& ptr) { /* Stuff */}\n\n int main()\n {\n myFunc(nullptr); // This fails.\n // as you defined an explicit constructor.\n // But this is totaly safe so it would be nice if it\n // simply worked rather than forcing the long hand.\n }\n</code></pre>\n<p>So I would add a constructor for this situation.</p>\n<pre><code> smp::shared_ptr::shared_ptr(std::nullptr_t);\n</code></pre>\n<hr />\n<p>Non standard copy constructor and move constructor:</p>\n<pre><code> shared_ptr(shared_ptr& ptr); // Would expect const ref\n shared_ptr operator=(shared_ptr& ptr); // \n</code></pre>\n<p>In the current state these can not catch temporary values.</p>\n<hr />\n<p>Most people forget the <code>noexcept</code>. So well done.</p>\n<pre><code> shared_ptr(shared_ptr&& ptr) noexcept;\n shared_ptr operator=(shared_ptr&& ptr) noexcept;\n</code></pre>\n<hr />\n<p>You should probably return a reference here:</p>\n<pre><code> T operator*();\n</code></pre>\n<p>Otherwise you are going to force a copy of the internal object as it is returned. Just like the <code>operator-></code> this does not affect the state of the shared pointer so this is const.</p>\n<p>In std::shared_ptr this is a noexcept operation. I could personally argue over that. But smarter people than me wrote the standard so I would go with them.</p>\n<pre><code> T& operator*() const noexcept;\n</code></pre>\n<hr />\n<p>Good.\nT* operator->() const;</p>\n<p>But like the <code>operator*</code> can be <code>noexcept</code>.</p>\n<pre><code> T* operator->() const noexcept;\n</code></pre>\n<hr />\n<p>You don't want this accidentally converting in non boolean contexts.</p>\n<pre><code> operator bool() const;\n</code></pre>\n<p>In this situation:</p>\n<pre><code> smp::shared_ptr<int> x(new int{6});\n smp::shared_ptr<float> y(new float{5});\n\n if (x == y) {\n // Because of your bool operator\n // they are converted to bool (for both this is true)\n // resulting in this code saying they are equal.\n std::cout << "Equal\\n";\n }\n</code></pre>\n<p>Use the explicit here:</p>\n<pre><code> explicit operator bool() const;\n</code></pre>\n<hr />\n<p>The issue I have hear is that if the new fails (for RefCount) then you leak the pointer.</p>\n<p>Once you had the pointer to the constructor of a shared pointer you are seeding all responsibility of the pointer. That mean if the object fails to correctly construct you need to make sure the passed pointer is deleted. So in the situation of new failing you need to call delete on the pointer.</p>\n<pre><code>template<typename T>\nshared_ptr<T>::shared_ptr(T* ptr)\n : obj_ptr{ptr}, ref_cnt{new RefCount()}\n{\n ref_cnt->object_ = ptr;\n if(ptr)\n ++ref_cnt->use_count_;\n}\n</code></pre>\n<p>Add a try catch block to the initializer list:</p>\n<pre><code>template<typename T>\nshared_ptr<T>::shared_ptr(T* ptr)\ntry\n : obj_ptr{ptr}\n , ref_cnt{new RefCount()}\n{\n ref_cnt->object_ = ptr;\n if(ptr)\n ++ref_cnt->use_count_;\n}\ncatch(...)\n{\n delete ptr;\n}\n</code></pre>\n<hr />\n<p>If you are copying a <code>shared_ptr</code> then you should be using the same <code>ref_cnt</code> not a brand new one.</p>\n<p>You should prefer to do as much work in the initializer list as possible to prevent multiple initializations.</p>\n<pre><code> shared_ptr<T>::shared_ptr(shared_ptr& ptr)\n : ref_cnt{new RefCount()} \n {\n obj_ptr = ptr.obj_ptr;\n ref_cnt = ptr.ref_cnt;\n\n ++ref_cnt->use_count_;\n }\n</code></pre>\n<p>// Fixed:</p>\n<pre><code> shared_ptr<T>::shared_ptr(shared_ptr& ptr)\n : obj_ptr(ptr.obj_ptr)\n , ref_cnt{ptr.ref_cnt} \n {\n if (obj_ptr) {\n ++ref_cnt->use_count_;\n }\n }\n</code></pre>\n<hr />\n<p>Here you forget to decrement the ref_counter of the previous object (so potentially allowing a leak). I would use the copy and swap idiom to provide the strong exception guarantee (it also covers self assignment).</p>\n<pre><code> template<typename T>\n shared_ptr<T> shared_ptr<T>::operator=(shared_ptr& ptr)\n {\n obj_ptr = ptr.obj_ptr; // Old object potentially leaked.\n ref_cnt = ptr.ref_cnt; // Old ref count potentially leaked.\n ++ref_cnt->use_count_;\n\n return *this;\n }\n</code></pre>\n<hr />\n<p>Again incorrectly increment the counter.</p>\n<pre><code> template<typename T>\n shared_ptr<T>::shared_ptr(shared_ptr&& ptr) noexcept\n : obj_ptr{nullptr}, ref_cnt{new RefCount()}\n {\n obj_ptr = std::move(ptr.obj_ptr);\n ref_cnt = std::move(ptr.ref_cnt);\n\n ptr.reset();\n }\n</code></pre>\n<p>The reset will decrement the counter. Since you have moved the object there has been no decrement.</p>\n<p>Simpler to simply set this one up as null and then swap.</p>\n<hr />\n<p>This can fail.</p>\n<pre><code> template<typename T>\n shared_ptr<T> shared_ptr<T>::operator=(shared_ptr&& ptr) noexcept\n {\n if(obj_ptr)\n reset();\n</code></pre>\n<p>If <code>ptr</code> is the only copy. Then calling reset is going to free the object. Thus any other code is going to now manipulate a freeed object.</p>\n<pre><code> obj_ptr = std::move(ptr.obj_ptr);\n ref_cnt = std::move(ptr.ref_cnt);\n\n\n ptr.obj_ptr = nullptr;\n // If you don't reset the ref count object then\n // eventually `ptr` is going to go out of scope and\n // its destructor is going to mess with the ref count object.\n</code></pre>\n<p>Simpler to simply set this one up as null and then swap.</p>\n<hr />\n<p>Why does the shared object have to be copied constructed?</p>\n<pre><code> template<typename T>\n shared_ptr<T> make_shared(T object)\n {\n return shared_ptr<T>(new T{object});\n }\n</code></pre>\n<p>Would be nive to allow the type <code>T</code> to be constructed using any of its normal constructors that take parameters.</p>\n<pre><code> template<typename T, typename... Args>\n shared_ptr<T> make_shared(Args...&& args)\n {\n // Though this is the simplist way to do it.\n // The standard version tries to make the whole thing more efficient.\n // by allocating the space for the object T and the ref-count\n // in a single allocation (thus removing the need for an extra\n // call to new).\n return shared_ptr<T>(new T{std::forward<Args>(args)...});\n }\n</code></pre>\n<hr />\n<pre><code> template<typename T>\n T* shared_ptr<T>::operator->() const\n {\n return &*obj_ptr; // Not sure why that is rewquired.\n }\n</code></pre>\n<hr />\n<p>This implies you don't keep a reference count object for nullptr. But your object always has a reference counter and you will need to make sure it is updated correctly.</p>\n<pre><code>template<typename T>\nshared_ptr<T>::~shared_ptr()\n{\n if(obj_ptr) // Always call reset.\n // Otherwise you are potentially leaking\n // the reference count object.\n reset();\n}\n</code></pre>\n<hr />\n<p>Which leads us to the reference count object handling. In reset you need to call delete on the object managed and the reference count object if the count reaches zero.</p>\n<pre><code>template<typename T>\nvoid shared_ptr<T>::reset()\n{\n obj_ptr = nullptr;\n\n if(ref_cnt)\n --ref_cnt->use_count_;\n\n if(ref_cnt->use_count_ == 0)\n // This is not correct.\n // You have called the destructor but leaked the object space.\n ref_cnt->object_->~T();\n\n // You need to delete the object and the memory used by the\n // reference count object\n // delete ref_cnt->object_;\n // delete ref_cnt;\n}\n</code></pre>\n<hr />\n<p>Self Plug: Wrote a lot about shared pointers here:</p>\n<p><a href=\"https://lokiastari.com/series/\" rel=\"nofollow noreferrer\">https://lokiastari.com/series/</a></p>\n<p>Read three articles on shared pointers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:11:51.430",
"Id": "254291",
"ParentId": "254279",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254291",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T17:25:32.817",
"Id": "254279",
"Score": "1",
"Tags": [
"c++",
"reinventing-the-wheel",
"template",
"pointers"
],
"Title": "C++ Shared_Ptr implementation"
}
|
254279
|
<p>You are assigned to put some amount of boxes onto one truck. You are given a 2D vector of <code>box_types</code> where box_type[0] is the number of a type of box and box_type[1] is the units per box for that type. You are also given an integer value for the truck size, this the maximum boxes you can put in the truck. Return the maximum unit that can be put in a given truck.</p>
<p>Example</p>
<p>input : box_types = {{1, 3}, {2, 2}, {3, 1}}
truck_size = 4</p>
<p>output: 8</p>
<p>Explanation:</p>
<p>There are</p>
<ul>
<li>1 box of type 0</li>
<li>2 box of type 1</li>
<li>3 box of type 2</li>
</ul>
<p>where 0, 1, 2 is the index of the vector</p>
<p>You can take all the boxes of the first type, second type and one box from the third type</p>
<p>max_unit = (1 * 3) + (2 * 2) + (1 * 1) = 8</p>
<p>Here is my implementation</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <vector>
void sort_boxtypes(std::vector<std::vector<int>> &box_types)
{
std::sort(
box_types.begin(), box_types.end(),
[](const std::vector<int>& a, const std::vector<int> &b)
{return a[1] > b[1]; }
);
}
int maximum_units(std::vector<std::vector<int>> box_types, int truck_size)
{
sort_boxtypes(box_types);
int max_unit = 0;
for(const auto& box_type : box_types)
{
truck_size -= box_type[0];
if(truck_size >= 0)
max_unit += box_type[0] * box_type[1];
else
{
max_unit += (box_type[0] + truck_size) * box_type[1];
return max_unit;
}
}
return max_unit;
}
int main()
{
std::vector<std::vector<int>> box_types = {{5, 10}, {2, 5}, {4, 7}, {3, 9}};
int max = maximum_units(box_types, 10);
std::cout << max << '\n';
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Names are better then indices. Consider</p>\n<pre><code> struct box_type {\n int amount;\n int capacity;\n };\n</code></pre>\n<p><code>box.amount</code> seems cleaner that <code>box[0]</code>.</p>\n</li>\n<li><p>Along the same line, declaring such a structure would let you define</p>\n<pre><code> friend bool box_type::operator <(const box_type& l, const box_type& r) {\n return l.capacity < r.capacity;\n }\n</code></pre>\n<p>and eliminate a lambda, as well as <code>sort_boxtypes</code> function.</p>\n</li>\n<li><p>I don't like <code>max_units</code> (it sounds like there are <code>min_units</code> somewhere). Similarly, <code>truck_size</code> is a <em>truck size</em>, a constant; consider a <code>remaining_size</code> or something like that.</p>\n</li>\n<li><p>It feels that a <code>truck_size >= 0</code> comparison shall be done beforehand. Consider</p>\n<pre><code> std::sort(boxes.begin(), boxes.end());\n for (auto box = boxes.rbegin(); box != boxes.rend(); ++box) {\n auto the_load = std::min(box.amount, remaining_size());\n units += box.capacity * box.amount;\n remaining_size -= the_load;\n if (remaining_size == 0) {\n break;\n }\n }\n return units;\n</code></pre>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:13:59.253",
"Id": "254292",
"ParentId": "254283",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T18:34:46.347",
"Id": "254283",
"Score": "0",
"Tags": [
"c++",
"algorithm"
],
"Title": "C++ Coding Exercise - Maximum unit to load into a truck given it size"
}
|
254283
|
<p>For my CS class I the task given was to take a given Person Class with a name and age attributes.</p>
<p>Then, with an existing list of Person Objects, create a function that returns a tuple of (mean, median, mode) on the given age attribute.</p>
<p>Simple enough, but I wondered if my solution is really all that efficient. I basically iterated a new list of ages from an existing list of Person objects, and that almost feels like there's a better opportunity to optimize a solution...</p>
<p>Wondering if I'm missing something obvious.</p>
<pre><code>from statistics import mean, median, mode
class Person:
def __init__(self, name, age):
"""
initializes a person objects name and age
"""
self._name = name
self._age = age
def get_age(self):
"""
returns the private data member _age
"""
return self._age
def basic_stats(person_list):
"""
creates a list of ages from a list of person objects then calculates
mean, median, and mode from the statistics module
"""
age_list = [i.get_age() for i in person_list]
return (mean(age_list), median(age_list), mode(age_list))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T22:47:36.133",
"Id": "501484",
"Score": "1",
"body": "The iteration is unavoidable and list generators are pretty cheap. Overall, the get_age() attribute seems quite roundabout but OOP is pretty poorly taught so I suspect they're enforcing it and you just have to go with it"
}
] |
[
{
"body": "<p>In terms of performance, to create a list of ages, <code>[i.get_age() for i in person_list]</code> is about as good as you'll get. The only real way to avoid this is to adjust the <code>mean</code>, <code>median</code>, and <code>mode</code> functions to accept a <code>key</code> parameter (much like the built-in <code>sort</code> function does) so that each function will access the correct attribute of the object. I wouldn't worry about removing that list comprehension though. Unless <code>person_list</code> is huge, and you require this code to run often, and as fast as possible, that would be a premature optimization.</p>\n<p>Another way to potentially speed it up would be to have a single function that iterates the list once, and calculates all three statistics in one go. Again though, I would consider that to be premature unless you had a very good reason to optimize that.</p>\n<p>Your solution is fine until you run into a situation in which it isn't performing well. Favor readability and simplicity until performance becomes an actual concern (or you have good reason to believe that it will become an actual concern in the near future).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T00:25:34.350",
"Id": "254293",
"ParentId": "254287",
"Score": "6"
}
},
{
"body": "<p>For efficiency's sake, without breaking the parameters of your assignment, the only other thing you can add is <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__slots__\" rel=\"nofollow noreferrer\"><code>__slots__</code></a>.</p>\n<p>Beyond that - in the "real world" - if this were a truly massive list, you would want to do away with the class representation and instead use a Numpy matrix, for which the calculation of summary statistics will be faster due to vectorization.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T15:59:04.500",
"Id": "254311",
"ParentId": "254287",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254293",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T22:29:46.577",
"Id": "254287",
"Score": "7",
"Tags": [
"python",
"object-oriented"
],
"Title": "Object Attribute Stored in New List from Existing List of Objects"
}
|
254287
|
<p>I made a tree structure (<code>Tree</code>) that represents an algebraic expression that contains two binary opperators the "question mark" <code>Q</code>/<code>"?"</code> and the "exclamation mark" <code>E</code>/<code>"!"</code>.</p>
<p>Both are associative (that means <code>a!(b!c)=(a!b)!c</code>, and the same for the questionmark; this means the order of evaluation doesn't matter and we can omit the parenthesis if we have a chain of the same operator), we do however have no precedence rules, that means we have to use parenthesis if we have a mix of operators: <code>a?b!c</code> would be invalid, it must be <code>(a?b)!c</code> or <code>a?(b!c)</code>.</p>
<p>So now I wanted to make it a <code>Show</code> instance that prints out this expression in one line according to the rules outlined above. For that I wrote some helper functions <code>surroundX</code> that add parenthesis where needed.</p>
<p>So my question is: Is there a way to reduce the duplicated code, especially in the <code>surroundX</code> functions?</p>
<p>I thought that it would be nice to be able to pass <code>E</code> or <code>Q</code> as an additional parameter, but I didn't find a way to make that work. But maybe there are other ways to simplify this.</p>
<pre class="lang-hs prettyprint-override"><code>data Tree = Unit | E Tree Tree | Q Tree Tree
surroundE a@(E _ _) = "(" ++ show a ++ ")"
surroundE x = show x
surroundQ a@(Q _ _) = "(" ++ show a ++ ")"
surroundQ x = show x
instance Show Tree where
show Unit = "1"
show (E a b) = surroundQ a ++ "!" ++ surroundQ b
show (Q a b) = surroundE a ++ "?" ++ surroundE b
--example output
main = do
print $ E (E Unit Unit) (E Unit (Q Unit Unit))
print $ Q (E Unit Unit) (Q Unit (Q Unit Unit))
</code></pre>
<p><a href="https://tio.run/##jZBBDsIgFET3nGIkLmyMCw9gdMMBiLo2X0vSxkobSmMX3r1@qLbVuHBD@MM8ZiCj@mqKoutS8oSDMwYbHG3u8YDq57g8oMdJiLpxrmxsqkC7hcIJp4Q5uZBYLlFn5R0UdjKRE2vLlnjWDqIOvP6L11Ne5Lb2ZC8G@yDEZvfMOCN6R3wBX7iWL4FLEs4hZBIdI2Z95qCe34T@JtSL2H4QigmxWpmWblVhUDa@ary4UW4ZTUuByuXWY87fySVisbAkw8RBo5qMfv3t17/8XfcE" rel="noreferrer" title="Haskell – Try It Online">Try it online!</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T09:07:53.977",
"Id": "501508",
"Score": "3",
"body": "Your code is very concise so there's little room for improvement. That being said I would consider changing the constructors so something like `data Tree = Unit | Subtree Kind Tree Tree`. `Kind` could be the argument for `surround` and produce connecting symbol in `show`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T09:36:55.427",
"Id": "501511",
"Score": "0",
"body": "@bdecaf Thanks for your comment! This change change in the definition of the `Tree` makes it a lot easier to handle, also for other applications one might have. I think your suggestion covers exactly what I was asking for. So please consider adding it as an anwer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T08:06:47.210",
"Id": "501666",
"Score": "0",
"body": "you are most welcome. I don't bother about the points, and as your question is already solved I don't want to put in more research. I'd suggest you post your simplified code and self answer."
}
] |
[
{
"body": "<p>Placing the recursion in show and adding the operator character as an extra parameter simplifies the helper function.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>data Tree = Unit | E Tree Tree | Q Tree Tree\n\ninstance Show Tree where\n show Unit = "1"\n show (E a@(Q _ _) b) = showExp "!" (surround (show a)) (show b)\n show (E a b@(Q _ _)) = showExp "!" (show a) (surround (show b))\n show (E a b) = showExp "!" (show a) (show b)\n show (Q a@(E _ _) b) = showExp "?" (surround (show a)) (show b)\n show (Q a b@(E _ _)) = showExp "?" (show a) (surround (show b))\n show (Q a b) = showExp "?" (show a) (show b)\n\nshowExp op a b = a ++ op ++ b\n\nsurround t = "(" ++ t ++ ")"\n</code></pre>\n<p><a href=\"https://tio.run/##bY9BDoIwFET3/xRj44KGlQcgrjhAox6gSBMasRBoggvuXn@rQKJsJp35r7/TRo8P07Yh1NprXAdjUODmrMeM8uOTzFCbI7Ju9NrdDS5NN30GU2MGQ8AYk7ShgDiJJclKaFSSw2jLVw9xEMjSTMvvoZIrrv7w8x5Oy7jr44X4ZiaQ52xYOGStoggpiOiprWOm7gj9YJ3HkX/J1VLfKHJ13GBL5carX17t8SG8AQ\" rel=\"nofollow noreferrer\" title=\"Haskell – Try It Online\">Try it online!</a></p>\n<p>Edit: Taking into account associativity by pattern matching in show.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:31:53.873",
"Id": "502017",
"Score": "1",
"body": "Thanks for the suggestion. Please do note though that your snippet does not the actually preseve the behaviour of the original one: Yours parenthesizes ALL operators, so for the first example we get `((1!1)!(1!(1?1)))` instead of `1!1!1!(1?1)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T22:56:10.827",
"Id": "254506",
"ParentId": "254288",
"Score": "2"
}
},
{
"body": "<h2>Food for thought:</h2>\n<p>From my (now deleted) comment:\nYour operators are associative, but your data structure is not. Is there a different data representation which is associative?</p>\n<p>I think you want to do more with this tree than just printing it, right?\nThe problem is you want <code>Q Unit (Q Unit Unit)</code> to be equal to <code>Q (Q Unit Unit) Unit</code>. Find a 'canonical' representation!</p>\n<p>Think about an answer or scroll down to find mine. The next steps just set it up.</p>\n<h2>Pulling out the operator?</h2>\n<p>You've already seen this in the comment:</p>\n<pre><code>data Operator = ExclamationMark | QuestionMark\ndata Tree = Unit | BinaryNode Operator Tree Tree\n</code></pre>\n<h2>Type parameters</h2>\n<p>Your example seems to be a minimal working example, but you certainly want your <code>Unit</code> to contain some identifier, e.g. <code>data BinTree a = Leaf a | BinaryNode Operator BinTree BinTree</code>. Do the same with <code>Operator</code> and you've got:</p>\n<pre><code>data BinTree op a = Leaf a | BinaryNode op (BinTree op a) (BinTree op a)\n</code></pre>\n<p>Based on your haskell experience, you might want to write your <code>Functor</code>, <code>Applicative</code>, <code>Monad</code> and <code>Traversable</code> instances.</p>\n<p>The type parameter <code>op</code> can be instantiated with <code>Operator</code>, but maybe also <code>String</code> in the context of (pretty-)printing. Or go further and have a function in place of <code>op</code>:</p>\n<pre><code>evalBinTree :: BinTree (a -> a -> a) a -> a\nevalBinTree (Leaf x) = x\nevalBinTree (BinaryNode f left right) = f (eval left) (eval right) \n</code></pre>\n<p>of course get yourself a function to make these tasks easier:</p>\n<pre><code>mapOp :: (op -> op') -> BinTree op a -> BinTree op' a\n</code></pre>\n<h2>Associativity Hint</h2>\n<p><code>data Binary a = Binary a a</code> is isomorphic to a pair <code>(a,a)</code>, which always contains two <code>a</code>s. What data structure allows you to have an arbitrary number of <code>a</code>s? Next section is some sort of filler to hide the solution.</p>\n<h2>Haskell philosophy</h2>\n<p>Haskell is a functional language. While "functional" puts the emphasis on functions, it is actually data-centric. Defining new data structures and converting between them is easier and more concise than in, say, Java. What I am trying to say here: You can keep the <code>BinTree</code> and the <code>AssocTree</code> of the following section and write functions that transforms one representation to the other.</p>\n<h2>Associativity Solution</h2>\n<p>First a non-parametric data type that allows an arbitrary number of children:</p>\n<pre><code>data AssocTree = Unit | Node [AssocTree]\n</code></pre>\n<p>but I will continue with:</p>\n<pre><code>data AssocTree op a = ALeaf a | ANode op [AssocTree op a]\n</code></pre>\n<p>And left as an exercise, you want a function:</p>\n<pre><code>toAssocTree :: BinTree op a -> AssocTree op a\n</code></pre>\n<p>But <code>toAssocTree</code> cannot collect your associative operators. That needs equality on <code>op</code>:</p>\n<pre><code>collectAssoc :: (Eq op) => AssocTree op a -> AssocTree op a\n</code></pre>\n<p>This way, you divide your computation into little steps.</p>\n<h2>Why turn <code>Operator</code> into a type parameter <code>op</code></h2>\n<p>Here is the reason why I supposed to make the operation a type parameter: With an abstract type, the type system prevents this error:</p>\n<pre><code>data BTree = Unit | E Tree Tree | Q Tree Tree\ndata ATree = AUnit | AE [Tree] | AQ [Tree]\ntoATree (E left right) = AE [left,right]\ntoATree (Q left right) = AE [left,right] -- c&p error: should be AQ, not AE\n</code></pre>\n<p>Yes, abstracting out the type prevents errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T09:06:36.593",
"Id": "502069",
"Score": "0",
"body": "Thanks a lot for your insights! I now do think converting the binary tree to an associative one does make a lot of sense, especially in light of the paragraph you wrote about the data-centricity of Haskell."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T22:16:08.383",
"Id": "254572",
"ParentId": "254288",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T22:58:19.127",
"Id": "254288",
"Score": "5",
"Tags": [
"haskell"
],
"Title": "Parametrize by type constructor?"
}
|
254288
|
<p>I'm working on making a text adventure using Electron. I have the basics of the engine working, you can walk around an infinite map. Maps contain things, and you can enter a few basic commands. I'm wondering if the fundamentals of the game (what I currently have) can be improved at all before I go through adding the game's content.</p>
<p>The code currently supports these commands:</p>
<ol>
<li>look/look around - Prints your location and the contents of the current room</li>
<li>look at - Prints an error (what do you want to look at)</li>
<li>look at [thing] - Prints whether the thing exists where you currently are</li>
<li>north/east/south/west - Moves the player</li>
</ol>
<p>I'm leaving out index.js (the script that starts electron) and the CSS, since it doesn't seem relevant.</p>
<p><strong>index.html</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en-US">
<head>
<title>ProceduralTA</title>
<link rel="stylesheet" href="css/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="log"></div>
<div id="input-prefix">&gt</div>
<div id="input-wrapper">
<form onsubmit="newInput(); return false">
<label>
<input id="input-box" type="text" placeholder="You can type here!" autocomplete="off">
</label>
</form>
</div>
<script src="js/game.js"></script>
<script src="js/input-handler.js"></script>
<script src="js/map.js"></script>
<script src="js/player.js"></script>
<script src="js/room.js"></script>
</body>
</html>
</code></pre>
<p><strong>game.js</strong></p>
<pre><code>'use strict';
const {ipcRenderer} = window.require('electron');
window.$ = window.require('jquery');
const inputBox = $('#input-box');
const log = $('#log');
const charDelay = 10;
const titleMessage = 'Welcome to ProceduralTA!';
const introMessage = 'You are in a room.';
const gameData = {};
async function logMessage(message, type) {
const entry = $('<div></div>').addClass(type).appendTo(log);
for (const char of message) {
if (char === '\n')
entry.append('<br>');
else
entry.append(char);
await new Promise(resolve => setTimeout(resolve, charDelay));
}
}
$(() => {
gameData.map = new GameMap();
gameData.player = new Player();
logMessage(titleMessage, 'msg-system').then();
logMessage(introMessage, 'msg-game').then();
});
</code></pre>
<p><strong>input-handler.js</strong></p>
<pre><code>'use strict';
let input;
let inputArray;
$(() => {
inputBox.trigger('focus');
});
$(window).keypress(() => {
inputBox.trigger('focus');
});
function newInput() {
input = inputBox.val();
inputArray = input.toLowerCase().split(' ');
inputArray = inputArray.filter(word => word !== 'a');
inputArray = inputArray.filter(word => word !== 'an');
inputArray = inputArray.filter(word => word !== 'the');
inputBox.val('');
logMessage('> ' + input, 'msg-player').then();
logMessage(matchInput(), 'msg-game').then();
ipcRenderer.send('saveGame', JSON.parse(JSON.stringify(gameData)));
}
function matchInput() {
const cMap = gameData.map;
const cPlayer = gameData.player;
let response = 'Unknown command.'
if (nextWord('north')) {
cPlayer.y++;
response = 'You move north.';
}
if (nextWord('south')) {
cPlayer.y--;
response = 'You move south.';
}
if (nextWord('east')) {
cPlayer.x++;
response = 'You move east.';
}
if (nextWord('west')) {
cPlayer.x--;
response = 'You move west.';
}
if (!cMap[cPlayer.y]) {
cMap.addRoom(cPlayer.y, cPlayer.x);
} else if (!cMap[cPlayer.y][cPlayer.x]) {
cMap.addRoom(cPlayer.y, cPlayer.x);
}
const cRoom = gameData.map[gameData.player.y][gameData.player.x];
if (nextWord('look')) {
if (nextWord('around') || !wordsLeft())
return 'You are at [' + cPlayer.x + ', ' + cPlayer.y + '].\n' +
'Contents of this room: ' + cRoom.printMonsters();
if (nextWord('at') && !wordsLeft())
return 'What do you want to look at?';
const object = cRoom.printObject(wordsLeft());
if (object)
return object;
else
return 'That doesn\'t exist here.';
}
const object = cRoom.printObject(wordsLeft());
if (object)
return object;
gameData.map = cMap;
gameData.player = cPlayer;
return response;
}
function nextWord(match) {
const word = inputArray[0];
if (word === match)
inputArray.shift();
return word === match;
}
function wordsLeft() {
return inputArray.join(' ');
}
</code></pre>
<p><strong>map.js</strong></p>
<pre><code>'use strict';
function GameMap() {
this.addRoom = (y, x) => {
if (!this[y]) {
this[y] = {};
}
if (!this[y][x]) {
this[y][x] = new Room();
this[y][x].addMonster('Zombie', 10);
this[y][x].addMonster('Skeleton', 5);
}
}
this.addRoom(0, 0);
}
</code></pre>
<p><strong>room.js</strong></p>
<pre><code>'use strict';
function Room() {
this.monsters = [];
this.addMonster = (name, hp) => {
this.monsters.push({
name: name,
hp: hp
});
}
this.printMonsters = () => {
let monsterDescriptions = '';
for (const [index, monster] of this.monsters.entries()) {
monsterDescriptions += `\n${(index + 1)}) ${monster.name} - ${monster.hp} HP`;
}
return monsterDescriptions;
}
this.printObject = name => {
for (const monster of this.monsters) {
if (monster.name.toLowerCase() === name) {
return 'You are looking at: ' + monster.name;
}
}
return false;
}
}
</code></pre>
<p><strong>player.js</strong></p>
<pre><code>'use strict';
function Player() {
this.y = 0;
this.x = 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I like this question.</p>\n<p><strong>Validator stuff</strong></p>\n<ul>\n<li>You probably meant <code>&gt;</code> instead of <code>&gt</code></li>\n<li>You should consider adding a charset meta tag like <code><meta charset="UTF-8"></code></li>\n<li>You should wire <code>newInput(); return false</code> in JavaScript, HTML is not a good home for JS</li>\n<li>You are missing a number of semi colons in <em>room.js</em></li>\n<li>Not strictly validator issues, but using a <code>form</code> for this seems wrong, I would advocate a key press listener on the input box and altogether throw away the form related code</li>\n</ul>\n<p><strong>Possible problems</strong></p>\n<ul>\n<li>I might be missing something but it seems that you might mingle the title and intro message, why not <code>logMessage(titleMessage, 'msg-system').then(logMessage(introMessage, 'msg-game'));</code></li>\n</ul>\n<p><strong>Major Design things</strong></p>\n<ul>\n<li>Avoid globals, or at least keep them to a minimum, the reference to the inputfield, the actual input, the array with the word list, all those things have no place in the global scope</li>\n<li>Read up on MVC, this kind of project would greatly benefit from it</li>\n</ul>\n<p><strong>Minor Design things</strong></p>\n<ul>\n<li><p><code>Map.js</code> should not need to know the hitpoints of a monster, I would capture this in something like <em>bestiary.js</em></p>\n</li>\n<li><p>I would let <code>addMonster</code> return <code>this</code> so that you can chain like <code>'room.addMonster('Zombie').addMonster('Skeleton')</code></p>\n</li>\n<li><p>In fact, I am torn on whether the map should know what monster are there, or the room. I am guessing if one day you go with map themes, it should be the map.</p>\n</li>\n<li><p><code>this.printObject</code> can either return a string or a boolean (false), it should probably always return strings</p>\n</li>\n<li><p>You should not need this;</p>\n<pre><code>gameData.map = cMap;\ngameData.player = cPlayer;\n</code></pre>\n<p>cMap can be considered a 'pointer'</p>\n</li>\n</ul>\n<p><strong>Naming</strong></p>\n<ul>\n<li><code>printMonsters</code> does not print, <code>describeMonsters</code> might be more appropriate</li>\n<li><code>matchInput</code> does way more than matching input (this is also a design problem)</li>\n<li>I am not super excited about the <code>c</code> in <code>cMap</code>, it's not very JS like</li>\n</ul>\n<p><strong>Array functions</strong></p>\n<ul>\n<li><p>Consider using <code>this.monsters.find</code> in <code>printObject</code>, it would be more elegant and equally readable</p>\n</li>\n<li><p><code>printMonsters</code> could be done with a <code>.map()</code> building strings and then a <code>.join('\\n')</code></p>\n</li>\n<li><p>You can filter out words in a shorter and more readable way like this;</p>\n<pre><code> wordList.filter(word => !['a','an','the'].includes(word));\n</code></pre>\n</li>\n<li><p>Direction processing uses very similar code, I tend to group the data in an array with the related data. This becomes even more important once you start supporting non-cardinal directions like northwest or even up/down.</p>\n</li>\n</ul>\n<p><strong>Not right now</strong></p>\n<ul>\n<li>At a later stage you want to encapsulate all the UI stuff with jQUery in like ui.js</li>\n</ul>\n<p>On the whole, this looks well enough structured. This kind of project sometimes lays dormant for months and you don't want to rack your brain when you pick it up again.</p>\n<p>A possible counter-example;\n(Looking forward to see your version 2 with more features btw)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>'use strict';\n\nconst data = {\n titleMessage: 'Welcome to ProceduralTA!',\n introMessage: 'You are in a room.'\n};\n\nconst ui = new (function UI(){\n const inputBox = $('#input-box');\n const log = $('#log');\n const charDelay = 10;\n \n this.logMessage = async function logMessage(message, type) {\n const entry = $('<div></div>').addClass(type).appendTo(log);\n for (const char of message) {\n if (char === '\\n')\n entry.append('<br>');\n else\n entry.append(char);\n await new Promise(resolve => setTimeout(resolve, charDelay));\n }\n }\n \n this.focusOnBox = function focusOnBox(){\n inputBox.trigger('focus');\n }\n \n this.clearBox = function clearBox(){\n inputBox.val('');\n }\n \n this.getBoxValue = function getBoxValue(){\n return inputBox.val();\n }\n \n $(window).keypress((e) => {\n ui.focusOnBox();\n if(e.which == 13){\n processNewInput();\n }\n });\n \n})();\n\n$(() => {\n data.map = new GameMap();\n data.player = new Player();\n ui.logMessage(data.titleMessage, 'msg-system').then(ui.logMessage(data.introMessage, 'msg-game'));\n ui.focusOnBox();\n});\n\nfunction processNewInput() {\n const input = ui.getBoxValue();\n let wordList = input.toLowerCase().split(' ');\n wordList = wordList.filter(word => !['a','an','the'].includes(word));\n ui.clearBox();\n ui.logMessage('> ' + input, 'msg-player').then(ui.logMessage(matchInput(input, wordList), 'msg-game'));\n\n //ipcRenderer.send('saveGame', JSON.parse(JSON.stringify(data)));\n}\n\nfunction matchInput(input, wordList) {\n const map = data.map;\n const player = data.player;\n const movementsMap = {\n north: {response: 'You move north', vector: {y:1, x:0}},\n south: {response: 'You move south', vector: {y:-1, x:0}},\n east: {response: 'You move east', vector: {y:0, x:1}},\n west: {response: 'You move west', vector: {y:0, x:-1}},\n };\n //Default response\n let response = 'Unknown command.'\n const word = wordList.shift();\n\n //Is the player trying to move?\n if(movementsMap[word]){\n const movement = movementsMap[word];\n response = movement.response;\n player.x += movement.vector.x;\n player.y += movement.vector.y;\n //We only need to check this when we move around\n if( !map[player.y] || !map[player.y][player.x]) {\n map.addRoom(player.y, player.x);\n } \n }\n\n const room = map[player.y][player.x];\n\n if (word == 'look') {\n\n if (nextWord(wordList, 'around') || !wordsLeft(wordList))\n return 'You are at [' + player.x + ', ' + player.y + '].\\n' +\n 'Contents of this room: ' + room.printMonsters();\n\n if (nextWord(wordList, 'at') && !wordsLeft(wordList))\n return 'What do you want to look at?';\n\n return room.printObject(wordsLeft(wordList)) || 'That doesn\\'t exist here.';\n }\n\n const object = room.printObject(wordsLeft(wordList));\n return object || response;\n}\n\nfunction nextWord(wordList, match) {\n const word = wordList[0];\n if (word === match)\n wordList.shift();\n return word === match;\n}\n\nfunction wordsLeft(wordList) {\n return wordList.join(' ');\n}\n\nfunction GameMap() {\n this.addRoom = (y, x) => {\n if (!this[y]) {\n this[y] = {};\n }\n if (!this[y][x]) {\n this[y][x] = new Room();\n this[y][x].addMonster('Zombie', 10);\n this[y][x].addMonster('Skeleton', 5);\n }\n }\n\n this.addRoom(0, 0);\n}\n\nfunction Room() {\n this.monsters = [];\n\n this.addMonster = (name, hp) => {\n this.monsters.push({\n name: name,\n hp: hp\n });\n }\n\n this.printMonsters = () => {\n let monsterDescriptions = '';\n for (const [index, monster] of this.monsters.entries()) {\n monsterDescriptions += `\\n${(index + 1)}) ${monster.name} - ${monster.hp} HP`;\n }\n return monsterDescriptions;\n }\n\n this.printObject = name => {\n for (const monster of this.monsters) {\n if (monster.name.toLowerCase() === name) {\n return 'You are looking at: ' + monster.name;\n }\n }\n return false;\n }\n}\n\nfunction Player() {\n this.y = 0;\n this.x = 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js\"></script>\n<!DOCTYPE html>\n<html lang=\"en-US\">\n<head>\n <title>ProceduralTA</title>\n <link rel=\"stylesheet\" href=\"css/styles.css\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n</head>\n<body>\n\n<div id=\"log\"></div>\n<span id=\"input-wrapper\">\n <label>&gt;</label>\n <input id=\"input-box\" type=\"text\" placeholder=\"You can type here!\" autocomplete=\"off\">\n</span>\n\n\n<script src=\"js/game.js\"></script>\n\n<script src=\"js/input-handler.js\"></script>\n<script src=\"js/map.js\"></script>\n<script src=\"js/player.js\"></script>\n<script src=\"js/room.js\"></script>\n\n</body>\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T14:20:35.057",
"Id": "254383",
"ParentId": "254290",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254383",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-03T23:40:48.600",
"Id": "254290",
"Score": "2",
"Tags": [
"javascript",
"game",
"node.js",
"electron"
],
"Title": "Simple text adventure engine built in electron"
}
|
254290
|
<p>I'm on week 2 of learning go. I just completed the golang.org exercise on creating web crawler (<a href="https://tour.golang.org/concurrency/10" rel="nofollow noreferrer">https://tour.golang.org/concurrency/10</a>) and I would please like feedback on my code. It feels overly complicated but I'm a noob so I don't know.</p>
<p>I came across <a href="https://codereview.stackexchange.com/questions/125087/golang-tour-webcrawler-exercise">this post on the same exercies</a> a few minutes ago while writing up this question. The only posted feedback there is one that I already implemented, so I'm hoping to get something different.</p>
<p>I also am not a fan of that implementation because it relies on knowing exactly how many urls will need to be fetched, which works with the fake data but wouldn't work with real data.</p>
<pre class="lang-golang prettyprint-override"><code>type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, err error)
}
type FetchState struct {
sync.Mutex
fetchedUrls map[string]bool
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, state *FetchState) {
if depth <= 0 {
return
}
state.Lock()
if _, ok := state.fetchedUrls[url]; ok {
state.Unlock()
return
}
state.Unlock()
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
state.Lock()
state.fetchedUrls[url] = true
state.Unlock()
var wg sync.WaitGroup
for _, u := range urls {
wg.Add(1)
go func(urlToCrawl string, group *sync.WaitGroup) {
Crawl(urlToCrawl, depth-1, fetcher, state)
group.Done()
}(u, &wg)
}
wg.Wait()
return
}
func main() {
state := &FetchState{
fetchedUrls: make(map[string]bool),
}
Crawl("https://golang.org/", 4, fetcher, state)
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
time.Sleep(1000 * time.Millisecond)
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/cmd/": &fakeResult{
"Package cmd",
[]string{
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
</code></pre>
<ul>
<li>Original Exercise: <a href="https://tour.golang.org/concurrency/10" rel="nofollow noreferrer">https://tour.golang.org/concurrency/10</a></li>
<li>This solution: <a href="https://play.golang.org/p/PKnquXa0D82" rel="nofollow noreferrer">https://play.golang.org/p/PKnquXa0D82</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T03:49:20.307",
"Id": "254295",
"Score": "0",
"Tags": [
"beginner",
"go",
"concurrency"
],
"Title": "2 Weeks into Go: Golang Tour WebCrawler Exercise"
}
|
254295
|
<p><em>The Debounce technique allow us to “group” multiple sequential calls in a single one - The debounce() function forces a function to wait a certain amount of time before running again.</em></p>
<p>I wrote both <code>debounce_1</code> & <code>debounce_2</code> functions while solving a programming challenge, they produce the same result but I want to know which implementation is better and why, as I'm currently studying JavaScript to improve the quality of my code.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* Write a function called 'debounce' that accepts a function and returns a
new function that only allows invocation of the given function after
'interval' milliseconds have passed since the last time the returned
function ran.
Additional calls to the returned function within the 'interval' time
should not be invoked or queued, but the timer should still get reset. */
function debounce_1(callback, interval) {
let lastTime = -Infinity;
return function(){
let now = Date.now(), res;
if (now - lastTime > interval) {
res = callback();
}
lastTime = now;
return res;
}
}
function debounce_2(callback, interval) {
let timeout = null;
return function(){
let res;
if (!timeout) { res = callback(); }
clearInterval(timeout);
timeout = setTimeout(() => timeout = null, interval);
return res;
}
}
/* TESTING */
function hello() { return 'hello'; }
// UNCOMMENT BELOW TO TRY EITHER ONE:
const sayHello = debounce_1(hello, 3000);
// const sayHello = debounce_2(hello, 3000);
console.log( sayHello() ); // -> 'hello'
setTimeout(function() { console.log(sayHello()); }, 2000); // -> undefined
setTimeout(function() { console.log(sayHello()); }, 4000); // -> undefined
setTimeout(function() { console.log(sayHello()); }, 8000); // -> 'hello'</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T06:52:26.360",
"Id": "501732",
"Score": "0",
"body": "One (very minor) advantage to doing math with timestamps is that your debounce function would be more accurate. A setTimeout callback can only fire when the javascript engine isn't currently busy doing something else."
}
] |
[
{
"body": "<p>I think the solution with the timeout variable is far more clear, and avoids arithmetic operations. However, your implementation has some odd behaviours. That is, using debounce with a high frequency will postpone the callback indefinitely.</p>\n<pre><code>const debounce = (func, interval) => {\n let timeout = null;\n return ()=>{\n if (timeout) return undefined;\n timeout = setTimeout( ()=>timeout=null, interval)\n return func();\n }\n}\n</code></pre>\n<p>As an alternative, I propose this. Using this code, the timeout is only set when an actual function call occurs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T15:56:09.243",
"Id": "501528",
"Score": "1",
"body": "Adding `...args` to the returned function as well as the call to `func(...args)` makes this more generally-usable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T06:48:55.240",
"Id": "501731",
"Score": "1",
"body": "Actually, debouncing is supposed to be able to be delayed indefinitely. You might be thinking of throttling. See https://css-tricks.com/debouncing-throttling-explained-examples/"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T07:55:04.027",
"Id": "254299",
"ParentId": "254297",
"Score": "1"
}
},
{
"body": "<p><strong>This isn't quite debouncing</strong>. It's similar, but it's not the same thing, at least not in the way <code>debounce</code> is commonly understood in the programming community. With debouncing, when an event is triggered, the function to run later may be <em>delayed</em> (if the event was triggered recently), but it's never <em>skipped entirely</em>. See <a href=\"https://miro.medium.com/max/700/1*-r8hP_iDBPrj-odjIZajzw.gif\" rel=\"nofollow noreferrer\">here</a> for an animated example of what this looks like.</p>\n<p>To implement a debouncer, I'd either expect the <em>function to run</em> to have all the needed side-effects (for example, to change text on the screen). I wouldn't expect the function to return anything. In the very unusual case that it <em>would</em> return something, I'd expect it to return a Promise that resolves after the next time said function runs. For example, with a debounce time of 3 seconds, I'd expect this:</p>\n<pre><code>sayHello();\nsetTimeout(sayHello, 2000);\nsetTimeout(sayHello, 4000);\nsetTimeout(sayHello, 8000);\n</code></pre>\n<p>to result in the original hello function to run at millisecond 7000, and at millisecond 11000 (since both of those points are when the last call was 3 seconds earlier).</p>\n<p>It's just terminology, but communication is important in programming. (I'd lay the blame for this at the <em>writers of the challenge</em> - you're just implementing the challenge, after all)</p>\n<p><strong>Time management</strong> I strongly agree with the other answer that calculating timestamp differences from each other and from <code>interval</code> mathematically seems much worse than just using <code>setTimeout</code>. The logic is easier to understand at a glance when you just have to clear and set a timeout.</p>\n<p><strong><code>lastTime</code></strong> If you <em>were</em> to calculate timestamp differences, since <code>Date.now()</code> will always return a large positive number, you could consider initializing <code>lastTime</code> just to 0 rather than to -Infinity.</p>\n<p><strong>Interval vs timeout</strong> An interval is not a timeout. While the below <em>just so happens to work</em>, a reader of the code could easily not expect it to:</p>\n<pre><code>clearInterval(timeout);\ntimeout = setTimeout(() => timeout = null, interval);\n</code></pre>\n<p>Use <code>clearTimeout</code> with <code>setTimeout</code> to make things clear.</p>\n<p><strong>This <a href=\"https://codereview.stackexchange.com/revisions/254297/1\">isn't functional programming</a></strong> - functional programming uses, among other things, pure functions (that don't rely on non-argument state). Keeping track of the last function call time or the last timeout requires state. The logic this is implementing is fundamentally stateful and impure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T18:43:10.853",
"Id": "254322",
"ParentId": "254297",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254322",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T03:52:31.073",
"Id": "254297",
"Score": "3",
"Tags": [
"javascript",
"programming-challenge",
"comparative-review"
],
"Title": "Debounce function that limits the rate a callback is triggered. Which implementation is better, and why?"
}
|
254297
|
<p>My pet project, is a <a href="https://bejebeje.com" rel="nofollow noreferrer">community driven lyrics archive</a>, it is still a work in progress, and all code is <a href="https://github.com/JwanKhalaf/Bejebeje" rel="nofollow noreferrer">open sourced on GitHub</a>.</p>
<p>I have a local git branch <code>tests/add-controller-tests</code> where I wish to add some unit tests on my controllers. I have purposefully kept my controllers basic, for example here is my <code>HTTP GET Index</code> action on the <code>HomeController</code>:</p>
<pre><code>namespace Bejebeje.Mvc.Controllers
{
using System.Diagnostics;
using System.Threading.Tasks;
using Bejebeje.Models.Lyric;
using Bejebeje.Services.Services.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Models;
public class HomeController : Controller
{
private readonly IArtistsService _artistsService;
private readonly ILyricsService _lyricsService;
public HomeController(
IArtistsService artistsService,
ILyricsService lyricsService)
{
_artistsService = artistsService;
_lyricsService = lyricsService;
}
public async Task<IActionResult> Index()
{
IndexViewModel viewModel = new IndexViewModel();
viewModel.Lyrics = await _lyricsService
.GetRecentLyricsAsync();
viewModel.FemaleArtists = await _artistsService
.GetTopTenFemaleArtistsByLyricsCountAsync();
return View(viewModel);
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
ErrorViewModel viewModel = new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier,
};
return View(viewModel);
}
}
}
</code></pre>
<p>And here is my unit test (just one):</p>
<pre><code>namespace Bejebeje.Mvc.Tests.Controllers
{
using System.Collections.Generic;
using System.Threading.Tasks;
using Bejebeje.Models.Artist;
using Bejebeje.Models.Lyric;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Mvc.Controllers;
using NUnit.Framework;
using Services.Services.Interfaces;
[TestFixture]
public class HomeControllerTests
{
[Test]
public async Task Index_ReturnsAViewResult_WithAnIndexViewModel()
{
// arrange
IEnumerable<ArtistItemViewModel> tenFemaleArtists = new List<ArtistItemViewModel>
{
new ArtistItemViewModel
{
FirstName = "A1",
LastName = "A1",
ImageAlternateText = "A1",
ImageUrl = "A1",
PrimarySlug = "A1",
},
new ArtistItemViewModel
{
FirstName = "A2",
LastName = "A2",
ImageAlternateText = "A2",
ImageUrl = "A2",
PrimarySlug = "A2",
},
new ArtistItemViewModel
{
FirstName = "A3",
LastName = "A3",
ImageAlternateText = "A3",
ImageUrl = "A3",
PrimarySlug = "A3",
},
new ArtistItemViewModel
{
FirstName = "A4",
LastName = "A4",
ImageAlternateText = "A4",
ImageUrl = "A4",
PrimarySlug = "A4",
},
new ArtistItemViewModel
{
FirstName = "A5",
LastName = "A5",
ImageAlternateText = "A5",
ImageUrl = "A5",
PrimarySlug = "A5",
},
new ArtistItemViewModel
{
FirstName = "A6",
LastName = "A6",
ImageAlternateText = "A6",
ImageUrl = "A6",
PrimarySlug = "A6",
},
new ArtistItemViewModel
{
FirstName = "A7",
LastName = "A7",
ImageAlternateText = "A7",
ImageUrl = "A7",
PrimarySlug = "A7",
},
new ArtistItemViewModel
{
FirstName = "A8",
LastName = "A8",
ImageAlternateText = "A8",
ImageUrl = "A8",
PrimarySlug = "A8",
},
new ArtistItemViewModel
{
FirstName = "A9",
LastName = "A9",
ImageAlternateText = "A9",
ImageUrl = "A9",
PrimarySlug = "A9",
},
new ArtistItemViewModel
{
FirstName = "A10",
LastName = "A10",
ImageAlternateText = "A10",
ImageUrl = "A10",
PrimarySlug = "A10",
}
};
Mock<IArtistsService> mockArtistsService = new Mock<IArtistsService>();
mockArtistsService
.Setup(x => x.GetTopTenFemaleArtistsByLyricsCountAsync())
.ReturnsAsync(tenFemaleArtists);
IEnumerable<LyricItemViewModel> tenRecentLyrics = new List<LyricItemViewModel>
{
new LyricItemViewModel
{
Title = "L1",
LyricPrimarySlug = "L1",
ArtistId = 1,
ArtistName = "L1",
ArtistPrimarySlug = "L1",
ArtistImageUrl = "L1",
ArtistImageAlternateText = "L1",
},
new LyricItemViewModel
{
Title = "L2",
LyricPrimarySlug = "L2",
ArtistId = 2,
ArtistName = "L2",
ArtistPrimarySlug = "L2",
ArtistImageUrl = "L2",
ArtistImageAlternateText = "L2",
},
new LyricItemViewModel
{
Title = "L3",
LyricPrimarySlug = "L3",
ArtistId = 3,
ArtistName = "L3",
ArtistPrimarySlug = "L3",
ArtistImageUrl = "L3",
ArtistImageAlternateText = "L3",
},
new LyricItemViewModel
{
Title = "L4",
LyricPrimarySlug = "L4",
ArtistId = 4,
ArtistName = "L4",
ArtistPrimarySlug = "L4",
ArtistImageUrl = "L4",
ArtistImageAlternateText = "L4",
},
new LyricItemViewModel
{
Title = "L5",
LyricPrimarySlug = "L5",
ArtistId = 5,
ArtistName = "L5",
ArtistPrimarySlug = "L5",
ArtistImageUrl = "L5",
ArtistImageAlternateText = "L5",
},
new LyricItemViewModel
{
Title = "L6",
LyricPrimarySlug = "L6",
ArtistId = 6,
ArtistName = "L6",
ArtistPrimarySlug = "L6",
ArtistImageUrl = "L6",
ArtistImageAlternateText = "L6",
},
new LyricItemViewModel
{
Title = "L7",
LyricPrimarySlug = "L7",
ArtistId = 7,
ArtistName = "L7",
ArtistPrimarySlug = "L7",
ArtistImageUrl = "L7",
ArtistImageAlternateText = "L7",
},
new LyricItemViewModel
{
Title = "L8",
LyricPrimarySlug = "L8",
ArtistId = 8,
ArtistName = "L8",
ArtistPrimarySlug = "L8",
ArtistImageUrl = "L8",
ArtistImageAlternateText = "L8",
},
new LyricItemViewModel
{
Title = "L9",
LyricPrimarySlug = "L9",
ArtistId = 9,
ArtistName = "L9",
ArtistPrimarySlug = "L9",
ArtistImageUrl = "L9",
ArtistImageAlternateText = "L9",
},
new LyricItemViewModel
{
Title = "L10",
LyricPrimarySlug = "L10",
ArtistId = 10,
ArtistName = "L10",
ArtistPrimarySlug = "L10",
ArtistImageUrl = "L10",
ArtistImageAlternateText = "L10",
},
};
Mock<ILyricsService> mockLyricsService = new Mock<ILyricsService>();
mockLyricsService
.Setup(x => x.GetRecentLyricsAsync())
.ReturnsAsync(tenRecentLyrics);
HomeController homeController = new HomeController(mockArtistsService.Object, mockLyricsService.Object);
// act
IActionResult actionResult = await homeController.Index();
// assert
ViewResult view = actionResult.Should().BeOfType<ViewResult>().Subject;
IndexViewModel viewModel = view.Model.Should().BeOfType<IndexViewModel>().Subject;
viewModel.FemaleArtists.Should().HaveCount(10);
viewModel.Lyrics.Should().HaveCount(10);
}
}
}
</code></pre>
<p>As far as tests concenrning the controller, is there anything else that I should test? Also, any other suggestions on naming or making things more readable ...etc</p>
<p>In my test, I can extract the code that builds the lists to a method, is there anything else?</p>
|
[] |
[
{
"body": "<p>First, here are some quick observations about your implementation:</p>\n<ol>\n<li>It does not handle faulty or malfunctioning cases:\n<ul>\n<li>What if one of the services fails?</li>\n<li>What if one of the services responds quite slowly?</li>\n</ul>\n</li>\n<li>It does not take advantage of concurrent async calls\n<ul>\n<li>As I can see the <code>artistsService</code> call does not depend on the previous service call</li>\n<li>You can run them concurrently like this or you can <a href=\"https://www.meziantou.net/get-the-result-of-multiple-tasks-in-a-valuetuple-and-whenall.htm\" rel=\"nofollow noreferrer\">further enhance it</a>:</li>\n</ul>\n</li>\n</ol>\n<pre class=\"lang-cs prettyprint-override\"><code>var recentLyrics =_lyricsService.GetRecentLyricsAsync();\nvar topTenFemailArtists = _artistsService.GetTopTenFemaleArtistsByLyricsCountAsync();\n\nawait Task.WhenAll(recentLyrics, topTenFemailArtists);\n\nviewModel.Lyrics = await recentLyrics;\nviewModel.FemaleArtists = await topTenFemailArtists;\n</code></pre>\n<ol start=\"3\">\n<li>It relies on implicit routing\n<ul>\n<li>Make it explicit via the <code>HttpGetAttribute</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.httpgetattribute\" rel=\"nofollow noreferrer\">1</a>) then you can & should test this aspect as well:</li>\n</ul>\n</li>\n</ol>\n<pre class=\"lang-cs prettyprint-override\"><code>[HttpGet, Route("Home/Index")]\npublic async Task<IActionResult> Index()\n</code></pre>\n<ol start=\"4\">\n<li><code>viewModel</code> is not really good name for your variable.\n<ul>\n<li>It uses <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a> which should be avoided if possible.</li>\n</ul>\n</li>\n<li>Try to separate data retrieval and response creation.\n<ul>\n<li>It could help you a lot during debugging.</li>\n</ul>\n</li>\n</ol>\n<p>Now, let's review your test</p>\n<ol>\n<li>First of all: naming. Please try to use the Given-When-Then structure in order to describe under what circumstances which method how should behave\n<ul>\n<li>In your case, for example: <code>GivenAFlawlessArtists_AndAFlawlessLyricsServices_WhenTheIndexActionIsCalled_ThenItFetchesDataFromTheServices_AndPopulatesTheResponseWithTheResults</code></li>\n<li><strong>Given</strong> a flawless Artists And a flawless Lyrics Services</li>\n<li><strong>When</strong> the Index action is called</li>\n<li><strong>Then</strong> it fetches data from the Services And populates the response with the Results</li>\n<li>It describe what do you except under certain conditions</li>\n</ul>\n</li>\n<li>As you have already mentioned the sample data generation could and should be extracted away.</li>\n<li>The <code>homeController</code> is not a really good name. In general you can name it to <code>SUT</code>. This abbreviates the following: <em>System Under Test</em>.\n<ul>\n<li>It helps the reader of your code to remain focused.</li>\n</ul>\n</li>\n<li>It might make sense to perform deep comparison on your viewmodel as well\n<ul>\n<li>To make sure that the data is not changed / masked / tampered by the\ncontroller's action.</li>\n</ul>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T16:42:25.747",
"Id": "501701",
"Score": "2",
"body": "I agree with a lot of your points, however I don't see the problem with `viewModel`. Hungarian Notation means using the type of a variable in its name, but `viewModel` is just what the variable represents in the context of MVVM. I also think it is perfectly fine to keep the name `homeController` for the tests. `SUT` refers to a system, but unit tests usually test units, hence the term *Unit Under Test* (`UUT`) exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T10:34:14.883",
"Id": "501801",
"Score": "0",
"body": "In terms of handling things going wrong, do I just wrap in a try / catch? and if error, redirect to an error controller/action?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T12:46:29.527",
"Id": "501815",
"Score": "0",
"body": "@J86 As always it depends. Is there anything what you can do in case of failure? For example perform a retry or fallback to another read replica, etc. If your ASP.NET application has been configured with a global error handler then you should not need to try/catch and manually redirect. ASP.NET will do that on your behalf."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T13:58:42.687",
"Id": "501817",
"Score": "0",
"body": "Thanks, I really can't think of anything that would go wrong :/ I mean unless the database connection string is wrong, but there's not much we can do about that"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T12:49:34.630",
"Id": "254303",
"ParentId": "254302",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254303",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T11:33:05.353",
"Id": "254302",
"Score": "0",
"Tags": [
"c#",
"unit-testing",
"asp.net-core"
],
"Title": "Is this enough for unit testing a basic controller?"
}
|
254302
|
<p>you can find the challenge <a href="https://adventofcode.com/2020/day/1" rel="nofollow noreferrer">here</a> for more details, but the subject says it all;</p>
<p>Check a provided list of entries for 2 numbers which sum to 2020, return the product of those addends.</p>
<p>I waited until the event was over to keep things fair.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*This will search for 2 numbers in the `list that sum to `target`
Assumption;
* We only get integers in a string that are new-line separated
* The sum is there, so we dont stop searching even if it doesnt make sense
*/
function findTargetSum(listAsString, target){
const list = entries.split('\n').map(s => s*1);
const set = new Set(list);
for (const i of set) {
if(set.has(target - i)){
return i * (target - i);
}
}
}
function findTargetSum3(listAsString, target){
const list = entries.split('\n').map(s => s*1);
const set = new Set(list);
for (const i of set){
for(const i2 of set){
if(i != i2){
if(set.has(target -i - i2)){
return i * i2 * (target -i - i2);
}
}
}
}
}
const entries = `1780
1693
1830
1756
1858
1868
1968
1809
1996
1962
1800
1974
1805
1795
170
1684
1659
1713
1848
1749
1717
1734
956
1782
1834
1785
1786
1994
1652
1669
1812
1954
1984
1665
1987
1562
2004
2010
1551
961
1854
2005
1883
1965
475
1776
1791
262
1912
1227
1486
1989
1857
825
1683
1991
1875
1982
1654
1767
1673
1973
1886
1731
1745
1770
1995
1721
1662
1679
1783
1999
1889
1746
1902
2003
1698
1794
1798
1951
1953
2007
1899
1658
1705
62
1819
1708
1666
2006
1763
1732
1613
1841
1747
1489
1845
2008
1885
2002
1735
1656
1771
1950
1704
1737
1748
1759
1802
2000
1955
1738
1761
1765
1853
1900
1709
1979
1911
1775
1813
1949
1966
1774
1977
1757
1992
2009
1956
1840
1988
1985
1993
1718
1976
1078
1997
1897
1792
1790
1801
1871
1727
1700
1485
942
1686
1859
1676
802
1952
1998
1961
1844
1808
1703
1980
1766
1963
1849
1670
1716
1957
1660
1816
1762
1829
526
359
2001
1874
1778
1873
1511
1810
1699
1970
1690
1978
1892
1691
1781
1777
1975
1967
1694
1969
1959
1910
1826
1672
1655
1839
1986
1872
1983
1981
1972
1772
1760`;
console.log(findTargetSum(entries, 2020));
console.log(findTargetSum3(entries, 2020));</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Looks mostly fine, though there are a few issues:</p>\n<p><strong>Argument bug/typo</strong> You're referring to top-level variable <code>entries</code> inside the function instead of to the <code>listAsString</code> argument.</p>\n<p><strong>Match numbers?</strong> Even if it's said that the input will contain line-separated numbers, I'd feel safer matching numeric characters instead of splitting by newlines. It'll be more robust if the input happens to not be formatted perfectly correctly, or <em>at least</em> makes the intent (to extract an array of only digit characters from the input) a bit clearer, without relying on the description.</p>\n<p><strong>Maybe use <code>Number</code></strong>? Once you have an array of digit characters, you turn them all into numbers with <code>.map(s => s*1)</code>. I think the intent - to cast to numbers - would be a bit clearer by using <code>.map(Number)</code> instead.</p>\n<p><strong>i</strong> is conventionally used to indicate the <em>index</em> being iterated over. Here, <code>i</code> isn't being used as the index, but as the <em>element</em> being iterated over. Maybe use <code>num</code> instead?</p>\n<p><strong><code>target - i</code></strong> can be saved into a variable instead of repeating it twice, if you want.</p>\n<p><strong>Counting bug</strong> If the target sum happens to be a sum of two of the <em>same number</em>, eg: <code>1010 + 1010</code>, those will be matched even if the input only contains one of those numbers, since you're using a Set which doesn't differentiate one occurrence from multiple.</p>\n<p>To fix this, you could add an index check to the original array if the two numbers happen to be the same (as I've done below), or count up occurrences into an object, or something like that.</p>\n<hr />\n<p>With <code>findTargetSum3</code>, in addition to the above:</p>\n<p><strong>Computational complexity is unnecessarily large</strong> The first approach is <code>O(n)</code>, which is good. This second approach is <code>O(n ^ 2)</code>, since you're checking every element <em>against every other element</em>. I'd ditch <code>findTargetSum3</code> completely.</p>\n<p><strong>Prefer strict equality</strong> over loose equality - yes, the types are surely the same, so it doesn't make a difference in the logic, but strict equality with <code>!==</code> and <code>===</code> is easier to understand at a glance due to the lack of <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">strange coercion rules</a>. Whenever I see sloppy comparison (especially in professional code), I think: "Why isn't strict comparison being used, is there some possible type coercion weirdness going on that wasn't explicit?" Better to be consistent and use strict equality comparison everywhere.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function findTargetSum(listAsString, target){\n const numbers = listAsString.match(/\\d+/g).map(Number);\n const set = new Set(numbers);\n for (const num of set) {\n const otherNum = target - num;\n if (\n set.has(otherNum) &&\n (num !== otherNum || numbers.indexOf(num) !== numbers.lastIndexOf(otherNum))\n ) {\n return num * otherNum;\n }\n }\n}\n\nconst entries = `1780\n1693\n1830\n1756\n1858\n1868\n1968\n1809\n1996\n1962\n1800\n1974\n1805\n1795\n170\n1684\n1659\n1713\n1848\n1749\n1717\n1734\n956\n1782\n1834\n1785\n1786\n1994\n1652\n1669\n1812\n1954\n1984\n1665\n1987\n1562\n2004\n2010\n1551\n961\n1854\n2005\n1883\n1965\n475\n1776\n1791\n262\n1912\n1227\n1486\n1989\n1857\n825\n1683\n1991\n1875\n1982\n1654\n1767\n1673\n1973\n1886\n1731\n1745\n1770\n1995\n1721\n1662\n1679\n1783\n1999\n1889\n1746\n1902\n2003\n1698\n1794\n1798\n1951\n1953\n2007\n1899\n1658\n1705\n62\n1819\n1708\n1666\n2006\n1763\n1732\n1613\n1841\n1747\n1489\n1845\n2008\n1885\n2002\n1735\n1656\n1771\n1950\n1704\n1737\n1748\n1759\n1802\n2000\n1955\n1738\n1761\n1765\n1853\n1900\n1709\n1979\n1911\n1775\n1813\n1949\n1966\n1774\n1977\n1757\n1992\n2009\n1956\n1840\n1988\n1985\n1993\n1718\n1976\n1078\n1997\n1897\n1792\n1790\n1801\n1871\n1727\n1700\n1485\n942\n1686\n1859\n1676\n802\n1952\n1998\n1961\n1844\n1808\n1703\n1980\n1766\n1963\n1849\n1670\n1716\n1957\n1660\n1816\n1762\n1829\n526\n359\n2001\n1874\n1778\n1873\n1511\n1810\n1699\n1970\n1690\n1978\n1892\n1691\n1781\n1777\n1975\n1967\n1694\n1969\n1959\n1910\n1826\n1672\n1655\n1839\n1986\n1872\n1983\n1981\n1972\n1772\n1760`;\nconsole.log(findTargetSum(entries, 2020));\nconsole.log(findTargetSum(`1\n3\n3\n5`, 6));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T15:09:03.767",
"Id": "254309",
"ParentId": "254304",
"Score": "1"
}
},
{
"body": "<h2>Bugs</h2>\n<p>There are 3 bugs, or two depending on input.</p>\n<ol>\n<li><p>Both functions use an undefined variable. <code>entries</code> which should be either <code>listAsString</code> or change the argument <code>listAsString</code> to <code>entries</code></p>\n</li>\n<li><p>The second function does not return the correct values. This function is not at all worth considering because you are iterating the set for each item in the set. Sets use generated hash keys to locate items, they eliminate the need to do this type of search.</p>\n</li>\n<li><p>Will 1010 appear alone in the input list?</p>\n<p>If yes, then your code does not work as it may return <code>1010 * 1010 === 1020100</code> because your search will find the match <code>set.has(target - i)</code>.</p>\n<p>If no, then this is not a bug.</p>\n</li>\n</ol>\n<hr />\n<h2>Review</h2>\n<p>As your question is tagged <em>"programming challenge"</em> this review focuses on performance,</p>\n<h2>Programming challenges</h2>\n<p>The main purpose of programming challenge sites is to provide problems to gain experience programming. The challenge is to complete the task and provide the correct return. Thus the focus is much less on how you write the code and much more about what the code does.</p>\n<p>Apart from the correct return value these sites use performance to rate the code. (I am not a member of linked site so it is unclear if this is true for that site)</p>\n<p>There is no other non subjective metric to rate code apart from code length and as there is no mention of code golf on the site, code length is not being considered in this review.</p>\n<p>One assumes that as you are member you are interested in the rating system and getting the best scores for submissions. Thus an eye for performance will be important in your solutions.</p>\n<h2>Avoid unneeded processing</h2>\n<p>There is no need to create the <code>Set</code> for all numbers before you start testing each number. Adding a number to a <code>Set</code> though not complex is not quick as there is a overhead associated with calculating the hash.</p>\n<p>The same with the conversion of the string into a number. This can also be done while you iterate.</p>\n<h2>Number from a string</h2>\n<p>There are many ways to coerce a string value to a number. The most perform-ant standard way is to use <code>Number("1234")</code>. Though there are special cases where this can be improved (see Rewrite 2)</p>\n<p>It is unclear what type the <code>target</code> value is. If it is a string then you will need to ensure you convert it to a number before you use it inside a loop. Using it as a string inside a loop will mean it is converted to a number each iteration, an unneeded overhead.</p>\n<h2>Best, Average and Worst cases</h2>\n<p>The rewrite (below) is tuned for performance, to ensure that there are no cases where performance is degraded too much, the functions is tested for the best and worst case data sets. Then the final estimate of performance is on a random set of inputs</p>\n<ul>\n<li><p>Average performance. If we assume that the string of numbers has the two values randomly inserted and then test performance over a large number of these random arrays the performance increase of the rewrite is <strong>132% faster</strong>.</p>\n</li>\n<li><p>For worst possible case (values summing to 2020 as last two items in the input list) there is no significant performance gain.</p>\n</li>\n<li><p>For the best case (values are first 2 items in the list) the improvement is a huge, ruining 5200% faster than your original.</p>\n</li>\n</ul>\n<p>If the argument <code>target</code> is a string and you convert it to a number once before the loops you gain another 5% reduction in time to complete.</p>\n<hr />\n<h2>Rewrite 1</h2>\n<p>The rewrite assumes that target is also a string.</p>\n<p>There is no need for long names in functions. The size of the scope dictates the size of the variable name. This is why we have scope. The rewrite uses shorter names.</p>\n<p><code>set</code> is never a good name for a <code>Set</code> name it for what it holds, not what it is.</p>\n<p>Rewrite assumes that 1010 may appear only once in the list. The optimization of adding to the set of <code>values</code> inside the loop will prevent a false positive match for single 1010.</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>function findTargetSum(list, target){\n list = list.split(\"\\n\");\n target = Number(target); // only if target is type string\n const values = new Set();\n for (const str of list) {\n const num = Number(str), val = target - num;\n if (set.has(val)) { return val * (target - val ) }\n set.add(num);\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2>Is there a quicker way?</h2>\n<p>Yes.</p>\n<p>Javascript is bad at handling strings. Assigning a string to a variable requires that the string is copied, which unlike an object, that just needs a reference, the copied string needs iteration as well.</p>\n<p>The line <code>for (const str of list)</code> creates a copy of each string. This can be avoided, in fact all the string copying can be avoided by decoding the numbers using <code>String.charCodeAt</code></p>\n<p>Assuming positive values only in the list the following function is <strong>400% faster</strong> than your first function on a set of random arrays, the second function that includes negative values is <strong>350% faster</strong>.</p>\n<h2>Rewrite 2</h2>\n<p>This rewrite is tightly focused on performance. It avoids the slow <code>string.split</code> by decoding the numbers one character at a time. Each time it encounters a newline (char code 10) it checks the number decoded, exits if values found, or continues.</p>\n<p>As only the characters <code>"0-9"</code> and <code>"\\n"</code> are expected the function can run very fast.</p>\n<p>On a random set of numbers with the two values randomly inserted the following function is 400% faster than your original code.</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>function test(list, target) {\n var i = 0, num = 0;\n const numbers = new Set();\n while (i < list.length) {\n const code = list.charCodeAt(i++) - 48;\n if (code === -38) {\n if (numbers.has(target - num)) { return num * (target - num) }\n numbers.add(num);\n num = list.charCodeAt(i++) - 48;\n } else { num = num * 10 + code }\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Negatives</h3>\n<p>The input set may contain negative values some numbers will have a <code>"-"</code> (code 45) to avoid too much overhead the test for negative need only be done once per number. As the list does not contain to new lines in a row we know that after a new line is either a "-" or digit "0"-"9".</p>\n<p>As the check for negative bites into that parts of the code that give the above function its performance advantage the following function on a random set of numbers is 350% faster. Still a significant performance increase.</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>function test(list, target) {\n var i = 0, code = list.charCodeAt(i++);\n var num = code === 45 ? -(list.charCodeAt(i++) - 48) : code - 48;\n const numbers = new Set();\n while (i < list.length) {\n code = list.charCodeAt(i++) - 48;\n if (code === -38) {\n if (numbers.has(target - num)) { return num * (target - num) }\n numbers.add(num);\n code = list.charCodeAt(i++);\n num = code === 45 ? -(list.charCodeAt(i++) - 48) : code - 48;\n } else { num = num * 10 + code }\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>One could make the negative test a function, but this could reduce performance, because in-lining the function will only happen after the JS optimizer has seen the function run many times. For a small set of runs < ~100 the optimizer will not get a chance to do its magic.</p>\n<p>Including constants rather than magic numbers</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>function test(list, target) {\n const CHAR_0 = 48, CHAR_NEWLINE_SUB_0 = -38, CHAR_NEG = 45;\n const startNumber = () => [\n const code = list.charCodeAt(i++);\n return code === CHAR_NEG ? -(list.charCodeAt(i++) - CHAR_0) : code - CHAR_0;\n }\n var i = 0, num = startNumber();\n const numbers = new Set();\n while (i < list.length) {\n const code = list.charCodeAt(i++) - CHAR_0;\n if (code === CHAR_NEWLINE_SUB_0 ) {\n if (numbers.has(target - num)) { return num * (target - num) }\n numbers.add(num);\n num = startNumber();\n } else { num = num * 10 + code }\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h3>Notes</h3>\n<ul>\n<li><p>All code run on Chrome 87 Win x64.</p>\n</li>\n<li><p>Code used your original data as posted moving the matching values from top to bottom of list to determine best and worst cases.</p>\n</li>\n<li><p>The second rewrite used a similar input set of number (3 - 4) characters long. It is unclear what size ints the inputs could be. Performance for rewrite2 will be effected more by long numbers than the first (or your original)</p>\n</li>\n<li><p>The random data sets were created as follows. (two version on positive only values)</p>\n</li>\n</ul>\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 SUM = 2020;\n const LENGTH = 200;\n const MIN = 900;\n const MAX = 4000;\n const POSITIVE = true;\n function createTestData() {\n const a = $setOf(LENGTH, () => $randI(MIN, MAX));\n var find = true;\n while (find) {\n v = a[$randI(LENGTH)];\n if (v < SUM || !POSITIVE) {\n a.splice($randI(LENGTH), 0, SUM - v)\n break;\n }\n }\n return [a.join(\"\\n\"), SUM];\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n<h2>Performance matters</h2>\n<p>In the real world performance is very important.</p>\n<p>CPU cycles have a cost.</p>\n<ul>\n<li><p>For server based code, this cost is literal, power, infrastructure.</p>\n</li>\n<li><p>For client based code, it is more subtle as performance equates to quality, low quality apps drain batteries and appears sluggish, which in a competitive market will reduce uptake and ultimately be born as a cost of lost clients.</p>\n</li>\n<li><p>Client costs. Code running on the client will use their power, reducing battery life, and costing them money. Perform-ant code is considerate code.</p>\n</li>\n<li><p>Social and ethical responsibilities. Every CPU cycle will generate some CO<sub>2</sub>, collectively even small performance gains can make big reductions in CO<sub>2</sub> output. Increasing device life reduces waste.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T14:09:34.373",
"Id": "254344",
"ParentId": "254304",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254344",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T13:57:02.953",
"Id": "254304",
"Score": "1",
"Tags": [
"javascript",
"programming-challenge"
],
"Title": "Advent Of Code 2020, day 1, find desired sum and multiply the addends"
}
|
254304
|
<p>I need to sort a list of strings that I'm reading in but the sorted order of that list is not predetermined (I can't hard code it); I read in the sort order from a source and build a comparator by assigning a numerical value to each entry in a map and then use that to determine the order.</p>
<p>My implementation is pretty simple and straightforward. I don't know if there is any room to optimize this but given that sorting is generally a slow process in itself, I wanted to submit this for code review in case there are in fact any improvements to be made.</p>
<p>The custom comparator will be cached after creation so I won't be building a new one unless required to do so.</p>
<pre><code>import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class RunTest {
// Runnable test
public static void main(String[] args) {
CustomComparator comparator = CustomComparator.fromList(getSortOrder());
List<String> list1 = getTestList();
System.out.println("Test list: \n " + list1);
Collections.sort(list1, comparator);
System.out.println("Test list (sorted): \n " + list1);
}
// Comparator
public static class CustomComparator implements Comparator<String> {
private Map<String, Integer> _sortOrder;
public CustomComparator(Map<String, Integer> sortOrder) {
_sortOrder = sortOrder;
}
@Override
public int compare(String l, String r) {
Integer lvalue = _sortOrder.get(l);
Integer rvalue = _sortOrder.get(r);
if (lvalue == null || rvalue == null)
return 0;
if (lvalue < rvalue)
return -1;
return 1;
}
public static CustomComparator fromList(List<String> sortOrder) {
// Map each list item to a comparable integer
Map<String, Integer> customSortOrder = new HashMap<>();
int i = 0;
for (String s : sortOrder)
customSortOrder.put(s, i++);
return new CustomComparator(customSortOrder);
}
}
// Custom sort order
public static List<String> getSortOrder() {
List<String> customSortOrder = new LinkedList<>();
customSortOrder.add("c");
customSortOrder.add("b");
customSortOrder.add("a");
return customSortOrder;
}
// Test list
public static List<String> getTestList() {
List<String> randomList = new LinkedList<>();
randomList.add("b");
randomList.add("a");
randomList.add("c");
return randomList;
}
}
</code></pre>
<p>Output:</p>
<pre>
Test list:
[b, a, c]
Test list (sorted):
[c, b, a]
</pre>
|
[] |
[
{
"body": "<p>This:</p>\n<pre><code> if (lvalue == null || rvalue == null)\n return 0;\n</code></pre>\n<p>doesn't seem very safe. It says that if <em>either</em> of the values does not have a defined order, then don't care about the order, consider them equivalent. This will have the effect of interleaving such items throughout your sorted list.</p>\n<p>Technically this fails the requirement of <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html\" rel=\"nofollow noreferrer\">Comparator</a> that</p>\n<blockquote>\n<p>The implementor must also ensure that the relation is transitive</p>\n</blockquote>\n<p>In other words, given some strings <code>a</code>, <code>b</code> and <code>c</code> with ordering indices 1, <code>null</code> and 2, your existing implementation will say that <code>a</code> == <code>b</code>, <code>b</code> == <code>c</code> but <code>a</code> != <code>c</code> - this is non-transitive.</p>\n<p>Instead: either throw an exception if there is a value with an undefined order; or choose to default undefined-order values at the beginning or end of the list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T15:06:56.020",
"Id": "254308",
"ParentId": "254306",
"Score": "3"
}
},
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>// Runnable test\n</code></pre>\n<p><a href=\"https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html\" rel=\"nofollow noreferrer\">Javadoc</a></p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private Map<String, Integer> _sortOrder;\n</code></pre>\n<p>The Java convention does not use underscores to mark fields or members. You'd use the name and then prefix it with <code>this.</code> as needed. Obviously, that's still up to you what you use.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private Map<String, Integer> _sortOrder;\n \n public CustomComparator(Map<String, Integer> sortOrder) {\n _sortOrder = sortOrder;\n }\n</code></pre>\n<p>That allows <code>_sortOrder</code> to be changed from outside the class during runtime, mind you.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public int compare(String l, String r) {\n Integer lvalue = _sortOrder.get(l);\n Integer rvalue = _sortOrder.get(r);\n</code></pre>\n<p>Don't shorten names just because you can! Shortened names only lead to less readable and less maintainable code.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if (lvalue < rvalue)\n return -1;\n \n return 1;\n</code></pre>\n<p>That's incorrect, as far as I can see. If both values match you're returning <code>1</code>, which is not correct and might lead to an endless loop depending on how the sorting algorithm works. <code>Comparator</code>s are supposed to return <code>-1/0/1</code>, but all implementations are compelled/supposed to also accept <code>-n/0/n</code>. SO you can simply subtract both values and return the result:</p>\n<pre class=\"lang-java prettyprint-override\"><code>return lvalue.intValue() - rvalue.intValue();\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> int i = 0;\n \n for (String s : sortOrder)\n customSortOrder.put(s, i++);\n</code></pre>\n<p>Be aware of <a href=\"https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html\" rel=\"nofollow noreferrer\">Autoboxing</a>.</p>\n<p>And again, don't shorten names.</p>\n<pre class=\"lang-java prettyprint-override\"><code> int value = 0;\n \n for (String item : sortOrder) {\n customSortOrderMap.put(item, Integer.valueOf(value++));\n }\n</code></pre>\n<p>Whether or not you use braces for single lines, is again up to you, it's advised against, though.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>List<String> customSortOrder = new LinkedList<>();\n</code></pre>\n<p>By default you'd be using an <code>ArrayList</code>, as it is the cheapest implementation when it comes to various operations, that include adding and removing.</p>\n<hr />\n<p>There's not much else to say about the actual logic, as far as I can see it should work.</p>\n<p>Using a <code>Map</code> as intermediate object might not be the nicest choice. Instead, you could allow to modify the <code>Comparator</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class ValueBasedComparator implements Comparator<String> {\n private Map<String, Integer> values = new HashMap<>();\n \n public ValueBasedComparator addValue(String item, int value) {\n values.put(item, Integer.valueOf(value));\n }\n}\n</code></pre>\n<p>Also, I believe you could use generics to make the class generic:</p>\n<pre class=\"lang-java prettyprint-override\"><code> public static class CustomComparator<ITEM_TYPE> implements Comparator<ITEM_TYPE> {\n private Map<ITEM_TYPE, Integer> _sortOrder;\n\n @Override\n public int compare(ITEM_TYPE first, ITEM_TYPE second) {\n</code></pre>\n<p>But there might be an edge-case not allowing that, have not tested it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T18:47:00.720",
"Id": "254323",
"ParentId": "254306",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T14:34:56.523",
"Id": "254306",
"Score": "3",
"Tags": [
"java",
"sorting"
],
"Title": "Sorting a list but the sort order isn't known until runtime"
}
|
254306
|
<p>I'm solving <a href="https://projecteuler.net/problem=7" rel="nofollow noreferrer">Euler exercise number 7</a> and trying to go a bit further on bigger primes.
It is too slow with big numbers. I've been reading ways to optimize the sieve, but I would like to ask people with more experience with this.</p>
<pre><code>import time
from math import log, ceil
start = time.time()
primes = [2]
op_count = 0
limitN = 0
pr_count = 0
def primes_goto(prime_index):
global primes
global op_count
global limitN
global pr_count
if prime_index < 6:
limitN = 100
else:
limitN = ceil(prime_index * (log(prime_index) + log(log(prime_index)))) #bound
not_prime = set()
while pr_count < prime_index:
for i in range(3, limitN, 2):
if i in not_prime:
continue
for j in range(i*3, limitN, i*2):
not_prime.add(j)
primes.append(i)
pr_count += 1
return primes
ind = int(10001)
primes_goto(ind)
ind_prime = primes[ind-1]
end = time.time()
print("Prime number at posizion: {} = {}".format(ind, ind_prime))
print("Runtime: {}".format(end-start))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T01:36:44.080",
"Id": "501550",
"Score": "1",
"body": "What big numbers have you tried and what is the expected performance? By the way, 1 is not prime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T08:22:21.093",
"Id": "501562",
"Score": "0",
"body": "https://projecteuler.net/problem=7"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T08:23:03.810",
"Id": "501563",
"Score": "0",
"body": "I've tried to calculate the 1000000 prime number, and it took 5 seconds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T10:20:26.963",
"Id": "501568",
"Score": "0",
"body": "Python is very slow, if you care about optimised performance you would write in C/C++, which is roughly 20x-100x faster than python."
}
] |
[
{
"body": "<p>You can make this part a bit faster:</p>\n<pre><code> for j in range(i*3, limitN, i*2):\n not_prime.add(j)\n</code></pre>\n<p>Better start at <code>i*i</code>, and better don't do your own loop. So it becomes:</p>\n<pre><code> not_prime.update(range(i*i, limitN, i*2))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T11:31:28.720",
"Id": "254340",
"ParentId": "254317",
"Score": "1"
}
},
{
"body": "<p>You can use <code>bitarray</code>, this tends to be a little faster.</p>\n<p>The code using <code>bitarray</code> is</p>\n<pre><code>from bitarray import bitarray\nimport time \nfrom math import sqrt, ceil, log\n\ndef primes_goto2(index: int):\n prime_up_to = ceil(index * (log(index) + log(log(index)))) + 4\n primes = bitarray(prime_up_to)\n primes.setall(True)\n primes[0] = primes[1] = False\n primes[4::2] = False\n for i in range(3, int(sqrt(prime_up_to)), 2):\n if primes[i]:\n primes[i * i::i] = False\n \n prime_list = [i for i in range(len(primes)) if primes[i]]\n return prime_list[index]\n</code></pre>\n<p>Time taken for <code>1000000</code> (NOTE: my index does not require index - 1, so in order to get same value as me you have to use <code>1000001</code>)</p>\n<pre><code>index = 1000000\nt0 = time.perf_counter()\nprime_number = primes_goto2(index)\nt1 = time.perf_counter()\n\nprint("Prime number at position: {} = {}".format(index, prime_number))\nprint("Runtime: {}".format(t1-t0))\n</code></pre>\n<p>Output:</p>\n<pre><code>Prime number at position: 1000000 = 15485867\nRuntime: 1.888874288000011\n</code></pre>\n<p>Which is very much better than yours.</p>\n<p>I also noticed, yours consumes a lot of memory, running <code>1000001</code> ate up all my free memory(6gb)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:10:47.820",
"Id": "501615",
"Score": "1",
"body": "You should use `isqrt()` instead of `int(sqrt())`, especially for large numbers, where floating point accuracy will corrupt the result. You've got an off-by-one error, since range is half-open. You want `isqrt(prime_up_to)+1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:13:13.847",
"Id": "501616",
"Score": "1",
"body": "Using `2*i` for step will increase your speed: `primes[i*i::2*i] = False`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T17:03:24.033",
"Id": "501702",
"Score": "0",
"body": "this solution, with suggestions implemented, took only 0.76 secs, which is dramatically better than mine"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T17:51:14.230",
"Id": "254350",
"ParentId": "254317",
"Score": "1"
}
},
{
"body": "<h1>Unused variables</h1>\n<p><code>op_count</code> is declared in the global scope, pulled into the <code>primes_goto</code> local scope, but is never used. It may be deleted.</p>\n<h1>Unnecessary Globals</h1>\n<p><code>limitN</code> and <code>pr_count</code> are declared in the global scope, but only ever used inside the <code>primes_goto</code> function. They may be removed from the global scope, and simply declared inside the <code>primes_goto</code> function.</p>\n<h1>Unused Return</h1>\n<p>The <code>primes_goto</code> function ends with <code>return primes</code>, but the returned value is not assigned to anything.</p>\n<p>One way to fix this would be to remove the <code>return primes</code> statement.</p>\n<p>A better way would be to move the <code>primes = [2]</code> initialization inside the <code>primes_goto</code> function, and remove <code>global primes</code> declaration. Then, return this local result, and assign the result to a variable in the caller’s context. Ie)</p>\n<p><code>primes = primes_goto(ind)</code></p>\n<h1>Unnecessary cast</h1>\n<p><code>ind = int(10001)</code></p>\n<p>The value <code>10001</code> is already an integer; there is no need to “cast” it.</p>\n<h1>Organization</h1>\n<p>Python programs should follow the following organization:</p>\n<ul>\n<li>imports</li>\n<li>function & class declarations</li>\n<li>mainline</li>\n</ul>\n<p>The initialization of variables should be moved from before <code>primes_goto</code> to after all function declarations.</p>\n<h1>Profiling</h1>\n<p><code>time.time()</code> has limited resolution, due to it expressing the time from an epoch decades in the past, in factions of a second. <code>time.perf_counter()</code> expresses time from an arbitrary epoch to the highest resolution available, making it ideal for measuring time intervals.</p>\n<h1>Reworked code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>import time\nfrom math import log, ceil\n\ndef primes_goto(prime_index):\n\n primes = [2]\n pr_count = 0\n\n if prime_index < 6:\n limitN = 100\n else:\n limitN = ceil(prime_index * (log(prime_index) + log(log(prime_index)))) #bound\n\n not_prime = set()\n\n while pr_count < prime_index:\n for i in range(3, limitN, 2):\n if i in not_prime:\n continue\n\n for j in range(i*3, limitN, i*2):\n not_prime.add(j)\n\n primes.append(i)\n pr_count += 1\n\n return primes\n\n\nstart = time.perf_counter()\n\nind = 10001\nprimes_goto(ind)\nind_prime = primes[ind-1]\n\nend = time.perf_counter()\n\nprint("Prime number at position: {} = {}".format(ind, ind_prime))\nprint("Runtime: {}".format(end-start))\n</code></pre>\n<h1>Optimization</h1>\n<h2>bitarray</h2>\n<p>As pointed out in other reviews, <code>bitarray</code> can be efficiently used to store the sieve flags, and <code>i*i</code> is a better starting point for crossing off prime candidates due to all smaller multiples already being eliminated as multiples of smaller primes.</p>\n<h2>Avoid unnecessary work</h2>\n<p>Again, as pointed out in other answers: marking off primes candidates as <code>3*i</code> (or <code>i*i</code>) is pointless once <code>i</code> exceeds <code>limitN//3</code> (or <code>isqrt(limitN)</code>), you can gain efficiency by separating the prime your <code>while</code> loop into two: the first part crossing off multiples of a prime number while adding that prime to the <code>primes</code> list, the second <code>while</code> loop just adding discovered primes to the <code>primes</code> list.</p>\n<h1>PEP 8</h1>\n<p>The Style Guide for Python Programs enumerates several rules that Python programs should follow. The main violation in your code relates to naming: You should use only <code>snake_case</code> for variables. <code>limitN</code> should be renamed to <code>limit_n</code>, or <code>upper_limit</code>.</p>\n<h1>Naming</h1>\n<p>Why we’re talking about names, <code>ind</code>, <code>ind_prime</code>, <code>pr_count</code> and <code>prime_goto</code> are all terrible names. You might know what they mean today, but other programmers reading the code will have a hard time trying to elude their meaning; you may even have problems if you revisit the code months down the road.</p>\n<p><code>first_n_primes(n)</code> would be a better function name. I’ll leave you to come up with better variable names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T05:28:02.530",
"Id": "501657",
"Score": "0",
"body": "Nice review, I didn't point those issues out cause I felt the OP needed just performance review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T07:04:13.583",
"Id": "501661",
"Score": "0",
"body": "@theProgrammer The OP **wanted** a performance review. They **needed** a full code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T16:09:05.973",
"Id": "501697",
"Score": "0",
"body": "@theProgrammer I actually struggled between upvoting and downvoting your answer. From the help centre: \"_Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\" Your answer was dangerously close to just being an alternate solution. In the end I decided that the \"consuming all free memory (6GB)\" was enough of an insightful observation to allow the answer to stand, and instead added my own review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T16:31:46.853",
"Id": "501700",
"Score": "0",
"body": "thanks @AJNeufeld for the review"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T04:04:52.360",
"Id": "254368",
"ParentId": "254317",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254368",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T18:01:50.617",
"Id": "254317",
"Score": "5",
"Tags": [
"python",
"performance",
"sieve-of-eratosthenes"
],
"Title": "Optimize Sieve of Eratosthenes for big numbers in Python"
}
|
254317
|
<p><a href="https://github.com/speedrun-program/load-extender" rel="nofollow noreferrer">https://github.com/speedrun-program/load-extender</a></p>
<p>It’s a pair of programs for extending load times, one for Windows and one for Linux. The Windows version is written in C++, and the Linux version is written in C so it can work with LD_PRELOAD.</p>
<p>I'm mainly interested in making sure I'm not doing anything that could cause a crash since I know these languages have a lot of undefined behavior, but I'll try to fix any other problems that get pointed out too. I'm sure there are problems with how it's written because I have very limited coding experience, and this is the first thing I've ever written in C/C++.</p>
<p>Here's the code for Linux:</p>
<p>fopen_interceptor.c:</p>
<pre class="lang-c prettyprint-override"><code>#define _GNU_SOURCE
#include <stdio.h>
#include <dlfcn.h>
#include <time.h>
#include <pthread.h>
#include "khash.h"
// thank you for making this hash map, attractivechaos.
// here's his github: https://github.com/attractivechaos
// these are global so fopen and khash_destruction can see them
static pthread_mutex_t lock;
static unsigned char LOCK_SUCCESS = 0; // used so it won't try to destroy lock if it failed to be made
static unsigned char SETUP_SUCCEEDED = 0; // if this is 0 then the fopen interception function skips to calling the real fopen function
static const int khStrInt = 32;
KHASH_MAP_INIT_STR(khStrInt, unsigned int*)
static khash_t(khStrInt) *my_khash_map;
#include "khash_setup_header.h" // included here so it recognizes kh_khStrInt_t
static void __attribute__((constructor)) khash_setup();
static void khash_setup()
{
my_khash_map = kh_init(khStrInt);
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("mutex init failed\n");
return;
}
LOCK_SUCCESS = 1; // LOCK_SUCCESS only changed here
FILE *my_file;
FILE *(*original_fopen)(const char*, const char*);
original_fopen = dlsym(RTLD_NEXT, "fopen");
my_file = original_fopen("./files_and_delays.txt", "r");
if (my_file == NULL)
{
printf("error opening files_and_delays.txt\n");
return;
}
// longest_name, longest_sequence, longest_delay, and line_count made here so they can be printed in fopen_interceptor_test
size_t longest_name = 1; // starts at 1 for null character
size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence
unsigned char longest_delay = 1; // starts at 1 for null character
unsigned int line_count = 1; // starts at 1 because there's always at least 1 line. khash map largest value is UINT_MAX
unsigned char khash_succeeded = prepare_to_setup(my_khash_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);
fclose(my_file);
if (khash_succeeded == 0) // khash failed to be made. Error message is printed in khash_setup_header in prepare_to_setup.
{
return;
}
SETUP_SUCCEEDED = 1; // SETUP_SUCCEEDED only changed here
}
static void __attribute__((destructor)) khash_destruction();
static void khash_destruction()
{
khiter_t khash_map_iter;
for (khash_map_iter = 0; khash_map_iter < kh_end(my_khash_map); ++khash_map_iter) // kh_destroy doesn't free keys and values, they need to be freed like this
{
if (kh_exist(my_khash_map, khash_map_iter))
{
free((char*)kh_key(my_khash_map, khash_map_iter));
kh_key(my_khash_map, khash_map_iter) = NULL;
free((unsigned int*)kh_val(my_khash_map, khash_map_iter));
kh_val(my_khash_map, khash_map_iter) = NULL;
}
}
kh_destroy(khStrInt, my_khash_map);
if (LOCK_SUCCESS == 1)
{
pthread_mutex_destroy(&lock);
}
}
FILE *fopen(const char *path, const char *mode)
{
if (SETUP_SUCCEEDED == 1) // skip to calling original fopen if setup failed
{
short slash_index = -1;
for (unsigned short i = 0; path[i] != '\0'; i++) // look for start of filename by finding last occurence of '/' character
{
if (path[i] == '/')
{
slash_index = i % SHRT_MAX; // will cause key to not be found, but prevents unsigned int overflow
}
}
// +1 so '/' isn't included. If '/' not found in path, slash_index stays -1 and entire path argument is checked as key since "path + -1 + 1" is the same as just "path"
khiter_t khash_map_iter = kh_get(khStrInt, my_khash_map, path + slash_index + 1);
if (khash_map_iter != kh_end(my_khash_map)) // key found
{
unsigned int *delay_sequence = kh_val(my_khash_map, khash_map_iter);
pthread_mutex_lock(&lock); // don't let other threads change delay sequence when it's being read or changed
if (delay_sequence[2] == UINT_MAX) // reset all delay sequences
{
unsigned int *sequence_to_reset;
kh_foreach_value(my_khash_map, sequence_to_reset, {sequence_to_reset[1] = 2;});
pthread_mutex_unlock(&lock);
}
else if (delay_sequence[1] < delay_sequence[0])
{
if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence
{
delay_sequence[1] = 2;
}
unsigned int sleep_time = delay_sequence[delay_sequence[1]];
delay_sequence[1] += 1;
pthread_mutex_unlock(&lock);
long time_nanoseconds = (sleep_time % 1000) * 1000000;
struct timespec ts = {sleep_time / 1000, time_nanoseconds};
nanosleep(&ts, NULL);
}
else // delay sequence already finished
{
pthread_mutex_unlock(&lock);
}
}
}
FILE *(*original_fopen)(const char*, const char*);
original_fopen = dlsym(RTLD_NEXT, "fopen");
return (*original_fopen)(path, mode);
}
</code></pre>
<p>fopen_interceptor_test.c:</p>
<pre class="lang-c prettyprint-override"><code>#define _GNU_SOURCE
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include "khash.h"
// thank you for making this hash map, attractivechaos.
// here's his github: https://github.com/attractivechaos
// these are global so fopen and khash_destruction can see them
static pthread_mutex_t lock;
static unsigned char LOCK_SUCCESS = 0; // used so it won't try to destroy lock if it failed to be made
static unsigned char SETUP_SUCCEEDED = 0; // if this is 0 then the fopen interception function skips to calling the real fopen function
static const int khStrInt = 32;
KHASH_MAP_INIT_STR(khStrInt, unsigned int*)
static khash_t(khStrInt) *my_khash_map;
#include "khash_setup_header.h" // included here so it recognizes kh_khStrInt_t
static void __attribute__((constructor)) khash_setup();
static void khash_setup()
{
my_khash_map = kh_init(khStrInt);
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("mutex init failed\n");
return;
}
LOCK_SUCCESS = 1; // LOCK_SUCCESS only changed here
FILE *my_file;
/*FILE *(*original_fopen)(const char*, const char*);
original_fopen = dlsym(RTLD_NEXT, "fopen");
my_file = original_fopen("./files_and_delays.txt", "r");*/
my_file = fopen("./files_and_delays.txt", "r");
if (my_file == NULL)
{
printf("error opening files_and_delays.txt\n");
return;
}
size_t longest_name = 1; // starts at 1 for null character
size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence
unsigned char longest_delay = 1; // starts at 1 for null character
unsigned int line_count = 1; // starts at 1 because there's always at least 1 line. khash map largest value is UINT_MAX
unsigned char khash_succeeded = prepare_to_setup(my_khash_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);
fclose(my_file);
if (khash_succeeded == 0) // khash failed to be made. Error message is printed in khash_setup_header in prepare_to_setup.
{
return;
}
printf("\nlongest filename (plus null character and whitespace in file): %zu\n"
"longest delay sequence (+2 for current delay and sequence length): %zu\n"
"most digits in delay (+1 for null character, max delay is UINT_MAX): %u\n"
"lines in file (overestimates slightly): %u\n"
"khash map size (lines should be less than 70%% of this): %zu\n", longest_name, longest_sequence, longest_delay, line_count, kh_n_buckets(my_khash_map));
SETUP_SUCCEEDED = 1; // SETUP_SUCCEEDED only changed here
}
static void __attribute__((destructor)) khash_destruction();
static void khash_destruction()
{
khiter_t khash_map_iter;
for (khash_map_iter = 0; khash_map_iter < kh_end(my_khash_map); ++khash_map_iter) // kh_destroy doesn't free keys and values, they need to be freed like this
{
if (kh_exist(my_khash_map, khash_map_iter))
{
free((char*)kh_key(my_khash_map, khash_map_iter));
kh_key(my_khash_map, khash_map_iter) = NULL;
free((unsigned int*)kh_val(my_khash_map, khash_map_iter));
kh_val(my_khash_map, khash_map_iter) = NULL;
}
}
kh_destroy(khStrInt, my_khash_map);
if (LOCK_SUCCESS == 1)
{
pthread_mutex_destroy(&lock);
}
}
static void fopen_test(const char *path, const char *mode)
{
if (SETUP_SUCCEEDED == 1) // skip to calling original fopen if setup failed
{
short slash_index = -1;
for (unsigned short i = 0; path[i] != '\0'; i++) // look for start of filename by finding last occurence of '/' character
{
if (path[i] == '/')
{
slash_index = i % SHRT_MAX; // will cause key to not be found, but prevents unsigned int overflow
}
}
// +1 so '/' isn't included. If '/' not found in path, slash_index stays -1 and entire path argument is checked as key since "path + -1 + 1" is the same as just "path"
khiter_t khash_map_iter = kh_get(khStrInt, my_khash_map, path + slash_index + 1);
if (khash_map_iter != kh_end(my_khash_map)) // key found
{
unsigned int *delay_sequence = kh_val(my_khash_map, khash_map_iter);
printf("%s successfully found in khash map\n", path + slash_index + 1);
pthread_mutex_lock(&lock); // don't let other threads change delay sequence when it's being read or changed
if (delay_sequence[2] == UINT_MAX) // reset all delay sequences
{
unsigned int *sequence_to_reset;
kh_foreach_value(my_khash_map, sequence_to_reset, {sequence_to_reset[1] = 2;});
pthread_mutex_unlock(&lock);
printf("all delay sequences reset\n");
}
else if (delay_sequence[1] < delay_sequence[0])
{
if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence
{
delay_sequence[1] = 2;
printf("%s delay sequence reset\n", path + slash_index + 1);
}
unsigned int sleep_time = delay_sequence[delay_sequence[1]];
delay_sequence[1] += 1;
pthread_mutex_unlock(&lock);
long time_nanoseconds = (sleep_time % 1000) * 1000000;
struct timespec ts = {sleep_time / 1000, time_nanoseconds};
//nanosleep(&ts, NULL);
printf("sleep for %ld second(s) and %ld millisecond(s)\n", ts.tv_sec, ts.tv_nsec / 1000000);
}
else // delay sequence already finished
{
pthread_mutex_unlock(&lock);
printf("%s delay sequence already finished\n", path + slash_index + 1);
}
}
else // key not found
{
printf("%s not found in khash map\n", path + slash_index + 1);
}
}
/*FILE *(*original_fopen)(const char*, const char*);
original_fopen = dlsym(RTLD_NEXT, "fopen");
return (*original_fopen)(path, mode);*/
}
static size_t find_longest_input_length(FILE *test_input) // find how much space to give to array used to hold input
{
size_t longest_input = 1;
size_t current_input = 1; // starts at 1 for null character
char ch = '\0';
while (ch != EOF && current_input < SIZE_MAX)
{
ch = fgetc(test_input);
if (ch == '\n' || ch == EOF)
{
if (current_input > longest_input)
{
longest_input = current_input;
}
current_input = 1;
}
else
{
current_input += 1;
}
}
if (current_input == SIZE_MAX)
{
return SIZE_MAX; // a test path was too big
}
return longest_input;
}
static void print_khash()
{
printf("\n---------- khash map current state ----------\n");
const char *key_to_print;
unsigned int *sequence_to_print;
kh_foreach(my_khash_map, key_to_print, sequence_to_print,
{
printf("%s / ", key_to_print);
for (unsigned int i = 0; i < sequence_to_print[0]; i++)
{
if (sequence_to_print[i] == UINT_MAX) // it's a reset point
{
printf("RESET"); // it doesn't need a space because the line always ends here
}
else
{
printf("%u ", sequence_to_print[i]);
}
}
printf("\n");
});
printf("---------------------------------------------\n\n");
}
static void test_all_inputs(FILE *test_input, size_t longest_input)
{
char *input_array = (char*)malloc(longest_input); // find_longest_input_length accounts for null character. Always greater than 0, shouldn't return NULL
if (input_array == NULL)
{
printf("malloc failed in test_all_inputs\n");
return;
}
size_t ch_position = 0;
char ch = '\0';
while (ch != EOF)
{
ch = fgetc(test_input);
if (ch == '\n' || ch == EOF)
{
input_array[ch_position] = '\0';
ch_position = 0;
if (ch != EOF) // avoids extra test
{
printf("testing fopen input: %s\n", input_array);
fopen_test(input_array, "r");
print_khash();
}
}
else
{
input_array[ch_position] = ch;
ch_position += 1;
}
}
free((char*)input_array);
input_array = NULL;
}
int main()
{
FILE *test_input;
test_input = fopen("./test_input.txt", "r");
if (test_input == NULL)
{
printf("error opening test_input.txt\n");
return 1;
}
size_t longest_input = find_longest_input_length(test_input);
if (longest_input == SIZE_MAX) // check_file will return SIZE_MAX if a test path is too big
{
printf("a test path is too big\n");
fclose(test_input);
return 1;
}
if (fseek(test_input, 0, SEEK_SET) != 0)
{
printf("fseek on test_input.txt failed\n");
fclose(test_input);
return 1;
}
printf("\nlongest test path (+1 for null character): %zu\n", longest_input);
printf("\ntest start\n");
print_khash();
test_all_inputs(test_input, longest_input);
fclose(test_input);
printf("test finish\n\n");
return 0;
}
</code></pre>
<p>khash_setup_header.h:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdint.h>
static unsigned char TOO_BIG_DELAY_SEEN = 0; // used so user won't be alerted more than once that they entered a delay that's too big
// checks line count to know how much space to give to khash
// updates longest_name and longest_sequence to know how much space to give to arrays used to hold key and value
static void check_file(FILE *my_file, size_t *longest_name, size_t *longest_sequence, unsigned char *longest_delay, unsigned int *line_count, unsigned char digits_in_uint)
{
unsigned char checking_sequence = 0; // 0 if checking a filename's length, 1 if checking a delay sequence's length
size_t current_name = 1; // starts at 1 for null character
size_t current_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence
unsigned char current_delay = 1; // starts at 1 for null character
char ch = '\0';
// longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints
while (ch != EOF && current_name < SIZE_MAX && current_sequence < (SIZE_MAX / sizeof(unsigned int)) && *line_count < UINT_MAX && current_sequence < UINT_MAX)
{
ch = fgetc(my_file);
if (ch == EOF || ch == '\n')
{
if (checking_sequence == 1)
{
if (current_delay > *longest_delay)
{
*longest_delay = current_delay;
}
if (current_sequence > *longest_sequence)
{
*longest_sequence = current_sequence;
}
checking_sequence = 0;
current_sequence = 3;
current_delay = 1;
}
*line_count += 1; // if for some reason there are a lot of hash collisions, the user can put empty lines in files_and_delays.txt to try to fix it
current_name = 1;
}
else if (ch == '/')
{
if (checking_sequence == 0)
{
if (current_name > *longest_name)
{
*longest_name = current_name;
}
checking_sequence = 1;
}
else
{
if (current_delay > *longest_delay)
{
*longest_delay = current_delay;
}
current_sequence += 1;
current_delay = 1;
}
}
else if (checking_sequence == 0)
{
current_name += 1;
}
// ignores non-digits and leading zeros. maximum space is digits_in_uint + 1. +1 is for null character
else if (((ch >= 49 && ch <= 57) || (ch == 48 && current_delay > 1)) && current_delay < digits_in_uint + 1)
{
current_delay += 1;
}
}
if (current_name == SIZE_MAX || current_sequence == (SIZE_MAX / sizeof(unsigned int)) || current_sequence == UINT_MAX)
{
*line_count = UINT_MAX; // something was too big
}
}
// reads the next filename and writes it in name_array
static size_t read_name(FILE *my_file, char *ch, char *name_array)
{
size_t ch_position = 0;
*ch = fgetc(my_file);
while (*ch != EOF && *ch != '\n' && *ch != '/')
{
name_array[ch_position] = *ch;
ch_position += 1;
*ch = fgetc(my_file);
}
name_array[ch_position] = '\0';
if (*ch == '/') // filename given and line didn't end abruptly
{
for (; ch_position > 0 && (name_array[ch_position - 1] == ' ' || name_array[ch_position - 1] == '\t'); ch_position--)
{
name_array[ch_position - 1] = '\0'; // remove whitespace between '/' and end of filename if the user has it written like that
}
}
return ch_position + 1; // +1 for null character
}
static unsigned int my_atoi(char *delay_array, unsigned int max_power_of_ten, unsigned char digits_in_uint, unsigned char number_position)
{
unsigned char delay_too_big = 0;
unsigned int current_power_of_ten = 1;
unsigned int accumulator = 0;
if (delay_array[0] == '\0') // no digits found, assume delay is 0
{
return 0;
}
// delay has more digits than UINT_MAX or it has as many digits and the most significant digit is bigger in the delay than in UINT_MAX
else if (delay_array[0] == '+' || (number_position == digits_in_uint && delay_array[0] - 48 > UINT_MAX / max_power_of_ten))
{
delay_too_big = 1;
}
else
{
number_position -= 1;
for (; number_position > 0; number_position--) // sum everything except most significant digit
{
accumulator += ((delay_array[number_position] - 48) * current_power_of_ten);
current_power_of_ten *= 10;
}
// checking that adding final value won't make accumulator overflow
// delay_array[0] won't be bigger than UINT_MAX / max_power_of_ten here because the other else if block checks for that
if (current_power_of_ten == max_power_of_ten && UINT_MAX - ((delay_array[0] - 48) * max_power_of_ten) - 1 < accumulator)
{
delay_too_big = 1;
}
else
{
accumulator += ((delay_array[0] - 48) * current_power_of_ten);
}
}
if (delay_too_big == 1)
{
if (TOO_BIG_DELAY_SEEN == 0)
{
printf("\nWARNING: maximum delay time is %u\n", UINT_MAX - 1);
TOO_BIG_DELAY_SEEN = 1; // TOO_BIG_DELAY_SEEN only changed here
}
return UINT_MAX - 1;
}
return accumulator;
}
// reads the next delay sequence and writes it in sequence_array
// also returns how many numbers are in the sequence so the right amount will be copied into the array given to khash
// there can't be more than UINT_MAX delays in one sequence
static unsigned int read_sequence(FILE *my_file, char *ch, char *delay_array, unsigned int *sequence_array, unsigned int max_power_of_ten, unsigned char digits_in_uint)
{
unsigned char number_position = 0; // next digit in current delay time. Also used in my_atoi to see if delay is too big
size_t sequence_position = 2; // starts at 2 because first two indexes are used to store sequence length and what the next delay is
delay_array[0] = '\0'; // initializing to use in condition
while (*ch != EOF && *ch != '\n')
{
*ch = fgetc(my_file);
if (*ch == EOF || *ch == '\n')
{
delay_array[number_position] = '\0';
unsigned int last_delay = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input
if (last_delay != 0) // no point adding 0 as final delay time
{
sequence_array[sequence_position] = last_delay;
sequence_position += 1;
}
}
else if (*ch == '/') // end of current delay, about to read next delay
{
delay_array[number_position] = '\0';
sequence_array[sequence_position] = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input
sequence_position += 1;
number_position = 0;
}
// ch is a digit and the digit isn't a leading zero and the maximum delay isn't reached
else if (((*ch >= 49 && *ch <= 57) || (*ch == 48 && number_position > 0)) && delay_array[0] != '+')
{
if (number_position != digits_in_uint) // if it's already equal to digits_in_uint then the delay is too big
{
delay_array[number_position] = *ch;
number_position += 1;
}
else
{
delay_array[0] = '+'; // '+' used to check if the delay is too big in my_atoi
}
}
else if (*ch == '-')
{
sequence_array[sequence_position] = UINT_MAX; // used for saying reset should happen
sequence_position += 1;
break; // no point checking delay times beyond where reset happens
}
}
while (*ch != EOF && *ch != '\n') // finish reading line if it's not already read
{
*ch = fgetc(my_file);
}
if (sequence_array[sequence_position - 1] != UINT_MAX) // numbers entered and not a reset-all-sequences file
{
for (unsigned int i = sequence_position - 1; i > 1 && sequence_array[i] == 0; i--) // don't copy pointless zeros
{
sequence_position -= 1;
}
}
return sequence_position;
}
static unsigned char set_keys_and_values(kh_khStrInt_t *my_khash_map, FILE *my_file, size_t longest_name, size_t longest_sequence, unsigned char longest_delay, unsigned int line_count, unsigned int max_power_of_ten, unsigned char digits_in_uint)
{
khiter_t khash_map_iter;
char *name_array = (char*)malloc(longest_name); // array for filename text. Always greater than 0, shouldn't return NULL.
unsigned int *sequence_array = (unsigned int*)malloc(longest_sequence * sizeof(unsigned int)); // array for delay sequence. Always greater than 0, shouldn't return NULL.
char *delay_array = (char*)malloc(longest_delay); // array for delay text. Always greater than 0, shouldn't return NULL.
if (name_array == NULL || sequence_array == NULL || delay_array == NULL)
{
return 0;
}
if ((size_t)(UINT_MAX / 2) < line_count) // khash resizes by powers of two, so if line_count is this big then khash can't resize any bigger
{
kh_resize(khStrInt, my_khash_map, UINT_MAX);
}
else
{
kh_resize(khStrInt, my_khash_map, (unsigned int)((line_count / 0.7) + 1)); // khash map will always be at 70% or less capacity
}
sequence_array[0] = 2; // first index stores length of array
sequence_array[1] = 2; // second index stores what the next delay to use in the sequence is
size_t chars_to_copy;
unsigned int numbers_to_copy;
char ch = '\0';
while (ch != EOF)
{
chars_to_copy = read_name(my_file, &ch, name_array); // accounts for null character
if (ch != EOF && ch != '\n') // checks if the line had a delay sequence. If it didn't, moves on to next line
{
numbers_to_copy = read_sequence(my_file, &ch, delay_array, sequence_array, max_power_of_ten, digits_in_uint);
if (numbers_to_copy > 2) // read_sequence returns 2 if either the sequence was pointless or the user didn't enter anything for it
{
int ret;
sequence_array[0] = numbers_to_copy;
char *key_for_khash = (char*)malloc(chars_to_copy); // always greater than 0, shouldn't return NULL
unsigned int *value_for_khash = (unsigned int*)malloc(numbers_to_copy * sizeof(unsigned int)); // always greater than 0, shouldn't return NULL
if (key_for_khash == NULL || value_for_khash == NULL)
{
return 0;
}
for (size_t i = 0; i < chars_to_copy; i++)
{
key_for_khash[i] = name_array[i];
}
for (unsigned int i = 0; i < numbers_to_copy; i++)
{
value_for_khash[i] = sequence_array[i];
}
khash_map_iter = kh_put(khStrInt, my_khash_map, key_for_khash, &ret);
kh_val(my_khash_map, khash_map_iter) = value_for_khash;
}
}
sequence_array[0] = 2;
sequence_array[1] = 2;
}
free((char*)name_array);
name_array = NULL;
free((unsigned int*)sequence_array);
sequence_array = NULL;
free((char*)delay_array);
delay_array = NULL;
return 1;
}
static unsigned char prepare_to_setup(kh_khStrInt_t *my_khash_map, FILE *my_file, size_t *longest_name, size_t *longest_sequence, unsigned char *longest_delay, unsigned int *line_count)
{
unsigned int max_power_of_ten = 1; // biggest power of 10 less than UINT_MAX, used in my_atoi
unsigned char digits_in_uint = 1; // how many digits are in UINT_MAX, used for helping to see if a delay is too big
for (; UINT_MAX / max_power_of_ten > 9; max_power_of_ten *= 10)
{
digits_in_uint += 1;
}
check_file(my_file, longest_name, longest_sequence, longest_delay, line_count, digits_in_uint);
if (fseek(my_file, 0, SEEK_SET) != 0)
{
printf("fseek on files_and_delays.txt failed\n");
return 0;
}
// longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints
if (*line_count == UINT_MAX) // check_file will return UINT_MAX if something is too big
{
printf("filename, delay, delay sequence, and/or number of files is too big\n");
return 0;
}
unsigned char khash_succeeded = set_keys_and_values(my_khash_map, my_file, *longest_name, *longest_sequence, *longest_delay, *line_count, max_power_of_ten, digits_in_uint);
if (khash_succeeded == 0) // set_keys_and_values returns 0 if malloc fails
{
printf("malloc failed in set_keys_and_values\n");
return 0;
}
return 1;
}
</code></pre>
<p>Here's the code for Windows:</p>
<p>load_extender_exe.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <tchar.h>
#include <iostream>
#include <string>
#include <Windows.h>
#include <easyhook.h>
void get_exit_input()
{
std::wcout << "Press Enter to exit";
std::wstring input;
std::getline(std::wcin, input);
}
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR* dllToInject32 = NULL;
WCHAR* dllToInject64 = NULL;
LPCWSTR lpApplicationName = argv[0];
DWORD lpBinaryType;
if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))
{
std::wcout << "ERROR: This exe wasn't identified as 32-bit or as 64-bit";
get_exit_input();
return 1;
}
else if (lpBinaryType == 0)
{
dllToInject32 = (WCHAR*)L"load_extender_32.dll";
}
else
{
dllToInject64 = (WCHAR*)L"load_extender_64.dll";
}
DWORD processId;
std::wcout << "Enter the target process Id: ";
std::cin >> processId;
wprintf(L"Attempting to inject dll\n\n");
// Inject dllToInject into the target process Id, passing
// freqOffset as the pass through data.
NTSTATUS nt = RhInjectLibrary(
processId, // The process to inject into
0, // ThreadId to wake up upon injection
EASYHOOK_INJECT_DEFAULT,
dllToInject32, // 32-bit
dllToInject64, // 64-bit
NULL, // data to send to injected DLL entry point
0 // size of data to send
);
if (nt != 0)
{
printf("RhInjectLibrary failed with error code = %d\n", nt);
PWCHAR err = RtlGetLastErrorString();
std::wcout << err << "\n";
get_exit_input();
return 1;
}
else
{
std::wcout << L"Library injected successfully.\n";
}
get_exit_input();
return 0;
}
</code></pre>
<p>load_extender_dll.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <string>
#include <mutex>
#include <Windows.h>
#include <easyhook.h>
#include "robin_hood.h"
// thank you for making this hash map, martinus.
// here's his github: https://github.com/martinus/robin-hood-hashing
namespace rh = robin_hood;
// included here so alias can be used
#include "rh_map_setup_header.h"
static class rh_map_handler // this is used to free all the unsigned int array memory when the program ends
{
public:
rh::unordered_flat_map<std::wstring, unsigned int*> obj_map;
~rh_map_handler()
{
for (auto it = obj_map.begin(); it != obj_map.end();)
{
free((unsigned int*)it->second);
it->second = NULL;
it = obj_map.erase(it); // erasing so obj_map's destructor doesn't have to do as much
}
}
};
// my_map_handler is global so it will free all the unsigned int arrays when the program ends
// my_rh_map and mtx are global so the NtOpenFile hook function can see them
static rh_map_handler my_map_handler;
static rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map = my_map_handler.obj_map;
static std::mutex mtx;
static unsigned char rh_map_setup()
{
FILE* my_file = NULL;
if (fopen_s(&my_file, ".\\files_and_delays.txt", "r") != 0)
{
return 0;
}
size_t longest_name = 1; // starts at 1 for null character
size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence
unsigned char longest_delay = 1; // starts at 1 for null character
size_t line_count = 1; // starts at 1 because there's always at least 1 line
unsigned char rh_map_succeeded = prepare_to_setup(my_rh_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);
if (my_file != NULL) // this makes a warning go away
{
fclose(my_file);
}
if (rh_map_succeeded == 0) // rh map failed to be made. Error message is printed in rh_map_setup_header in prepare_to_setup.
{
return 0;
}
return 1;
}
static unsigned char SETUP_SUCCEEDED = rh_map_setup(); // if this is 0 then the hook function skips to calling the real function
static NTSTATUS WINAPI NtOpenFileHook(
PHANDLE FileHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,
PIO_STATUS_BLOCK IoStatusBlock,
ULONG ShareAccess,
ULONG OpenOptions) {
if (SETUP_SUCCEEDED == 1) // skip to calling original NtOpenProcess if setup failed
{
std::wstring file_path = ObjectAttributes->ObjectName->Buffer;
// +1 so '\' isn't included. If '\' not found in path, the whole wstring is checked because npos is -1
std::wstring file_name = file_path.substr(file_path.rfind(L"\\") + 1);
rh::unordered_flat_map<std::wstring, unsigned int*>::const_iterator rh_map_iter = my_rh_map.find(file_name);
if (rh_map_iter != my_rh_map.end()) // key found
{
unsigned int* delay_sequence = rh_map_iter->second;
mtx.lock(); // don't let other threads change delay sequence when it's being read or changed
if (delay_sequence[2] == UINT_MAX) // reset all delay sequences
{
for (auto& it : my_rh_map)
{
it.second[1] = 2;
}
mtx.unlock();
}
else if (delay_sequence[1] < delay_sequence[0])
{
if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence
{
delay_sequence[1] = 2;
}
unsigned int sleep_time = delay_sequence[delay_sequence[1]];
delay_sequence[1] += 1;
mtx.unlock();
Sleep(sleep_time);
}
else // delay sequence already finished
{
mtx.unlock();
}
}
}
return NtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions);
}
extern "C" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo);
void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) {
HOOK_TRACE_INFO hHook1 = { NULL };
LhInstallHook(
GetProcAddress(GetModuleHandle(TEXT("ntdll")), "NtOpenFile"),
NtOpenFileHook,
NULL,
&hHook1);
ULONG ACLEntries[1] = { 0 };
LhSetExclusiveACL(ACLEntries, 1, &hHook1);
return;
}
</code></pre>
<p>load_extender_test.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <string>
#include <mutex>
#include "robin_hood.h"
// thank you for making this hash map, martinus.
// here's his github: https://github.com/martinus/robin-hood-hashing
namespace rh = robin_hood;
// included here so alias can be used
#include "rh_map_setup_header.h"
static class rh_map_handler // this is used to free all the unsigned int array memory when the program ends
{
public:
rh::unordered_flat_map<std::wstring, unsigned int*> obj_map;
~rh_map_handler()
{
for (auto it = obj_map.begin(); it != obj_map.end();)
{
free((unsigned int*)it->second);
it->second = NULL;
it = obj_map.erase(it); // erasing so obj_map's destructor doesn't have to do as much
}
}
};
// my_map_handler is global so it will free all the unsigned int arrays when the program ends
// my_rh_map and mtx are global so the NtOpenFile hook function can see them
static rh_map_handler my_map_handler;
static rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map = my_map_handler.obj_map;
static std::mutex mtx;
static unsigned char rh_map_setup()
{
FILE* my_file = NULL;
if (fopen_s(&my_file, ".\\files_and_delays.txt", "r") != 0)
{
printf("error opening files_and_delays.txt\n");
return 0;
}
size_t longest_name = 1; // starts at 1 for null character
size_t longest_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence
unsigned char longest_delay = 1; // starts at 1 for null character
size_t line_count = 1; // starts at 1 because there's always at least 1 line
unsigned char rh_map_succeeded = prepare_to_setup(my_rh_map, my_file, &longest_name, &longest_sequence, &longest_delay, &line_count);
if (my_file != NULL) // this makes a warning go away
{
fclose(my_file);
}
if (rh_map_succeeded == 0) // rh map failed to be made. Error message is printed in rh_map_setup_header in prepare_to_setup.
{
return 0;
}
printf("\nlongest filename (plus null character and whitespace in file): %zu\n"
"longest delay sequence (+2 for current delay and sequence length): %zu\n"
"most digits in delay (+1 for null character, max delay is UINT_MAX): %u\n"
"lines in file (overestimates slightly): %zu\n", longest_name, longest_sequence, longest_delay, line_count);
return 1;
}
static unsigned char SETUP_SUCCEEDED = rh_map_setup(); // if this is 0 then the hook function skips to calling the real function
static void NtOpenFile_test(std::wstring file_path)
{
if (SETUP_SUCCEEDED == 1) // skip to calling original NtOpenFile if setup failed
{
// +1 so '\' isn't included. If '\' not found in path, the whole wstring is checked because npos is -1
std::wstring file_name = file_path.substr(file_path.rfind(L"\\") + 1);
rh::unordered_flat_map<std::wstring, unsigned int*>::const_iterator rh_map_iter = my_rh_map.find(file_name);
if (rh_map_iter != my_rh_map.end()) // key found
{
unsigned int* delay_sequence = rh_map_iter->second;
printf("%ls successfully found in hash map\n", file_name.c_str());
mtx.lock(); // don't let other threads change delay sequence when it's being read or changed
if (delay_sequence[2] == UINT_MAX) // reset all delay sequences
{
for (auto& it : my_rh_map)
{
it.second[1] = 2;
}
mtx.unlock();
printf("all delay sequences reset\n");
}
else if (delay_sequence[1] < delay_sequence[0])
{
if (delay_sequence[delay_sequence[1]] == UINT_MAX) // reset delay sequence
{
delay_sequence[1] = 2;
printf("%ls delay sequence reset\n", file_name.c_str());
}
unsigned int sleep_time = delay_sequence[delay_sequence[1]];
delay_sequence[1] += 1;
mtx.unlock();
//Sleep(sleep_time);
printf("sleep for %u second(s) and %u millisecond(s)\n", sleep_time / 1000, sleep_time % 1000);
}
else // delay sequence already finished
{
mtx.unlock();
printf("%ls delay sequence already finished\n", file_name.c_str());
}
}
else // key not found
{
printf("%ls not found in khash map\n", file_name.c_str());
}
}
// NtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions);
}
static size_t find_longest_input_length(FILE* test_input) // find how much space to give to array used to hold input
{
size_t longest_input = 1;
size_t current_input = 1; // starts at 1 for null character
wchar_t ch = L'\0';
while (ch != WEOF && current_input < SIZE_MAX)
{
ch = fgetwc(test_input);
if (ch == L'\n' || ch == WEOF)
{
if (current_input > longest_input)
{
longest_input = current_input;
}
current_input = 1;
}
else
{
current_input += 1;
}
}
if (current_input == SIZE_MAX)
{
return SIZE_MAX; // a test path was too big
}
return longest_input;
}
static void print_rh_map()
{
printf("\n---------- khash map current state ----------\n");
for (auto& it : my_rh_map)
{
printf("%ls / ", it.first.c_str());
unsigned int* sequence_to_print = it.second;
for (unsigned int i = 0; i < sequence_to_print[0]; i++)
{
if (sequence_to_print[i] == UINT_MAX) // it's a reset point
{
printf("RESET"); // it doesn't need a space because the line always ends here
}
else
{
printf("%u ", sequence_to_print[i]);
}
}
printf("\n");
}
printf("---------------------------------------------\n\n");
}
static void test_all_inputs(FILE* test_input, size_t longest_input)
{
wchar_t* input_array = (wchar_t*)malloc(longest_input * sizeof(wchar_t)); // find_longest_input_length accounts for null character. Always greater than 0, shouldn't return NULL
if (input_array == NULL)
{
printf("malloc failed in test_all_inputs\n");
return;
}
size_t ch_position = 0;
wchar_t ch = L'\0';
while (ch != WEOF)
{
ch = fgetwc(test_input);
if (ch == L'\n' || ch == WEOF)
{
input_array[ch_position] = L'\0';
ch_position = 0;
if (ch != WEOF) // avoids extra test
{
printf("testing NtOpenFile input: %ls\n", input_array);
NtOpenFile_test((std::wstring)input_array);
print_rh_map();
}
}
else
{
input_array[ch_position] = ch;
ch_position += 1;
}
}
free((wchar_t*)input_array);
input_array = NULL;
}
static void get_exit_input()
{
printf("Press Enter to exit\n");
std::wstring input;
std::getline(std::wcin, input);
}
static int _tmain(int argc, _TCHAR* argv[])
{
LPCWSTR lpApplicationName = argv[0];
DWORD lpBinaryType;
if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0)
{
printf("\nERROR: couldn't read if this file is 32 bit or 64 bit\n");
get_exit_input();
return 1;
}
else if (lpBinaryType != 0)
{
printf("\nError: this file was incorrectly identified as not 32-bit\n");
get_exit_input();
return 1;
}
else
{
printf("\nthis file was correctly identified as 32-bit\n");
}
FILE* test_input;
if (fopen_s(&test_input, ".\\test_input.txt", "r") != 0)
{
printf("error opening test_input.txt\n");
get_exit_input();
return 1;
}
size_t longest_input = find_longest_input_length(test_input);
if (longest_input == SIZE_MAX) // check_file will return SIZE_MAX if a test path is too big
{
printf("a test path is too big\n");
if (test_input != NULL) // this makes a warning go away
{
fclose(test_input);
}
get_exit_input();
return 1;
}
// test_input != NULL check makes warning go away
if (test_input != NULL && fseek(test_input, 0, SEEK_SET) != 0)
{
printf("fseek on test_input.txt failed\n");
if (test_input != NULL) // this makes a warning go away
{
fclose(test_input);
}
get_exit_input();
return 1;
}
printf("\nlongest test path (+1 for null character): %zu\n", longest_input);
printf("\ntest start\n");
print_rh_map();
test_all_inputs(test_input, longest_input);
if (test_input != NULL) // this makes a warning go away
{
fclose(test_input);
}
get_exit_input();
return 0;
}
</code></pre>
<p>rh_map_setup_header:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <stdint.h>
// printf calls are used for debugging in load_extender_test.exe
static unsigned char TOO_BIG_DELAY_SEEN = 0; // used so user won't be alerted more than once that they entered a delay that's too big
// checks line count to know how much space to give to robin_hood map
// updates longest_name and longest_sequence to know how much space to give to arrays used to hold key and value
static void check_file(FILE* my_file, size_t* longest_name, size_t* longest_sequence, unsigned char* longest_delay, size_t* line_count, unsigned char digits_in_uint, size_t map_max_size)
{
unsigned char checking_sequence = 0; // 0 if checking a filename's length, 1 if checking a delay sequence's length
size_t current_name = 1; // starts at 1 for null character
size_t current_sequence = 3; // starts at 3 for index holding array length, index holding current position, and first number in delay sequence
unsigned char current_delay = 1; // starts at 1 for null character
wchar_t ch = L'\0';
// longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints
while (ch != WEOF && current_name < SIZE_MAX && current_sequence < (SIZE_MAX / sizeof(unsigned int)) && *line_count < SIZE_MAX && current_sequence < UINT_MAX)
{
ch = fgetwc(my_file);
if (ch == WEOF || ch == L'\n')
{
if (checking_sequence == 1)
{
if (current_delay > * longest_delay)
{
*longest_delay = current_delay;
}
if (current_sequence > * longest_sequence)
{
*longest_sequence = current_sequence;
}
checking_sequence = 0;
current_sequence = 3;
current_delay = 1;
}
*line_count += 1; // if for some reason there are a lot of hash collisions, the user can put empty lines in files_and_delays.txt to try to fix it
current_name = 1;
}
else if (ch == L'/')
{
if (checking_sequence == 0)
{
if (current_name > * longest_name)
{
*longest_name = current_name;
}
checking_sequence = 1;
}
else
{
if (current_delay > * longest_delay)
{
*longest_delay = current_delay;
}
current_sequence += 1;
current_delay = 1;
}
}
else if (checking_sequence == 0)
{
current_name += 1;
}
// ignores non-digits and leading zeros. maximum space is digits_in_uint + 1. +1 is for null character
else if (((ch >= 49 && ch <= 57) || (ch == 48 && current_delay > 1)) && current_delay < digits_in_uint + 1)
{
current_delay += 1;
}
}
if (current_name == SIZE_MAX ||
current_sequence == (SIZE_MAX / sizeof(unsigned int)) ||
current_sequence == UINT_MAX
|| *line_count > map_max_size)
{
*line_count = SIZE_MAX; // something was too big
}
}
// reads the next filename and writes it in name_array
static void read_name(FILE* my_file, wchar_t* ch, wchar_t* name_array)
{
size_t ch_position = 0;
*ch = fgetwc(my_file);
while (*ch != WEOF && *ch != L'\n' && *ch != L'/')
{
name_array[ch_position] = *ch;
ch_position += 1;
*ch = fgetwc(my_file);
}
name_array[ch_position] = L'\0';
if (*ch == L'/') // filename given and line didn't end abruptly
{
for (; ch_position > 0 && (name_array[ch_position - 1] == L' ' || name_array[ch_position - 1] == L'\t'); ch_position--)
{
name_array[ch_position - 1] = L'\0'; // remove whitespace between '/' and end of filename if the user has it written like that
}
}
}
static unsigned int my_atoi(wchar_t* delay_array, unsigned int max_power_of_ten, unsigned char digits_in_uint, unsigned char number_position)
{
unsigned char delay_too_big = 0;
unsigned int current_power_of_ten = 1;
unsigned int accumulator = 0;
if (delay_array[0] == L'\0') // no digits found, assume delay is 0
{
return 0;
}
// delay has more digits than UINT_MAX or it has as many digits and the most significant digit is bigger in the delay than in UINT_MAX
else if (delay_array[0] == L'+' || (number_position == digits_in_uint && delay_array[0] - 48 > UINT_MAX / max_power_of_ten))
{
delay_too_big = 1;
}
else
{
number_position -= 1;
for (; number_position > 0; number_position--) // sum everything except most significant digit
{
accumulator += ((delay_array[number_position] - 48) * current_power_of_ten);
current_power_of_ten *= 10;
}
// checking that adding final value won't make accumulator overflow
// delay_array[0] won't be bigger than UINT_MAX / max_power_of_ten here because the other else if block checks for that
if (current_power_of_ten == max_power_of_ten && UINT_MAX - ((delay_array[0] - 48) * max_power_of_ten) - 1 < accumulator)
{
delay_too_big = 1;
}
else
{
accumulator += ((delay_array[0] - 48) * current_power_of_ten);
}
}
if (delay_too_big == 1)
{
if (TOO_BIG_DELAY_SEEN == 0)
{
printf("\nWARNING: maximum delay time is %u\n", UINT_MAX - 1);
TOO_BIG_DELAY_SEEN = 1; // TOO_BIG_DELAY_SEEN only changed here
}
return UINT_MAX - 1;
}
return accumulator;
}
// reads the next delay sequence and writes it in sequence_array
// also returns how many numbers are in the sequence so the right amount will be copied into the array given to robin_hood map
// there can't be more than UINT_MAX delays in one sequence
static unsigned int read_sequence(FILE* my_file, wchar_t* ch, wchar_t* delay_array, unsigned int* sequence_array, unsigned int max_power_of_ten, unsigned char digits_in_uint)
{
unsigned char number_position = 0; // next digit in current delay time. Also used in my_atoi to see if delay is too big
size_t sequence_position = 2; // starts at 2 because first two indexes are used to store sequence length and what the next delay is
delay_array[0] = L'\0'; // initializing to use in condition
while (*ch != WEOF && *ch != L'\n')
{
*ch = fgetwc(my_file);
if (*ch == WEOF || *ch == L'\n')
{
delay_array[number_position] = L'\0';
unsigned int last_delay = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input
if (last_delay != 0) // no point adding 0 as final delay time
{
sequence_array[sequence_position] = last_delay;
sequence_position += 1;
}
}
else if (*ch == L'/') // end of current delay, about to read next delay
{
delay_array[number_position] = L'\0';
sequence_array[sequence_position] = my_atoi(delay_array, max_power_of_ten, digits_in_uint, number_position); // atoi can't be used because delay_array might have wrong input
sequence_position += 1;
number_position = 0;
}
// ch is a digit and the digit isn't a leading zero and the maximum delay isn't reached
else if (((*ch >= 49 && *ch <= 57) || (*ch == 48 && number_position > 0)) && delay_array[0] != L'+')
{
if (number_position != digits_in_uint) // if it's already equal to digits_in_uint then the delay is too big
{
delay_array[number_position] = *ch;
number_position += 1;
}
else
{
delay_array[0] = L'+'; // '+' used to check if the delay is too big in my_atoi
}
}
else if (*ch == L'-')
{
sequence_array[sequence_position] = UINT_MAX; // used for saying reset should happen
sequence_position += 1;
break; // no point checking delay times beyond where reset happens
}
}
while (*ch != WEOF && *ch != L'\n') // finish reading line if it's not already read
{
*ch = fgetwc(my_file);
}
if (sequence_array[sequence_position - 1] != UINT_MAX) // numbers entered and not a reset-all-sequences file
{
for (unsigned int i = sequence_position - 1; i > 1 && sequence_array[i] == 0; i--) // don't copy pointless zeros
{
sequence_position -= 1;
}
}
return sequence_position;
}
static unsigned char set_keys_and_values(rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map, FILE* my_file, size_t longest_name, size_t longest_sequence, unsigned char longest_delay, size_t line_count, unsigned int max_power_of_ten, unsigned char digits_in_uint)
{
wchar_t* name_array = (wchar_t*)malloc(longest_name * sizeof(wchar_t)); // array for filename text. Always greater than 0, shouldn't return NULL. Null character is accounted for.
unsigned int* sequence_array = (unsigned int*)malloc(longest_sequence * sizeof(unsigned int)); // array for delay sequence. Always greater than 0, shouldn't return NULL.
wchar_t* delay_array = (wchar_t*)malloc(longest_delay * sizeof(wchar_t)); // array for delay text. Always greater than 0, shouldn't return NULL.
if (name_array == NULL || sequence_array == NULL || delay_array == NULL)
{
return 0;
}
my_rh_map.reserve(line_count);
sequence_array[0] = 2; // first index stores length of array
sequence_array[1] = 2; // second index stores what the next delay to use in the sequence is
size_t chars_to_copy;
unsigned int numbers_to_copy;
wchar_t ch = L'\0';
while (ch != WEOF)
{
read_name(my_file, &ch, name_array); // puts characters in name_array
if (ch != WEOF && ch != L'\n') // checks if the line had a delay sequence. If it didn't, moves on to next line
{
numbers_to_copy = read_sequence(my_file, &ch, delay_array, sequence_array, max_power_of_ten, digits_in_uint);
if (numbers_to_copy > 2) // read_sequence returns 2 if either the sequence was pointless or the user didn't enter anything for it
{
sequence_array[0] = numbers_to_copy;
unsigned int* value_for_rh = (unsigned int*)malloc(numbers_to_copy * sizeof(unsigned int)); // always greater than 0, shouldn't return NULL
if (value_for_rh == NULL)
{
return 0;
}
std::wstring key_for_rh(name_array); // null character added to name_array in read_name function
for (unsigned int i = 0; i < numbers_to_copy; i++)
{
value_for_rh[i] = sequence_array[i];
}
my_rh_map[key_for_rh] = value_for_rh;
}
}
sequence_array[0] = 2;
sequence_array[1] = 2;
}
free((wchar_t*)name_array);
name_array = NULL;
free((unsigned int*)sequence_array);
sequence_array = NULL;
free((wchar_t*)delay_array);
delay_array = NULL;
return 1;
}
static unsigned char prepare_to_setup(rh::unordered_flat_map<std::wstring, unsigned int*>& my_rh_map, FILE* my_file, size_t* longest_name, size_t* longest_sequence, unsigned char* longest_delay, size_t* line_count)
{
unsigned int max_power_of_ten = 1; // biggest power of 10 less than UINT_MAX, used in my_atoi
unsigned char digits_in_uint = 1; // how many digits are in UINT_MAX, used for helping to see if a delay is too big
for (; UINT_MAX / max_power_of_ten > 9; max_power_of_ten *= 10)
{
digits_in_uint += 1;
}
size_t map_max_size = my_rh_map.max_size();
check_file(my_file, longest_name, longest_sequence, longest_delay, line_count, digits_in_uint, map_max_size);
if (fseek(my_file, 0, SEEK_SET) != 0)
{
printf("fseek on files_and_delays.txt failed\n");
return 0;
}
// longest_sequence can't be bigger than UINT_MAX because the size is recorded in the array, and the array uses unsigned ints
if (*line_count == SIZE_MAX) // check_file will return UINT_MAX if something is too big
{
printf("filename, delay, delay sequence, and/or number of files is too big\n");
return 0;
}
unsigned char rh_succeeded = set_keys_and_values(my_rh_map, my_file, *longest_name, *longest_sequence, *longest_delay, *line_count, max_power_of_ten, digits_in_uint);
if (rh_succeeded == 0) // set_keys_and_values returns 0 if malloc fails
{
printf("malloc failed in set_keys_and_values\n");
return 0;
}
return 1;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T19:07:17.613",
"Id": "501540",
"Score": "0",
"body": "I want the whole thing reviewed. So I should post the whole program? It's a lot of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T19:19:49.707",
"Id": "501541",
"Score": "3",
"body": "Please refer to [this meta answer](https://codereview.meta.stackexchange.com/a/1309/120114)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T19:35:09.123",
"Id": "501542",
"Score": "2",
"body": "Okay I edited it, thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T08:10:54.063",
"Id": "501667",
"Score": "3",
"body": "I spent a long time not understanding this, because of the ambiguity in the title - I understood it as extending the time to *load* programs into memory, rather than for those loaded programs to *access* files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T18:55:32.160",
"Id": "501966",
"Score": "0",
"body": "I posted the revised version of this code: https://codereview.stackexchange.com/questions/254528/c-programs-for-windows-and-linux-which-let-you-lengthen-the-time-it-takes-to-a"
}
] |
[
{
"body": "<h1>Make use of the standard library</h1>\n<p>You are reinventing lots of wheels in your programs. There is already a lot that the standard library you are using will do for you. Even in C on Linux, you can use POSIX functions for managing hash tables: <a href=\"https://linux.die.net/man/3/hcreate\" rel=\"noreferrer\"><code>hcreate()</code></a> and <a href=\"https://linux.die.net/man/3/hsearch\" rel=\"noreferrer\"><code>hsearch()</code></a>. But even better is probably to write both the Linux and Windows versions in C++, and make use of <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"noreferrer\"><code>std::unordered_map</code></a>. With C++, you can also avoid all of the manual memory management you are doing.</p>\n<p>You are also reading the input files character by character, which is very slow. Why not use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"noreferrer\"><code>std::getline()</code></a> to read whole lines at a time, and then split them further as necessary? Or ensure your input is in such a format that you can use the <code>>></code> operator to read each element. You even reimplemented number parsing in <code>my_atoi()</code>. It is much better to leave that up to a standard function, such as <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stol\" rel=\"noreferrer\"><code>std::stoi()</code></a>.</p>\n<p>There is almost nothing in your code that needs to be low level. Keep everything as simple and easy as possible.</p>\n<h1>Make your code as platform-independent as possible</h1>\n<p>You should not need two completely different implementations. A lot of code can be shared. The only things that are different between Linux and Windows are the function calls that need to be intercepted, and how you intercept them. You should be able to share the processing of the processing of the input file, lookups into the hash table, and the sleeping. So, the <code>fopen()</code> hook should look as simple as this:</p>\n<pre><code>static auto original_fopen = reinterpret_cast<FILE *(*)(const char *path, const char *mode)>(dlsym(RTLD_NEXT, "fopen"));\n\nFILE *fopen(const char *path, const char *mode)\n{\n delay_file(path);\n return original_fopen(path, mode);\n}\n</code></pre>\n<p>And the Windows hook should look like:</p>\n<pre><code>static NTSTATUS WINAPI NtOpenFileHook(\n PHANDLE FileHandle,\n ACCESS_MASK DesiredAccess,\n POBJECT_ATTRIBUTES ObjectAttributes,\n PIO_STATUS_BLOCK IoStatusBlock,\n ULONG ShareAccess,\n ULONG OpenOptions)\n{\n delay_file(ObjectAttributes->ObjectName->Buffer);\n return NtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions);\n}\n</code></pre>\n<p>The function <code>delay_file()</code> should take care of everything else. The string type used for filenames is different between Linux and Windows, but since you mentioned C++17, you should be able to use <a href=\"https://en.cppreference.com/w/cpp/filesystem/path\" rel=\"noreferrer\"><code>std::filesystem::path</code></a> as the type without having to worry about that:</p>\n<pre><code>static std::unordered_map<std::filesystem::path, ...> delay_sequences;\n\ndelay_file(std::filesystem::path filename)\n{\n if (auto it = delay_sequences.find(filename); it != delay_sequences.end()) {\n auto &sequence = it->second;\n ...\n }\n}\n</code></pre>\n<h1>Create a <code>struct</code> or <code>class</code> to manage the delay sequence</h1>\n<p>You store the delay sequence as an array of integers, but some elements of that array are special, and the length can supposedly vary. It is better to create a proper data structure for it, whether you want to do it in C or in C++. With C++, I would write something like:</p>\n<pre><code>struct delay_sequence {\n std::size_t index = 0;\n std::vector<std::chrono::milliseconds> delays;\n}\n</code></pre>\n<p>The vector <code>delays</code> holds the actual delay values using a <a href=\"https://en.cppreference.com/w/cpp/chrono/duration\" rel=\"noreferrer\"><code>std::chrono::duration</code></a> type. The advantage is that you can pass it directly to <a href=\"https://en.cppreference.com/w/cpp/thread/sleep_for\" rel=\"noreferrer\"><code>std::this_thread::sleep_for()</code></a> to sleep for the given time. A <code>std::vector</code> knows its own length, so you don't have to store that separately. The only other item necessary is the current index.</p>\n<h1>Avoid manual mutex locking</h1>\n<p>Instead of manually calling <code>mutex.lock()</code> and <code>mutex.unlock()</code>, use a <a href=\"https://en.cppreference.com/w/cpp/thread/lock_guard\" rel=\"noreferrer\"><code>std::lock_guard</code></a> object to do this for you.</p>\n<p>Alternatively:</p>\n<h1>Consider using atomic variables</h1>\n<p>The index into the array of delays is just a simple counter that needs to be incremented or reset. Consider making it a <a href=\"https://en.cppreference.com/w/cpp/atomic/atomic\" rel=\"noreferrer\"><code>std::atomic<std::size_t></code></a>, like so:</p>\n<pre><code>struct delay_sequence {\n std::atomic<std::size_t> index;\n std::vector<std::chrono::milliseconds> delays;\n}\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>auto &sequence = it->second;\nauto index = sequence.index++;\n\nif (index < sequence.delays.size()) {\n std::this_thread::sleep_for(sequence.delays[index]);\n} else {\n // we've already finished, if you are worried about index wrapping, do:\n sequence.index--;\n}\n</code></pre>\n<p>You can also reset all counters atomically:</p>\n<pre><code>for (auto &[filename, sequence]: delay_sequences) {\n sequence.index = 0;\n}\n</code></pre>\n<p>However, the trick with <code>if (delay_sequence[...] == UINT_MAX)</code> is not as nice with atomics. You could still have a special duration (perhaps a negative one?) indicate that you want to reset one or all of the indices, but I would rather a flag to <code>struct delay_sequence</code> to indicate whether you want to repeat a sequence, and another flag to indicate that you want to reset all indices when the given file is opened, like so:</p>\n<pre><code>struct delay_sequence {\n std::atomic<std::size_t> index;\n std::vector<std::chrono::milliseconds> delays;\n bool repeat;\n bool reset_all;\n};\n\n...\n\nauto &sequence = it->second;\n\nif (sequence.reset_all) {\n for (auto &[filename, sequence]: delay_sequences) {\n sequence.index = 0;\n }\n} else {\n auto index = sequence.index++;\n\n if (sequence.repeat) {\n index %= sequence.delays.size();\n }\n\n if (index < sequence.delays.size()) {\n std::this_thread::sleep_for(sequence.delays[index]);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T20:11:43.210",
"Id": "501717",
"Score": "0",
"body": "Thank you for taking the time to look at this. I’ll try to change it with your suggestions. I also think I should use forward_lists instead of vectors if I’m using structs. I can keep track of the current position in the struct and decide to reset it to the start of the forward_list when it reaches the end position. So I’ll try to rewrite it like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T20:15:05.667",
"Id": "501718",
"Score": "1",
"body": "I would still use `std::vector` to hold the delay times, since accessing a vector is faster than a list, and it seems to me that after reading in the configuration file, you never change the delays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T20:18:50.503",
"Id": "501719",
"Score": "0",
"body": "Ok, in that case I’ll use vectors."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:10:03.060",
"Id": "254351",
"ParentId": "254324",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "254351",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T18:49:00.623",
"Id": "254324",
"Score": "3",
"Tags": [
"beginner",
"c",
"c++17"
],
"Title": "C and C++ programs which let you lengthen the time it takes to access files"
}
|
254324
|
<p>This is a class representing an exponent. Its main purpose is to deal with logarithmic quantities.</p>
<pre class="lang-cpp prettyprint-override"><code>template<std::floating_point Representation>
class Exponent
{
public:
using representation = Representation;
struct Literal{};
constexpr explicit Exponent(representation val, Literal):m_val{val}
{}
constexpr explicit Exponent(representation val):m_val{std::log2(val)}
{}
constexpr representation value() const
{
return m_val;
}
constexpr operator representation() const
{
return std::exp2(m_val);
}
constexpr Exponent& operator+=(Exponent other)
{
m_val += other.m_val;
return *this;
}
constexpr Exponent& operator-=(Exponent other)
{
m_val -= other.m_val;
return *this;
}
constexpr Exponent& operator/=(Exponent other)
{
m_val /= other.m_val;
return *this;
}
constexpr Exponent& operator*=(Exponent other)
{
m_val *= other.m_val;
return *this;
}
constexpr auto operator<=>(Exponent const&) const = default;
private:
representation m_val;
};
template<std::floating_point T>
constexpr Exponent<T> operator+(Exponent<T> a, Exponent<T> b)
{
return a+=b;
}
//...
</code></pre>
<p>What I am not sure about is how to properly disambiguate between data converting casts (taking logarithm vs exponent) operations and pure value casts (simple assign).</p>
<p>Another question is if the API should emulate real values. With the above API:</p>
<pre class="lang-cpp prettyprint-override"><code>constexpr double multiply(double a, double b)
{return Exponent{a} + Exponent{b};}
static_assert(multiply(2.0, 3.0) == 6.0);
</code></pre>
<p>However, if you define operator* on exponents to behave as addition, you would instead simply write:</p>
<pre class="lang-cpp prettyprint-override"><code>constexpr double multiply(Exponent a, Exponent b)
{return a*b;}
static_assert(multiply(2.0, 3.0) == 6.0);
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T20:11:37.893",
"Id": "254326",
"Score": "1",
"Tags": [
"c++",
"wrapper"
],
"Title": "API for value boxing and unboxing"
}
|
254326
|
<p>I wrote a desktop application in java (with JavaFX). Program first find given title in Imdb via: <a href="https://imdb-internet-movie-database-unofficial.p.rapidapi.com" rel="nofollow noreferrer">https://imdb-internet-movie-database-unofficial.p.rapidapi.com</a> and then when user select a movie, search in the pirate bay site for magnets link, seeds and leechers.</p>
<p>Here is an example:</p>
<p><a href="https://i.stack.imgur.com/npYCk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/npYCk.png" alt="enter image description here" /></a></p>
<p>Here are two classes:</p>
<p><strong>ImdbFinder</strong></p>
<pre><code>package service.movie;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonArray;
import exception.NoMovieFoundException;
import model.Movie;
import service.util.JsonParserUtil;
import service.util.PropertyHelper;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
public class ImdbFinder implements MovieFinder {
private static ImdbFinder instance;
private static Properties properties;
private static ObjectMapper objectMapper;
private ImdbFinder() { }
public static ImdbFinder getInstance() {
if (instance == null) {
instance = new ImdbFinder();
objectMapper = new ObjectMapper();
properties = PropertyHelper.loadPropertyFileForFilename("ImdbHttpInfo.properties");
}
return instance;
}
@Override
public Movie getMovieDetailsForMovieId(String movieId) {
return new Movie();
}
@Override
public List<Movie> getMovieListForSearchedPhrase(String phrase) throws IOException, InterruptedException, NoMovieFoundException {
List<Movie> movies = mapTitlesToMovieList(foundMovies(phrase).body());
if (movies == null || movies.isEmpty()) {
throw new NoMovieFoundException();
}
return movies;
}
private List<Movie> mapTitlesToMovieList(String response) throws IOException {
Optional<JsonArray> jsonArray = Optional.ofNullable(
JsonParserUtil.parseStringToJsonObject(response).getAsJsonArray("titles"));
List<Movie> movieList = new ArrayList<>();
if (jsonArray.isPresent()) {
movieList = objectMapper.readValue(jsonArray.get().toString(), new TypeReference<List<Movie>>() {});
}
return movieList;
}
private HttpResponse<String> foundMovies(String title) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(properties.getProperty("search-api-url") + formatTitle(title)))
.header("x-rapidapi-key", properties.getProperty("x-rapidapi-key"))
.header("x-rapidapi-host", properties.getProperty("x-rapidapi-host"))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
System.out.println(URI.create(properties.getProperty("search-api-url") + formatTitle(title)));
return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
}
private String formatTitle(String title) {
return title.replaceAll("\\s+", "%20")
.replaceAll("[^a-zA-Z\\d\\s%]", "");
}
}
</code></pre>
<p><strong>PirateBayFinder</strong></p>
<pre><code>package service.torrent;
import exception.NoTorrentFoundException;
import model.Torrent;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PirateBayFinder implements TorrentFinder {
private static TorrentFinder instance;
private static final String SEARCH_URL = "https://tpb.party/search/";
private static final String MAGNET_REGEX = "magnet:\\?xt=(.*?)(?=\")";
private static final String TITLE_INSIDE_MAGNET_REGEX = "(?<=&dn=)(.*?)(?=&tr)";
private static final String SEEDS_LECHERS_PATTERN = "(?<=<td align=\"right\">)([0-9]*?)(?=</td>)";
private PirateBayFinder() { }
public static TorrentFinder getInstance() {
if (instance == null) {
instance = new PirateBayFinder();
}
return instance;
}
@Override
public List<Torrent> findTorrentsForPhrase(String phrase) throws IOException, InterruptedException, NoTorrentFoundException {
String htmlPage = foundTorrents(phrase).body();
List<Torrent> foundTorrents = new ArrayList<>();
scrapTorrentInfo(htmlPage, foundTorrents);
scrapSeedsAndLeechers(htmlPage, foundTorrents);
if (foundTorrents.isEmpty()) {
throw new NoTorrentFoundException();
}
return foundTorrents;
}
private void scrapTorrentInfo(String htmlPage, List<Torrent> foundTorrents) {
Matcher magnetMatcher = Pattern.compile(MAGNET_REGEX).matcher(htmlPage);
Pattern titlePattern = Pattern.compile(TITLE_INSIDE_MAGNET_REGEX);
Matcher titleMatcher;
String title;
String magnet;
while (magnetMatcher.find()) {
magnet = magnetMatcher.group();
titleMatcher = titlePattern.matcher(magnet);
if (titleMatcher.find()) {
title = titleMatcher.group();
foundTorrents.add(new Torrent(title, magnet));
}
}
}
private void scrapSeedsAndLeechers(String htmlPage, List<Torrent> foundTorrents) {
final Matcher seedsLeechersMatcher = Pattern.compile(SEEDS_LECHERS_PATTERN).matcher(htmlPage);
int seeds, lecheers;
int counter = 0;
while(seedsLeechersMatcher.find()) {
seeds = Integer.parseInt(seedsLeechersMatcher.group());
lecheers = 0;
if (seedsLeechersMatcher.find()) {
lecheers = Integer.parseInt(seedsLeechersMatcher.group());
}
foundTorrents.get(counter).setSeeds(seeds);
foundTorrents.get(counter).setLeechers(lecheers);
counter++;
}
}
private HttpResponse<String> foundTorrents(String title) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(SEARCH_URL + title.replaceAll("\\s+","%20")))
.method("GET", HttpRequest.BodyPublishers.noBody())
.build();
System.out.println(request.uri());
return HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
}
}
</code></pre>
<p>and two interfaces:</p>
<p><strong>MovieFinder</strong></p>
<pre><code>public interface MovieFinder {
Movie getMovieDetailsForMovieId(String id);
List<Movie> getMovieListForSearchedPhrase(String phrase) throws IOException, InterruptedException;
}
</code></pre>
<p><strong>TorrentFinder</strong></p>
<pre><code>public interface TorrentFinder {
List<Torrent> findTorrentsForPhrase(String phrase) throws IOException, InterruptedException;
}
</code></pre>
<p>Can you please tell me what I can improve these two classes? I think code which contains matchers and patterns looks too complicated.</p>
|
[] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code>package service.movie;\n</code></pre>\n<p>Package names normally associate the code with the author/organization, like "com.github.mrfisherman.moviefinder" or "com.company.ourapp".</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static ImdbFinder getInstance() {\n if (instance == null) {\n instance = new ImdbFinder();\n objectMapper = new ObjectMapper();\n properties = PropertyHelper.loadPropertyFileForFilename("ImdbHttpInfo.properties");\n }\n return instance;\n }\n</code></pre>\n<p>That's not thread-safe, when invoked from multiple threads n instances might be created. There are three ways to fix it:</p>\n<ol>\n<li>Create the instance in the <code>static</code> constructor. I'd advice against this as to not make it a habit, because if no instance is ever needed, one still might be created if only <code>static</code> fields or methods are accessed.</li>\n<li>Make the whole method <code>synchronized</code>.</li>\n<li>Use double-checked locking with a <code>volatile</code> field.</li>\n</ol>\n<pre class=\"lang-java prettyprint-override\"><code>private static volatile ImdbFinder instance;\n\npublic static ImdbFinder gestInstance() {\n if (instance == null) {\n synchronized(ImdbFinder.class) {\n if (instance == null) {\n // TODO Init instance here.\n }\n }\n }\n \n return instance;\n}\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private static Properties properties;\n private static ObjectMapper objectMapper;\n</code></pre>\n<p>This seem to be better suited as instance fields.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> @Override\n public Movie getMovieDetailsForMovieId(String movieId) {\n return new Movie();\n }\n</code></pre>\n<p>???</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public List<Movie> getMovieListForSearchedPhrase(String phrase) throws IOException, InterruptedException, NoMovieFoundException \n</code></pre>\n<p>If a method throws an <code>InterruptedException</code>, something smells.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> @Override\n public List<Movie> getMovieListForSearchedPhrase(String phrase) throws IOException, InterruptedException, NoMovieFoundException {\n List<Movie> movies = mapTitlesToMovieList(foundMovies(phrase).body());\n if (movies == null || movies.isEmpty()) {\n throw new NoMovieFoundException();\n }\n return movies;\n }\n</code></pre>\n<p>Do not signal "no items found" with an <code>Exception</code>, return an empty list instead (not <code>null</code>). That will reduce the code using this function from having to use a <code>try...catch</code> block to maybe not even having to do an <code>if</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> Matcher titleMatcher;\n String title;\n String magnet;\n while (magnetMatcher.find()) {\n magnet = magnetMatcher.group();\n titleMatcher = titlePattern.matcher(magnet);\n if (titleMatcher.find()) {\n title = titleMatcher.group();\n foundTorrents.add(new Torrent(title, magnet));\n }\n }\n</code></pre>\n<p>This isn't C for some embedded system with low resources, this is Java. Whether you declare the variable outside the loop or not does not matter in the slightest, except for readability and maintainability. Declare your variables in the lowest scope possible.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>System.out.println(URI.create(properties.getProperty("search-api-url") + formatTitle(title)));\n</code></pre>\n<p>Don't print to stdout unless expected to. Use a logger, like the Java default one, and even then try to keep your logging as meaningful as possible. This seems more like a debug information you might need in certain circumstances then during the normal operation of the application.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public interface MovieFinder {\n\n Movie getMovieDetailsForMovieId(String id);\n\n List<Movie> getMovieListForSearchedPhrase(String phrase) throws IOException, InterruptedException;\n\n}\n</code></pre>\n<p>I always advice people to be as descriptive as possible in names, but that is a little bit too much. <code>Movie getMovie(String id)</code> and <code>List<Movie> findMovies(String searchterm)</code> tells me everything I need to know when looking at the API.</p>\n<p>Additionally, <code>getMovieListForSearchedPhrase</code> should not declare <code>InterruptedException</code> and <code>IOException</code> (not every finder might do IO and therefor need), but should throw a specialized exception, like <code>MovieException</code> or <code>MovieFinderException</code>, if they <em>really</em> need to throw something. In this case, both might be fine without exceptions, as the first returns <code>null</code> if there is not movie, and the second returns an empty <code>List</code> if no movies were found. If you want to communicate failures, as they might be expected of some sort, then use the same specialized exception for both methods.</p>\n<hr />\n<p>Last but not least, a word of warning regarding the law and legality. <em>Technically</em> what you do here is, without question, okay, as you're only providing a tool. However, <em>legally</em> it depends on the jurisdiction you are under. A tool with the sole purpose to break copyright is seen just as bad as breaking copyright on many parts of the world. Even if not directly illegally, there are groups ("representative of artists") which might <em>still</em> try to go against this.</p>\n<p>If in doubt, ask a lawyer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T20:25:53.297",
"Id": "501626",
"Score": "0",
"body": "Thank you very much for this CR. This is what I needed. About last point, I left a note on github: [Attention!] I am not responsible for any misuse or any legal consequences of using the program. I also do not encourage you to download movies from illegal sources. The program was created for an educational purpose. hope it is enough for now because I don't share any illegal data etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T20:30:21.077",
"Id": "501627",
"Score": "0",
"body": "\"hope it is enough for now\", as I said, technically yes, legally, ask a lawyer. Also keep in mind that the country of the *hosting service* is important in these questions. Overall, what might also be a nice design exercise, is to not make it a \"MovieFinder\" but a \"TorrentFinder\" which sports the ability to match different items against torrents. So, the IMDB one just becomes one of many implementations, for another to find Linux distributions, or abandoned games, or public domain books and so forth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T20:43:40.710",
"Id": "501628",
"Score": "0",
"body": "I have one more question, I know you say that I shouldn't throw exceptions outside of methods but I did it to catch them all in Controller when I can show gui alert to the user. So what should I do now, leave it like it is and catch them later or as you said try catch them in same method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T05:35:52.930",
"Id": "501658",
"Score": "0",
"body": "Use a dedicated exception, as I've pointed out. The problem here is, as I've said, that throwing `InterruptedException` is odd, and an implementation detail. So is throwing an `IOException`. The interface should not depend on behavior of an implementation, but both of these are implementation specific exceptions. The best way would be to provide a generic, custom exception, as said, which is being thrown from both methods if you need to signal that an exception occurred during these methods. That means that implemenations catch any specific exceptions, and rethrow them as custom ones."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:57:12.007",
"Id": "254356",
"ParentId": "254328",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254356",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-04T21:15:13.030",
"Id": "254328",
"Score": "1",
"Tags": [
"java"
],
"Title": "Program that helps you search for torrents"
}
|
254328
|
<p>update: a new version of this code is <a href="https://codereview.stackexchange.com/questions/254395/c-multithreaded-message-broadcaster-using-callbacks">posted here</a></p>
<hr />
<p>With this post, i would like to 1) ask for feedback on below code as it stands:</p>
<ul>
<li>do i apply all best practices for c++20?</li>
<li>is it safe?</li>
<li>is my way to update a callback from inside a running callback sensible/best?</li>
</ul>
<p>Based on code and design advice found on stackoverflow (e.g. <a href="https://stackoverflow.com/a/47872677/3103767">here</a>), I have written a class that handles listeners registering callbacks to receive messages in multithreaded code (listeners can be added from different threads than the thread that messages are sent from, only one thread every sends messages). This code also needed multiple ways for listeners to unregister themselves:</p>
<ol>
<li>when the class owning the receiver destructs or is otherwise done receiving: hence <code>add_listener()</code> returns a cookie in the form of a <code>std::list::const_iterator</code> (list because iterators to none of the other elements are invalidated when an element is removed, and other cookies thus stay valid)</li>
<li>when the callback during execution determines it no longer needs further messages, this is handled by returning true ("remove myself please").</li>
</ol>
<p>I now run into the situation where a listener callback, when invoked, needs to replace itself with another callback. I can't call <code>add_listener()</code> as that would deadlock when called from inside an invoked callback. Unless i move to use a <code>std::recursive_mutex</code> instead. That seems heavy.</p>
<p>So instead i have added a replacement list to the broadcaster storing a pair of <code><listenerCookie, listener></code> which lists what updates should be done once the current message has been broadcasted to all listeners. The updates are performed at the end of the <code>notify_all</code> function. This guarantees that the old callback is never called again and that the cookie held stays valid but now points to the new callback. But this design seems complicated and unsafe: it required adding an extra member function to the broadcaster class, which should only be called from inside a callback. And that is easy to misuse unless code comments (and the horrible function name :p) saying to only invoke from inside a callback are honored. Or is there a way to ensure a function can only be called by the invoked callback?</p>
<p>Am i missing some simpler solution?</p>
<p>A simpler, but sadly impossible solution i considered was for the callback to return the new callback to register, which would replace the currently registered one (the cookie thus stays valid). But I do not know what my listener's function signature would then be, as you cannot do something CRTP-like with using statements (<code>using listener = std::function<listener(Message...)>;</code> is invalid) (NB: in reality if this option were possible i'd return a variant with bool as well i guess, as i need to also maintain self-deregistration functionality.)</p>
<h2>Implementation</h2>
<pre><code>#include <list>
#include <mutex>
#include <functional>
#include <vector>
#include <utility>
template <class... Message>
class Broadcaster
{
public:
using listener = std::function<bool(Message...)>;
using listenerCookie = typename std::list<listener>::const_iterator;
listenerCookie add_listener(listener&& r_)
{
auto l = lock();
return targets.emplace(targets.cend(), std::move(r_));
}
void remove_listener(listenerCookie it_)
{
auto l = lock();
remove_listener_impl(it_);
}
void notify_all(Message... msg_)
{
auto l = lock();
for (auto it = targets.cbegin(), e = targets.cend(); it != e; )
if ((*it)(msg_...))
it = remove_listener_impl(it);
else
++it;
if (!update_list.empty())
{
for (auto&& [c_it, r] : update_list)
{
// turn cookie into non-const iterator
auto it = targets.erase(c_it, c_it); // NB, [c_it, c_it) is an empty range, so nothing is removed
// update callback
*it = std::move(r);
}
update_list.clear();
}
}
// NB: should only be called from running callback!
void update_callback_from_inside_callback(listenerCookie it_, listener&& r_)
{
update_list.emplace_back(it_, std::move(r_));
}
private:
auto lock()
{
return std::unique_lock<std::mutex>(m);
}
listenerCookie remove_listener_impl(listenerCookie it_)
{
return targets.erase(it_);
}
private:
std::mutex m;
std::list<listener> targets;
std::vector<std::pair<listenerCookie, listener>> update_list;
};
</code></pre>
<h2>Example usage</h2>
<pre><code>#include <iostream>
#include <string>
#include <functional>
#include <optional>
struct test
{
using StringBroadcaster = Broadcaster<std::string>;
bool simpleCallback(std::string msg_)
{
std::cout << "from simpleCallback: " << msg_ << std::endl;
return false; // don't remove self: run indefinitely
}
bool oneShotCallback(std::string msg_)
{
std::cout << "from oneShotCallback: " << msg_ << std::endl;
return true; // remove self
}
bool twoStepCallback_step1(std::string msg_)
{
std::cout << "from twoStepCallback_step1: " << msg_ << std::endl;
// replace callback (so don't request to delete through return argument!)
broadcast.update_callback_from_inside_callback(*cb_twostep_cookie, std::bind(&test::twoStepCallback_step2, this, std::placeholders::_1));
return false; // don't remove self: we just indicated another callback be placed in our slot: slot needs to remain existent
}
bool twoStepCallback_step2(std::string msg_)
{
std::cout << "from twoStepCallback_step2: " << msg_ << std::endl;
return false; // don't remove self: run indefinitely
}
void runExample()
{
cb_simple_cookie = broadcast.add_listener(std::bind(&test::simpleCallback , this, std::placeholders::_1));
cb_oneShot_cookie = broadcast.add_listener(std::bind(&test::oneShotCallback , this, std::placeholders::_1));
cb_twostep_cookie = broadcast.add_listener(std::bind(&test::twoStepCallback_step1, this, std::placeholders::_1));
broadcast.notify_all("message 1"); // should be received by simpleCallback, oneShotCallback, twoStepCallback_step1
// NB: cb_oneShot_cookie is an invalid iterator now, oneShotCallback removed itself through its return argument. clear it
cb_oneShot_cookie.reset();
broadcast.notify_all("message 2"); // should be received by simpleCallback and twoStepCallback_step2
broadcast.remove_listener(*cb_simple_cookie);
broadcast.notify_all("message 3"); // should be received by twoStepCallback_step2
broadcast.remove_listener(*cb_twostep_cookie);
broadcast.notify_all("message 4"); // should be received by none
}
StringBroadcaster broadcast;
std::optional<StringBroadcaster::listenerCookie> cb_simple_cookie;
std::optional<StringBroadcaster::listenerCookie> cb_oneShot_cookie;
std::optional<StringBroadcaster::listenerCookie> cb_twostep_cookie;
};
int main(int argc, char **argv)
{
test t;
t.runExample();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T11:18:25.913",
"Id": "501571",
"Score": "0",
"body": "`<class... Message>` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T11:40:27.220",
"Id": "501572",
"Score": "0",
"body": "@L.F.: whoops, copy paste error. fixed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T15:26:38.523",
"Id": "501588",
"Score": "0",
"body": "Please provide some examples of how the class is invoked and used. If you have written a unit test, add that to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T22:31:43.310",
"Id": "501637",
"Score": "1",
"body": "@pacmaninbw: added, thanks for feedback!"
}
] |
[
{
"body": "<p>Very good design! And very clean code. As-is, there’s very little I can recommend to improve things. In fact, the only code suggestions I can come up with off the top of my head are:</p>\n<ul>\n<li><p>You should probably take all arguments in the callbacks (and notify function) by <code>const&</code>. That allows you to pass more complicated (and even non-copyable) types to callback functions.</p>\n<p>This <em>may</em> add some overhead if the compiler doesn’t optimize trivial or built-in types like <code>int</code> to by-val parameters, but the overhead should be so small as to be impossible to detect if the callback functions are really small, because then the callback arguments will all be hot in cache. (And if the callback functions are <em>not</em> really small, then you won’t notice the extra indirection anyway.)</p>\n</li>\n<li><p>You are not considering exceptions, and that’s usually not a <em>major</em> problem if you just write good code—and your code <em>is</em> well-written—but there are some places where it might be a problem.</p>\n<p>What happens if a callback throws? You could end up with surprising behaviour. Nothing will leak, and no UB will be triggered (at least in the code visible), but what will happen is that all remaining callbacks that were supposed to be notified won’t be. That may or may not be a serious problem, depending on the nature of the message.</p>\n<p>What may be more deadly is that callbacks that have replaced themselves will be surprised to discover… they haven’t been replaced. That will be at least surprising… but if the callbacks have already deleted themselves some way, under the assumption that they have replaced themselves and successfully returned, so they’re done, right?… boom.</p>\n<p>So how to fix this? Well, the easiest way is to require the callbacks to be <code>noexcept</code>. Not like the broadcaster is going to handle any failures on their part, right?</p>\n<p>Another way would be to toss the <code>update_list</code>, and instead only keep track of a single <code>optional<pair<listenerCookie, listener>></code>. If it <code>has_value()</code>, then <em>right after</em> the callback—<em>before</em> either removing anything, or advancing the iterator—you replace the contents of <code>*it</code> then and there. That way, even if a callback throws, at least all previous callbacks that completed successfully and wanted to be replaced are cool.</p>\n<p>(I’ll also offer another option, later, in the design review.)</p>\n<p>That still leaves the issue that if a callback throws, no other callbacks will be notified… which will lead to non-deterministic behaviour in multi-threaded code, because there doesn’t seem to be a way to sort callbacks. In other words, if you start a <code>notify_all()</code>, and a callback throws, you have no way of knowing which callbacks completed and which didn’t. So you can’t even catch the exception, handle/ignore it, then continue notifying.</p>\n<p>You could catch any exceptions thrown by callbacks in a <code>std::exception_ptr</code>, continue notifying, and then, at the end, throw if the exception pointer tests <code>true</code>. But that would only handle a single exception. What if multiple callbacks throw? Tricky! Not impossible to handle, but damn tricky. (You might need an exception type that holds a list of exceptions!) Making callbacks <code>noexcept</code> is a <em>MUCH</em> easier solution. But that’s a design decision you’ll have to wrestle over.</p>\n</li>\n<li><p>You have a serious bug, in that callbacks can deadlock your program if they call any public member functions of the broadcast type.</p>\n<p>The problem is that you are allowing arbitrary code execution <em><strong>while holding a lock</strong></em> within your <code>notify_all()</code> function. Each callback being notified can do… bugger-well anything! There’s nothing to stop one from calling <code>notify_all()</code> again! Or from calling one of the other public member function of the broadcast type.</p>\n<p>Now, you can argue that doing so would be logically stupid, and for the most part that’s true: You already provide means to remove <em>and</em> replace callbacks <em>within</em> the notify loop, so there should never be a need to call <code>remove_listener()</code> from a callback. But a callback might very well reasonably want to <em>add</em> a listener, and there’s no other way to do that other than via <code>add_listener()</code>. It might also be reasonable for a callback to want to trigger a new notification, in which case it will need to call <code>notify_all()</code>.</p>\n<p>I can’t tell you the “right” way to fix this problem, because it will depend on your design space. I can offer suggestions.</p>\n<ol>\n<li><p>Within <code>notify_all()</code>, do the lock, <strong>COPY THE LIST OF LISTENERS</strong>, then release the lock, and start notifying using the copied list. That way, all the callbacks are done <em>without</em> holding the lock. If you need to reacquire the lock—such as to do a remove or replace of a listener—that’s fine.</p>\n<p>This is not a perfect solution, because you could still end up with the situation where a listener has removed itself and returned successfully, then gets called again. (And, of course, you’ve pretty much lost everything you gained by using <code>std::list</code> iterators in the first place.) Fixing <em>that</em> issue will be tricky. (One potential solution would be to require all the callbacks to be <code>std::shared_ptr</code>. That’s an interesting solution in that it allows thread-safe auto-deregistration any time if you only hold a container of <code>std::weak_ptr</code>.)</p>\n<p>However, it would allow you to do the notifies concurrently, which could be a huge gain.</p>\n</li>\n<li><p>Disallow callbacks to do anything dirty by using <code>std::try_lock()</code>. In each function, replace the lock line with: `auto lock = std::unique_lock{m}; if (auto res = std::try_lock(m); res == -1) { /* do your business */ } else { throw std::logic_error{"recursive lock"}; }</p>\n</li>\n<li><p><s>Use a recursive mutex so callbacks won’t actually lock.</s> No, don’t do this. It will only work if the callbacks stay in the same thread (and there’s no way to force that), and even then, it will require herculean efforts to handle race conditions.</p>\n</li>\n</ol>\n</li>\n</ul>\n<p>There’s one style issue I’d like to critique, then I’d like to discuss your design. So this will be more of an overall design review than a specifically-code review.</p>\n<h1>Style issue: naming convetions</h1>\n<p>On the style front, I find your choice to mangle member function <em>arguments</em>… but not <em>data members</em>… a bit odd. Standard practice is to add an underscore to data member names (or to tag them with <code>m_</code>, or something else like that). Why? Because those data members are visible in multiple places (every member function, for example). But member function arguments are only visible in that one, single member function. There doesn’t seem to be any point in mangling them, because no one else will ever see them.</p>\n<p>For example, if I see the following member function:</p>\n<pre><code>auto class_t::func(int a)\n{\n a = 1;\n b = 2;\n _c = 3;\n}\n</code></pre>\n<p>… one of the most important things I want to be able to do is see the definitions of those three variables. When I see an undecorated variable name, like <code>a</code>, the <em>first</em> place I look is within the closest scope. Then the next scope, and the next scope, and so on, until I reach function scope, at which point I check the function arguments. In this case, that’s where I’ll find <code>a</code>.</p>\n<p>But I won’t find <code>b</code>. So the <em>next</em> step is to check the class scope, for static data members. If I don’t find it there, then I know <code>b</code> is at namespace scope—it’s a “global variable”—and start looking out in the world for it.</p>\n<p>All of which is to say is that variables like <code>b</code> are a pain in the ass. Well, if they’re static data members, they’re only <em>mildly</em> annoying for forcing me to leave function I’m investigating and go digging through the class declaration. But if I have to go search the entire friggin’ project for a variable declaration (and even then, never be 100% sure I haven’t missed a declaration in some other namespace that might get picked up first)… yeah, I be peeved. Luckily this isn’t that great a problem in practice.</p>\n<p>Which is why variables names like <code>_c</code> (or <code>c_</code> or <code>m_c</code>; whatever the project convention) are so lovely. When I don’t find the definition locally—and, frankly, I usually don’t even bother to <em>check</em> locally, because, yanno, convention—I know <em>EXACTLY</em> where to find it. I look in the class definition, and, if it’s a <code>const</code> member function, add <code>const</code>, and… done. Simple.</p>\n<p>In general, when I see an undecorated name that isn’t local, I know it’s a global variable of some kind—either literally global (that is, at namespace scope) or functionally global (that is, a class static member). In either case, I know without even looking whether this function is one of those functions whose side-effects are going to be a problem. If a function has only undecorated names that are local, and decorated names, then I know at a glance that its effects are all local; either completely internal to the function itself, or completely internal to the object being operated on (that is, <code>*this</code>).</p>\n<p>In other words, without even the foggiest clue about the rest of the project, I can look at <code>func()</code> above and <em>know</em> that it has globally-visible side-effects, because of <code>b</code>. I don’t even need to know what <code>b</code> is, or where <code>b</code> is defined, or <em>anything</em> about <code>class_t</code>. Just by the convention, I can tell that this is a function that <em>may</em> cause surprises elsewhere in the code. I can be pretty damn sure that it’s not re-entrant (and thus not thread-safe). On the other hand, if <code>b</code> were removed, then I would be able to assume that <code>func()</code> is safe; that if I call it, it won’t touch anything other than its own internals and <code>*this</code>, which means it’s thread-safe (so long as <code>*this</code> isn’t being shared among threads, in which case, if it were, I would assume it’s being synchronized externally). That’s the power of a good convention.</p>\n<p>Now let’s consider your convention:</p>\n<pre><code>auto class_t::func(int a_)\n{\n a_ = 1;\n b = 2;\n c = 3;\n}\n</code></pre>\n<p>Okay, so I see <code>a_</code>, and I know to check the local scope, and eventually find it as a function argument. Cool.</p>\n<p>Now what happens with <code>b</code> and <code>c</code>? Where do I even begin looking? Should I assume they are non-static data members? Static data members? Globals? Is this function re-entrant? I mean, if I went hunting around for the definitions of <code>b</code> and <code>c</code> eventually I would find out… but that’s a far cry from being able to know just from a glance.</p>\n<h1>Design review</h1>\n<p>First off, I think the idea to take advantage of the invalidation characteristics of <code>std::list</code>’s iterators is brilliant. I admit I rarely think about <code>std::list</code> when reaching for a container (honestly, the only time I think of it is when testing bi-di iterators), but now you’ve inspired me to give it a second look for some design problems I’ve run into.</p>\n<p>Now, when I considered your design questions, I have to admit I went down <em>exactly</em> the same trail you did. I first thought, well, let’s use a variant for the return with an optional replacement… oh, no, that won’t work because that would make the function’s type recursive… okay, what if we made the <code>update_callback_from_inside_callback()</code> safer… could use a <code>recursive_mutex</code>, oh you already thought of that…. I ended up stuck exactly where you are.</p>\n<p>But then I had one of those face-palming brainstorms, and came up with this (<em><strong>note</strong></em>, code is not tested, probably won’t compile, and is likely broken and incomplete—this is just for illustration of an idea):</p>\n<pre><code>struct return_t {};\nstruct remove_t {};\n\nusing replace_t = std::any;\n\nusing result_t = std::variant<return_t, remove_t, replace_t>;\n\ntemplate <typename... Args>\nclass broadcaster\n{\n // ... [snip] ...\n\n using listener = std::function<result_t (Args const&...)>;\n\n // ... [snip] ...\n\n void notify_all(Args const&... args)\n {\n auto l = lock();\n\n for (auto it = _targets.cbegin(); it != _targets.cend(); )\n {\n // "overload" is a pretty common utility type - for example,\n // there's a version on the cppreference page on visit().\n //\n // Until we get pattern-matching, this is the prettiest we can do.\n\n it = std::visit(\n overload{\n // Remove listener.\n [&_targets, it](remove_t) { return _targets.erase(it); },\n\n // Replace listener.\n [&_targets, it](replace_t& r)\n {\n auto i = _targets.erase(it, it);\n *i = std::move(std::any_cast<listener>(r));\n return ++it;\n },\n\n // Default: just continue notifying.\n [it](auto&&) { return ++it; },\n },\n (*it)(args...));\n }\n }\n\n // ... [snip] ...\n};\n</code></pre>\n<p>Now, as written, this will work (I presume!), but because <code>std::any</code> is smaller than <code>std::function</code> in every stdlib I’m aware of, it will always trigger an allocation. Now, you may not care, because replacing a listener will be damn rare, so… meh. But if you <em>do</em> care, then you could replace <code>std::any</code> with a custom type-erasing type that holds a properly aligned array of <code>std::byte</code> that is <code>sizeof(std::function)</code> large. Doesn’t even matter <em>which</em> instantiation of <code>std::function</code> you use to determine the type, so you don’t need to know <code>Args...</code>. In fact, rather than <code>std::any</code>, you could just use <code>std::function<void()></code>, because function pointers can be converted to other function pointers, and back. But then you lose the type check of <code>any_cast</code>. As written, it is type safe because <code>any_cast</code> will detect shenanigans. If you want this check done earlier—like <em>within</em> the callback, or even at compile-time—there are tricks you can use, like making <code>replace_t</code> a type with a private constructor, and <code>broadcast<Args...></code> is a friend, and it has a <code>make_replace_token(std::function<result_t(Args const&...)>)</code> function, or something like that.</p>\n<p>You could even add another behaviour—<code>add_t</code>—which is a type-erased callback that gets added. (Of course, you can’t do it the way <code>notify_all()</code> is currently written, because you can’t modify the list while iterating on it. But it may work with other options!) You may even add <code>add_multiple_t</code>, which allows a callback to register multiple listeners.</p>\n<p>But, honestly, it would be better if it were safe for callbacks to modify the broadcaster safely, because then they could add, remove, or even notify-all without a care. Then you wouldn’t even need any of these gymnastics, because a callback could simply call <code>remove_listener()</code> (and you could have a <code>replace_listener()</code>, too!).</p>\n<p>The key point to keep in mind is that allowing arbitrary code to execute <em><strong>while holding a lock</strong></em> is like break-dancing at a pyrotechnics display while doused in gasoline.</p>\n<p>The best possible fix is to do all the callbacks while <em><strong>not</strong></em> holding the lock. If you can make this work, it’s all wins: callbacks can add new callbacks, remove callbacks (including themselves), replace callbacks, do new notify runs… basically <em>anything</em>. The tricky part is making this work.</p>\n<p>The big catch to pulling off the trick is to make sure a callback can know <em>for damn, 100% sure</em> if it’s been removed (or replaced), so it can know <em>cannot</em> be called again (and thus, is safe to destruct). This is <em>not</em> trivial. One solution is to share ownership between the broadcaster and anything else that wants to know if the callback is live; with <code>std::shared_ptr</code> (used properly), there’s no possible way to call or otherwise access an already-deleted callback. There are other, lighter solutions, too, like keeping an atomic “is alive” flag for each callback… but you have to be careful about TOCTOU issues. As I said, tricky!</p>\n<h1>Extras</h1>\n<h2>Compile-time checking for <code>noexcept</code> functions</h2>\n<p>Unfortunately <code>std::function</code> doesn’t properly support <code>noexcept</code> functions as of C++20. This has been a known problem since C++17; I don’t know why it hasn’t been fixed yet. (Well, okay, I can guess it’s because it isn’t an <em>easy</em> fix, and because the pandemic did slow things down for the committee. Maybe it just slipped under the priority bar.)</p>\n<p>But that’s not that big a deal, because there are only two places where you need to <em>verify</em> the callback: <code>add_listener()</code> and <code>update_callback_from_inside_callback()</code>. Everywhere else you just <em>use</em> the callback, and you can put a <code>noexcept</code> function in a non-<code>noexcept</code> <code>std::function</code>. (You just can’t do the opposite; you can’t put a non-<code>noexcept</code> function in a <code>noexcept</code> <code>std::function</code>.)</p>\n<p>So here’s how you could fix <code>add_listener()</code>:</p>\n<pre><code>template <class... Message>\nclass Broadcaster\n{\nprivate:\n using listener = std::function<bool(Message...)>; // this no longer needs to be public\npublic:\n using listenerCookie = typename std::list<listener>::const_iterator;\n\n // ... [snip] ...\n\n // if you don't have C++20 concepts, that's fine; the concept is just\n // an extra check, not a necessary one\n template <std::invocable<Message...> F>\n listenerCookie add_listener(F&& r_)\n {\n // this is where the real check happens\n static_assert(std::is_nothrow_invocable_r_v<bool, F, Message...>);\n\n auto l = lock();\n\n // it's cool to put a noexcept function in a non-noexcept std::function\n // so we just forward what we're given into a function<bool(Message...)>\n\n return targets.emplace(targets.cend(), listener{std::forward<F>(r_)});\n }\n\n // ... [snip] ...\n</code></pre>\n<p>Same idea for <code>update_callback_from_inside_callback()</code>.</p>\n<p>This will bloat the interface a bit, so you might want to do:</p>\n<pre><code> template <std::invocable<Message...> F>\n listenerCookie add_listener(F&& r_)\n {\n static_assert(std::is_nothrow_invocable_r_v<bool, F, Message...>);\n\n return add_listener_impl_(listener{std::forward<F>(r_)});\n }\n\n // ... [snip] ...\n\nprivate:\n listenerCookie add_listener_impl_(listener&& r)\n {\n auto l = lock();\n return targets.emplace(targets.cend(), std::move(r));\n }\n\n // ... [snip] ...\n</code></pre>\n<p>Either way, it will make no difference at the call site (except, of course, if your callback is not <code>noexcept</code>, it will no longer compile). All these should work:</p>\n<pre><code>auto foo_1(int, double) noexcept -> bool;\n\nb.add_listener(foo_1);\n\nauto foo_2 = [=](int, double) noexcept -> bool { return true; };\n\nb.add_listener(foo_2);\n// or\nb.add_listener(std::move(foo_2));\n\nb.add_listener([](int, double) noexcept -> bool { return true; });\n\nstruct func\n{\n std::string name = {};\n int call_count = 0;\n\n auto operator()(int, double) noexcept\n {\n std::cout << name << " has been called " << ++call_count << " times";\n\n return call_count < 100;\n }\n};\n\nb.add_listener(func{.name = "steve"});\n\nauto f = func{.name = "anya"};\nb.add_listener(std::move(f));\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T21:25:17.083",
"Id": "501631",
"Score": "0",
"body": "Careful with names ending in `_t` - can collide with names from C headers (reserved for standard library)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T21:45:32.733",
"Id": "501634",
"Score": "1",
"body": "@TobySpeight AFAIK, that’s a POSIX rule, not a C rule. C only reserves `(u)int*_t`, or something like that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T22:52:45.323",
"Id": "501639",
"Score": "0",
"body": "@indi thank you very much for the extensive review! I'll take some time to process. One question: Should i add an updated design to the bottom of my original post, or post it in a new question if i like further review? The idea of std::list iterators as cookies is from somewhere on SO, can't trace anymore. The post i linked to actually uses your copy-locked-then-use-outside-lock technique (didn't even notice!). I need to think through what that means for ordering. It would certainly simplify things. I avoided weak_ptr/shared_ptr to deal with lifetime issues, perhaps premature optimization ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T22:56:21.693",
"Id": "501640",
"Score": "0",
"body": "I question i can ask now: I would very much like my callbacks to be noexcept. Can i enforce that? something like `std::function<bool(Message...) noexcept>` doesn't exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T02:00:19.433",
"Id": "501643",
"Score": "0",
"body": "I think the SOP on CR is to make a new post when you want significantly-changed code re-reviewed; you can always link back to this post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T02:03:07.637",
"Id": "501644",
"Score": "0",
"body": "Yeah, I forgot that `std::function` doesn’t support `noexcept` yet. Honestly, I was more focused on using `std::any` and type-erasure and so on… and for those things, you can’t really enforce type-safety at the call site, or at compile time. If you really want compile-time checking, you might have to ditch `std::function` in the interface, and just take a template argument instead, and put *that* in `std::function`. Hm… I’ll extend the answer to explain better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T08:35:30.300",
"Id": "501670",
"Score": "0",
"body": "Thanks for the extension! Cool! I'm on latest MSVC and the two longer forms of concept spec seem to work, so i could use this solution. I need to also support member functions (so std::binding the this pointer), but i think i see how i could easily extend your suggestion. Will make for a nice second round of review in a new post! Now to puzzling over the various options ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T10:17:19.253",
"Id": "501677",
"Score": "0",
"body": "and of course i can use lambdas instead of std::bind [for anything](https://stackoverflow.com/a/17545183/3103767). Ok :) No more comments here now unless i have questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T22:05:17.470",
"Id": "501723",
"Score": "0",
"body": "Thanks for the lots of input! I have made quite some changes. In the end didn't use your return type design idea as i would lose ability to check for noexcept using that way of replacing listeners using std::any. Good brainwave tho! And while list was nice, the possibly invalid iterators, and no way of knowing if they are, were painful. Now solved with an int identifier, and a registry."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T21:10:02.377",
"Id": "254358",
"ParentId": "254331",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254358",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T00:40:28.063",
"Id": "254331",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"c++17",
"callback",
"c++20"
],
"Title": "C++ callback multithreaded, can unregister itself"
}
|
254331
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/254178/231235">A recursive_copy_if Template Function Implementation in C++</a>. Besides the recursive version <a href="https://en.cppreference.com/w/cpp/algorithm/ranges/copy" rel="nofollow noreferrer"><code>std::ranges::copy_if</code></a>, I am trying to implement a recursive version <a href="https://en.cppreference.com/w/cpp/algorithm/replace_copy" rel="nofollow noreferrer"><code>std::replace_copy_if</code></a>.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>// recursive_replace_copy_if implementation
template<std::ranges::range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate, class T>
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::replace_copy_if(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate,
new_value);
return output;
}
template<std::ranges::input_range Range, class UnaryPredicate, class T>
requires (!std::invocable<UnaryPredicate, std::ranges::range_value_t<Range>>)
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate, &new_value](auto&& element) { return recursive_replace_copy_if(element, unary_predicate, new_value); }
);
return output;
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The test cases for <code>recursive_replace_copy_if</code> function including <code>std::vector<int></code>, <code>std::vector<std::vector<int>></code>, <code>std::vector<std::string></code>, <code>std::vector<std::vector<std::string>></code>, <code>std::deque<int></code>, <code>std::deque<std::deque<int>></code>, <code>std::list<int></code> and <code>std::list<std::list<int>></code> type input are as below.</p>
<pre><code>int main()
{
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_replace_copy_if(test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
recursive_print(test_vector);
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_replace_copy_if(test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_replace_copy_if(
test_string_vector, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_replace_copy_if(
test_string_vector2, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_replace_copy_if(test_deque, [](int x) { return (x % 2) == 0; }, 0));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_replace_copy_if(test_deque2, [](int x) { return (x % 2) == 0; }, 0));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_replace_copy_if(test_list, [](int x) { return (x % 2) == 0; }, 0));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_replace_copy_if(test_list2, [](int x) { return (x % 2) == 0; }, 0));
return 0;
}
</code></pre>
<p>The output of the testing code above:</p>
<pre><code>Level 0:
5
7
55
55
8
6
55
9
55
55
Level 0:
Level 1:
5
7
55
55
8
6
55
9
55
55
Level 1:
5
7
55
55
8
6
55
9
55
55
Level 1:
5
7
55
55
8
6
55
9
55
55
Level 0:
Level 1:
0
Level 1:
1
1
Level 1:
2
Level 1:
3
Level 1:
4
Level 1:
5
Level 1:
6
Level 1:
7
Level 1:
8
Level 1:
9
Level 1:
1
0
Level 1:
1
1
Level 1:
1
2
Level 1:
1
3
Level 1:
1
4
Level 1:
1
5
Level 1:
1
6
Level 1:
1
7
Level 1:
1
8
Level 1:
1
9
Level 1:
2
0
Level 0:
Level 1:
Level 2:
0
Level 2:
1
1
Level 2:
2
Level 2:
3
Level 2:
4
Level 2:
5
Level 2:
6
Level 2:
7
Level 2:
8
Level 2:
9
Level 2:
1
0
Level 2:
1
1
Level 2:
1
2
Level 2:
1
3
Level 2:
1
4
Level 2:
1
5
Level 2:
1
6
Level 2:
1
7
Level 2:
1
8
Level 2:
1
9
Level 2:
2
0
Level 1:
Level 2:
0
Level 2:
1
1
Level 2:
2
Level 2:
3
Level 2:
4
Level 2:
5
Level 2:
6
Level 2:
7
Level 2:
8
Level 2:
9
Level 2:
1
0
Level 2:
1
1
Level 2:
1
2
Level 2:
1
3
Level 2:
1
4
Level 2:
1
5
Level 2:
1
6
Level 2:
1
7
Level 2:
1
8
Level 2:
1
9
Level 2:
2
0
Level 1:
Level 2:
0
Level 2:
1
1
Level 2:
2
Level 2:
3
Level 2:
4
Level 2:
5
Level 2:
6
Level 2:
7
Level 2:
8
Level 2:
9
Level 2:
1
0
Level 2:
1
1
Level 2:
1
2
Level 2:
1
3
Level 2:
1
4
Level 2:
1
5
Level 2:
1
6
Level 2:
1
7
Level 2:
1
8
Level 2:
1
9
Level 2:
2
0
Level 0:
1
0
3
0
5
0
Level 0:
Level 1:
1
0
3
0
5
0
Level 1:
1
0
3
0
5
0
Level 1:
1
0
3
0
5
0
Level 0:
1
0
3
0
5
0
Level 0:
Level 1:
1
0
3
0
5
0
Level 1:
1
0
3
0
5
0
Level 1:
1
0
3
0
5
0
Level 1:
1
0
3
0
5
0
</code></pre>
<p></p>
<b>Full Testing Code</b>
<p>
<p>The full testing code:</p>
<pre><code>#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <exception>
#include <execution>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
#endif
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return 0;
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + 1;
}
// recursive_copy_if function
template <std::ranges::input_range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate);
return output;
}
template <
std::ranges::input_range Range,
class UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate](auto&& element) { return recursive_copy_if(element, unary_predicate); }
);
return output;
}
// recursive_count implementation
// recursive_count implementation (the version with unwrap_level)
template<std::size_t unwrap_level, class T>
constexpr auto recursive_count(const T& input, const auto& target)
{
if constexpr (unwrap_level > 0)
{
static_assert(unwrap_level <= recursive_depth<T>(),
"unwrap level higher than recursion depth of input");
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [&target](auto&& element) {
return recursive_count<unwrap_level - 1>(element, target);
});
}
else
{
return (input == target) ? 1 : 0;
}
}
// recursive_count implementation (the version without unwrap_level)
template<std::ranges::input_range Range>
constexpr auto recursive_count(const Range& input, const auto& target)
{
return recursive_count<recursive_depth<Range>()>(input, target);
}
// recursive_count implementation (with execution policy)
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::count(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), target);
}
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [execution_policy, target](auto&& element) {
return recursive_count(execution_policy, element, target);
});
}
// recursive_count_if implementation
template<class T, std::invocable<T> Pred>
constexpr std::size_t recursive_count_if(const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<std::ranges::input_range Range, class Pred>
requires (!std::invocable<Pred, Range>)
constexpr auto recursive_count_if(const Range& input, const Pred& predicate)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (with execution policy)
template<class ExPo, class T, std::invocable<T> Pred>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr std::size_t recursive_count_if(ExPo execution_policy, const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<class ExPo, std::ranges::input_range Range, class Pred>
requires ((std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<Pred, Range>))
constexpr auto recursive_count_if(ExPo execution_policy, const Range& input, const Pred& predicate)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (the version with unwrap_level)
template<std::size_t unwrap_level, std::ranges::range T, class Pred>
auto recursive_count_if(const T& input, const Pred& predicate)
{
if constexpr (unwrap_level > 1)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if<unwrap_level - 1>(element, predicate);
});
}
else
{
return std::count_if(std::ranges::cbegin(input), std::ranges::cend(input), predicate);
}
}
// recursive_print implementation
template<typename T>
constexpr void recursive_print(const T& input, const std::size_t level = 0)
{
std::cout << std::string(level, ' ') << input << '\n';
}
template<std::ranges::input_range Range>
constexpr void recursive_print(const Range& input, const std::size_t level = 0)
{
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::for_each(input, [level](auto&& element) {
recursive_print(element, level + 1);
});
}
// recursive_replace_copy_if implementation
template<std::ranges::range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate, class T>
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::replace_copy_if(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate,
new_value);
return output;
}
template<std::ranges::input_range Range, class UnaryPredicate, class T>
requires (!std::invocable<UnaryPredicate, std::ranges::range_value_t<Range>>)
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate, &new_value](auto&& element) { return recursive_replace_copy_if(element, unary_predicate, new_value); }
);
return output;
}
// recursive_size implementation
template<class T> requires (!std::ranges::range<T>)
constexpr auto recursive_size(const T& input)
{
return 1;
}
template<std::ranges::range Range> requires (!(std::ranges::input_range<std::ranges::range_value_t<Range>>))
constexpr auto recursive_size(const Range& input)
{
return std::ranges::size(input);
}
template<std::ranges::range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_size(const Range& input)
{
return std::transform_reduce(std::ranges::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto& element) {
return recursive_size(element);
});
}
// recursive_transform implementation
// recursive_invoke_result_t implementation
// from https://stackoverflow.com/a/65504127/6667035
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>> &&
std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
template <std::ranges::range Range>
constexpr auto get_output_iterator(Range& output)
{
return std::inserter(output, std::ranges::end(output));
}
template <class T, std::invocable<T> F>
constexpr auto recursive_transform(const T& input, const F& f)
{
return f(input);
}
template <
std::ranges::input_range Range,
class F>
requires (!std::invocable<F, Range>)
constexpr auto recursive_transform(const Range& input, const F& f)
{
recursive_invoke_result_t<F, Range> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform(element, f); }
);
return output;
}
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::begin(output), std::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
int main()
{
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_replace_copy_if(test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
recursive_print(recursive_replace_copy_if(test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_replace_copy_if(
test_string_vector, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_replace_copy_if(
test_string_vector2, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_replace_copy_if(test_deque, [](int x) { return (x % 2) == 0; }, 0));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_replace_copy_if(test_deque2, [](int x) { return (x % 2) == 0; }, 0));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_replace_copy_if(test_list, [](int x) { return (x % 2) == 0; }, 0));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_replace_copy_if(test_list2, [](int x) { return (x % 2) == 0; }, 0));
return 0;
}
</code></pre>
</p>
<p><a href="https://godbolt.org/z/Gdx8jWEdz" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/254178/231235">A recursive_copy_if Template Function Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The implementation of <code>recursive_replace_copy_if</code> template function is the main idea in this question.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T02:10:58.857",
"Id": "501645",
"Score": "0",
"body": "@G.Sliepen Thank you for the comments. Already updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-04T14:53:20.683",
"Id": "532281",
"Score": "1",
"body": "I think it looks good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-04T23:50:40.300",
"Id": "532314",
"Score": "0",
"body": "@JDługosz Thank you :-)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T01:38:15.067",
"Id": "254332",
"Score": "1",
"Tags": [
"c++",
"recursion",
"template",
"lambda",
"c++20"
],
"Title": "A recursive_replace_copy_if Template Function Implementation in C++"
}
|
254332
|
<h2>Background</h2>
<p>Given some random array of numbers like <code>[3, 5, -4, 8, 11, 1, -1, 6]</code> and a target value <code>10</code>, find two numbers within the array that equal to the target value.</p>
<h2>Code</h2>
<pre><code>def two_Number_Sum(array, target):
unique_number_set = set()
for num in array:
required_value = target - num
if required_value in unique_number_set:
return [num, required_value]
else:
unique_number_set.add(num)
return []
print(two_Number_Sum([3, 5, -4, 8, 11, 1, -1, 6], 10))
</code></pre>
<p>I am wondering if I can make this answer more pythonic. I don't have a Python background so a lot of times I write code like Java or another language, and I figure it will be good practice to critique myself and write code that is more pythonic so it becomes natural.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T03:19:17.353",
"Id": "501553",
"Score": "0",
"body": "`two_Number_Sum` should be wrritten as `two_number_sum`"
}
] |
[
{
"body": "<p>You can accomplish this with <code>itertools.combinations</code>. A lot of the pythonic code you will see is just clever use of built-in functions and libraries. Getting familiar with these will greatly speed up your learning of this language :).</p>\n<pre><code>import itertools\nfrom typing import List\n\ndef two_number_sum_2(array: List[int], target: int) -> List[int]:\n for x, y in itertools.combinations(array, 2):\n if x + y == target:\n return [x, y]\n</code></pre>\n<p>It's shorter, cleaner, and is faster than your original code (faster with small datasets). A couple more tips:</p>\n<ul>\n<li>Functions and variables should be <code>snake_case</code>, not <code>Snake_Case</code> or <code>camel_Snake_Case</code>.</li>\n<li>Add type hints to display what types you accept as parameters, and what value you return from the function.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T02:49:48.560",
"Id": "501551",
"Score": "0",
"body": "That helps and is there a way to make it more pythonic without using built-in functions? I think in a typical interview you can't use built-in functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T03:01:06.957",
"Id": "501552",
"Score": "5",
"body": "Why using `itertools.combinations` is faster than OP's solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T14:24:22.047",
"Id": "501580",
"Score": "0",
"body": "@Marc, perhaps it's faster when you include programmer time and CPU time..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T16:01:05.077",
"Id": "501590",
"Score": "1",
"body": "This is a very common interview question, if you were to answer with a solution that generates all combinations without solid reasoning this is going to reflect badly. For large input the `O(N)` by OP is going to outperform this `O(N^2)` solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:23:58.843",
"Id": "501620",
"Score": "0",
"body": "@Marc For the tests I ran my solution was faster, but I can see with bigger data sets my solution is considerably slower. I'll leave this answer here because it can still be a viable alternative when dealing with small datasets."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T02:41:40.797",
"Id": "254334",
"ParentId": "254333",
"Score": "0"
}
},
{
"body": "<p>Few suggestions:</p>\n<ul>\n<li><strong>Naming</strong>: <code>array</code> is not an array, a more appropriate name can be <code>numbers</code>. Also <code>unique_number_set</code> can be just <code>unique_numbers</code>, the name already tells that there are no duplicates.</li>\n<li><strong>Unnecessary else</strong>: the <code>else</code> is not required so it can be removed.</li>\n<li><strong>Type hints</strong>: @Linny already pointed this out. I add that, if the result doesn't need to be modified, consider returning a tuple. Additionally, it tells the caller that the result will only contain two numbers.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List, Tuple, Union\n\ndef two_number_sum(numbers: List[int], target: int) -> Union[Tuple[int, int], Tuple[()]]:\n unique_numbers = set()\n for num in numbers:\n required_value = target - num\n if required_value in unique_numbers:\n return num, required_value\n unique_numbers.add(num)\n return ()\n</code></pre>\n<p>Thanks to @KellyBundy and @AJNeufeld for the feedbacks in the comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T06:12:21.353",
"Id": "501559",
"Score": "2",
"body": "Your return type is wrong. `()` is not a `Tuple[int,int]`. You'd need `Union[Tuple[int,int], Tuple[]]`. Alternately, return `None` and use `Optional[Tuple[int,int]]`. Or, keep the return type and raise an exception if no pair can be found."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T06:45:09.893",
"Id": "501560",
"Score": "0",
"body": "@AJNeufeld thanks, I updated the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T01:00:06.460",
"Id": "501641",
"Score": "0",
"body": "Just curious what does \"Union\" indicate? Does it mean that the return type can either be an empty tuple or a tuple with int,int?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T02:55:28.687",
"Id": "501649",
"Score": "0",
"body": "@Dinero yes. More info [here](https://docs.python.org/3/library/typing.html#typing.Union)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T03:39:24.783",
"Id": "254335",
"ParentId": "254333",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254335",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T02:15:25.510",
"Id": "254333",
"Score": "5",
"Tags": [
"python"
],
"Title": "Find two numbers that equal to target value"
}
|
254333
|
<p><strong>Motivation:</strong></p>
<p>I very often face a task where I need to check that dataframe's values are correct or not. Based on it I can create another dataframe with <em>True</em>/<em>False</em> values which are based on the first dataframe. I demonstrate an example of such a task below. I have a dataframe with logs, and I need to check that each value corresponds to a certain range. If it is in the range then an algorithm returns <em>True</em> in the corresponding cell of a new dataframe. Essentially the algorithm could be used to anomaly detection in dataframes. In simple examples, it is pretty easy to use <em>apply methods</em> and built in <em>NumPy</em> functions. Bellow is a nontrivial example for which I am struggling to find fast implementation.</p>
<p><strong>Input:</strong></p>
<p>I am trying to understand how to make code works faster by converting for-loops to vectorized operations.</p>
<p><strong>Desired output:</strong></p>
<p>Based on this dataframe I want to create a new dataframe where each value is <strong>True</strong> or <strong>False</strong> based on some specific rules</p>
<p><strong>Data:</strong></p>
<p>Data is presented in json format <strong>data.json</strong>:</p>
<pre><code>[
{
"Med": "9/20/2020 8:50",
"KE": 1,
"SL": 154
},
{
"Med": "9/20/2020 8:50",
"KE": 2,
"SL": 123
},
{
"Med": "9/20/2020 8:50",
"KE": 3,
"SL": 132
},
{
"Med": "9/20/2020 8:57",
"KE": 1,
"SL": 141
},
{
"Med": "9/20/2020 8:57",
"KE": 8,
"SL": 151
},
{
"Med": "9/20/2020 8:57",
"KE": 2,
"SL": 155
},
{
"Med": "9/20/2020 9:12",
"KE": 1,
"SL": 151
},
{
"Med": "9/20/2020 9:12",
"KE": 5,
"SL": 154
},
{
"Med": "9/20/2020 9:12",
"KE": 3,
"SL": 144
},
{
"Med": "9/20/2020 9:20",
"KE": 1,
"SL": 134
},
{
"Med": "9/20/2020 9:20",
"KE": 4,
"SL": 155
},
{
"Med": "9/20/2020 9:20",
"KE": 3,
"SL": 153
}
]
</code></pre>
<p><strong>My implementation:</strong></p>
<p>I upload data as the following:</p>
<pre><code>def upload_data(file):
df = pd.read_json(file)
df['Med'] = pd.to_Medtime(df['Med'], format="%Y-%d-%m %H:%M:%S")
df['EQE'] = np.nan
return df
df = upload_data('data.json')
</code></pre>
<p>Next, I create an additional row. I managed to do it in a vectorized way:</p>
<pre><code>df['EQE'] = (df['Med'] != df['Med'].shift()).cumsum()
</code></pre>
<p>Finally I create dataframe with the results:</p>
<pre><code>def create_df_with_reslts(df):
df_results = pd.DataFrame().reindex_like(df)
df_results['Pred'] = np.nan
return df_results
df_results = create_df_with_reslts(df)
</code></pre>
<p>And now I am looking at how to speed up and vectorize a main part of the code</p>
<pre><code>def check_df(df, df_results):
# check Med format
Med_format = '%Y-%m-%d %H:%M:%S'
for index, row in df.iterrows():
Med_string = row['Med']
try:
df_results['Med'][index] = True
except ValueError:
df_results['Med'][index] = False
# checking that number of KEs is between 1 and 500
df_results['KE'] = np.where((df['KE'] >=1) & (df['KE'] <=500), True, False)
# finding bordes for EQE's spans
previous_row = df['Med'].astype(str)[0]
EQE_index = 0
EQE_list = []
for index, row in df.iterrows():
# for same EQE
if row['Med'] == previous_row:
EQE_index += 1
previous_row = row['Med']
# for next EQE in table
else:
EQE_list.append(EQE_index)
EQE_index = 1
previous_row = row['Med']
EQE_list.append(EQE_index)
# checking whether or not borders are correct
k=0
for i in range(len(EQE_list)):
if EQE_list[i] == 6 or EQE_list[i] == 8:
for j in range(EQE_list[i]):
df_results['EQE'][j+k] = True
else:
for j in range(EQE_list[i]):
df_results['EQE'][j+k] = False
j=EQE_list[i]
k=k+j
# Values of SL corresponds to uniform distribution with epsilon 10%
list_of_columns = ['SL']
for n in range(len(list_of_columns)):
# find the highest number for each EQE (EQE_MAX)
k=0
max_list = []
for i in range(len(EQE_list)):
X = df[list_of_columns[n]][k:k+EQE_list[i]+1]
max_list.append(X[X == X.max()].iloc[0])
k=k+EQE_list[i]
# check that each value in [max_list*10/100, max_list]
k=0
for i in range(len(EQE_list)):
for j in range(EQE_list[i]):
if float(df[list_of_columns[n]][j+k]) >= float(max_list[i])*90/100 and float(df[list_of_columns[n]][j+k]) <= float(max_list[i]):
df_results[list_of_columns[n]][j+k] = True
else:
df_results[list_of_columns[n]][j+k] = False
j=EQE_list[i]
k=k+j
# final results for each column
df_results['Pred'] = df_results.prod(axis=1).astype(bool)
# return max_list
return df_results
%timeit check_df(df, df_results)
# 19.5 ms ± 2.84 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>I changed iteration over dataframe into iteration over iterrows: <em>range(len(df))</em> into <em>df.iterrows()</em>. It gave only ~20% speedup. Also one for-loop was changed with vectorized operation (<em>np.where</em>). I don't know how to do the same for other for-loops.</p>
<p><strong>My question:</strong></p>
<p>Is it possible to speedup and vectorize other parts of the code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T16:12:56.010",
"Id": "501698",
"Score": "2",
"body": "(There is (speed up)(anomaly detection), and there is (speed up anomaly)(detection).) As a title, just state the purpose of the code presented - see [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T23:59:52.387",
"Id": "503234",
"Score": "0",
"body": "\"*In simple examples, it is pretty easy to use apply methods and built in NumPy functions.*\" `apply` is inefficient in general and should be used only if there are no alternative built-in functions that can achieve the same goal."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T04:56:29.023",
"Id": "254336",
"Score": "0",
"Tags": [
"python",
"performance",
"pandas",
"complexity",
"vectorization"
],
"Title": "Speed-up anomaly detection for pandas dataframes with vectorized operations"
}
|
254336
|
<p>Please consider evaluating the code below for best practices, efficiency, and mistakes. I got some of the code from W3 schools (I know, I know, but they've come a long way) and assimilated it to what I need. Particularly, the <code>days = hours = minutes = seconds = 0;</code> is likely going to cause people stress but after research and evaluation, I found that it works well in this case.</p>
<p>Please evaluate my <strong>JS</strong> code. Thank you. <a href="https://codepen.io/phoshen/pen/BaLxVxv" rel="nofollow noreferrer">CODEPEN</a></p>
<p><strong>IMPRORTANT</strong>: The code below checks for the existence of an ACF variable (exposed via the functions.php with a WordPress backend), upon which this entire code is based. I replaced the variable with an example string which would be returned by this field.</p>
<pre><code>(function () {
let acf_vars = {timer: "2021 1 21 13 08 00"}; // this code is a replacement for the ACF variable
if (!acf_vars.timer) {
return document
.querySelectorAll('.mobile-ticker')
.forEach((container) => (container.style.display = 'none'));
}
const backendTimer = acf_vars.timer.split(' ');
const y = backendTimer[0];
const M = +backendTimer[1] - 1; // monthIndex in Date Object begins with 0, so we subtract 1
const d = backendTimer[2];
const h = backendTimer[3];
const m = backendTimer[4];
const s = backendTimer[5];
// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
const countDownDate = new Date(y, M, d, h, m, s, 0).getTime();
const timerInterval = setInterval(() => {
const now = new Date().getTime();
const distance = countDownDate - now;
const expiredTimer = distance <= 0;
let days = Math.floor(distance / (1000 * 60 * 60 * 24));
let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
let seconds = Math.floor((distance % (1000 * 60)) / 1000);
if (expiredTimer) {
days = hours = minutes = seconds = 0;
clearInterval(timerInterval);
}
if (typeof window.innerWidth === 'number' && window.innerWidth < 768) {
document.querySelector('.ticker-mobile #days').innerHTML = days;
document.querySelector('.ticker-mobile #hours').innerHTML = hours;
document.querySelector('.ticker-mobile #minutes').innerHTML = minutes;
document.querySelector('.ticker-mobile #seconds').innerHTML = seconds;
} else {
document.querySelector('.ticker-desktop #days').innerHTML = days;
document.querySelector('.ticker-desktop #hours').innerHTML = hours;
document.querySelector('.ticker-desktop #minutes').innerHTML = minutes;
document.querySelector('.ticker-desktop #seconds').innerHTML = seconds;
}
}, 1000);
})();
</code></pre>
|
[] |
[
{
"body": "<p><strong>Can you send the timestamp instead?</strong> Manipulating dates in JS is a bit tedious without a library. This is probably pretty clear to you already from having to declare all the <code>y M d h m s</code> variables. PHP, on the other hand, has <a href=\"https://www.php.net/manual/en/datetime.createfromformat.php\" rel=\"nofollow noreferrer\"><code>createFromFormat</code></a>, which has a flexible and friendly API. For example, I believe you could pass a formatting string of <code>'Y m d H i s'</code> (corresponding to the input of <code>'2021 1 4 13 08 00'</code>) and get the timestamp out of it immediately.</p>\n<p>Working with timestamps is easier than working with custom formatted strings anyway. I don't know the source of the original date string, but I'd turn it into a timestamp as soon as possible once your app receives it (and, for example, save the timestamp in the database instead of the string).</p>\n<p>When you <em>do</em> have to pass around a string instead of a timestamp, use a standardized <a href=\"https://www.iso.org/iso-8601-date-and-time-format.html\" rel=\"nofollow noreferrer\">ISO 8601 string</a>, which can be parsed automatically in most languages.</p>\n<p><strong>Ticker display</strong> Currently, the tickers are hidden via the JS if there's no timer. Consider if you could carry out this check (and this whole conditional code) in the PHP, rather than sending the HTML markup regardless and then possibly hide it if there's no timer. For example, you might change it so that the server only serves this <code>.js</code> if there's a timer to begin with, otherwise the <code><script></code> tag (and maybe the tickers) are omitted entirely by the backend.</p>\n<p><strong>Destructure</strong> If you do need to parse the date string on the frontend, you can make things more concise by destructuring instead of listing all the indicies of <code>backendTimer</code>. I'd also at least use <code>month</code> and <code>minutes</code> instead of <code>M</code> and <code>m</code> (you might also expand the other variable names for consistency):</p>\n<pre><code>const [y, month, d, h, minutes, s] = acf_vars.timer.split(' ');\n// The month in the input string is 1-indexed\n// The month the date constructor accepts is 0-indexed, so subtract 1:\nconst countDownDate = new Date(y, month - 1, d, h, minutes, s).getTime();\n</code></pre>\n<p>The number of milliseconds can be omitted entirely when passing to the Date constructor.</p>\n<p><strong>Show the timer immediately</strong> Right now, the tickers start getting populated 1000ms after this script runs. Until then, they'll be empty. Consider putting the interval callback into a named function first, and call that function immediately, so that the user doesn't have to wait an additional second. Eg</p>\n<pre><code>const updateCountdown = () => {\n const now = new Date().getTime();\n // ...\n};\nconst timerInterval = setInterval(updateCountdown, 1000);\nupdateCountdown();\n</code></pre>\n<p><strong>Duplicate IDs are invalid HTML</strong> There should only ever be at most one element with a given ID in a document. If a certain sort of element might be repeated, use a class instead of an ID. But, even better:</p>\n<p><strong>Can you combine the tickers?</strong> You have one ticker for mobile, and a separate ticker for desktop. This is odd and results in code repetition. Unless there's a good reason not to, figure out if there's any way they can be combined. (I don't see anything substantial differentiating the two tickers in the code given, so I'm not sure what the obstacle might be. If it's just for CSS, use media queries instead.)</p>\n<p><strong>Mobile ticker vs ticker mobile?</strong> The HTML is a bit confusing:</p>\n<pre><code><section class="mobile-ticker">\n <div class="ticker ticker-desktop">\n ...\n </div>\n <div class="ticker ticker-mobile">\n</code></pre>\n<p>So there's <code>.mobile-ticker</code>, the container, and then there's a <code>.ticker-desktop</code>, a child, and then there's a <code>.ticker-mobile</code>, another child. Maybe call the container something like <code>ticker-container</code> instead?</p>\n<p><strong>Only use <code>.innerHTML</code> when deliberately working with HTML markup</strong>. If what you have or want is <em>plain text</em>, it's faster, safer, and more semantically appropriate to use <code>.textContent</code> instead of <code>.innerHTML</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T21:15:17.117",
"Id": "501630",
"Score": "0",
"body": "This is really good, thank you very much for the detailed response. I'm implementing some of these changes as we speak, but the element's innerHTML/textContent doesn't seem to be available when putting the interval callback in a named function first: `Uncaught TypeError: Cannot set property 'innerHTML' of null`. In order to fix this, one option I found was to replace the IIFE with `jQuery(function() {})`, but I don't fully understand why this would be an issue in the first place"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T21:32:43.320",
"Id": "501632",
"Score": "0",
"body": "Your script is running before the element exists. See [here](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). My preferred solution is to give the `<script>` tag the `defer` attribute."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T18:30:42.243",
"Id": "254352",
"ParentId": "254348",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T17:40:57.953",
"Id": "254348",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Countdown Timer evaluation"
}
|
254348
|
<p>In my rails application, I have 2 different types of active record user, for e.g. User1 has first_name, email etc and User2 also has these attributes but for user 2 we get the data from an external API, so when creating the invoices I am passing the user model to the invoice, and I am thinking of doing something like this for User2</p>
<pre><code>class User2
def first_name
if persisted?
data['firstName']
end
end
def email
if persisted?
data['email']
end
end
private
def data
@__data ||= ExternalUserInfo.new(external_id).call
end
end
</code></pre>
<p>The ExternalUserInfo client will make the call to the external API and return the response as such</p>
<pre><code>{
firstName: "John", email: "john@example.com"
}
</code></pre>
<p>The problem with this approach is that whenever I will need to write a spec which needs to create this user, then I will need to wrap that test around VCR cassette or stub the external request. So I wanted to review what could be a potential solution to avoid this or if this design even make sense at all</p>
|
[] |
[
{
"body": "<p>I think this design makes sense. For the problem with testing you could have a fake / dummy client stored on the class which you can swap out in the tests.</p>\n<p>Something like</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class RemoteUser\n class << self\n def client\n @client ||= ExternalUserInfo.new\n end\n end\n\n def first_name\n if persisted?\n data['firstName']\n end\n end\n\n def email\n if persisted?\n data['email']\n end\n end\n\n private\n\n def data\n self.class.client.call(external_id)\n end\nend\n</code></pre>\n<p>And in your tests you do something like this</p>\n<pre><code>class RemoteUserTest\n class DummyClient\n def call(id)\n {\n firstName: "John", email: "john@example.com"\n }\n end\n end\n\n setup do\n # this could of course happen in your test helper for every test\n RemoteUser.client = DummyClient.new\n end\n\n def teardown\n RemoteUser.client = nil\n end\n\n test "#foo"\n # do your tests\n end\nend\n</code></pre>\n<p>Another approach could be to use <a href=\"https://github.com/bblimke/webmock\" rel=\"nofollow noreferrer\">Webmock</a> instead of VCR (VCR uses Webmock actually under the hood). Either use the stub methods or build a fake (e.g. with Sinatra).</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class FakeUserRemoteApp\n\n def self.call(env)\n json = {\n firstName: "John", email: "john@example.com"\n }\n [200, {}, [json]]\n end\nend\n\nstub_request(:get, "www.example.com").to_rack(MyRackApp)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-24T21:20:02.523",
"Id": "264360",
"ParentId": "254349",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T17:48:00.710",
"Id": "254349",
"Score": "1",
"Tags": [
"ruby-on-rails"
],
"Title": "Hooking up active record model with external api in rails app"
}
|
254349
|
<p>I have a project that runs an image until an accepted rfid card is scanned. At this point, a video is played and an unlock signal is sent. Before and after the accepted card runs, an image is displayed. Right now when script runs the image is displayed, when card is scanned nothing happens. Alt-Tab into code, enter cursor to shell and scan accepted card, the program works without the background image. Please help....????</p>
<p>Accepted cards are checked against a txt file.</p>
<p>Here is my code:</p>
<pre><code>#!/usr/bin/env python3
from evdev import InputDevice
from select import select
import RPi.GPIO as GPIO
import time
from time import sleep
import subprocess
from subprocess import run
import datetime
import os
import sys
import re
import pygame
from pygame.locals import *
#def main():
def check_if_string_in_file(file_name, string_to_search):
"""Check if any line in the file contains given string"""
with open(file_name,'r') as read_obj:
for line in read_obj:
if string_to_search in line:
return True
return False
keys = "X^1234567890asdfghjklXXXXXycbnmXXXXXXXXXXXXXXXXXXXXXXX"
dev = InputDevice('/dev/input/event0')
pygame.init()
windowSurface = pygame.display.set_mode ((1024, 600), pygame.NOFRAME)
img = pygame.image.load("/home/pi/Access/New Phone Wallpaper copy.jpg")
pygame.mouse.set_cursor((8,8),(0,0), (0,0,0,0,0,0,0,0), (0,0,0,0,0,0,0,0))
windowSurface.blit(img, (0,0))
pygame.display.flip()
pygame.event.clear()
while True:
r,w,x = select([dev], [],[])
for event in dev.read():
if event.type==1 and event.value==1:
if event.code==28:
rfid_presented=input()
e = rfid_presented
if check_if_string_in_file("/home/pi/Access/Loaded_Cards.txt", e):
videoPath = "/home/pi/Access/18 Test_1.mp4"
omx = run(["omxplayer", '--win', '1,1,1024,600', videoPath])
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(26, GPIO.OUT, initial=GPIO.LOW)
GPIO.output(26, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(26, GPIO.LOW)
else:
rfid_presented = ""
else:
rfid_presented += keys[event.code]
del e
root.mainloop()
#main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T20:00:40.037",
"Id": "501624",
"Score": "0",
"body": "Welcome to Code Review! – I'm afraid that your question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T22:24:03.907",
"Id": "501636",
"Score": "0",
"body": "@Martin R....I see these types of questions all the time with codes that contain errors and will not work. My code works, just not exactly as intended"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T19:52:48.963",
"Id": "254355",
"Score": "1",
"Tags": [
"python"
],
"Title": "Python Expertise Needed for RFID Door Lock"
}
|
254355
|
<p>I have created a REST auth layer in front of my GraphQL API, I would like to know if it is secure enough or if I can improve anything, I will be adding more auth providers, in the end this API will serve a web app using the demonstrated Google log in and a React Native app with email, SMS, Facebook and Apple auth</p>
<pre><code>// index.ts
server
.register(fastifyCors, {
origin: process.env.CORS_ORIGIN,
credentials: true,
})
.register(fastifyCookie)
.register(fastifySession, {
cookieName: "fid",
store: new RedisStore({
client: new Redis(process.env.REDIS_URI),
ttl: SESSION_TTL,
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 365 * 10, // 10 years
httpOnly: true,
sameSite: "lax",
secure: true,
},
saveUninitialized: false,
secret: process.env.SESSION_SECRET,
})
.register(fastifyPassport.initialize())
.register(apolloServer.createHandler({ cors: false }))
.register(authRoutes)
</code></pre>
<pre><code>// setupPassport.ts
export const setupPassport = (prisma: PrismaClient) => {
fastifyPassport.registerUserSerializer<User, User["id"]>(
async (user) => user.id
)
fastifyPassport.registerUserDeserializer<User["id"], User>(async (id) => {
const user = await prisma.user.findUnique({
where: {
id,
},
})
if (!user) {
throw new Error("No user")
}
return user
})
fastifyPassport.use(
new Strategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:4000/auth/google/callback",
},
async (_accessToken, _refreshToken, profile, done) => {
const existingUser = await prisma.identity.findFirst({
where: {
provider: "GOOGLE",
providerId: profile.id,
},
include: {
user: true,
},
})
if (existingUser) {
return done(undefined, existingUser)
}
if (!profile.emails?.length || !profile.name) {
throw new Error("No email or name")
}
const newUser = await prisma.user.create({
data: {
...profile.name,
email: profile.emails[0].value,
identities: {
create: [{ provider: "GOOGLE", providerId: profile.id }],
},
},
})
return done(undefined, newUser)
}
)
)
}
</code></pre>
<pre><code>// authRoutes.ts
export const authRoutes: FastifyPluginCallback = (fastify, _opts, done) => {
fastify.get(
"/auth/google",
{
preValidation: fastifyPassport.authenticate("google", {
scope: ["profile", "email"],
}),
},
async (request, reply) => {}
)
fastify.get(
"/auth/google/callback",
{
preValidation: fastifyPassport.authorize("google", { session: false }),
},
async (request, reply) => {}
)
done()
}
</code></pre>
<pre><code>// permissions.ts
import { shield } from "graphql-shield"
export const permissions = shield({
Query: {},
Mutation: {},
ShopLocation: rules.isAuthenticatedUser,
})
// rules.ts
import { rule } from "graphql-shield"
export const rules = {
isAuthenticatedUser: rule()(async (_parent, _args, ctx: Context) => {
return ctx.request.isAuthenticated()
}),
isAdmin: rule()(async (_parent, _args, ctx: Context) => {
return ctx.request.user.role === Role.ADMIN
}),
isOperator: rule()(async (_parent, _args, ctx: Context) => {
return ctx.request.user.role === Role.OPERATOR
}),
isUser: rule()(async (_parent, _args, ctx: Context) => {
return ctx.request.user.role === Role.USER
}),
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T20:34:55.810",
"Id": "254357",
"Score": "1",
"Tags": [
"api",
"authentication",
"session",
"oauth",
"graphql"
],
"Title": "Secure GraphQL API with REST auth layer"
}
|
254357
|
<p>I'm a new programmer and I'm periodically going into the Intro To Algorithms CLRS textbook and trying to translate pseudocode into Ruby for skill practice. This is my implementation/translation of insertion sort.</p>
<p>I'm looking for feedback on readability as well as efficiency.</p>
<p>Pseudocode is found on page 17 of Intro To Algorithms Second Edition just in case you happen to have it lying around, more interested in the feedback just on the code itself.</p>
<pre><code>class InsertionSort
attr_accessor :arr
def initialize(arr)
@arr = arr
end
def sort
key = 1
to_the_left = key - 1
while key < self.arr.length
if arr[key] < arr[to_the_left]
mover_key = key
left_ele_moving_right = to_the_left
until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right < 0
arr[left_ele_moving_right], arr[mover_key] =
arr[mover_key], arr[left_ele_moving_right]
mover_key -= 1
left_ele_moving_right -= 1
end
end
key += 1
to_the_left += 1
end
self.arr
end
end
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Consistency</h1>\n<p>Sometimes you are using 4 spaces for indentation, sometimes 2. Sometimes you are using vertical whitespace (an empty line) before a method definition, sometimes you don't. Sometimes you have whitespace at the end of a line, sometimes you don't. In one case, you indent a couple of lines just for no discernible reason.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).</p>\n<p>In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing <em>IFF</em> you actually <em>want</em> to convey some extra information.</p>\n<p>For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a <em>good</em> reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).</p>\n<h1>Indentation</h1>\n<p>The community standard for indentation is 2 spaces. For example, your first two lines should look like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class InsertionSort\n attr_accessor :arr\n</code></pre>\n<p>Instead of this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class InsertionSort\n attr_accessor :arr\n</code></pre>\n<p>Furthermore, you should only indent in places where there is a logically nested structure, e.g. a method definition inside a class definition, the body of the method definition, the body of a block, etc. An exception is a continuation of the previous line, this should also be indented.</p>\n<p>Here, you are indenting for no apparent reason:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>arr[left_ele_moving_right], arr[mover_key] =\narr[mover_key], arr[left_ele_moving_right]\n\n mover_key -= 1 \n left_ele_moving_right -= 1\n</code></pre>\n<p>On the other hand, in the same place, you <em>should</em> indent this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>arr[left_ele_moving_right], arr[mover_key] =\n arr[mover_key], arr[left_ele_moving_right]\n</code></pre>\n<p>To make it clear that the second line is a continuation of the first.</p>\n<h1>No whitespace at the end of the line</h1>\n<p>There should be no whitespace at the end of the line. For example, this line:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>if arr[key] < arr[to_the_left] \n</code></pre>\n<p>Has a space at the end. That shouldn't be there. And there are two more lines like this.</p>\n<p>Also, there are multiple "empty" lines that actually contain <em>only</em> spaces. Again, those shouldn't be there.</p>\n<h1>No empty line at the end of the file</h1>\n<p>Your file should end with a single newline. There should not be an extra empty line at the end of the file.</p>\n<h1>Vertical whitespace</h1>\n<p>There should be a blank line after every "logical" break. In particular, there should be a blank line after the <code>attr_accessor</code>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>attr_accessor :arr\n\ndef initialize(arr)\n</code></pre>\n<p>On the other hand, there should be no empty line directly after the <code>if</code> and the <code>until</code>.</p>\n<p>Otherwise, your use of vertical whitespace looks good! Logical steps in the method are clearly separated by empty lines, the code looks "light", not all bunched together with "room to breathe". I like it, well done!</p>\n<h1><code>self</code> is the implicit receiver</h1>\n<p>In Ruby, if you don't explicitly specify the receiver of a message send, the receiver is <code>self</code>. In idiomatic code, you should never explicitly specify the receiver <code>self</code>, unless it is absolutely necessary.</p>\n<p>Right now, I can only think of two cases, where it would be necessary:</p>\n<ul>\n<li>To use an attribute writer method: <code>self.foo = bar</code>.</li>\n<li>To use an operator: <code>self + foo</code></li>\n</ul>\n<p>So, this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>self.arr\n</code></pre>\n<p>should just be:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>arr\n</code></pre>\n<p>Same here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>while key < self.arr.length\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>while key < arr.length\n</code></pre>\n<h1>Prefer predicate methods over relational operators</h1>\n<p>You should prefer "speaking" predicate methods such as <a href=\"https://ruby-doc.org/core/Numeric.html#method-i-negative-3F\" rel=\"nofollow noreferrer\"><code>Numeric#negative?</code></a> over relational operators such as <code>< 0</code>.</p>\n<p>So, this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>left_ele_moving_right < 0\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>left_ele_moving_right.negative?\n</code></pre>\n<h1>Code Formatting</h1>\n<p>If possible, you should set your editor or IDE to automatically format your code when you type, when you paste, and when you save, and set up your version control system to automatically format your commit when you push, as well as set up your CI system to reject code that is not correctly formatted. If not possible, you should seriously consider using a different editor or IDE, version control system, or CI system.</p>\n<p>Here's the result of your code, when I simply paste it into my editor, without doing anything else:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class InsertionSort\n attr_accessor :arr\n\n def initialize(arr)\n @arr = arr\n end\n\n def sort\n key = 1\n to_the_left = key - 1\n\n while key < arr.length\n if arr[key] < arr[to_the_left]\n\n mover_key = key\n left_ele_moving_right = to_the_left\n\n until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right < 0\n\n arr[left_ele_moving_right], arr[mover_key] =\n arr[mover_key], arr[left_ele_moving_right]\n\n mover_key -= 1\n left_ele_moving_right -= 1\n end\n end\n\n key += 1\n to_the_left += 1\n end\n\n arr\n end\nend\n</code></pre>\n<p>As you can see, simply copying your code into my editor, the editor corrected every single thing I wrote above except one.</p>\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 above (plus some more), and also was able to autocorrect all of the ones I listed.</p>\n<p>Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can <em>actually</em> correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".</p>\n<p>In particular, running Rubocop on your code, it detects 26 offenses, of which it can automatically correct 23.</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class InsertionSort\n attr_accessor :arr\n\n def initialize(arr)\n @arr = arr\n end\n\n def sort\n key = 1\n to_the_left = key - 1\n\n while key < arr.length\n if arr[key] < arr[to_the_left]\n\n mover_key = key\n left_ele_moving_right = to_the_left\n\n until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?\n\n arr[left_ele_moving_right], arr[mover_key] =\n arr[mover_key], arr[left_ele_moving_right]\n\n mover_key -= 1\n left_ele_moving_right -= 1\n end\n end\n\n key += 1\n to_the_left += 1\n end\n\n arr\n end\nend\n</code></pre>\n<p>And here are the offenses that Rubocop could not automatically correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Inspecting 1 file\nC\n\nOffenses:\n\ninsertion_sort.rb:1:1: C: Style/Documentation: Missing top-level class documentation comment.\nclass InsertionSort\n^^^^^\ninsertion_sort.rb:8:3: C: Metrics/AbcSize: Assignment Branch Condition size for sort is too high. [<10, 21, 7> 24.29/17]\n def sort ...\n ^^^^^^^^\ninsertion_sort.rb:8:3: C: Metrics/MethodLength: Method has too many lines. [17/10]\n def sort ...\n ^^^^^^^^\n\n1 file inspected, 3 offenses detected\n</code></pre>\n<p>Similar to Code Formatting, it is a good idea to set up your tools such that the linter is automatically run when you paste code, edit code, save code, commit code, or build your project, and that passing the linter is a criterium for your CI pipeline.</p>\n<h1><code>attr_reader</code> vs. <code>attr_accessor</code></h1>\n<p>You are never writing to <code>arr</code>, so it should probably be a <a href=\"https://ruby-doc.org/core/Module.html#method-i-attr_reader\" rel=\"nofollow noreferrer\"><code>Module#attr_reader</code></a> instead of a <a href=\"https://ruby-doc.org/core/Module.html#method-i-attr_accessor\" rel=\"nofollow noreferrer\"><code>Module#attr_accessor</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>attr_reader :arr\n</code></pre>\n<h1>Access Restrictions</h1>\n<p><code>arr</code> is not intended to be used by other objects. In fact, it <em>shouldn't</em> be used by other objects! It is private internal state of the sorter object. Therefore, it should not be part of the public API, it should be <a href=\"https://ruby-doc.org/core/Module.html#method-i-private\" rel=\"nofollow noreferrer\"><code>private</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>private attr_reader :arr\n</code></pre>\n<h1>Iterators</h1>\n<p>In Ruby, you almost never use loops. You would normally use <em>at least</em> an low-level iterator such as <a href=\"https://ruby-doc.org/core/Kernel.html#method-i-loop\" rel=\"nofollow noreferrer\"><code>Kernel#loop</code></a>, <code>#each</code>, or <a href=\"https://ruby-doc.org/core/Integer.html#method-i-times\" rel=\"nofollow noreferrer\"><code>Integer#times</code></a>. Really, you want to use higher-level iterators such as <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-map\" rel=\"nofollow noreferrer\"><code>Enumerable#map</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-select\" rel=\"nofollow noreferrer\"><code>Enumerable#select</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-group_by\" rel=\"nofollow noreferrer\"><code>Enumerable#group_by</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-flat_map\" rel=\"nofollow noreferrer\"><code>Enumerable#flat_map</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-inject\" rel=\"nofollow noreferrer\"><code>Enumerable#inject</code></a>, etc.</p>\n<p>In this case, we are going to use <code>Integer#times</code> for the outer loop.</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def sort\n arr.length.times do |key|\n to_the_left = key - 1\n\n if arr[key] < arr[to_the_left]\n mover_key = key\n left_ele_moving_right = to_the_left\n\n until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?\n arr[left_ele_moving_right], arr[mover_key] =\n arr[mover_key], arr[left_ele_moving_right]\n\n mover_key -= 1\n left_ele_moving_right -= 1\n end\n end\n end\n\n arr\nend\n</code></pre>\n<h1>Guard clauses</h1>\n<p>If you have a case where an entire method or block is wrapped in a conditional, you can replace that with a "guard clause" and reduce the level of nesting.</p>\n<p>E.g. this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def something\n if foo\n bar\n baz\n quux\n else\n 42\n end\nend\n</code></pre>\n<p>can become this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def something\n return 42 unless foo\n\n bar\n baz\n quux\nend\n</code></pre>\n<p>After the above change, there is now an opportunity to do that in your code:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def sort\n arr.length.times do |key|\n to_the_left = key - 1\n\n next unless arr[key] < arr[to_the_left]\n\n mover_key = key\n left_ele_moving_right = to_the_left\n\n until arr[mover_key] > arr[left_ele_moving_right] || left_ele_moving_right.negative?\n arr[left_ele_moving_right], arr[mover_key] =\n arr[mover_key], arr[left_ele_moving_right]\n\n mover_key -= 1\n left_ele_moving_right -= 1\n end\n end\n\n arr\nend\n</code></pre>\n<h1>Objects</h1>\n<p>I don't see a particular reason why insertion sort should be an object. It doesn't have any state (having the array to be sorted, as you do, as state is somewhat weird), and it only has a simple single behavior. It would make more sense for a sorting algorithm to be an object if it carries some complex state that persists between different runs of the algorithm.</p>\n<p>In a language which supports procedures or functions, this should probably be a function.</p>\n<p>In Ruby, I would make it maybe a singleton method of a module, or an instance method of <a href=\"https://ruby-doc.org/core/Array.html\" rel=\"nofollow noreferrer\"><code>Array</code></a>. However, I would not name it <code>sort</code> because that method already exists. I would also not name it <code>insertion_sort</code> because that is an implementation detail. I think <code>stable_sort</code> would be a good name, because the fact that insertion sort is <em>stable</em> (if implemented correctly) is an important distinguishing feature that sets it apart from the default <code>sort</code> in Ruby, which is not stable.</p>\n<p>So, either something like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>module Sort\n module_function def stable_sort(arr)\n # …\n end\nend\n</code></pre>\n<p>or something like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>class Array\n def stable_sort\n length.times do |key|\n # …\n end\n end\nend\n</code></pre>\n<p>Actually, I am not a big fan of monkey-patching core classes. <em>At least</em> put the method in a separate mixin, so that it is easier to trace where the code is coming from:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>module StableSortExtension\n def stable_sort\n length.times do |key|\n # …\n end\n end\nend\n\nclass Array\n include StableSortExtension\nend\n</code></pre>\n<p>But even better would be to make it a <em>Refinement</em>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>module StableSort\n module StableSortExtension\n def stable_sort\n length.times do |key|\n to_the_left = key - 1\n\n next unless self[key] < self[to_the_left]\n\n mover_key = key\n left_ele_moving_right = to_the_left\n\n while self[mover_key] <= self[left_ele_moving_right] && left_ele_moving_right >= 0\n\n self[left_ele_moving_right], self[mover_key] =\n self[mover_key], self[left_ele_moving_right]\n\n mover_key -= 1\n left_ele_moving_right -= 1\n end\n end\n end\n end\n\n refine Array do\n include StableSortExtension\n end\nend\n</code></pre>\n<p>Now, the <code>Array#stable_sort</code> method will <em>only</em> exist for code which <em>explicitly</em> activates the Refinement with</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>using StableSort\n</code></pre>\n<p>Observe:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>ary = [5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10]\n\nary.stable_sort\n# undefined method `stable_sort' for [5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10]:Array (NoMethodError)\n\nusing StableSort\n\nary.stable_sort\n\np ary\n# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n</code></pre>\n<p>However, I would not do it this way. This <code>stable_sort</code> method mutates its receiver, which is generally not the case for other <code>sort</code> methods in Ruby, and thus very surprising to people.</p>\n<p>So, the method should at least <code>dup</code> the receiver and perform its mutations on that duplicate, then return it.</p>\n<p>Which brings me to my next point:</p>\n<h1>Mutation</h1>\n<p>Your method mutates its argument. That is an absolute no-go. You should <em>never-ever</em> break someone else's toy. An argument that is handed to you, is <em>sacred</em>.</p>\n<p>You can fix this by simply adding something like <code>arr = arr.dup</code> at the beginning of the method (or <code>arr = dup</code> for the case where you want to make it an instance method). But I believe we can improve the code more generally.</p>\n<p>More generally, your code looks more like FORTRAN, Pascal, or C, with lots of mutation, looping, manual fiddling with indices.</p>\n<p>Insertion sort can actually be expressed very elegantly without mutation and without looping, which will not only simplify the code, but also get rid of the mutation problem.</p>\n<p>Something like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>module Enumerable\n protected def ins(element)\n return [element] if count.zero?\n\n head = first\n return [element] + self if element <= head\n\n [head] + drop(1).ins(element)\n end\n\n def stable_sort\n return [] if count.zero?\n\n drop(1).stable_sort.ins(first)\n end\nend\n</code></pre>\n<p>This version does not mutate anything, and it works with <em>all</em> <a href=\"https://ruby-doc.org/core/Enumerable.html\" rel=\"nofollow noreferrer\"><code>Enumerable</code></a>s (including <a href=\"https://ruby-doc.org/core/Enumerator.html\" rel=\"nofollow noreferrer\"><code>Enumerator</code></a>s), not just <code>Array</code>s. (It does not work with <em>infinite</em> <code>Enumerator</code>s, though.)</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 <a href=\"https://bugs.ruby-lang.org/issues/8976\" rel=\"nofollow noreferrer\">magic comment</a> 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.</p>\n<p>Note: I put this at the very end, because there actually are no <code>String</code> literals in your code, so it doesn't matter. Rubocop and some other Linters will complain about this regardless. It's your choice whether you want to get into the habit of <em>always</em> adding it, regardless of whether you use <code>String</code> literals in the code or not. Personally, I always add it, just in case I add a <code>String</code> literal later on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T06:12:36.537",
"Id": "501948",
"Score": "0",
"body": "What is the purpose of StableSortExtension?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T08:09:23.300",
"Id": "501950",
"Score": "0",
"body": "As I wrote in my answer: \"put the method in a separate mixin, so that it is easier to trace where the code is coming from\". Now, if you do something like `Array.ancestors`, `StableSortExtension` will show up in the inheritance tree, and if you are wondering where this `stable_sort` method that you never heard about and never noticed before comes from, you can probably guess it came from there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T17:48:12.097",
"Id": "254456",
"ParentId": "254359",
"Score": "3"
}
},
{
"body": "<p>Insertion sort is undoubtedly the easiest-to-understand and easiest-to-code sorting method, requiring but one line of Ruby code. It seems overkill in the extreme to define a class with instance variables and multiple instance methods. I have written a single method <code>insertion_sort</code>.</p>\n<p>If desired it could be written as a module method in a module that could be required as needed. Assuming you wished to compare sorting methods (considering that the more efficient built-in methods <a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-sort\" rel=\"nofollow noreferrer\">Array#sort</a>, <a href=\"https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-sort\" rel=\"nofollow noreferrer\">Enumerable#sort</a> and <a href=\"https://ruby-doc.org/core-2.7.0/Enumerable.html#method-i-sort_by\" rel=\"nofollow noreferrer\">Enumerable#sort_by</a> would be the methods of choice for general sorting needs) you might create a module such as the following.</p>\n<pre><code>module SortingMethods\n def self.insertion_sort(arr)\n ...\n end\n\n def self.bubble_sort(arr)\n ...\n end\n \n ...\n\nend\n</code></pre>\n<p>The method would then be invoked</p>\n<pre><code>sorted = SortingMethods.insertion_sort(arr)\n</code></pre>\n<p>This is analogous to the use of the built-in <a href=\"https://ruby-doc.org/core-2.7.0/Math.html\" rel=\"nofollow noreferrer\">Math</a> module, which contains module methods only, methods that would serve as <em>functions</em> (which are not invoked on receivers) in other languages.</p>\n<p>The method <code>insertion_sort</code> can be written is as follows.</p>\n<pre><code>def insertion_sort(arr)\n arr.each_with_object([]) do |o, sorted|\n sorted.insert(sorted.bsearch_index { |e| e >= o } || sorted.size, o)\n end\nend\n</code></pre>\n\n<pre><code>insertion_sort [8, 29, 10, 20, 26, 5, 20, 2]\n #=> [2, 5, 8, 10, 20, 20, 26, 29]\n</code></pre>\n\n<pre><code>insertion_sort ["dog", "cat", "pig", "owl", "cow", "bat"]\n #=> ["bat", "cat", "cow", "dog", "owl", "pig"]\n</code></pre>\n<p>This relies on two methods.</p>\n<p><a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-insert\" rel=\"nofollow noreferrer\">Array#insert</a>\ninserts a given object into <code>self</code> before the element at a given index. If that index equals the size of (the array that is) <code>self</code>, the element is inserted after the last element of <code>self</code>.</p>\n<p><a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-bsearch_index\" rel=\"nofollow noreferrer\">Array#bsearch_index</a> returns the index of the element of <code>sorted</code> before which a given object is to be inserted in order to keep <code>sorted</code> sorted. <code>nil</code> is returned if the given object is greater than the last element of <code>sorted</code> (hence the need for <code>|| sorted.size</code>). See also <a href=\"https://ruby-doc.org/core-2.7.0/Array.html#method-i-bsearch\" rel=\"nofollow noreferrer\">Array#bsearch</a> for details.</p>\n<p>Note that the argument is not mutated (modified).</p>\n<p>The easiest way to demonstrate the calculations is to run the code after having salted it with <code>puts</code> statements. I will write the code in a simpler way that effectively performs the same operations.</p>\n<pre><code>arr = [8, 29, 10, 20, 26, 5, 20, 2]\n</code></pre>\n\n<pre><code>sorted = []\narr.each do |o|\n puts "\\no = #{o}, sorted = #{sorted}"\n idx = sorted.bsearch_index { |e| e >= o }\n puts "idx from bsearch initially = #{ idx.nil? ? 'nil' : idx }"\n idx = idx || sorted.size\n puts "idx after 'idx || sorted' = #{idx}"\n sorted.insert(idx, o)\n puts "sorted after sorted.insert(#{idx}, #{o}) = #{sorted}"\nend\n</code></pre>\n\n<pre><code>o = 8, sorted = []\nidx from bsearch initially = nil\nidx after 'idx || sorted' = 0\nsorted after sorted.insert(0, 8) = [8]\n</code></pre>\n \n<pre><code>o = 29, sorted = [8]\nidx from bsearch initially = nil\nidx after 'idx || sorted' = 1\nsorted after sorted.insert(1, 29) = [8, 29]\n</code></pre>\n \n<pre><code>o = 10, sorted = [8, 29]\nidx from bsearch initially = 1\nidx after 'idx || sorted' = 1\nsorted after sorted.insert(1, 10) = [8, 10, 29]\n</code></pre>\n \n<pre><code>o = 20, sorted = [8, 10, 29]\nidx from bsearch initially = 2\nidx after 'idx || sorted' = 2\nsorted after sorted.insert(2, 20) = [8, 10, 20, 29]\n</code></pre>\n \n<pre><code>o = 26, sorted = [8, 10, 20, 29]\nidx from bsearch initially = 3\nidx after 'idx || sorted' = 3\nsorted after sorted.insert(3, 26) = [8, 10, 20, 26, 29]\n</code></pre>\n \n<pre><code>o = 5, sorted = [8, 10, 20, 26, 29]\nidx from bsearch initially = 0\nidx after 'idx || sorted' = 0\nsorted after sorted.insert(0, 5) = [5, 8, 10, 20, 26, 29]\n</code></pre>\n \n<pre><code>o = 20, sorted = [5, 8, 10, 20, 26, 29]\nidx from bsearch initially = 3\nidx after 'idx || sorted' = 3\nsorted after sorted.insert(3, 20) = [5, 8, 10, 20, 20, 26, 29]\n</code></pre>\n \n<pre><code>o = 2, sorted = [5, 8, 10, 20, 20, 26, 29]\nidx from bsearch initially = 0\nidx after 'idx || sorted' = 0\nsorted after sorted.insert(0, 2) = [2, 5, 8, 10, 20, 20, 26, 29]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-12T21:16:04.923",
"Id": "533014",
"Score": "0",
"body": "It was in reference to a different answer to this review. I've deleted it to avoid any further confusion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T01:01:23.743",
"Id": "255482",
"ParentId": "254359",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254456",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T21:18:26.530",
"Id": "254359",
"Score": "0",
"Tags": [
"beginner",
"ruby",
"insertion-sort"
],
"Title": "Insertion Sort Implemented in Ruby"
}
|
254359
|
<pre><code> $spotify_track = '1HbcclMpw0q2WDWpdGCKdS';
$client_id = '[my_id]';
$client_secret = '[my_secret]';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://accounts.spotify.com/api/token' );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, 'grant_type=client_credentials' );
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($client_id.':'.$client_secret)));
$response = curl_exec($curl);
$token = json_decode($response)->access_token;
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
curl_close($curl);
} else {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.spotify.com/v1/audio-features/".$spotify_track,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"Authorization: Bearer ".$token,
),
));
$track_info = curl_exec($curl);
var_dump($track_info);
curl_close($curl);
}
</code></pre>
<p>I've modified the code suggested on <a href="https://stackoverflow.com/questions/50346751/how-do-i-use-oauth2-using-curl-and-php">stackoverflow</a> and came up with my own solution. I successfully fetch the song information. However, I wonder if this is the proper way in handling API using curl in php. I also noticed the page reloads a little bit slower compared to without the code aforementioned.</p>
|
[] |
[
{
"body": "<p>There's not much you can do wrong here. It works. I don't want to go into details of how to handle Spotify's API, but I would like to comment on your code.</p>\n<p>One thing I noticed is that, if there's an error, you call <code>curl_close()</code> twice. That looks like a bug.</p>\n<p>You're using <code>curl</code> two times, and in quite a different way. The first time you set individual options with <code>curl_setopt()</code>, the second time you combine all options and call <code>curl_setopt_array()</code>. Your code would be more consistent if you used the same method both times.</p>\n<p>Better still, why not make a simple function to do the <code>curl</code> call for you? Something like this:</p>\n<pre><code>function callSpotifyApi($options) \n{\n $curl = curl_init();\n curl_setopt_array($curl, $options); \n $json = curl_exec($curl);\n $error = curl_error($curl);\n curl_close($curl);\n if ($error) {\n return ['error' => TRUE,\n 'message' => $error];\n }\n $data = json_decode($json);\n if (is_null($data)) {\n return ['error' => TRUE,\n 'message' => json_last_error_msg()];\n }\n return $data; \n}\n</code></pre>\n<p>This function combines all the things that are common between the two <code>curl</code> calls, and therefore saves you writing code twice, and the reader reading it twice. This function also checks if the returned json code was valid and tells you what was wrong. You would normally use <a href=\"https://www.php.net/manual/en/function.json-last-error.php\" rel=\"nofollow noreferrer\">json_last_error()</a> to detect json errors, but if a Spotify call returns <code>null</code> then there's surely an error.</p>\n<p>Given the above function, the first <code>curl</code> call would now become:</p>\n<pre><code>$headers = ['Authorization: Basic '.base64_encode($client_id.':'.$client_secret)];\n$url = 'https://accounts.spotify.com/api/token';\n$options = [CURLOPT_URL => $url,\n CURLOPT_RETURNTRANSFER => TRUE,\n CURLOPT_POST => TRUE,\n CURLOPT_POSTFIELDS => 'grant_type=client_credentials',\n CURLOPT_HTTPHEADER => $headers];\n$credentials = callSpotifyApi($options); \n$token = $credentials->access_token;\n</code></pre>\n<p>I haven't tested this code, so there might be errors. The second call will now be very similar:</p>\n<pre><code>$headers = ['Content-Type: application/json',\n 'Authorization: Bearer '.$token];\n$url = 'https://api.spotify.com/v1/audio-features/'.$spotify_track;\n$options = [CURLOPT_URL => $url,\n CURLOPT_RETURNTRANSFER => TRUE,\n CURLOPT_FOLLOWLOCATION => TRUE,\n CURLOPT_ENCODING => '',\n CURLOPT_MAXREDIRS => 10,\n CURLOPT_TIMEOUT => 30,\n CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n CURLOPT_CUSTOMREQUEST => 'GET',\n CURLOPT_HTTPHEADER => $headers];\n$features = callSpotifyApi($options); \nvar_dump($features);\n</code></pre>\n<p>Writing calls to Spotify consistently this way makes it easier to read the code, and find and correct bugs.</p>\n<p>I didn't really review how you use the <code>curl</code> options, or whether this is the best way to use the Spotify API. Others may have more experience with this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T01:54:53.557",
"Id": "501642",
"Score": "0",
"body": "Thanks for that knowledge, sir. I'll give it a try"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T02:18:30.293",
"Id": "501646",
"Score": "0",
"body": "I modified it a little bit and surprisingly it's much better compared to what I did before. WOW! Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T03:46:08.270",
"Id": "501651",
"Score": "0",
"body": "Why did you suggest the change from `if ($err)` to yhe more verbose `if ($error != '')`? Why are you not using curly braces for condition blocks? Please recommend PSR-12 compliance in all php reviews. https://www.php-fig.org/psr/psr-12/#5-control-structures and spacing when concatenating and newlines in array declarations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T09:30:00.227",
"Id": "501672",
"Score": "0",
"body": "@mickmackusa I adopted your first two suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T09:49:42.050",
"Id": "501673",
"Score": "0",
"body": "`is_null($json)` or `is_null($data)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T09:54:06.290",
"Id": "501674",
"Score": "0",
"body": "@mickmackusa: The latter, I corrected it. Good catch."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T01:07:10.913",
"Id": "254362",
"ParentId": "254360",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254362",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-05T23:59:05.393",
"Id": "254360",
"Score": "0",
"Tags": [
"php"
],
"Title": "Spotify API GET curl with auth using php - is this code good?"
}
|
254360
|
<p>I've written the following sample program as a way to help improve my understanding of passing pointers to a function, and it currently works:</p>
<pre><code>#include "stdio.h"
typedef struct Car {
char* name;
unsigned int price;
} Car;
void print_cars(Car* cars[]) {
for (int i=0; cars[i] != NULL;i++) {
printf("\n<Car: %s, Price: $%d>", car->name, car->price);
}
}
void depreciate(Car* cars[]) {
for (int i=0; cars[i] != NULL; i++) {
cars[i]->price = cars[i]->price * 0.95;
}
}
int main(int argc, char* argv[]) {
Car chevy = {.name = "Chevy", .price = 45000};
Car mazda = {.name = "Mazda", .price = 30000};
Car ferrari = {.name = "Ferrari", .price = 200000};
Car* my_cars[] = {&chevy, &mazda, &ferrari, NULL};
print_cars(my_cars);
printf("\n--------- Depreciating -----------");
depreciate(my_cars); // <-- ignoring this
print_cars(my_cars);
return 1;
}
</code></pre>
<p>Ignoring the line that modifies the value of the struct, would it be possible to do the <code>print_cars</code> function without using a pointer? When I tried doing it I would receive the error:</p>
<blockquote>
<p>new5.c:13:27: error: invalid operands to binary expression ('Car' (aka 'struct Car') and 'void *')</p>
</blockquote>
<p>Which I think may be related to using the <code>NULL</code> in the <code>my_cars</code> array to signal the end of it, but wasn't positive. Additionally, is using <code>NULL</code> in a non-char array a common way to show that the end has been reached? Where else could this be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T02:53:18.110",
"Id": "501648",
"Score": "0",
"body": "This appears to be a cross-posting of: https://stackoverflow.com/questions/65588231/using-a-struct-vs-a-pointer-to-a-struct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T03:51:02.993",
"Id": "501652",
"Score": "0",
"body": "@CraigEstey this is a follow-up. Here I'm iterating over arrays, then depreciating and doing other things. The question you link asks between the difference between `print_cars` and `print_cars2` (print_cars2 doesn't exist in the above)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T22:01:57.910",
"Id": "501722",
"Score": "0",
"body": "\"would it be possible to do the print_cars function without using a pointer?\" --> Yes. Yet not worth using a non-pointer approach."
}
] |
[
{
"body": "<p>While your code "works" for you, there are a lot of small mistakes in it. I'm listing them straight from top to bottom.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include "stdio.h"\n</code></pre>\n<p>Since <code>stdio.h</code> is a header from the standard library, as opposed to a header you define yourself in your project, you should include it using <code>#include <stdio.h></code> instead.</p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct Car {\n char* name;\n unsigned int price;\n} Car;\n</code></pre>\n<p>The <code>name</code> of the car should be a <code>const char *</code> since later, you assign string literals like <code>"Chevy"</code> to that field, and string literals are read-only.</p>\n<p>To prevent this possible bug in the future, let the C compiler warn you about issues like these. For GCC, pass the compile options <code>-Wall -Wextra -Werror -O2</code>. Since you didn't say which development environment you use, you have to find out how to add these options yourself.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void print_cars(Car* cars[]) {\n for (int i=0; cars[i] != NULL;i++) {\n printf("\\n<Car: %s, Price: $%d>", car->name, car->price);\n }\n}\n</code></pre>\n<p>Since <code>print_cars</code> does not modify the cars, its parameter should be <code>const Car* cars[]</code>, just add the <code>const</code>.</p>\n<p>There should be a single space around assignment operators. That is, write <code>int i = 0</code> instead of <code>int i=0</code>. There should be a single space after the semicolon as well.</p>\n<p>When a program produces output, the end-of-line marker <code>\\n</code> should go to the <em>end</em> of the line, not to the <em>beginning</em>.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void depreciate(Car* cars[]) {\n for (int i=0; cars[i] != NULL; i++) {\n cars[i]->price = cars[i]->price * 0.95;\n }\n}\n</code></pre>\n<p>Instead of writing <code>cars[i]->price</code> twice, you can make use of the combined assignment operator <code>*=</code> by writing: <code>cars[i]->price *= 0.95</code>.</p>\n<p>The floating-point number 0.95 cannot be represented exactly in binary. You should experiment a little with a car price that would end up evenly. But even then you could end up with rounding errors. I wrote the following test snippet, which shows that for some prices, the actual result ends up lower than expected, because what you see as 0.95 is really 0.9499999999999999555910790149937383830547332763671875 for the computer.</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\nint main(void)\n{\n for (int i = 0; i < 1000; i++) {\n printf("%d: %.20f, %.20f, %d\\n",\n i,\n i * 0.95,\n i * 95 / 100.0,\n i * 95 / 100);\n }\n}\n</code></pre>\n<p>To keep the programming simple, you should stick to the last variant <code>i * 95 / 100</code>, until you get more experienced with floating point numbers.</p>\n<pre><code>int main(int argc, char* argv[]) {\n\n ...\n return 1;\n}\n</code></pre>\n<p>The function <code>main</code> is special regarding its return value. Returning 1 means failure, returning 0 means success. Many other C functions return 0 for success (just like <code>main</code>) and -1 for failure. Others return non-zero for success and zero for failure. Things vary a lot, and you have to learn the meaning for each function individually. There are some patterns though, so it's not completely chaotic.</p>\n<p>All in all, it's a well-written program. After modifying the few details I mentioned, it's perfect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T03:52:44.943",
"Id": "501653",
"Score": "0",
"body": "thanks for your time and feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T04:21:56.437",
"Id": "501654",
"Score": "0",
"body": "Why would `-O2` affect warnings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T07:55:55.727",
"Id": "501663",
"Score": "1",
"body": "@Reinderien Some compilers don't generate _all_ warnings without it. (e.g): `void set(int *x) { } int main(void) { int i; set(&i); return i; }` With `gcc -Wall` compiles cleanly. If we add: `-O`, we get: `warning: ‘i’ is used uninitialized in this function [-Wuninitialized]` Note that `gcc` [correctly] detected that `set` did _not_ actually assign a value to `*x`, so it was flagged. If we add `*x = 3;` to `set`, no warning occurs. With `-O`, `gcc` did cross function analysis. If we have _just_ `void set(int *x);`, no warning because `set` is extern and `gcc` can't see the body of `set` ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T08:02:09.393",
"Id": "501664",
"Score": "0",
"body": "@Reinderien ... `gcc` [I presume] detected the issue when it did analysis to determine if it could automatically _inline_ the `set` call in `main`. Such inlining, and therefore the analysis [AFAIK] is only done with optimization enabled"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T15:14:14.303",
"Id": "501691",
"Score": "1",
"body": "\"After modifying the few details I mentioned, it's perfect.\" -- Nitpick: No, after that, it is not yet perfect. It still causes undefined behavior due to a wrong conversion specifier, as pointed out in my answer. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T21:42:07.417",
"Id": "501720",
"Score": "0",
"body": "Agree will all except `i * 95 / 100`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T01:32:25.170",
"Id": "501783",
"Score": "0",
"body": "@chux What's wrong about sticking to integer calculations first? Or did you just mean that the code should round properly, even with integers? Something like `(i * 95 + 50) / 100`, even though that would not be round-half-even. But that expects how rounding should be done and should be specified elsewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T03:19:25.733",
"Id": "501787",
"Score": "1",
"body": "It is the lack of rounding."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T01:16:17.177",
"Id": "254364",
"ParentId": "254361",
"Score": "4"
}
},
{
"body": "<p>In the line</p>\n<p><code>printf("\\n<Car: %s, Price: $%d>", car->name, car->price);</code></p>\n<p>the variable <code>car->price</code> is of type <code>unsigned int</code>, but you are using <code>%d</code> to print it, which is intended for <code>signed int</code>. This causes <a href=\"https://en.wikipedia.org/wiki/Undefined_behavior\" rel=\"nofollow noreferrer\">undefined behavior</a> according to <a href=\"http://port70.net/%7Ensz/c/c11/n1570.html#7.21.6.1p9\" rel=\"nofollow noreferrer\">§7.21.6.1 ¶9 of the ISO C standard</a>. However, on most platforms, this will probably just cause the number to be reinterpreted as signed.</p>\n<p>The correct conversion specifier for <code>unsigned int</code> is <code>%u</code>.</p>\n<hr />\n<blockquote>\n<p>Additionally, is using NULL in a non-char array a common way to show that the end has been reached? Where else could this be improved?</p>\n</blockquote>\n<p>It is more common to store the length of the array in a separate variable.</p>\n<p>In your specific use-case, it doesn't matter which way you do it. However, generally, I would recommend to store the length in a separate variable instead. For example, if you want to add random-access with bounds-checking, then it would be better to store the length in a separate variable. Otherwise, you would have to traverse the entire array for every such access.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T21:58:28.823",
"Id": "501721",
"Score": "0",
"body": "\"This causes undefined behavior\" --> Not UB when the value is representable as an `int` and `unsigned`. C17dr § 6.5.2.2 6. Still, best to match type/specifier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T19:30:36.987",
"Id": "501764",
"Score": "0",
"body": "@chux: The paragraph you refer to addresses cases in which functions are declared without a parameter type list, i.e. cases where the compiler must guess the parameter types. That paragraph specifies in which cases mismatches between the guessed parameter types and actual paramater types are acceptable and in which cases they lead to undefined behavior. In the case of a variadic function, a missing parameter list in the function declaration always leads to undefined behavior. I fail to see how that paragraph is relevant here, as it has nothing to do with `printf` conversion specifiers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T20:22:37.177",
"Id": "501766",
"Score": "0",
"body": "Would you consider `int printf(const char * restrict format, ...);` a variadic function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T21:17:38.133",
"Id": "501769",
"Score": "0",
"body": "@chux: Yes, that is a prototype declaration of a variadic function. The paragraph you reference only applies to translation units without a prototype declaration before the function call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T21:32:38.670",
"Id": "501771",
"Score": "0",
"body": "Paragraph has \"If the function is defined with a type that includes a prototype, and either the prototype ends with an ellipsis (, ...) or ...\" so is at odds with \"only applies to translation units without a prototype declaration\". I am using draft N2176."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T21:40:58.813",
"Id": "501772",
"Score": "0",
"body": "@chux: I used the term \"prototype declaration\", meaning \"function declaration with a prototype\". The sentence you are quoting is referring to the function **definition**, not **declaration**. You must view that sentence in context with the first sentence, which refers to a function declaration without a prototype. [This link](https://stackoverflow.com/q/55615219/12149471) may help explain the meaning of that paragraph."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T21:57:38.130",
"Id": "501775",
"Score": "0",
"body": "\"and either the prototype ends with an ellipsis\" refers to the declaration. \"A function prototype is a declaration of a function that declares the types of its parameters.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T20:39:15.900",
"Id": "501841",
"Score": "0",
"body": "@chux: In informal usage, it is common to distinguish between declarations and definitions and to treat them as mutually exclusive. However, in formal usage, every definition is also a declaration, so a definition is just a special case of a declaration (see §6.7 ¶5 of the ISO C standard). Therefore, nothing you have quoted excludes the possiblity of a function definition having a prototype. Most function definitions actually have prototypes. For example, `void foo(){}` is a function definition without a prototype, whereas `void foo(void){}` is a function definition with a prototype."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T20:53:27.570",
"Id": "501843",
"Score": "0",
"body": "@chux: Sentence 4 of §6.5.2.2 ¶6 (which you quoted) addresses the situation in which the declaration in the current translation unit does not have a prototype, but the definition (in another translation unit or later in the current translation unit) does have a prototype. That sentence specifies that for variadic functions, this situation always leads to undefined behavior. All of this is explained in greater detail in the link that I provided in my third comment."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T15:06:34.990",
"Id": "254387",
"ParentId": "254361",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>is using <code>NULL</code> in a non-char array a common way to show that the end has been reached?</p>\n</blockquote>\n<p><code>NULL</code>, the <em>null pointer constant</em>, <strong>is</strong> often used to indicate the end of an <strong>array of pointers</strong> as done nicely below. It is not a question if the array if "non-char" or not. It is a question if the array elements are pointers or not.</p>\n<pre><code>Car* my_cars[] = {&chevy, &mazda, &ferrari, NULL};\n</code></pre>\n<p>An alternative is to pass the array (or allocated memory) count. This is not the sizeof of the data, but the number of elements in the data.</p>\n<pre><code>Car* my_cars[] = {&chevy, &mazda, &ferrari}; // No NULL here.\nconst size_t my_cars_n = sizeof my_cars_n / sizeof my_cars_n[0];\nprint_cars(my_cars_n, my_cars);\n\n// or\n\nsize_t my_cars_n = 3;\nCar* my_cars = malloc(sizeof *my_cars * my_cars_n);\nmy_cars[0] = &chevy;\nmy_cars[1] = &mazda;\nmy_cars[2] = &ferrari;\nprint_cars(my_cars_n, my_cars);\nfree(my_cars);\n</code></pre>\n<hr />\n<p>A <code>char</code> array often uses a <em>null character</em>, to indicate the end of a <em>string</em>.</p>\n<p>Do not mix <code>NULL</code>, the <em>null pointer constant</em>, with <code>(char) '\\0'</code>, a <em>null character</em>. The first is used with pointers, the second with strings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T23:19:20.780",
"Id": "254399",
"ParentId": "254361",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254364",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T00:25:07.527",
"Id": "254361",
"Score": "1",
"Tags": [
"c"
],
"Title": "Struct iteration with/without a pointer"
}
|
254361
|
<p>I'm pretty new to programming and made a few programs so far. I recently made a Calculator program and I hope you guys could tell me what I could do to improve.</p>
<pre class="lang-cs prettyprint-override"><code>int firstNumber;
string sign;
int secondNumber;
int answer;
Console.WriteLine("Input Number:");
firstNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.WriteLine("Input Sign:");
sign = Console.ReadLine();
Console.Clear();
Console.WriteLine("Input Second Number:");
secondNumber = Convert.ToInt32(Console.ReadLine());
Console.Clear();
switch (sign)
{
case "+":
answer = firstNumber + secondNumber;
Console.WriteLine(answer);
Console.ReadKey();
break;
case "-":
answer = firstNumber - secondNumber;
Console.WriteLine(answer);
Console.ReadKey();
break;
case "*":
answer = firstNumber * secondNumber;
Console.WriteLine(answer);
Console.ReadKey();
break;
case "/":
answer = firstNumber / secondNumber;
Console.WriteLine(answer);
Console.ReadKey();
break;
default:
Console.WriteLine("Invalid Input");
break;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T04:56:18.953",
"Id": "501655",
"Score": "1",
"body": "I would split this into 2 functions. One which does the IO, console reads/writes. And another which does the actual calculation; primarily the current switch statement. This would separate the concerns, enabling many advantages like testing & reuse."
}
] |
[
{
"body": "<p>An excellent attempt to writing your Calculator, I find the variable names and syntax following well accepted conventions for nomenclature in C#</p>\n<p>One suggestion: anticipate invalid inputs from user. I would recommend using <code>int.TryParse</code> in place of <code>Convert.ToInt32()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T02:11:43.177",
"Id": "254365",
"ParentId": "254363",
"Score": "1"
}
},
{
"body": "<h2>In general</h2>\n<p>Whenever you try to implement an application try to use sentences to describe the desired behavior. After that ask yourself: <em>"Can it be further refined?"</em> If so, then write new sentences to detail your plan in a more fine-grained level.</p>\n<p>Let me show you what I mean:</p>\n<h3>The view from 10 000 feet</h3>\n<blockquote>\n<p>The application can perform basic operations between two operands.</p>\n</blockquote>\n<p>What can be further refined?</p>\n<ul>\n<li>What does it mean <em>basic operation</em>?</li>\n<li>What did we mean by <em>two operands</em>?</li>\n</ul>\n<h3>High-level view</h3>\n<blockquote>\n<p>The application can perform basic operations between two operands.</p>\n<blockquote>\n<p>It allows addition, subtraction, multiplication and division.</p>\n</blockquote>\n</blockquote>\n<blockquote>\n<blockquote>\n<p>User can provide two numbers and the desired operation.<br />\nThe application will perform it on the user's behalf.</p>\n</blockquote>\n</blockquote>\n<p>What can be further refined?</p>\n<ul>\n<li>How can an <em>user provide numbers</em>?</li>\n</ul>\n<h3>Fine-grained problem decomposition</h3>\n<blockquote>\n<p>The application can perform basic operations between two operands.</p>\n<blockquote>\n<p>It allows addition, subtraction, multiplication and division.</p>\n</blockquote>\n</blockquote>\n<blockquote>\n<blockquote>\n<p>User can provide two numbers and the desired operation.</p>\n<blockquote>\n<p>The application receives an input from the user then it perform a preliminary check.</p>\n<blockquote>\n<p>If it is valid then it goes to the next statement.<br />\nIf it is invalid then it ask the user again to provide a valid input.</p>\n</blockquote>\n</blockquote>\n</blockquote>\n</blockquote>\n<blockquote>\n<blockquote>\n<p>The application will perform it on the user's behalf.</p>\n</blockquote>\n</blockquote>\n<h3>Let's put together the skeleton</h3>\n<p>Now, we can translate each sentence into instructions.<br />\nThis problem decomposition also helps us to well-organize our code:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>///<summary>\n/// The application can perform basic operations between two operands.\n///</summary>\npublic static void Main()\n{\n\n}\n\n///<summary>\n/// User can provide two numbers and the desired operation.\n///</summary>\nprivate static void AskForInputs()\n{\n\n}\n\n///<summary>\n/// The application receives an input from the user then it perform a preliminary check.\n/// <list type="bullet">\n/// <item>\n/// <description>If it is valid then it goes to the next statement.</description>\n/// </item>\n/// <item>\n/// <description>If it is invalid then it ask the user again to provide a valid input.</description>\n/// </item>\n/// </list>\n///</summary>\n///</summary>\nprivate static int AskForNumber()\n{\n \n}\n\n///<summary>\n/// The application receives an input from the user then it perform a preliminary check. <para />\n/// It allows addition, subtraction, multiplication and division.\n///</summary>\nprivate static char AskForOperation()\n{\n \n}\n\n///<summary>\n/// The application will perform it on the users behalf.\n///</summary>\nprivate static void PerformRequestedOperation()\n{\n \n} \n</code></pre>\n<h2>Observations about your implementation</h2>\n<p>The implementation is bit naive, because:</p>\n<ul>\n<li>It does not handle those cases when the user provides malformed input\n<ul>\n<li>For example: instead of <code>3</code> (s)he provides <code>three</code></li>\n</ul>\n</li>\n<li>It does not handle under- or overflow cases\n<ul>\n<li>For example: <code>int.MaxValue + 100</code></li>\n</ul>\n</li>\n<li>It does not handle zero division case\n<ul>\n<li>For example: <code>100 / 0</code></li>\n</ul>\n</li>\n<li>It does not handle properly a division where the result is a floating number\n<ul>\n<li>For example: <code>10 / 3</code></li>\n</ul>\n</li>\n<li>etc.</li>\n</ul>\n<p>In your <code>switch</code> statement you repeat the following two statement in each <code>case</code>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Console.WriteLine(answer);\nConsole.ReadKey();\n</code></pre>\n<p>An alternative implementation could be:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>switch (operation)\n{\n case "+":\n answer = firstNumber + secondNumber;\n break;\n case "-":\n answer = firstNumber - secondNumber;\n break;\n case "*":\n answer = firstNumber * secondNumber;\n break;\n case "/":\n answer = firstNumber / secondNumber;\n break;\n}\n \nConsole.WriteLine(answer);\nConsole.ReadKey();\n</code></pre>\n<p>This can be easily enhanced to include all the above validations as well:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>switch (operation)\n{\n case "+":\n answer = PerformAddition(lhs, rhs);\n break;\n case "-":\n answer = PerformSubtraction(lhs, rhs);\n break;\n case "*":\n answer = PerformMultiplication(lhs, rhs);\n break;\n case "/":\n answer = PerformDivision(lhs, rhs);\n break;\n}\n \nConsole.WriteLine(answer);\nConsole.ReadKey();\n</code></pre>\n<p>Now as you can see we have introduced 4 new functions to abstract away the complexity to deal with different edge cases and the main flow remained easy to follow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T08:03:44.733",
"Id": "254374",
"ParentId": "254363",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "254374",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T01:15:08.227",
"Id": "254363",
"Score": "2",
"Tags": [
"c#",
"beginner",
"calculator"
],
"Title": "Calculator Program improvements"
}
|
254363
|
<p>There are 2 issues with my code:</p>
<p>a) If I put numbers in the following order (as my input) '1', '2', '3', '4',
'5', '6', '7' -- this where the game should end, because X (or O) would have
won now (because 3, 5, 7 are a diagonal win). But my program realizes this
after X (or again, O) plays their 4th turn (another turn is played by the
other player even after X or O has visually won). <-- you'll understand this
better (hopefully) when you try running it.</p>
<p>b) When I am asked if I want to play again and I say yes (more like 'y'), I get
a traceback error.</p>
<p>Here's my code:</p>
<pre><code># variables
board = ['-', '-', '-','-', '-', '-', '-', '-', '-']
count = 0 # will track the number of filled slots
winner = False # check if anyone has won
play = True # check if the game should continue
tie = False # check if there is a tie/draw
current_player = 'O' # variable that will hold the current player
player_details = [] # list that will hold the player identifier and marker
# functions
# takes one of the users' input.
# in ['X', 'O'] --> X is the first player and O is the second player.
def get_player_details(current_player):
if current_player == 'O':
return ['X', 'O']
else:
return ['O', 'X']
# this function is to display the board to the console.
def display_board(board):
print(' 1 | 2 | 3 ' + board[0] + ' | ' + board[1] + ' | ' + board[2])
print(' 4 | 5 | 6 ' + board[3] + ' | ' + board[4] + ' | ' + board[5])
print(' 7 | 8 | 9 ' + board[6] + ' | ' + board[7] + ' | ' + board[8])
# this function checks for a winner diagonally, across and down.
def win_game(marker, player_identification):
# all the winning combinations:
if ((board[0] == marker and board[1] == marker and board[2] == marker) or
(board[3] == marker and board[4] == marker and board[5] == marker) or
(board[6] == marker and board[7] == marker and board[8] == marker) or
(board[0] == marker and board[3] == marker and board[6] == marker) or
(board[1] == marker and board[4] == marker and board[7] == marker) or
(board[1] == marker and board[5] == marker and board[8] == marker) or
(board[3] == marker and board[5] == marker and board[7] == marker)):
display_board(board)
print('Player',player_identification,'wins!')
return True
else:
return False
# checks if the input is being put in an "open" space.
def insert_input(slot_number, marker):
print('slot number:',slot_number,'\nmarker:',marker)
print('board[slot_number]:',board[slot_number])
while board[slot_number] != '-':
print('Please pick another spot, this one is already taken!')
slot_number = int(input())
board[slot_number] = marker
# play again option, if the person wants to replay
def play_again():
print('Would you like to play again?')
play_again = input()
if play_again == 'Y' or play_again == 'y':
for v in board:
board[v] = ' '
return True
else:
print('Ok, thank you for playing!')
return False
# the main block of the program (where all the functions and variables are tied together)
while play:
display_board(board)
player_details = get_player_details(current_player)
current_player = player_details[0]
print('Please enter a number from 1 - 9.')
input_slot = int(input())
print('board:' + str(board))
insert_input(input_slot, player_details[1])
count += 1
print('player details[1]:',player_details[1],'\n')
winner = win_game(player_details[1], current_player)
if count == 9 and not winner:
print('It\'s a tie!')
tie = True
display_board(board)
if winner or tie:
play = play_again()
if play:
current_player = ''
count = 0
</code></pre>
<p>Note: I have added some debugging statements because I am still a "newbie" and I need them for clarity's sake.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T05:25:53.823",
"Id": "501656",
"Score": "0",
"body": "Welcome to code review. This question is not fit for `codereview.stackexchange` site. Please read our [tour](https://codereview.stackexchange.com/tour) on how to ask questions here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T14:14:27.557",
"Id": "501686",
"Score": "0",
"body": "Ok, sorry about that. I thought this was a valid question, as I have all my code, and I'm just running into errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T15:09:12.173",
"Id": "501689",
"Score": "1",
"body": "For future reference, note that this site is for improving working code, not fixing broken code. You want Stack Overflow to help with errors."
}
] |
[
{
"body": "<p>I can help with part b) of your issue.</p>\n<p>But before that,</p>\n<pre><code># checks if the input is being put in an "open" space.\ndef insert_input(slot_number, marker):\n print('slot number:',slot_number,'\\nmarker:',marker)\n print('board[slot_number]:',board[slot_number])\n while board[slot_number] != '-':\n print('Please pick another spot, this one is already taken!')\n slot_number = int(input())\n board[slot_number] = marker # <-- ⭐ this line of code is causing your program to crash. \n</code></pre>\n<p>You have some broken code. With board[slot_number] = marker, when I insert 1, my marker isn't placed on the first section of the board, it is instead placed on the 2nd section as your program is taking in the index, not the position. You have to look at the relationship between your positions on your 'dupe board' and your actual board, what do you see? Your position is 1 more than your index or (in code) your position is <code>board[slot_number - 1] = marker</code></p>\n<p>Therefore, your code block should look like this:</p>\n<pre><code>def insert_input(slot_number, marker):\n print('slot number: ' + str(slot_number) + '\\nmarker: ' + str(marker))\n print('board[slot_number]: ' + board[slot_number])\n while board[slot_number] != '-':\n print('Please pick another spot, this one is already taken!')\n slot_number = int(input())\n board[slot_number - 1] = marker # <-- ⭐ this is the line I fixed\n</code></pre>\n<p>And now for part b) of your problem.</p>\n<p>This is your code segment:</p>\n<pre><code>def play_again():\n print('Would you like to play again?')\n play_again = input()\n\n if play_again == 'Y' or play_again == 'y':\n for v in board:\n board[v] = ' '\n return True\n\n else:\n print('Ok, thank you for playing!')\n return False\n</code></pre>\n<p>and particularly this section of the segment is incorrect:</p>\n<pre><code> for v in board:\n board[v] = ' '\n</code></pre>\n<p>you can't put strings into [] (which is where your variable 'v' is held), as this is for indices. And all the values that belong to 'v' are strings ⚠</p>\n<p>what you should do instead is use the len() function.</p>\n<pre><code>for v in range(0, len(board)):\n board[v] = '-'\n</code></pre>\n<p>instead of</p>\n<pre><code>for v in board:\n board[v] = ' ' # <-- here you're not even clearing the board to what it was before ('-')\n</code></pre>\n<p>and this is what your segment should look like:</p>\n<pre><code>def play_again():\n print('Would you like to play again?')\n play_again = input()\n print(type(board))\n if play_again == 'Y' or play_again == 'y':\n for v in range(0, len(board)):\n board[v] = '-'\n return True\n\n else:\n print('Ok, thank you for playing!')\n return False\n</code></pre>\n<p>and, guess what? the board is actually returned back like this:</p>\n<pre><code> 1 | 2 | 3 - | - | -\n 4 | 5 | 6 - | - | -\n 7 | 8 | 9 - | - | -\n</code></pre>\n<p>Hope you found this helpful ✌</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T14:15:44.713",
"Id": "501687",
"Score": "0",
"body": "thank you so much for this! I appreciate your time and effort!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T04:56:45.933",
"Id": "254371",
"ParentId": "254369",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254371",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T04:35:41.933",
"Id": "254369",
"Score": "-1",
"Tags": [
"game",
"tic-tac-toe"
],
"Title": "python simple 2 player tic tac toe"
}
|
254369
|
<p>I'm implementing a simple data reader to get image sequences from either a pre-recorded video file (In my case ROS bag file), or a camera device (In my case Intel Realsense). Basically I intend for users to use it in the following way:</p>
<ol>
<li><p>When a non-empty file path is provided, the reader reads from the video file; otherwise if an empty path is specified, the reader reads from the camera device. (For now in case of any failure, throwing exceptions and terminating the program will be fine.)</p>
</li>
<li><p>The user iteratively calls <code>bool get_next_frame(Frame&)</code> to get all the frames, until reaching the end of the video, upon which the function returns <code>false</code>.</p>
</li>
</ol>
<p>I'm trying to implement the above-mentioned functionality using the factory pattern, in C++ as follows:</p>
<pre><code>class DataReader;
typedef std::shared_ptr<DataReader> datareader_ptr;
class DataReader {
friend datareader_ptr make_data_reader(const std::string& ros_bag_path);
public:
virtual bool get_next_frameset(rs2::frameset& frames)=0;
virtual void finalize() {
pipe_.stop();
}
virtual ~DataReader() {
std::cout << "dtor for DataReader called." << std::endl;
finalize();
}
protected:
DataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile)
:cfg_(cfg),pipe_(pipe),pipeline_profile_(pipeline_profile) {}
rs2::config cfg_;
rs2::pipeline_profile pipeline_profile_;
rs2::pipeline pipe_;
};
class RosBagDataReader : public DataReader {
friend datareader_ptr make_data_reader(const std::string& ros_bag_path);
public:
virtual bool get_next_frameset(rs2::frameset& frames) {
frames = pipe_.wait_for_frames();
return true;
}
virtual ~RosBagDataReader() {}
protected:
RosBagDataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile)
:DataReader(cfg, pipe, pipeline_profile) {}
};
class CameraDataReader : public DataReader {
friend datareader_ptr make_data_reader(const std::string& ros_bag_path);
public:
virtual bool get_next_frameset(rs2::frameset& frames) {
frames = pipe_.wait_for_frames();
return true;
}
virtual ~CameraDataReader() {}
protected:
CameraDataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile)
:DataReader(cfg, pipe, pipeline_profile) {}
};
datareader_ptr make_data_reader(const std::string& ros_bag_path) {
rs2::config cfg;
rs2::pipeline pipe;
if (ros_bag_path=="") {
rs2::pipeline_profile profile = pipe.start();
return datareader_ptr(new CameraDataReader(cfg, pipe, profile));
} else {
// from ros bag file
cfg.enable_device_from_file(ros_bag_path, false);
rs2::pipeline_profile profile = pipe.start(cfg); //File will be opened in read mode at this point
rs2::playback play(profile.get_device());
play.set_real_time(false);
return datareader_ptr(new RosBagDataReader(cfg, pipe, profile));
}
}
</code></pre>
<p>However, I'm really not sure whether this is the best practice. More specifically,</p>
<ol>
<li>Is the usage of factory pattern here justified ?</li>
<li>Is my implementation of factory pattern correct ? Or are there any pitfalls in the code ?</li>
</ol>
<p>For example, I used friend function to access the protected constructors in all the classes, is this appropriate or there are better ways to do this?</p>
<p>Another example, protected constructor is used so that the users may not directly construct the readers, but only through the factory function. Is this done correctly?</p>
<p>Thanks in advance!</p>
<p>Update: Definitions of stuff in namespace <code>rs2</code>: may refer to <a href="https://intelrealsense.github.io/librealsense/doxygen/classrs2_1_1pipeline.html" rel="nofollow noreferrer">this doc</a>. Basically they are all just thin wrappers holding a <code>shared_ptr</code> to the class doing the real work. (i.e. pimpl idiom)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T08:13:00.277",
"Id": "501668",
"Score": "1",
"body": "What's `rs2::frameset`? You seem to be missing an include for it, as well as for lots of stuff in the `std` namespace. It's going to be much harder to review without the definitions in scope. Also, your title needs to state the *purpose* of the code, rather than your concerns about it (e.g. **Read image frame sequences**)."
}
] |
[
{
"body": "<p>I’ll start by answering the questions.</p>\n<h1>Questions</h1>\n<blockquote>\n<p>Is the usage of factory pattern here justified ?</p>\n</blockquote>\n<p></p>\n<p>Going just by what’s visible in the code and your commentary, I don’t see any purpose to writing the code this way. I don’t see any purpose to the <code>RosBagDataReader</code> or <code>CameraDataReader</code> classes. They don’t actually do anything unique; you could just implement <code>get_next_frameset()</code> in the base class, and forget the whole hierarchy.</p>\n<p>In fact, the only difference at all between the classes is not what they <em>do</em>, but rather how their data is set up. I suppose you <em>could</em> sorta-kinda justify having different classes to handle the different types of initialization… but then, you should put the initialization in the classes—that is, in the constructors. However, you could just as easily use two constructors for <code>DataReader</code>, and again, forget the rest of the hierarchy.</p>\n<p>But the thing that really makes me scratch my head about why you’d want to use the factory pattern is the fact that you don’t even really have a single factory. You have two factories that you’ve just shoehorned into one by saying “go one way if there’s a path, the other way if not”. That shouldn’t be a single function; that’s poor design. That should be two functions, one taking a path, one not. And once you’ve done it that way, it kinda reveals that the factory pattern doesn’t really make sense here.</p>\n<p>Frankly, run-time polymorphism should always be the <em>last</em> tool you reach for in modern C++:</p>\n<ul>\n<li>It relies on reference semantics, and C++ is a value semantic language.</li>\n<li>It usually means you need to use dynamic allocation, which is slow, cumbersome, and error-prone (though smart pointers help).</li>\n<li>It doesn’t really work well with compile-time stuff like type-checking and <code>constexpr</code>… which, again, are C++’s strengths.</li>\n<li>It’s often less efficient because of the extra memory used, and extra indirection.</li>\n<li>And there are all kinds of nasty gotchas just waiting to bite your ass (like, slicing if you aren’t <em>VERY</em> careful writing copy ops, swap ops, and so on).</li>\n</ul>\n<p><em>HOWEVER</em>….</p>\n<p>Of course, there <em>are</em> situations where the factory pattern using run-time polymorphism is the <em>perfect</em> solution. One that springs to mind is the case where you’re writing a library: you’d only give <code>DataReader</code> and the factory function as the entire library interface, and client code can use the library without knowing any details about possible concrete readers, so you could swap them out without having to recompile the client. You could even add readers as plugins.</p>\n<p>If you were doing <em>that</em> kind of thing, then sure, the factory pattern makes sense. But… if you’re just writing a <em>program</em>—not a library, let alone an extensible library—then I don’t see the point of it.</p>\n<blockquote>\n<p>Is my implementation of factory pattern correct ? Or are there any pitfalls in the code ?</p>\n</blockquote>\n<p>Eh, it’s mostly okay. It’s not outright <em>wrong</em>, but… there are a few problems with doing things the way you’re doing them.</p>\n<p>The first issue is that you don’t seem to know whether you’re writing an <em>interface</em> hierarchy, or an <em>implementation</em> hierarchy. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-kind\" rel=\"nofollow noreferrer\">Those are two very different things, and they need to be handled in different ways</a>. If you are trying to build from an interface—in this case, the single function <code>get_next_frameset()</code>—then your base class should be a pure abstract class… what other languages like Java specifically call an interface: no data, only pure virtual functions. If you are building up an implementation, then you’d do things very differently.</p>\n<p>I can’t tell you which one you’re really doing here, because, frankly, you don’t have much of an interface <em>or</em> implementation hierarchy, and none of the commentary explains any of the reasoning for even wanting the factory pattern in the first place. As I noted earlier, there doesn’t really seem to be much justification for a hierarchy at all.</p>\n<p>I’m also not keen on using shared pointers as the default. It seems completely pointless, especially because you can’t even take advantage of <code>std::make_shared()</code> (because the constructors aren’t public). You should probably return a <code>std::unique_ptr</code> instead. If someone wants a shared pointer, they can always make one out of the unique pointer… but you can’t really do the opposite.</p>\n<blockquote>\n<p>For example, I used friend function to access the protected constructors in all the classes, is this appropriate or there are better ways to do this?</p>\n</blockquote>\n<p>I actually think pretty much <em>all</em> of your uses of <code>protected</code> are bad. But let’s set that aside for now.</p>\n<p>If the constructors are non-public, then yeah, you <em>have</em> to use a friend somehow. There’s really no choice.</p>\n<blockquote>\n<p>Another example, protected constructor is used so that the users may not directly construct the readers, but only through the factory function. Is this done correctly?</p>\n</blockquote>\n<p>I honestly don’t see the sense of making <em>any</em> of the constructors protected.</p>\n<p>Let’s start with the base class constructor. The only reason you need it protected is because you want initialize the protected data members. Now, I think the protected data members are <em>also</em> a bad idea, but one thing at a time. <em>If</em> you are going to have data members in the base class—which, again, is generally unwise—then, okay, it makes sense to have a protected constructor.</p>\n<p>As for the constructors of the other two classes, unlike the base class these are concrete classes. What is the reasoning for hiding <em>those</em> constructors? If you want people to use the factory function, fine, but why make that the only option? Why <em>don’t</em> you want users to directly construct the readers?</p>\n<p>By hiding those constructors, you prevent the use of <code>std::make_shared()</code>, which is an optimization opportunity lost. What’s the logic of that?</p>\n<p>Also, even <em>if</em> you wanted to hide those constructors, what’s the sense in making them protected, and not private? That seems to imply you expect the classes to be derived from… but that’s a terrible idea: non-leaf classes should be abstract. (Again, assuming you’re doing interface inheritance. If you’re doing <em>implementation</em> inheritance, then there’s a whole other set of rules.)</p>\n<h1>Code review</h1>\n<p>Because the code is not presented as it would be in the actual project, and is instead all packed into a single block as some kind of code soup, with no includes and no explanation of what some of the key types are, this isn’t going to be a very comprehensive code review. I’ll do what I can with what I’ve got, but as the saying goes, GIGO.</p>\n<pre><code>typedef std::shared_ptr<DataReader> datareader_ptr;\n</code></pre>\n<p>There’s no indication of why <code>shared_ptr</code> is used here, and not <code>unique_ptr</code>, and in fact the rest of the code is written in a way that hamstrings the use of <code>shared_ptr</code>.</p>\n<pre><code>virtual void finalize() {\n pipe_.stop();\n}\nvirtual ~DataReader() {\n std::cout << "dtor for DataReader called." << std::endl;\n finalize();\n}\n</code></pre>\n<p><em>NEVER</em> call virtual functions from constructors or destructors. It doesn’t do what you’d think, and only creates confusion for less experienced programmers.</p>\n<p>In this case it “works” only because… well, I mean, the whole hierarchy is actually pointless. If the hierarchy were actually doing something that justified its existence, then this would almost certainly not work.</p>\n<p>There is no visible purpose to <code>finalize()</code>. Just put <code>pipe_.stop()</code> in the destructor.</p>\n<pre><code>DataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile)\n :cfg_(cfg),pipe_(pipe),pipeline_profile_(pipeline_profile) {}\n</code></pre>\n<p>This is not a good way to write this constructor. (Or maybe it is? Who knows? Not enough information, forced to make guesses.)</p>\n<p>If you are going to take the arguments by value—which is the right thing to do, because they are sink arguments—then you should <em>move</em> them into their final place… not copy. The copy is unnecessary, and possibly wasteful. And, if the move ops for all those types is <code>noexcept</code> (which it should always be), then that would mean you could make the constructor <code>noexcept</code> too.</p>\n<p>The other issue is that you’ve mixed up the order of construction; it’s not the same as the order of declaration:</p>\n<pre><code>// order of declaration:\nrs2::config cfg_;\nrs2::pipeline_profile pipeline_profile_;\nrs2::pipeline pipe_;\n\n// order of construction:\ncfg_(cfg),\npipe_(pipe),\npipeline_profile_(pipeline_profile)\n</code></pre>\n<p>I’m surprised this compiled without warning. You <em>do</em> have all warnings turned on, don’t you?</p>\n<p>By the way, all the above is true of all the constructors, because they’re all identical. Which… again… is another issue.</p>\n<pre><code>class RosBagDataReader : public DataReader {\n // ... [snip] ...\n\n virtual bool get_next_frameset(rs2::frameset& frames) {\n</code></pre>\n<p><a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-override\" rel=\"nofollow noreferrer\">Prefer one of <code>virtual</code>, <code>override</code>, <code>final</code>, or none of the above</a>. In this case, the one you want is <em>NOT</em> <code>virtual</code>, it’s <code>override</code>.</p>\n<pre><code>virtual ~RosBagDataReader() {}\n</code></pre>\n<p>You don’t need this. Don’t write code you don’t need; it just becomes a maintenance burden, noise obscuring <em>important</em> code, and confusion for future coders who wonder why it was put there if it wasn’t necessary.</p>\n<pre><code>// in base class:\nvirtual bool get_next_frameset(rs2::frameset& frames)=0;\nrs2::pipeline pipe_;\n\n// in derived class 1:\nbool get_next_frameset(rs2::frameset& frames) override {\n frames = pipe_.wait_for_frames();\n return true;\n}\n\n// in derived class 2\nbool get_next_frameset(rs2::frameset& frames) override {\n frames = pipe_.wait_for_frames();\n return true;\n}\n</code></pre>\n<p>Why?</p>\n<p>Why not:</p>\n<pre><code>// in base class:\nvirtual bool get_next_frameset(rs2::frameset& frames) {\n frames = pipe_.wait_for_frames();\n return true;\n}\nrs2::pipeline pipe_;\n\n// in derived class 1:\n// nothing needed\n\n// in derived class 2:\n// nothing needed\n</code></pre>\n<p>This entire class hierarchy serves no purpose. If I were to reorganize it into something logical, it might look more like this:</p>\n<pre><code>// truly abstract base class\nclass DataReader\n{\npublic:\n virtual ~DataReader() /* = default; */\n {\n std::cout << "dtor for DataReader called." << std::endl;\n }\n\n virtual bool get_next_frameset(rs2::frameset& frames) = 0;\n};\n\n// concrete implementation 1\nclass RosBagDataReader : public DataReader\n{\n // all data is private, as it should be\n rs2::config cfg_;\n rs2::pipeline_profile pipeline_profile_;\n rs2::pipeline pipe_;\n\npublic:\n RosBagDataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :\n cfg_(std::move(cfg)),\n pipeline_profile_(std::move(pipeline_profile)),\n pipe_(std::move(pipe))\n {}\n\n ~RosBagDataReader()\n {\n pipe_.stop();\n }\n\n bool get_next_frameset(rs2::frameset& frames) override\n {\n frames = pipe_.wait_for_frames();\n return true;\n }\n};\n\n// concrete implementation 2... same as 1... which, yeah\nclass CameraDataReader : public DataReader\n{\n rs2::config cfg_;\n rs2::pipeline_profile pipeline_profile_;\n rs2::pipeline pipe_;\n\npublic:\n CameraDataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :\n cfg_(std::move(cfg)),\n pipeline_profile_(std::move(pipeline_profile)),\n pipe_(std::move(pipe))\n {}\n\n ~CameraDataReader()\n {\n pipe_.stop();\n }\n\n bool get_next_frameset(rs2::frameset& frames) override\n {\n frames = pipe_.wait_for_frames();\n return true;\n }\n};\n</code></pre>\n<p>Or:</p>\n<pre><code>// no longer abstract, or even designed for inheritance at all:\nclass DataReader\n{\n // all data is private, as it should be\n rs2::config cfg_;\n rs2::pipeline_profile pipeline_profile_;\n rs2::pipeline pipe_;\n\npublic:\n DataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :\n cfg_(std::move(cfg)),\n pipeline_profile_(std::move(pipeline_profile)),\n pipe_(std::move(pipe))\n {}\n\n ~DataReader()\n {\n std::cout << "dtor for DataReader called." << std::endl;\n pipe_.stop();\n }\n\n bool get_next_frameset(rs2::frameset& frames)\n {\n frames = pipe_.wait_for_frames();\n return true;\n }\n};\n\n// now pointless: class RosBagDataReader\n// now pointless: class CameraDataReader\n</code></pre>\n<p>Honestly, I don’t even know if the suggestions I’m making make any sense whatsoever, because without the definitions of <code>rs2::config</code> et cetera, I have no clue whether these classes are copyable, movable, or whatever. But I don’t know what else to say: you hide code from reviewers, you get shitty reviews.</p>\n<pre><code>datareader_ptr make_data_reader(const std::string& ros_bag_path)\n</code></pre>\n<p>My biggest peeve with this factory function is that the argument list is bullshit. If I want to construct a data reader for a camera, I have to create a completely spurious path. That’s a waste of time for me on every level: it’s a waste of time for me to write the code to create a path I neither want nor need, and it’s a waste of resources within the program to create this useless path only to make a pointless check that it’s empty and then discard it.</p>\n<p>If I were actually going to use this code, the very first thing I’d do is write my own wrapper functions:</p>\n<pre><code>auto make_camera_reader() { return make_data_reader({}); }\n\nauto make_ros_bag_reader(std::string const& path) { return make_data_reader(path); }\n</code></pre>\n<p>And then I’d use those instead of direct calls to the factory functions.</p>\n<p>Why? Because if I saw this in code:</p>\n<pre><code>auto reader = make_data_reader({}); // or make_data_reader("") or whatever\n</code></pre>\n<p>I’d immediately be forced to wonder… what is the <code>{}</code>? What does it mean? What am I constructing there at the call site? Will it be expensive? Does it have some semantics I should be aware of?</p>\n<p>I like reading mystery stories; I don’t like mystery code. Code shouldn’t challenge me to wonder what’s going on, or force me to go read the docs. It should be crystal clear about what’s going on, and what it’s doing.</p>\n<p>On the other hand, if I were to see:</p>\n<pre><code>auto reader = make_camera_reader();\n</code></pre>\n<p>That tells me pretty much everything I need to know. No mysteries.</p>\n<p>This is not a problem with factory functions in general. Factory functions can still be very clear about what they’re doing. For example:</p>\n<pre><code>auto renderer = make_renderer("opengl"); // or make_renderer("vulkan") or whatever\n\n// Here, make_renderer returns unique_ptr<renderer>, and renderer is an\n// abstract base class, and the factory function returns concrete renderer\n// implementations... but none of that matters! Just from the call above, I\n// understand generally what's going on.\n</code></pre>\n<p>Compare that to:</p>\n<pre><code>auto reader = make_data_reader("");\n\n// or even:\nauto reader = make_data_reader("/path/to/file");\n</code></pre>\n<p>What is really going on there? “Data reader”? Well that’s damn vague. In the first case: the hell is that string supposed to <em>mean</em>? Make a data reader for… nothing? Emptiness? Perhaps the <code>{}</code> refers to wanting only default options? In the second case: okay, we’re making a data reader for some path, probably a file. That’s still pretty damned vague. Are we making a data reader <em>for</em> the file? If so, what kind of data? Are we making a data reader <em>from</em> the file?</p>\n<p>If I were going to improve the design of your factory function, I might refactor it as follows:</p>\n<pre><code>auto make_data_reader(std::string_view name, std::string_view args)\n{\n rs2::config cfg;\n rs2::pipeline pipe;\n\n if (name == "camera")\n {\n // args is unused\n\n rs2::pipeline_profile profile = pipe.start();\n return datareader_ptr(new CameraDataReader(cfg, pipe, profile));\n }\n else if (name == "video file")\n {\n // args is the path to the video file\n\n cfg.enable_device_from_file(args, false);\n\n rs2::pipeline_profile profile = pipe.start(cfg);\n\n rs2::playback play(profile.get_device());\n play.set_real_time(false);\n\n return datareader_ptr(new RosBagDataReader(cfg, pipe, profile));\n }\n /* future expansion:\n else if (name == "url")\n {\n // args is the url\n\n // ... implementation...\n }\n */\n else\n {\n throw std::logic_error{std::string{"unknown data reader type: "} + name};\n }\n\n // this should never happen, so it could also be an assert\n throw std::logic_error{std::string{"data reader type "} + std::string{name} + " failed to return reader"};\n}\n\ninline auto make_data_reader(std::string_view name)\n{\n return make_data_reader(name, {});\n}\n</code></pre>\n<p>And the usage is:</p>\n<pre><code>// I want to read frames from a camera:\nauto reader = make_data_reader("camera");\n\n// I want to read frames from a file:\nauto reader = make_data_reader("video file", "/path/to/file");\n\n// Hypothetical extension: I want to read frames from a web service:\nauto reader = make_data_reader("url", "https://domain.com/path/to/service");\n</code></pre>\n<p>Let’s keep following the train of thought I started with my wrapper functions. What if they were more than mere wrappers?</p>\n<pre><code>auto make_camera_reader()\n{\n rs2::config cfg;\n rs2::pipeline pipe;\n rs2::pipeline_profile profile = pipe.start();\n\n // Note: using make_shared because I assume constructors are public.\n return std::make_shared<CameraDataReader>(std::move(cfg), std::move(pipe), std::move(profile));\n}\n\n// Note: taking a proper path rather than a random string. You should always\n// prefer proper, semantic types.\nauto make_ros_bag_reader(std::filesystem::path const& path)\n{\n rs2::config cfg;\n cfg.enable_device_from_file(ros_bag_path.string(), false);\n\n rs2::pipeline pipe;\n\n rs2::pipeline_profile profile = pipe.start(cfg);\n\n rs2::playback play(profile.get_device());\n play.set_real_time(false);\n\n return std::make_shared<RosBagDataReader>(std::move(cfg), std::move(pipe), std::move(profile));\n}\n</code></pre>\n<p>Now there doesn’t seem to be any point to returning pointers, rather than objects directly.</p>\n<p>In fact, let’s go one step further:</p>\n<pre><code>class image_sequence_reader // a better name than DataReader\n{\n rs2::config cfg_;\n rs2::pipeline pipe_;\n rs2::pipeline_profile pipeline_profile_;\n\npublic:\n static auto make_for_camera() -> image_sequence_reader\n {\n rs2::config cfg;\n rs2::pipeline pipe;\n rs2::pipeline_profile profile = pipe.start();\n\n return {std::move(cfg), std::move(pipe), std::move(profile)};\n }\n\n static auto make_for_video_file(std::filesystem::path const& path) -> image_sequence_reader\n {\n rs2::config cfg;\n cfg.enable_device_from_file(ros_bag_path.string(), false);\n\n rs2::pipeline pipe;\n\n rs2::pipeline_profile profile = pipe.start(cfg);\n\n rs2::playback play(profile.get_device());\n play.set_real_time(false);\n\n return {std::move(cfg), std::move(pipe), std::move(profile)};\n }\n\n ~DataReader()\n {\n pipe_.stop();\n }\n\n auto get_next_frameset(rs2::frameset& frames) -> bool\n {\n frames = pipe_.wait_for_frames();\n return true;\n }\n\nprivate:\n DataReader(rs2::config cfg, rs2::pipeline pipe, rs2::pipeline_profile pipeline_profile) :\n cfg_(std::move(cfg)),\n pipe_(std::move(pipe)),\n pipeline_profile_(std::move(pipeline_profile))\n {}\n};\n</code></pre>\n<p>Usage:</p>\n<pre><code>// I want to read frames from a camera:\nauto reader = image_sequence_reader::make_for_camera();\n\n// I want to read frames from a file:\nauto reader = image_sequence_reader::make_for_video_file("/path/to/file");\n</code></pre>\n<p>Want to extend the capabilities to read from some other source? No problem. Just add a new static member function:</p>\n<pre><code> static auto make_for_nondefault_camera(camera_id const& id) -> image_sequence_reader;\n static auto make_for_device(std::filesystem::path const& device_path) -> image_sequence_reader;\n static auto make_for_web_service(url const& location) -> image_sequence_reader;\n static auto make_for_retina_brain_interface(person const& name) -> image_sequence_reader;\n // and so on...\n</code></pre>\n<p>That’s much less work than adding a whole new derived class, and then monkeying with the factory function to be able to select it.</p>\n<p>It’s also clearer—both in the class and at the call site—safer, and, frankly, just easier to use.</p>\n<p>Okay, but what if you really, <em>REALLY</em> want to use the factory pattern, because this is going to be in a library, and you want to be able to extend the library without client code having to be recompiled.</p>\n<p>With some minor tweaks, you can even still enjoy all the other benefits of the factory pattern too:</p>\n<pre><code>////////////////////////////////////////////////////////////////////////\n// in header used by client code:\n\n// pure interface:\nclass image_sequence_reader_interface\n{\npublic:\n virtual ~image_sequence_reader_interface() = default;\n\n virtual auto get_next_frameset(rs2::frameset&) -> bool = 0;\n\n // run-time polymorphic classes should generally not be copyable.\n // usually you'd implement a clone() function. i'll skip all that here.\n};\n\n// concrete implementation: the only thing client code really needs to care\n// about.\nclass image_sequence_reader final : public image_sequence_reader_interface\n{\n // if necessary, you can use a custom deleter to make sure the library\n // deletes its own memory, and not the application.\n std::unique_ptr<image_sequence_reader_interface> _p_impl;\n\npublic:\n static auto make_for(std::string_view name, std::string_view args) -> image_sequence_reader;\n\n static auto make_for(std::string_view name) -> image_sequence_reader\n {\n return make_for(name, {});\n }\n\n ~image_sequence_reader() = default;\n\n auto get_next_frameset(rs2::frameset& frames) -> bool override\n {\n return _p_impl->get_next_frames(frames);\n }\n\n image_sequence_reader(image_sequence_reader&&) noexcept = default;\n auto operator=(image_sequence_reader&&) noexcept -> image_sequence_reader& = default;\n\nprivate:\n explicit image_sequence_reader(std::unique_ptr<impl>) noexcept;\n};\n\n////////////////////////////////////////////////////////////////////////\n// in implementation file (cpp file, or module, or library source code, depending):\n\nclass camera_image_sequence_reader : public image_sequence_reader_interface\n{\n rs2::config cfg_;\n rs2::pipeline pipe_;\n rs2::pipeline_profile pipeline_profile_;\n\npublic:\n camera_image_sequence_reader() :\n camera_image_sequence_reader(_construct())\n {}\n\n ~camera_image_sequence_reader()\n {\n pipe_.stop();\n }\n\n auto get_next_frameset(rs2::frameset& frames) -> bool override\n {\n frames = pipe_.wait_for_frames();\n return true;\n }\n\n camera_image_sequence_reader(camera_image_sequence_reader&&) noexcept = default;\n auto operator=(camera_image_sequence_reader&&) noexcept -> camera_image_sequence_reader& = default;\n\nprivate:\n // All this _construct() stuff *MIGHT BE* needed because the data\n // members all seem to need to be constructed in a specific order, and\n // with references to each other. Or none of it might be necessary;\n // there's no way to know because I don't know what the data types are.\n\n static auto _construct() -> std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile>\n {\n rs2::config cfg;\n rs2::pipeline pipe;\n rs2::pipeline_profile profile = pipe.start();\n\n return {std::move(cfg), std::move(pipe), std::move(profile)};\n }\n\n camera_image_sequence_reader(std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile> t) :\n cfg_(std::move(t.cfg)),\n pipe_(std::move(t.pipe)),\n pipeline_profile_(std::move(t.profile))\n {}\n};\n\nclass video_file_image_sequence_reader : public image_sequence_reader_interface\n{\n rs2::config cfg_;\n rs2::pipeline pipe_;\n rs2::pipeline_profile pipeline_profile_;\n\npublic:\n video_file_image_sequence_reader() :\n video_file_image_sequence_reader(_construct())\n {}\n\n ~video_file_image_sequence_reader()\n {\n pipe_.stop();\n }\n\n auto get_next_frameset(rs2::frameset& frames) -> bool override\n {\n frames = pipe_.wait_for_frames();\n return true;\n }\n\n video_file_image_sequence_reader(video_file_image_sequence_reader&&) noexcept = default;\n auto operator=(video_file_image_sequence_reader&&) noexcept -> video_file_image_sequence_reader& = default;\n\nprivate:\n static auto _construct() -> std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile>\n {\n rs2::config cfg;\n cfg.enable_device_from_file(ros_bag_path.string(), false);\n\n rs2::pipeline pipe;\n\n rs2::pipeline_profile profile = pipe.start(cfg);\n\n rs2::playback play(profile.get_device());\n play.set_real_time(false);\n\n return {std::move(cfg), std::move(pipe), std::move(profile)};\n }\n\n video_file_image_sequence_reader(std::tuple<rs2::config, rs2::pipeline, rs2::pipeline_profile> t) :\n cfg_(std::move(t.cfg)),\n pipe_(std::move(t.pipe)),\n pipeline_profile_(std::move(t.profile))\n {}\n};\n\n// add or include any other implementations\n\nauto image_sequence_reader::make_for(std::string_view name, std::string_view args) -> image_sequence_reader\n{\n auto p = std::unique_ptr<impl>{};\n\n if (name == "camera")\n {\n p.reset(new camera_image_sequence_reader{});\n }\n else if (name == "video file")\n {\n p.reset(new video_file_image_sequence_reader{args});\n }\n\n // add any other options ...\n\n else\n {\n throw std::logic_error{std::string{"unknown image sequence reader type: "} + name};\n }\n\n // assert(p);\n\n return image_sequence_reader{std::move(p)};\n}\n</code></pre>\n<p>And the usage is the same as before:</p>\n<pre><code>// I want to read frames from a camera:\nauto reader = image_sequence_reader::make_for("camera");\n\n// I want to read frames from a file:\nauto reader = image_sequence_reader::make_for("video file", "/path/to/file");\n</code></pre>\n<p>And not only that, but with very little extra work you could even allow clients to register their own extension implementations. Alls you need is a register function in <code>image_sequence_reader</code> that takes a name and a create function (which returns a unique pointer with an appropriate deleter), and then a map that maps names to create functions, and then in <code>image_sequence_reader::make_for()</code>, just query the map for the name, then use the create function.</p>\n<p>Is this a better design than what you have? Impossible to say with the information I have.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T05:25:58.573",
"Id": "502056",
"Score": "0",
"body": "Sincerely thankful for the detailed and inspiring answer. I'd like to add two comments: 1. the implementation of `get_next_frame` was initially intended to be different for a video file, by polling the next frame and returning false when failed. However, the `poll_for_frames` [didn't seem to work properly](https://github.com/IntelRealSense/librealsense/issues/2308) at least in my case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T05:26:04.243",
"Id": "502057",
"Score": "0",
"body": "2. all the classes in the `rs2` namespace are just thin wrappers holding a `shared_ptr`, which points to the class actually doing the job (i.e. pimpl idiom). [ref](https://intelrealsense.github.io/librealsense/doxygen/classrs2_1_1pipeline.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T06:19:29.827",
"Id": "502060",
"Score": "0",
"body": "As I'm digesting the answer, I have a question: I see the trailing return type used constantly in the final pieces of code. Is it always preferred to use the trailing return type? Or it's just a style issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T02:50:08.573",
"Id": "502163",
"Score": "0",
"body": "Ah, well, if you’re stuck using `shared_ptr` because of the library, I guess you might as well roll with it. Sucks that the library forces it on you, though. As for trailing return, it’s just a style thing. I’m a big fan of consistency, and old-style return *usually* works, but trailing-style *always* works, so, trailing wins. Also I write all functions as `auto f()` by default, and only add an explicit return if the circumstances warrant it, and trailing style really makes it stand out. But it’s just style; if you like old-style returns better, they work just fine."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T20:13:40.030",
"Id": "254464",
"ParentId": "254370",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254464",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T04:46:04.967",
"Id": "254370",
"Score": "0",
"Tags": [
"c++",
"factory-method",
"c++20",
"abstract-factory"
],
"Title": "Best practice for factory pattern in c++?"
}
|
254370
|
<p>I wanted to check and see if this was as efficient as can be. The goal is to get a user's data from a group of documents that contains references to users in <a href="https://firebase.google.com/docs/firestore" rel="nofollow noreferrer">Firestore</a>.</p>
<p><strong>ngOnInit</strong></p>
<pre><code>this.links = this.currentUserRef.collection('links', ref => ref.where('pendingRequest', '==', false)).get()
.pipe(map(querySnap => {
const ret = [];
querySnap.forEach(async doc => {
const val = await doc.get('otherUser').get().then(async userData => {
return {
id: userData.id,
img: await this.getImage(userData.get('profilepic')),
name: userData.get('name'),
bio: userData.get('bio')
}
});
ret.push(val);
});
return ret;
}));
</code></pre>
<p><strong>HTML</strong></p>
<pre><code><ion-item *ngFor="let link of links | async">
<ion-avatar slot="start">
<img src="{{link.img}}">
</ion-avatar>
<ion-label>
<h2>{{link.name}}</h2>
<p>{{link.bio}}</p>
</ion-label>
<ion-checkbox id="{{link.id}}"></ion-checkbox>
</ion-item>
</code></pre>
|
[] |
[
{
"body": "<p>What do you mean with "efficient" in this case?</p>\n<p>From the performance perspective its slow, because it handles one element after the other and for handling one element it needs to wait for an async call.<br />\nAs a result the browser will note be able to execute multiple requests at once.</p>\n<p>You could try to move the getImage request into the html with the async pipe.\nThen the browser will be able to fire multiple requests simultaniously.</p>\n<p>Beside that i personaly would divide the code in a few methods. So it would look like this:</p>\n<pre><code>__HTML__\n<img [src]="getImage(link.img) | async"\n\n\n\n__TypeScript__\ninterface Link{\n id: string,\n img: string,\n name: string,\n bio: string\n};\n\n...\nthis.links = this.getLinks(userRef);\n...\n\nprivate getLinks(userRef: ??? ): Link[] {\n return userRef.collection('links', ref.where('pendingRequest', '==', false)).get()\n .pipe(\n map(querySnap => mapSnapToLinks(querySnap))\n )\n}\n\nprivate mapSnapToLinks(querySnap: ???):Link[]{\n querySnap.forEach(async doc => {\n const val = doc.get('otherUser').get().then(userData => this.mapUserToLink(userData));\n ret.push(val);\n });\n}\n\nprivate mapUserToLink(userData): Link {\n return {\n id: userData.id,\n img: userData.get('profilepic'),\n name: userData.get('name'),\n bio: userData.get('bio')\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T10:10:38.813",
"Id": "257333",
"ParentId": "254373",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T07:03:49.360",
"Id": "254373",
"Score": "0",
"Tags": [
"beginner",
"angular-2+",
"observer-pattern",
"firebase"
],
"Title": "Angular observables piping"
}
|
254373
|
<p>I've created a travel agent website, I would like to know how can I improve, DRY my code and how to increase performance - I tinified img's but the bottom one I've made in PS takes much time to load.<br><br>
Here is a <strong><a href="https://isaayy.github.io/Front-end-projects/Adure/index.html" rel="nofollow noreferrer">preview</a></strong> hosted on github pages and <strong><a href="https://github.com/Isaayy/Front-end-projects/tree/master/Adure" rel="nofollow noreferrer">repository</a></strong><br></p>
<p>(idk if I could ask here for design feedback but it would be welcome too if possible)</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
// #####################################
// CHANING TEXT ON DIFFERENT DEVICES
const text = document.querySelectorAll('.review__feedback');
// TABLET
const userAgent = navigator.userAgent.toLowerCase();
const isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(
userAgent
);
if (isTablet) {
for (let item of text) {
item.textContent =
'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Illum quam fuga labore obcaecati, hic voluptates est laudantium corrupti. Possimus, soluta necessitatibus voluptatibus porro delectus, nemo tempora cupiditate sit excepturi voluptatem dolorem. Voluptatem officia ullam dignissimos laborum aliquid, soluta quidem odit?';
}
}
// PHONE
window.mobileCheck = function() {
let check = false;
(function(a) {
if (
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
a
) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
a.substr(0, 4)
)
)
check = true;
})(navigator.userAgent || navigator.vendor || window.opera);
return check;
};
if (mobileCheck()) {
for (let item of text) {
item.innerHTML =
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Hic natus laboriosam, veritatis distinctio, saepe earum libero veniam labore id, beatae suscipit magni similique numquam possimus.';
}
}
// #####################################
// HAMBURGER MENU
const hamburger = document.querySelector('.hamburger__outline');
const bar = document.querySelector('.hamburger__bar');
const nav = document.querySelector('nav');
const links = document.querySelectorAll('.header__link');
const body = document.querySelector('body');
const menu = (whatToDo) => {
hamburger.classList.toggle('hamburger--active');
nav.classList.toggle('nav--moveIn');
// body.classList.toggle('u-overflow-hidden');
if (whatToDo === 'Open') {
bar.classList.add('hamburger__bar--hidden'); // on first click
} else {
setTimeout(function() {
bar.classList.remove('hamburger__bar--hidden');
}, 100);
}
};
hamburger.addEventListener('click', function() {
if (bar.classList.contains('hamburger__bar--hidden')) {
menu('Close');
} else {
menu('Open');
}
});
for (let i = 0; i < links.length; i++) {
links[i].addEventListener('click', () => {
menu('Close');
});
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap");
*,
*::after,
*::before {
margin: 0;
padding: 0;
text-decoration: none;
-webkit-box-sizing: border-box;
box-sizing: border-box;
font-family: 'Quicksand', sans-serif;
}
html {
font-size: 62.5%;
scroll-behavior: smooth;
overflow-x: hidden;
}
.container {
width: 100%;
max-width: 144rem;
margin: 0 auto;
padding: 0 7rem;
}
@media (max-width: 36em) {
.container {
padding: 0 3rem;
}
}
.subheading {
margin-top: 14rem;
margin-bottom: 8rem;
}
:root {
--font-size: 1.6rem;
--heading: calc(var(--font-size) * 3.5);
--subheading: calc(var(--font-size) * 2);
}
@media (max-width: 62em) {
:root {
--font-size: 1.5rem;
--heading: calc(var(--font-size) * 3);
--subheading: calc(var(--font-size) * 1.8);
}
}
@media (max-width: 36em) {
:root {
--font-size: 1.4rem;
--heading: calc(var(--font-size) * 2.5);
--subheading: calc(var(--font-size) * 1.5);
}
}
.subheading {
font-size: var(--subheading);
font-weight: bold;
text-align: center;
}
.header__link {
font-size: 1.8rem;
color: #e7e7e7;
font-weight: 600;
}
.header__link:hover {
color: #fefefe;
}
.hero__heading {
color: #fefefe;
font-size: var(--heading);
font-weight: bold;
}
.hero__subheading {
color: #fefefe;
font-size: var(--subheading);
font-weight: 400;
}
.hero__cta {
color: black;
font-weight: bold;
font-size: var(--font-size);
}
.location__heading {
font-size: var(--subheading);
font-weight: 600;
color: #fefefe;
}
.location__location {
color: #fefefe;
font-weight: bold;
font-size: 1rem;
}
.location__desc {
font-size: var(--font-size);
font-weight: 300;
color: #c4c4c4;
line-height: 1.5;
}
.review__feedback {
font-size: var(--font-size);
font-weight: 300;
line-height: 1.5;
}
.review__name {
font-size: 2rem;
font-weight: 500;
}
.review__date {
font-size: 1rem;
font-weight: 500;
}
.booking__heading {
font-size: var(--subheading);
font-weight: 600;
}
.footer-city {
font-size: 1.8rem;
color: #fc6482;
font-weight: 300;
}
.footer-city:hover {
color: #fefefe;
}
.copy-right {
font-size: 1.2rem;
color: #fefefe;
}
.benefit {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
padding: 2rem;
}
.benefit__heading {
font-size: 2rem;
font-weight: 600;
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.benefit__desc {
font-size: var(--font-size);
text-align: center;
width: 70%;
}
.book-btn {
margin-top: 2.5rem;
-ms-flex-item-align: start;
align-self: flex-start;
color: #000;
font-size: 1.2rem;
font-weight: bold;
padding: 1.2rem 4.5rem;
border-radius: 0.3rem;
-webkit-transition: all .3s;
transition: all .3s;
}
.book-btn--green {
background: -webkit-gradient(linear, left top, right top, from(#00f5a0), to(#00d9f5));
background: linear-gradient(to right, #00f5a0, #00d9f5);
}
.book-btn--blue {
background: -webkit-gradient(linear, left top, right top, from(#00c6ff), to(#0072ff));
background: linear-gradient(to right, #00c6ff, #0072ff);
}
.book-btn--orange {
background: -webkit-gradient(linear, left top, right top, from(#ffe259), to(#ffa751));
background: linear-gradient(to right, #ffe259, #ffa751);
}
.book-btn:hover {
-webkit-transform: translateY(-3px);
transform: translateY(-3px);
}
.book-btn:active {
-webkit-transform: translateY(0);
transform: translateY(0);
}
.nav ul {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
list-style: none;
}
@media (max-width: 62em) {
.nav--header {
-webkit-transform: translateX(100%);
transform: translateX(100%);
-webkit-transition: all 0.3s;
transition: all 0.3s;
background-color: #fefefe;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.nav--header ul {
position: relative;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
top: 50%;
-webkit-transform: translateY(-50%);
transform: translateY(-50%);
}
.nav--header a {
color: #1a1919;
font-size: 4rem;
}
}
@media (max-width: 62em) and (max-width: 36em) {
.nav--header a {
font-size: 2.5rem;
}
}
.nav--header ul {
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.nav--header li:not(:first-child) {
margin-left: 5rem;
}
@media (max-width: 62em) {
.nav--header li:not(:first-child) {
margin-left: 0;
margin-top: 5rem;
}
}
.nav--footer ul {
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
@media (max-width: 62em) {
.nav--footer ul {
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-direction: row;
flex-direction: row;
}
}
.nav--footer li:not(:first-child) {
margin-top: 1.5rem;
}
@media (max-width: 62em) {
.nav--footer li:not(:first-child) {
margin-top: 0;
margin-left: 2rem;
}
}
.nav--moveIn {
-webkit-transform: translateX(0);
transform: translateX(0);
}
.hamburger {
display: none;
position: relative;
z-index: 100;
}
@media (max-width: 62em) {
.hamburger {
display: inline-block;
}
}
.hamburger__outline {
display: inline-block;
height: 2.4rem;
}
.hamburger__bar {
width: 3rem;
height: 0.4rem;
background-color: #61e786;
display: inline-block;
position: relative;
-webkit-transition: all 0.5s;
transition: all 0.5s;
}
.hamburger__bar::before,
.hamburger__bar::after {
content: '';
width: 100%;
height: 0.4rem;
background-color: #61e786;
position: absolute;
-webkit-transition: all 0.5s;
transition: all 0.5s;
}
.hamburger__bar::before {
top: -0.8rem;
}
.hamburger__bar::after {
top: 0.8rem;
}
.hamburger__bar--hidden {
background: transparent;
-webkit-transition: all 0s;
transition: all 0s;
}
.hamburger--active .hamburger__bar::before {
-webkit-transform: translatey(0.8rem) rotate(45deg);
transform: translatey(0.8rem) rotate(45deg);
}
.hamburger--active .hamburger__bar::after {
-webkit-transform: translatey(-0.8rem) rotate(-45deg);
transform: translatey(-0.8rem) rotate(-45deg);
}
.landing-page {
background-repeat: no-repeat;
background-size: cover;
height: 100vh;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
position: relative;
overflow-x: hidden;
}
.landing-page__blur {
z-index: -1;
height: 100%;
width: 40%;
position: absolute;
top: 0;
left: 0;
-webkit-backdrop-filter: blur(4px);
backdrop-filter: blur(4px);
}
@media (max-width: 62em) {
.landing-page__blur {
display: none;
}
}
.landing-page__blur::before {
content: '';
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: -9;
background-color: black;
opacity: 0.1;
}
.landing-page__bgc {
background: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.3))), url("../img/background-hero.jpg");
background: linear-gradient(rgba(0, 0, 0, 0.3)), url("../img/background-hero.jpg");
position: absolute;
top: 0;
background-position: center;
background-size: cover;
background-repeat: no-repeat;
left: 0;
width: 100%;
height: 100%;
z-index: -2;
}
.header {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding-top: 2rem;
}
.header__logo {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
color: #fefefe;
font-size: 1.4rem;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
font-weight: 600;
}
@media (min-width: 112.5em) {
.hero {
border-left: 0.5rem solid #fefefe;
padding: 5.5rem 8rem;
}
}
@media (max-width: 62em) {
.hero {
text-align: center;
}
}
.hero__subheading {
margin-bottom: 5rem;
margin-top: 1rem;
}
.hero__cta {
background: #61e786;
padding: 1.5rem 5rem;
border-radius: 0.3rem;
-webkit-transition: all 0.3s;
transition: all 0.3s;
}
@media (max-width: 36em) {
.hero__cta {
padding: 1rem 4rem;
}
}
.hero__cta:hover {
background: #3de46c;
}
.socials {
padding-bottom: 2rem;
}
@media (max-width: 62em) {
.socials {
text-align: center;
}
}
.socials a:first-child {
margin-right: 2.5rem;
}
.socials img {
width: 3rem;
height: 3rem;
}
.benefits-container {
display: -ms-grid;
display: grid;
-ms-grid-columns: (minmax(30rem, 1fr))[auto-fit];
grid-template-columns: repeat(auto-fit, minmax(30rem, 1fr));
grid-gap: 2rem;
}
@media (max-width: 75em) {
.benefits-container {
-ms-grid-columns: (1fr)[2];
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 36em) {
.benefits-container {
-ms-grid-columns: 1fr;
grid-template-columns: 1fr;
}
}
.locations-container {
background-color: #1a1919;
display: -ms-grid;
display: grid;
-ms-grid-columns: (50%)[2];
grid-template-columns: repeat(2, 50%);
}
@media (max-width: 75em) {
.locations-container {
-ms-grid-columns: 1fr;
grid-template-columns: 1fr;
background-color: transparent;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
}
.locations-img {
-o-object-fit: cover;
object-fit: cover;
width: 100%;
position: relative;
z-index: 1;
}
@media (max-width: 75em) {
.locations-img--green {
-ms-grid-row: 1;
-ms-grid-row-span: 1;
grid-row: 1/2;
}
}
@media (max-width: 75em) {
.locations-img--orange {
-ms-grid-row: 5;
-ms-grid-row-span: 1;
grid-row: 5/6;
}
}
.location {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
width: 100%;
margin: 0 auto;
padding: 0 5rem;
}
@media (min-width: 112.5em) {
.location {
width: 50%;
padding: 0;
}
}
@media (max-width: 75em) {
.location {
background-color: #1a1919;
padding: 10rem;
}
}
@media (max-width: 36em) {
.location {
background-color: #1a1919;
padding: 7rem 5rem;
}
}
@media (max-width: 36em) {
.location__desc span {
display: none;
}
}
.location__location {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin-top: 0.5rem;
margin-bottom: 2.5rem;
}
.location__location img {
margin-right: 0.5rem;
}
.more-locations {
border: 1px solid black;
border-radius: 0.5rem;
width: 60rem;
margin: 0 auto;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
padding: 1.5rem 3rem;
}
@media (max-width: 48em) {
.more-locations {
width: 100%;
}
}
.more-locations input {
outline: none;
border: none;
-webkit-box-flex: 1;
-ms-flex: 1;
flex: 1;
margin-right: 1rem;
}
.more-locations input::-webkit-input-placeholder {
color: black;
font-size: 1.8rem;
font-weight: 300;
}
.more-locations input:-ms-input-placeholder {
color: black;
font-size: 1.8rem;
font-weight: 300;
}
.more-locations input::-ms-input-placeholder {
color: black;
font-size: 1.8rem;
font-weight: 300;
}
.more-locations input::placeholder {
color: black;
font-size: 1.8rem;
font-weight: 300;
}
.reviews .reviews-container {
display: -ms-grid;
display: grid;
-ms-grid-rows: (1fr)[3];
grid-template-rows: repeat(3, 1fr);
grid-row-gap: 5rem;
}
.reviews .review {
padding: 5rem 8rem;
-webkit-box-shadow: 0 0 0.5rem rgba(0, 0, 0, 0.1);
box-shadow: 0 0 0.5rem rgba(0, 0, 0, 0.1);
border-radius: 0.3rem;
}
@media (max-width: 48em) {
.reviews .review {
padding: 4rem 7rem;
}
}
@media (max-width: 36em) {
.reviews .review {
padding: 3rem 4rem;
}
}
.reviews .review__img {
margin-right: 1.5rem;
}
.reviews .review__client {
display: -ms-grid;
display: grid;
-ms-grid-columns: min-content max-content 1fr;
grid-template-columns: -webkit-min-content -webkit-max-content 1fr;
grid-template-columns: min-content max-content 1fr;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
@media (max-width: 36em) {
.reviews .review__client {
-ms-grid-columns: min-content max-content;
grid-template-columns: -webkit-min-content -webkit-max-content;
grid-template-columns: min-content max-content;
}
}
.reviews .review__stars {
margin-left: 1.5rem;
-ms-grid-column-align: end;
justify-self: end;
}
@media (max-width: 36em) {
.reviews .review__stars {
grid-column: 1/-1;
-ms-grid-column-align: start;
justify-self: start;
margin-left: 0;
margin-top: 1.5rem;
}
}
.reviews .review__stars img {
width: 2.5rem;
}
.reviews .review__feedback {
position: relative;
}
.reviews .review__feedback::before {
content: "''";
font-size: 5rem;
position: absolute;
top: -2.5rem;
left: -2rem;
display: inline-block;
color: #61e786;
font-weight: 500;
}
.reviews .review__line {
margin: 2rem 0;
border: 0;
height: 0;
border-top: 1px solid rgba(0, 0, 0, 0.1);
border-bottom: 1px solid rgba(255, 255, 255, 0.3);
}
.booking {
margin-top: 14rem;
position: relative;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
@media (max-width: 62em) {
.booking {
display: none;
}
}
.booking .booking-container {
padding: 0 5rem;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
text-align: center;
width: 100%;
}
@media (max-width: 62em) {
.booking .booking-container {
top: 60%;
}
}
@media (max-width: 48em) {
.booking .booking-container {
display: none;
}
}
.booking__cta {
margin-top: 1.5rem;
display: inline-block;
background: #fb4b6e;
padding: 1rem 4rem;
border-radius: 0.3rem;
-webkit-transition: all 0.3s;
transition: all 0.3s;
font-size: 1.5rem;
font-weight: 600;
color: white;
}
.booking__cta:hover {
background: #fa325a;
}
.booking img {
width: 100%;
}
.footer {
padding: 5rem 0;
background-color: #1a1919;
display: -ms-grid;
display: grid;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-ms-grid-columns: min-content (max-content)[3];
grid-template-columns: -webkit-min-content repeat(3, -webkit-max-content);
grid-template-columns: min-content repeat(3, max-content);
}
@media (min-width: 112.5em) {
.footer {
-ms-grid-columns: (max-content)[5];
grid-template-columns: repeat(5, -webkit-max-content);
grid-template-columns: repeat(5, max-content);
}
}
@media (max-width: 75em) {
.footer {
-ms-grid-columns: (max-content)[3];
grid-template-columns: repeat(3, -webkit-max-content);
grid-template-columns: repeat(3, max-content);
}
}
@media (max-width: 62em) {
.footer {
-ms-grid-columns: 1fr;
grid-template-columns: 1fr;
justify-items: center;
grid-gap: 5rem;
}
}
.footer .footer-column {
padding: 0 6rem;
color: #fff;
position: relative;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-align: start;
-ms-flex-align: start;
align-items: flex-start;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
.footer .footer-column:nth-child(2) {
display: none;
}
@media (min-width: 112.5em) {
.footer .footer-column {
padding: 0 10rem;
}
.footer .footer-column:nth-child(2) {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
}
@media (max-width: 75em) {
.footer .footer-column:nth-child(3) {
display: none;
}
}
@media (max-width: 62em) {
.footer .footer-column:nth-child(1) div {
display: none;
}
.footer .footer-column:nth-child(2) {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.footer .footer-column:nth-child(4) p {
display: none;
}
.footer .footer-column:last-child {
display: none;
}
}
@media (max-width: 36em) {
.footer .footer-column:nth-child(1) img {
width: 6rem;
}
.footer .footer-column:nth-child(4) img {
width: 3rem;
}
.footer .footer-column:nth-child(2) {
display: none;
}
.footer .footer-column:last-child {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-ms-grid-row: 2;
-ms-grid-row-span: 1;
grid-row: 2/3;
}
}
.footer .footer-column hr {
border: 0;
height: 100%;
width: 1px;
background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(255, 255, 255, 0)), color-stop(rgba(255, 255, 255, 0.5)), to(rgba(255, 255, 255, 0)));
background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0));
position: absolute;
top: 0;
right: 0;
}
@media (max-width: 62em) {
.footer .footer-column hr {
display: none;
}
}
.footer .phone-box,
.footer .email-box {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
margin-top: 2rem;
}
.footer .phone-box img,
.footer .email-box img {
width: 2.5rem;
}
.footer .phone-box p,
.footer .email-box p {
margin-left: 1.5rem;
font-size: 1.5rem;
}
.footer .footer-cities {
list-style: none;
}
.footer .footer-cities li:not(:first-child) {
margin-top: 1.5rem;
}
.footer .footer-socials-box {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
width: 100%;
height: 100%;
}
.footer .footer-socials-box p {
margin-bottom: 2rem;
font-size: 2rem;
}
.footer .footer-socials-box a:first-child {
margin-right: 1.5rem;
}
.footer form {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
}
.footer form p {
font-size: 1.4rem;
margin-bottom: 3rem;
}
.footer form input {
margin-bottom: 2rem;
background-color: transparent;
border: none;
border-bottom: 1px solid #fefefe;
color: #fefefe;
padding: 1rem 0;
}
.footer form input::-webkit-input-placeholder {
color: #989898;
}
.footer form input:-ms-input-placeholder {
color: #989898;
}
.footer form input::-ms-input-placeholder {
color: #989898;
}
.footer form input::placeholder {
color: #989898;
}
.footer form button {
padding: 1rem 0;
border: 2px solid #fb4b6e;
background: none;
border-radius: 3px;
color: #fefefe;
cursor: pointer;
-webkit-transition: all 0.3s;
transition: all 0.3s;
}
.footer form button:hover {
background: #fb4b6e;
}
.copy-right {
padding: 1rem;
text-align: center;
background-color: #151414;
}
/*# sourceMappingURL=main.css.map */</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Adure</title>
<link rel="stylesheet" href="style/main.css" />
</head>
<body>
<div class="landing-page">
<div class="container">
<header class="header">
<div class="header__logo">
<img src="img/icons/logo.svg" alt="logo" />
<p>adure</p>
</div>
<nav class="nav nav--header">
<ul>
<li><a class="header__link" href="#benefits">Why us</a></li>
<li><a class="header__link" href="#locations">Locations</a></li>
<li><a class="header__link" href="#reviews">Reviews</a></li>
<li><a class="header__link" href="#booking">Booking</a></li>
<li><a class="header__link" href="#contact">Contact</a></li>
</ul>
</nav>
<div class="hamburger">
<span class="hamburger__outline">
<span class="hamburger__bar"></span>
</span>
</div>
</header>
</div>
<div class="hero container">
<img src="img/icons/logo-big-white.svg" alt="logo big" />
<h1 class="hero__heading">Your most exciting life experience</h1>
<h2 class="hero__subheading">Memorable experiences, wild natural environment</h2>
<a href="#" class="hero__cta">Book now</a>
</div>
<div class="socials container">
<a href="#"><img src="img/icons/twitter-logo.svg" alt="twitter" /></a>
<a href="#"><img src="img/icons/ig-logo.svg" alt="twitter" /></a>
</div>
<div class="landing-page__blur"></div>
<div class="landing-page__bgc"></div>
</div>
<section class="benefits" id="benefits">
<div class="container">
<h2 class="subheading">Why us</h2>
<div class="benefits-container">
<div class="benefit">
<img src="img/icons/fitness.svg" alt="fit" class="benefit__img" />
<h3 class="benefit__heading">Fit</h3>
<p class="benefit__desc">Lorem ipsum dolor sit amet consectetur</p>
</div>
<div class="benefit">
<img src="img/icons/map.svg" alt="fit" class="benefit__img" />
<h3 class="benefit__heading">Guidance</h3>
<p class="benefit__desc">Lorem ipsum dolor sit amet consectetur</p>
</div>
<div class="benefit">
<img src="img/icons/paw.svg" alt="fit" class="benefit__img" />
<h3 class="benefit__heading">Wild nature</h3>
<p class="benefit__desc">Lorem ipsum dolor sit amet consectetur</p>
</div>
<div class="benefit">
<img src="img/icons/star.svg" alt="fit" class="benefit__img" />
<h3 class="benefit__heading">High rated</h3>
<p class="benefit__desc">Lorem ipsum dolor sit amet consectetur</p>
</div>
</div>
</div>
</section>
<section class="locations" id="locations">
<h2 class="subheading">Locations</h2>
<div class="locations-container">
<div class="location">
<h2 class="location__heading">Banff National Park</h2>
<p class="location__location"><img src="img/icons/location-canada.svg" alt="pin" />Canada</p>
<p class="location__desc">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas consectetur amet ducimus corporis quaerat fugiat tempore.
<span>
Eos pariatur ipsum labore id voluptas voluptate odio. Repudiandae nobis quis placeat odio totam voluptate
praesentium nihil, ullam atque consequatur dolor consectetur quasi sit accusamus dolore cum qui quas.
</span>
</p>
<a href="#" class="book-btn book-btn--green">Book it</a>
</div>
<img src="img/location_1.jpg" alt="lake" class="locations-img locations-img--green" />
<img src="img/location_2.jpg" alt="lake" class="locations-img locations-img--blue" />
<div class="location">
<h2 class="location__heading">Perito Moreno Glacier</h2>
<p class="location__location"><img src="img/icons/location-argentina.svg" alt="pin" />Argentina</p>
<p class="location__desc">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Debitis nostrum voluptas repellendus!
<span>
Praesentium iste repellendus nesciunt quidem aut omnis, molestias eaque fugit fuga excepturi asperiores id magnam
quaerat illo incidunt ducimus amet esse sed mollitia ea nemo debitis atque sint. Dolor aperiam non aspernatur
beatae.
</span>
</p>
<a href="#" class="book-btn book-btn--blue">Book it</a>
</div>
<div class="location">
<h2 class="location__heading">Grand canyon</h2>
<p class="location__location"><img src="img/icons/location-arizona.svg" alt="pin" />Arizona US</p>
<p class="location__desc">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Necessitatibus eveniet esse rerum omnis, illum ex iste dolor eius odio.
<span>
Nam minus corrupti dolorem debitis porro voluptatem repellendus vel, sit odio assumenda provident suscipit ducimus,
distinctio quaerat consequatur, magni magnam delectus at explicabo a? Officiis, pariatur.
</span>
</p>
<a href="#" class="book-btn book-btn--orange">Book it</a>
</div>
<img src="img/location_3.jpg" alt="lake" class="locations-img locations-img--orange" />
</div>
<div class="container">
<h2 class="subheading">Search for more locations</h2>
<div class="more-locations">
<input type="text" placeholder="Location name" />
<a href="#">
<img src="img/icons/search.svg" alt="magnifier" />
</a>
</div>
</div>
</section>
<section class="reviews" id="reviews">
<div class="container">
<h2 class="subheading">From our clients</h2>
<div class="reviews-container">
<div class="review">
<div class="review__client">
<img src="img/client_1.png" alt="client 1" class="review__img" />
<div>
<p class="review__name">Ted Brigmond</p>
<p class="review__date">10.08.2020</p>
</div>
<div class="review__stars">
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
</div>
</div>
<hr class="review__line" />
<p class="review__feedback">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Commodi unde voluptas odio dolore beatae, voluptatem quas sint libero rem quae corporis non temporibus reiciendis doloribus voluptatibus nemo mollitia ex, perferendis, molestiae ad optio blanditiis
minus totam. Recusandae consequatur vero porro! Explicabo numquam eaque et tempora hic id, expedita molestias quidem eligendi veniam laboriosam exercitationem aperiam ipsa! In repellat unde atque velit provident tenetur temporibus officiis
a aliquid, et magni! Eius quod consequatur facere expedita reprehenderit.
</p>
</div>
<div class="review">
<div class="review__client">
<img src="img/client_2.png" alt="client 1" class="review__img" />
<div>
<p class="review__name">Norine Desh</p>
<p class="review__date">08.09.2020</p>
</div>
<div class="review__stars">
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-black.svg" alt="star" />
</div>
</div>
<hr class="review__line" />
<p class="review__feedback">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Aperiam expedita ex unde, quibusdam atque consectetur autem eius, iusto quidem at non, temporibus voluptate possimus! Suscipit voluptatem, voluptatum assumenda vitae voluptates, at eligendi ex est
a corrupti odio fugit debitis fugiat exercitationem ut aperiam repellat ea tenetur dolorem vero porro eaque quas quaerat! Commodi ipsa optio quidem, mollitia quibusdam ipsum distinctio molestiae asperiores, labore consequuntur provident.
</p>
</div>
<div class="review">
<div class="review__client">
<img src="img/client_3.png" alt="client 1" class="review__img" />
<div>
<p class="review__name">Janell Palos</p>
<p class="review__date">02.11.2020</p>
</div>
<div class="review__stars">
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
<img src="img/icons/star-filled.svg" alt="star" />
</div>
</div>
<hr class="review__line" />
<p class="review__feedback">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Cupiditate modi asperiores a totam? Quaerat voluptatibus rem delectus at, provident atque itaque vitae minima officia repellat enim commodi nisi exercitationem aperiam consequuntur inventore est
cupiditate maxime fuga nobis magnam accusamus animi rerum? Dolore quia inventore debitis accusantium culpa maxime asperiores doloremque vitae pariatur sed nam, animi labore atque aut, quos dolorem repellendus nulla? Repellendus quisquam unde,
quam eveniet officiis sapiente quae?
</p>
</div>
<p></p>
</div>
</div>
</section>
<section class="booking" id="booking">
<img src="img/bgc.png" alt="kyoto" />
<div class="booking-container">
<h2 class="booking__heading">Ready for an unforgettable adventure?</h2>
<a href="#" class="booking__cta">Book now</a>
</div>
</section>
<footer class="footer" id="contact">
<div class="footer-column">
<img src="img/icons/logo-big-white.svg" alt="logo big" />
<div class="phone-box">
<img src="img/icons/phone.svg" alt="phone" />
<p>536 272 926</p>
</div>
<div class="email-box">
<img src="img/icons/mail.svg" alt="phone" />
<p>adure@gmail.com</p>
</div>
<hr />
</div>
<div class="footer-column">
<nav class="nav nav--footer">
<ul>
<li><a class="header__link" href="#benefits">Why us</a></li>
<li><a class="header__link" href="#locations">Locations</a></li>
<li><a class="header__link" href="#reviews">Reviews</a></li>
<li><a class="header__link" href="#booking">Booking</a></li>
<li><a class="header__link" href="#contact">Contact</a></li>
</ul>
</nav>
<hr />
</div>
<div class="footer-column">
<ul class="footer-cities">
<li><a class="footer-city" href="#">Kyoto</a></li>
<li><a class="footer-city" href="#">Dubrovnik</a></li>
<li><a class="footer-city" href="#">St. Petersburg</a></li>
<li><a class="footer-city" href="#">Bergen</a></li>
<li><a class="footer-city" href="#">San Francisco</a></li>
</ul>
<hr />
</div>
<div class="footer-column">
<div class="footer-socials-box">
<p>Follow us</p>
<div>
<a href="#"><img src="img/icons/twitter-logo.svg" alt="twitter" /></a>
<a href="#"><img src="img/icons/ig-logo.svg" alt="instagram" /></a>
</div>
</div>
<hr />
</div>
<div class="footer-column">
<form action="#">
<p>Get updates about new adventures and more.</p>
<input type="text" placeholder="Your name" pattern="[a-zA-Z]+" required />
<input type="text" placeholder="Your email" required />
<button>Send</button>
</form>
</div>
</footer>
<div class="copy-right">Copyright &copy; 2021 Adure. All rights reserved.</div>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T13:22:52.377",
"Id": "254380",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"sass"
],
"Title": "Travel agent website"
}
|
254380
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/254332/231235">A recursive_replace_if Template Function Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/254178/231235">A recursive_copy_if Template Function Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. After implemented <code>recursive_replace_if</code> and <code>recursive_copy_if</code>, I am trying to generalize the operation of applying a function on elements in nested container. The unwrap level parameter is used here instead of <code>std::invocable</code> as the termination condition of the recursion process.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>// recursive_function_applier implementation
template<std::size_t unwrap_level, class F, std::ranges::range Range, class... Args>
constexpr auto recursive_function_applier(const F& function, const Range& input, Args... args)
{
if constexpr (unwrap_level >= 1)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&function, &args...](auto&& element) { return recursive_function_applier<unwrap_level - 1>(function, element, args...); }
);
return output;
}
else
{
Range output{};
function(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
args...);
return output;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<ul>
<li><p>Test cases with using <a href="https://en.cppreference.com/w/cpp/algorithm/ranges/copy" rel="nofollow noreferrer"><code>std::ranges::copy</code></a> function</p>
<pre><code>// std::copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_vector));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_vector2));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::copy, test_string_vector
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::copy, test_string_vector2
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_deque));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_deque2));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_list));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_list2));
recursive_print(
recursive_function_applier<10>(
std::ranges::copy,
n_dim_container_generator<10, std::list>(test_list, 3)
)
);
</code></pre>
</li>
<li><p>Test cases with using <a href="https://en.cppreference.com/w/cpp/algorithm/ranges/replace_copy" rel="nofollow noreferrer"><code>std::ranges::replace_copy_if</code></a> function</p>
<pre><code>// std::ranges::replace_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::replace_copy_if, test_string_vector, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::replace_copy_if, test_string_vector2, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_deque, [](int x) { return (x % 2) == 0; }, 0));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_deque2, [](int x) { return (x % 2) == 0; }, 0));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_list, [](int x) { return (x % 2) == 0; }, 0));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_list2, [](int x) { return (x % 2) == 0; }, 0));
recursive_print(
recursive_function_applier<10>(
std::ranges::replace_copy_if,
n_dim_container_generator<10, std::list>(test_list, 3),
[](int x) { return (x % 2) == 0; },
0
)
);
</code></pre>
</li>
<li><p>Test cases with using <a href="https://en.cppreference.com/w/cpp/algorithm/ranges/remove_copy" rel="nofollow noreferrer"><code>std::ranges::remove_copy</code></a> function</p>
<pre><code>// std::remove_copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_vector, 5));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_vector2, 5));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy, test_string_vector, "0"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy, test_string_vector2, "0"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_deque, 1));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_deque2, 1));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_list, 1));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_list2, 1));
recursive_print(
recursive_function_applier<10>(
std::ranges::remove_copy,
n_dim_container_generator<10, std::list>(test_list, 3),
1
)
);
</code></pre>
</li>
<li><p>Test cases with using <a href="https://en.cppreference.com/w/cpp/algorithm/remove_copy" rel="nofollow noreferrer"><code>std::ranges::remove_copy_if</code></a> function</p>
<pre><code>// std::remove_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy_if, test_string_vector, [](std::string x) { return (x == "0"); }
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy_if, test_string_vector2, [](std::string x) { return (x == "0"); }
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_deque, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_deque2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_list, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_list2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
recursive_print(
recursive_function_applier<5>(
std::ranges::remove_copy_if,
n_dim_container_generator<5, std::list>(test_list, 3),
std::bind(std::less<int>(), std::placeholders::_1, 5)
)
);
</code></pre>
</li>
</ul>
<p></p>
<b>Full Testing Code</b>
<p>
<p>The full testing code:</p>
<pre><code>#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <exception>
#include <execution>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
#endif
// recursive_copy_if function
template <std::ranges::input_range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate);
return output;
}
template <
std::ranges::input_range Range,
class UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate](auto&& element) { return recursive_copy_if(element, unary_predicate); }
);
return output;
}
// recursive_count implementation
template<std::ranges::input_range Range, typename T>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::count(std::ranges::cbegin(input), std::ranges::cend(input), target);
}
// transform_reduce version
template<std::ranges::input_range Range, typename T>
requires std::ranges::input_range<std::ranges::range_value_t<Range>>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [target](auto&& element) {
return recursive_count(element, target);
});
}
// recursive_count implementation (with execution policy)
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::count(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), target);
}
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [execution_policy, target](auto&& element) {
return recursive_count(execution_policy, element, target);
});
}
// recursive_count_if implementation
template<class T, std::invocable<T> Pred>
constexpr std::size_t recursive_count_if(const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<std::ranges::input_range Range, class Pred>
requires (!std::invocable<Pred, Range>)
constexpr auto recursive_count_if(const Range& input, const Pred& predicate)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (with execution policy)
template<class ExPo, class T, std::invocable<T> Pred>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr std::size_t recursive_count_if(ExPo execution_policy, const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<class ExPo, std::ranges::input_range Range, class Pred>
requires ((std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<Pred, Range>))
constexpr auto recursive_count_if(ExPo execution_policy, const Range& input, const Pred& predicate)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (the version with unwrap_level)
template<std::size_t unwrap_level, std::ranges::range T, class Pred>
auto recursive_count_if(const T& input, const Pred& predicate)
{
if constexpr (unwrap_level > 1)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if<unwrap_level - 1>(element, predicate);
});
}
else
{
return std::count_if(std::ranges::cbegin(input), std::ranges::cend(input), predicate);
}
}
// recursive_function_applier implementation
template<std::size_t unwrap_level, class F, std::ranges::range Range, class... Args>
constexpr auto recursive_function_applier(const F& function, const Range& input, Args... args)
{
if constexpr (unwrap_level >= 1)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&function, &args...](auto&& element) { return recursive_function_applier<unwrap_level - 1>(function, element, args...); }
);
return output;
}
else
{
Range output{};
function(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
args...);
return output;
}
}
// recursive_print implementation
template<std::ranges::input_range Range>
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
// recursive_replace_copy_if implementation
template<std::ranges::range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate, class T>
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::replace_copy_if(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate,
new_value);
return output;
}
template<std::ranges::input_range Range, class UnaryPredicate, class T>
requires (!std::invocable<UnaryPredicate, std::ranges::range_value_t<Range>>)
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate, &new_value](auto&& element) { return recursive_replace_copy_if(element, unary_predicate, new_value); }
);
return output;
}
// recursive_size implementation
template<class T> requires (!std::ranges::range<T>)
constexpr auto recursive_size(const T& input)
{
return 1;
}
template<std::ranges::range Range> requires (!(std::ranges::input_range<std::ranges::range_value_t<Range>>))
constexpr auto recursive_size(const Range& input)
{
return std::ranges::size(input);
}
template<std::ranges::range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_size(const Range& input)
{
return std::transform_reduce(std::ranges::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto& element) {
return recursive_size(element);
});
}
// recursive_transform implementation
// recursive_invoke_result_t implementation
// from https://stackoverflow.com/a/65504127/6667035
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>> &&
std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
template <std::ranges::range Range>
constexpr auto get_output_iterator(Range& output)
{
return std::inserter(output, std::ranges::end(output));
}
template <class T, std::invocable<T> F>
constexpr auto recursive_transform(const T& input, const F& f)
{
return f(input);
}
template <
std::ranges::input_range Range,
class F>
requires (!std::invocable<F, Range>)
constexpr auto recursive_transform(const Range& input, const F& f)
{
recursive_invoke_result_t<F, Range> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform(element, f); }
);
return output;
}
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::begin(output), std::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
void copy_test();
void replace_copy_if_test();
void remove_copy_test();
void remove_copy_if_test();
int main()
{
copy_test();
replace_copy_if_test();
remove_copy_test();
remove_copy_if_test();
return 0;
}
void copy_test()
{
// std::copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_vector));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_vector2));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::copy, test_string_vector
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::copy, test_string_vector2
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_deque));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_deque2));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_list));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_list2));
recursive_print(
recursive_function_applier<5>(
std::ranges::copy,
n_dim_container_generator<5, std::list>(test_list, 3)
)
);
return;
}
void replace_copy_if_test()
{
// std::ranges::replace_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::replace_copy_if, test_string_vector, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::replace_copy_if, test_string_vector2, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_deque, [](int x) { return (x % 2) == 0; }, 0));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_deque2, [](int x) { return (x % 2) == 0; }, 0));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_list, [](int x) { return (x % 2) == 0; }, 0));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_list2, [](int x) { return (x % 2) == 0; }, 0));
recursive_print(
recursive_function_applier<5>(
std::ranges::replace_copy_if,
n_dim_container_generator<5, std::list>(test_list, 3),
[](int x) { return (x % 2) == 0; },
0
)
);
return;
}
void remove_copy_test()
{
// std::remove_copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_vector, 5));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_vector2, 5));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy, test_string_vector, "0"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy, test_string_vector2, "0"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_deque, 1));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_deque2, 1));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_list, 1));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_list2, 1));
recursive_print(
recursive_function_applier<5>(
std::ranges::remove_copy,
n_dim_container_generator<5, std::list>(test_list, 3),
1
)
);
return;
}
void remove_copy_if_test()
{
// std::remove_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy_if, test_string_vector, [](std::string x) { return (x == "0"); }
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy_if, test_string_vector2, [](std::string x) { return (x == "0"); }
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_deque, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_deque2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_list, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_list2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
recursive_print(
recursive_function_applier<5>(
std::ranges::remove_copy_if,
n_dim_container_generator<5, std::list>(test_list, 3),
std::bind(std::less<int>(), std::placeholders::_1, 5)
)
);
return;
}
</code></pre>
</p>
<p><a href="https://godbolt.org/z/Tz8fb3" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/254332/231235">A recursive_replace_if Template Function Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/254178/231235">A recursive_copy_if Template Function Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/252053/231235">A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>I am trying to implement a <code>recursive_function_applier</code> template function as a function applier for applying various algorithms on nested container.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>Not sure the design of <code>recursive_function_applier</code> template function is a good idea or not. Whatever, this structure seems to be working fine in <code>std::ranges::copy</code>, <code>std::ranges::replace_copy_if</code>, <code>std::ranges::remove_copy</code> and <code>std::ranges::remove_copy_if</code> cases. If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T14:38:50.813",
"Id": "254384",
"Score": "1",
"Tags": [
"c++",
"recursion",
"lambda",
"c++20",
"variadic"
],
"Title": "A Function Applier for Applying Various Algorithms on Nested Container Things in C++"
}
|
254384
|
<p><em>Note - I am not sure whether this question belongs to stackoverflow or CSE stackexchange or here</em></p>
<h2>Problem:</h2>
<p>Given a list <code>L</code>consisting of not necessarily unique non-negative integers, find the minimum number of subset with maximum sum <code>k</code>(given) in which it can be divided such that:
each subset shouldn't contain consecutive elements from the list*.</p>
<p>(*): I can see an obvious ambiguity:<br />
Q: If there is <code>3 4</code>, is the restriction is on all <code>3</code> or just the adjacent three?</p>
<p>A: Just on adjacent <code>3</code>.</p>
<h3>Examples:</h3>
<pre><code>
1. L = [2, 1, 1, 2], k = 2 => 4
Explanation: First set can take 0th index element
second set can take 1st index element and similarly third and fourth can take 2nd and 3rd index element respectively
Here, you can see that k is working as a bottleneck
More examples:
L = [2, 4, 1, 0] k = 8 => 2
L = [3, 2, 3, 0, 0] k = 5 => 3
</code></pre>
<hr />
<p>This seems to have some features of dynamic programming problems, so I went for dynamic programming and wrote the following recursive code:</p>
<pre class="lang-py prettyprint-override"><code>from functools import lru_cache
def min_count(L, k):
'''
index - stores the current state's index
sets - this stores information of already stored sets:
It is tuple of tuple,
In each tuple:
First element - index of last stored element
Second element - stores the sum of current set
k - It is limit|capacity of each subset(same as the one given in arugment)
'''
@lru_cache(maxsize=None)
def recurse(index, sets, k):
#If control reaches to the end of the list
if index == len(L):
return len(sets)
#In case the current indexes is zero
if L[index] == 0:
#If this is the last index, then
if index + 1 == len(L):
return len(sets)
return recurse(index + 1, sets, k)
'''
The job of this for loop is iterate all of the stored sets:
And if that's capable of storing further, then add current index
to it, and recurse
'''
m = 1e10
for i, j in sets:
if i - index < -1 and j + L[index] <= k:
if index + 1 == len(sets):
return len(sets)
m = min(m, recurse(index + 1,tuple(_ if _ != (i, j) else (index, j + L[index]) for _ in sets) , k))
m = min(m, recurse(index + 1, sets + ((index, L[index]), ), k))
return m
return recurse(0, (), k)
</code></pre>
<p>The problem is that this code works, but is very slow(the expected time complexity must be lower than <code>O(n^2)</code>).</p>
<p>How can I make it fast?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T16:55:36.600",
"Id": "501761",
"Score": "0",
"body": "when would more than two subsets be required? Taking every other element should be non consecutive"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T17:04:35.450",
"Id": "501762",
"Score": "0",
"body": "Example: L = [2, 2, 2, 2, 2] with k = 2"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T17:10:02.300",
"Id": "254389",
"Score": "1",
"Tags": [
"python-3.x",
"dynamic-programming"
],
"Title": "Divide a set into subset with some constraints"
}
|
254389
|
<p><strong>Background</strong></p>
<p>I have a simple logic where i get <code>total_kits</code>. I usually make some function call to get the value for this variable. Then if <code>total_kits</code> is less than some <code>MIN_KITS_THRESHOLD</code> then i want to print some message and do nothing. If <code>is_delivery_created_earlier_today()</code> function returns true i also want to print some message and do nothing. If both those condtions are not violated then i want to call my function <code>launch_pipeline()</code>.</p>
<p>I am basically using a if elif else but i am wondering if i can organize my if else statements to be more clean.</p>
<p><strong>Code</strong></p>
<pre><code>total_kits = #Some number
if total_kits < MIN_KITS_THRESHOLD:
# print some message but don't launch pipeline
elif is_delivery_created_earlier_today():
# print some message but don't launch pipeline
else:
launch_pipeline()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T18:35:32.297",
"Id": "501705",
"Score": "0",
"body": "are the two messages mutually exclusive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T18:38:57.720",
"Id": "501706",
"Score": "0",
"body": "Please provide more complete code - e.g. complete script. [\"_there are significant pieces of the core functionality missing, and we need you to fill in the details. Excerpts of large projects are fine, but if you have omitted too much, then reviewers are left imagining how your program works._\"](https://codereview.meta.stackexchange.com/a/3652/120114)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T18:40:51.673",
"Id": "501707",
"Score": "1",
"body": "Also, 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 do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T18:59:11.953",
"Id": "501709",
"Score": "0",
"body": "@TedBrownlow no they are not mutually exclusive"
}
] |
[
{
"body": "<p>You have <code>launch_pipeline()</code> shown as a function, so I'll assume that you are comfortable with writing functions.</p>\n<p>Create a <em>boolean</em> function, something like <code>is_pipeline_allowed()</code>, and put your reasons inside that.</p>\n<pre><code>total_kits = get_number_of_kits()\n\nif is_pipeline_allowed(total_kits):\n launch_pipeline()\n</code></pre>\n<p>Elsewhere:</p>\n<pre><code>def is_pipeline_allowed(nkits):\n if nkits < MIN_KITS_THRESHOLD:\n print("not enough kits for pipeline to launch")\n return False\n \n if is_delivery_created_earlier_today():\n print("pipeline has already launched for today")\n return False\n return True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T22:52:37.830",
"Id": "254397",
"ParentId": "254390",
"Score": "1"
}
},
{
"body": "<p>If the code blocks below the <code>if</code> and <code>elif</code> are identical, you can merge those conditions into:</p>\n<pre><code>total_kits = #Some number\nif total_kits < MIN_KITS_THRESHOLD or is_delivery_created_earlier_today():\n # print some message but don't launch pipeline\nelse:\n launch_pipeline()\n</code></pre>\n<p>Otherwise I do not see a reason to change anything in this snippet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T23:27:06.093",
"Id": "254400",
"ParentId": "254390",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254397",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T17:26:09.967",
"Id": "254390",
"Score": "-4",
"Tags": [
"python"
],
"Title": "Clean up if else statement"
}
|
254390
|
<p>I have implemented (rather, edited the implementation of) a technique to automatically detect the optimal number of dimensions for <a href="https://en.wikipedia.org/wiki/Principal_component_analysis" rel="nofollow noreferrer">PCA</a>, <a href="https://papers.nips.cc/paper/2000/file/7503cfacd12053d309b6bed5c89de212-Paper.pdf" rel="nofollow noreferrer">based off of this paper</a>.</p>
<p>This was inspired by <code>sklearn</code>'s implementation of the algorithm described in the paper, <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/decomposition/_pca.py" rel="nofollow noreferrer">found here in their <code>_pca.py</code></a> module.</p>
<p>Code, including an example for anyone to use via <code>sklearn</code>'s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_multilabel_classification.html" rel="nofollow noreferrer"><code>make_classification</code></a> technique is below:</p>
<pre><code># Borrowed mainly from: https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/decomposition/_pca.py
import numpy as np, pandas as pd, warnings, numbers
from math import log1p, sqrt
from scipy import linalg
from scipy.special import gammaln
from scipy.sparse import issparse
from scipy.sparse.linalg import svds
from sklearn.datasets import make_multilabel_classification
from tqdm import tqdm
def infer_dimension(spectrum, n_samples):
ll = np.empty_like(spectrum)
ll[0] = -np.inf # we don't want to return n_components = 0
for rank in tqdm(range(1, spectrum.shape[0])):
ll[rank] = assess_dimension(spectrum, rank, n_samples)
return ll.argmax()
def stable_cumsum(arr, axis=None, rtol=1e-05, atol=1e-08):
out = np.cumsum(arr, axis=axis, dtype=np.float64)
expected = np.sum(arr, axis=axis, dtype=np.float64)
return out
def assess_dimension(spectrum, rank, n_samples):
n_features = spectrum.shape[0]
if not 1 <= rank < n_features:
raise ValueError("the tested rank should be in [1, n_features - 1]")
eps = 1e-15
if spectrum[rank - 1] < eps:
return -np.inf
pu = -rank * log1p(2.)
for i in range(1, rank + 1):
pu += (gammaln((n_features - i + 1) / 2.) - log1p(np.pi) * (n_features - i + 1) / 2.)
pl = np.sum(np.log(spectrum[:rank]))
pl = -pl * n_samples / 2.
v = max(eps, np.sum(spectrum[rank:]) / (n_features - rank))
pv = -np.log1p(v) * n_samples * (n_features - rank) / 2.
m = n_features * rank - rank * (rank + 1.) / 2.
pp = log1p(2. * np.pi) * (m + rank) / 2.
pa = 0.
spectrum_ = spectrum.copy()
spectrum_[rank:n_features] = v
for i in range(rank):
for j in range(i + 1, len(spectrum)):
pa += log1p((spectrum[i] - spectrum[j]) *
(1. / spectrum_[j] - 1. / spectrum_[i])) + log1p(n_samples)
ll = pu + pl + pv + pp - pa / 2. - rank * log1p(n_samples) / 2.
return ll
def find_components(data):
try:
X = data.to_numpy()
except:
X = data
warnings.warn('Data is already in numpy format, or cannot be converted', RuntimeWarning)
n_samples = X.shape[0]
av = np.mean(data, axis=0)
X -= av
print("Calculating S...")
U, S, Vt = linalg.svd(X, full_matrices=False)
print("Calculating explained variance...")
explained_variance_ = (S ** 2) / (n_samples - 1)
print("Calculating total variance variance...")
total_var = explained_variance_.sum()
print("Calculating explained variance ratio...")
explained_variance_ratio_ = explained_variance_ / total_var
print("Inferring dimensions...")
n_components = infer_dimension(explained_variance_, n_samples)
if 0 < n_components < 1.0:
print("n_components not complete | Calculating ratio cumsum...")
ratio_cumsum = stable_cumsum(explained_variance_ratio_)
n_components = np.searchsorted(ratio_cumsum, n_components,
side='right') + 1
return n_components
X, y = make_multilabel_classification(n_samples=10000, n_features=5000, n_classes=2)
n_components = find_components(X)
print(n_components)
</code></pre>
<p>While this code works well and outputs results properly, it takes an incredibly long time to process large datasets. The dataset in particular that I am using is an <a href="https://en.wikipedia.org/wiki/Natural_language_processing" rel="nofollow noreferrer"><code>NLP</code></a> dataset, particularly of <code>term frequency</code> values, so there are a LOT of zeroes and the data does not follow a normal distribution (not a single feature does) (not sure if that makes a difference). My dataset's size is <code>(550683, 10891)</code>. That is estimated to take more than 10 days to finish on my current hardware.</p>
<p>How can I optimize this code to improve performance? Using the <code>make_multilabel_classification</code> call above, even that takes a fair amount of time given the feature space. .</p>
<p>Please note, if you believe the algorithm was implemented incorrectly please feel free to fix that. Principally concerned with speed</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:27:44.653",
"Id": "502342",
"Score": "0",
"body": "Can you share a benchmark test (perhaps a subset of the real target data?) that we could easily replicate on our own machines?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:18:50.820",
"Id": "502351",
"Score": "0",
"body": "@ShapeOfMatter sure, running now. However, you could simply run the code I have now, vs your optimized code, on your own machine to demonstrate improvement. That way hardware differences between your machine and mine are not factored into play."
}
] |
[
{
"body": "<h2>Test harness:</h2>\n<p>To build a modular test rig around this, it seemed easiest to wrap stuff up in a class. I'm pretty sure I left everything else in the original implementation alone.</p>\n<p>I'm just using <code>time</code> to measure how long the function takes with various input values. I'm too impatient to run it with your original parameters, so I'm mostly using smaller ones. <strong>I have basically no idea what your code actually does, so it's possible I'm doing something wrong in how I test it.</strong></p>\n<h2>Cleanup:</h2>\n<p>This is fairly opinionated, and<br />\n<s>may not actually help with performance</s><br />\n<s>actually made the function a little slower</s><br />\n<s>each individual change is as likely to hurt performance as to help</s><br />\nonly helps performance by ~10%.</p>\n<ul>\n<li>I greatly prefer to use python built-ins over numpy/scipy etc for data-structure manipulation.</li>\n<li>Why is <code>stable_cumsum</code> a function? It looks like you had an assertion in there or something that got removed...</li>\n<li>Your variable names are pretty opaque. Without domain knowledge, I can't do much to fix this. You're also reassigning variables more than necessary, which is good to avoid.</li>\n<li>I golfed the math a little and I think it reads better.</li>\n</ul>\n<h2>Math:</h2>\n<p>The algorithm seams to be O(n^3). <code>calculate_pa</code> is (presumably) the bottleneck. What can we do to simplify it?</p>\n<ul>\n<li>We can pull the <code>+ log1p(self.n_samples)</code> term outside the <code>sum</code>, and just use multiplication.</li>\n<li>A sum of logs is a log of the product, and <code>log1p</code> is just "ln(x+1)", so we can move the log calculation outside the aggregation.</li>\n<li><strong>But then I think we're stuck.</strong> The calculation doesn't actually work in this form because of a math-overflow error, and I haven't actually figured out any <em>fundamental</em> simplification that would touch the complexity-class.</li>\n<li><strong>Your domain knowledge may be able to push this forward.</strong> In particular, I noticed that I could get it to work for <em>very small</em> tests by just omitting the <code>+1</code> from the product-term. It looks like the exact math in that area doesn't really matter too much; maybe there's a lighter-weight calculation you could be maximizing?</li>\n</ul>\n<h2>Code:</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np, pandas as pd, warnings, numbers\nfrom math import log1p, sqrt\nfrom scipy import linalg\nfrom scipy.special import gammaln\nfrom scipy.sparse import issparse\nfrom scipy.sparse.linalg import svds\nfrom sklearn.datasets import make_multilabel_classification\nfrom tqdm import tqdm\n\nfrom random import randint # insecure RNG is fine for this task.\nfrom time import time\nfrom operator import itemgetter, mul\nfrom functools import reduce\nfrom math import log\n\nclass Original:\n def __init__(self, verbose):\n self.verbose = verbose\n\n def log(self, *message):\n if self.verbose:\n print(*message)\n\n def infer_dimension(self, spectrum, n_samples):\n ll = np.empty_like(spectrum)\n ll[0] = -np.inf # we don't want to return n_components = 0\n for rank in (tqdm(range(1, spectrum.shape[0]))\n if self.verbose else range(1, spectrum.shape[0])):\n ll[rank] = self.assess_dimension(spectrum, rank, n_samples)\n return ll.argmax()\n\n def stable_cumsum(self, arr, axis=None, rtol=1e-05, atol=1e-08):\n out = np.cumsum(arr, axis=axis, dtype=np.float64)\n expected = np.sum(arr, axis=axis, dtype=np.float64)\n return out\n\n def assess_dimension(self, spectrum, rank, n_samples): \n n_features = spectrum.shape[0]\n if not 1 <= rank < n_features:\n raise ValueError("the tested rank should be in [1, n_features - 1]")\n eps = 1e-15\n\n if spectrum[rank - 1] < eps:\n return -np.inf\n\n pu = -rank * log1p(2.)\n for i in range(1, rank + 1):\n pu += (gammaln((n_features - i + 1) / 2.) - log1p(np.pi) * (n_features - i + 1) / 2.)\n\n pl = np.sum(np.log(spectrum[:rank]))\n pl = -pl * n_samples / 2.\n\n v = max(eps, np.sum(spectrum[rank:]) / (n_features - rank))\n pv = -np.log1p(v) * n_samples * (n_features - rank) / 2.\n\n m = n_features * rank - rank * (rank + 1.) / 2.\n pp = log1p(2. * np.pi) * (m + rank) / 2.\n\n pa = 0.\n spectrum_ = spectrum.copy()\n spectrum_[rank:n_features] = v\n for i in range(rank):\n for j in range(i + 1, len(spectrum)):\n pa += log1p((spectrum[i] - spectrum[j]) *\n (1. / spectrum_[j] - 1. / spectrum_[i])) + log1p(n_samples)\n \n ll = pu + pl + pv + pp - pa / 2. - rank * log1p(n_samples) / 2.\n\n return ll \n\n def find_components(self, data):\n try:\n X = data.to_numpy()\n except:\n X = data\n self.log('Data is already in numpy format, or cannot be converted')\n\n n_samples = X.shape[0]\n\n av = np.mean(data, axis=0)\n X -= av\n self.log("Calculating S...")\n U, S, Vt = linalg.svd(X, full_matrices=False)\n self.log("Calculating explained variance...")\n explained_variance_ = (S ** 2) / (n_samples - 1)\n self.log("Calculating total variance variance...")\n total_var = explained_variance_.sum()\n self.log("Calculating explained variance ratio...")\n explained_variance_ratio_ = explained_variance_ / total_var\n\n self.log("Inferring dimensions...")\n n_components = self.infer_dimension(explained_variance_, n_samples)\n\n if 0 < n_components < 1.0:\n self.log("n_components not complete | Calculating ratio cumsum...")\n ratio_cumsum = self.stable_cumsum(explained_variance_ratio_)\n n_components = np.searchsorted(ratio_cumsum, n_components,\n side='right') + 1\n\n return n_components\n\nclass Cleaned:\n def __init__(self, verbose):\n self.verbose = verbose\n\n def log(self, *message):\n if self.verbose:\n print(*message)\n\n def infer_dimension(self):\n return max(\n range(1, self.spectrum.shape[0]),\n key=self.assess_dimension,\n default=0\n )\n\n def stable_cumsum(self, arr, axis=None):\n # Why is this broken out at all? \n return np.cumsum(arr, axis=axis, dtype=np.float64)\n\n def assess_dimension(self, rank): \n assert 1 <= rank < self.n_features, "the tested rank should be in [1, n_features - 1]"\n\n epsilon = 1e-15\n if self.spectrum[rank - 1] < epsilon:\n return -np.inf\n else:\n pu = (-rank * log1p(2.)) + sum(\n gammaln((self.n_features - i + 1) / 2.) - log1p(np.pi) * (self.n_features - i + 1) / 2.\n for i in range(1, rank + 1)\n )\n pl = -np.sum(np.log(self.spectrum[:rank])) * self.n_samples / 2.\n\n v = max(epsilon, np.sum(self.spectrum[rank:]) / (self.n_features - rank))\n pv = -np.log1p(v) * self.n_samples * (self.n_features - rank) / 2.\n\n m = self.n_features * rank - rank * (rank + 1.) / 2.\n pp = log1p(2. * np.pi) * (m + rank) / 2.\n\n pa = self.calculate_pa(rank, v)\n\n return pu + pl + pv + pp - pa / 2. - rank * log1p(self.n_samples) / 2.\n\n def calculate_pa(self, rank, v):\n _spectrum = self.spectrum.copy()\n _spectrum[rank:self.n_features] = v\n i_spectrum = 1. / _spectrum\n return sum(\n log1p(\n (self.spectrum[i] - self.spectrum[j]) * (i_spectrum[j] - i_spectrum[i])\n ) + log1p(self.n_samples)\n for i in range(rank)\n for j in range(i + 1, self.n_features)\n )\n\n def find_components(self, X):\n self.n_samples = X.shape[0]\n centered = X - np.mean(X, axis=0)\n U, S, Vt = linalg.svd(centered, full_matrices=False)\n self.spectrum = (S ** 2) / (self.n_samples - 1)\n self.n_features = self.spectrum.shape[0]\n n_components = self.infer_dimension()\n\n if 0 < n_components < 1.0:\n explained_variance_ratio = self.spectrum / self.spectrum.sum()\n ratio_cumsum = self.stable_cumsum(explained_variance_ratio)\n return np.searchsorted(ratio_cumsum, n_components, side='right') + 1\n else:\n return n_components\n\nclass Optimized(Cleaned):\n def calculate_pa(self, rank, v):\n _spectrum = self.spectrum.copy()\n _spectrum[rank:self.n_features] = v\n i_spectrum = 1. / _spectrum\n number_of_terms = -0.5 * rank * (rank - (2 * len(self.spectrum)) + 1) # https://www.wolframalpha.com/input/?i=sum%28sum%281+for+j+from+i+%2B+1+to+s+-+1%29+for+i+from+0+to+r+-+1%29\n constant_part = log1p(self.n_samples) * number_of_terms\n # This commented-out block \n return log(reduce(mul, (\n ((self.spectrum[i] - self.spectrum[j]) * (i_spectrum[j] - i_spectrum[i]))\n for i in range(rank)\n for j in range(i + 1, self.n_features)\n ))) + constant_part\n #return sum(\n # log(\n # 1 + ((self.spectrum[i] - self.spectrum[j]) * (i_spectrum[j] - i_spectrum[i]))\n # )\n # for i in range(rank)\n # for j in range(i + 1, self.n_features)\n #) + constant_part\n\ndef make_test(samples, features, classes):\n X, _ = make_multilabel_classification(n_samples=samples, n_features=features, n_classes=classes)\n return (samples, features, classes, X, None)\n\ndef time_function(f, *args, post_process=lambda x: x):\n start = time()\n retval = f(*args)\n end = time()\n return post_process(retval), end - start\n\ndef print_row(*args):\n strings = [f'{a:^12}' if isinstance(a, str) else (f'{a:>12}' if isinstance(a, int) else f'{a:>12.6}')\n for a in args]\n print('|'.join(strings))\n\ndef main():\n candidates = {\n "Original": Original(False).find_components,\n "Cleaned": Cleaned(False).find_components,\n "Optimized": Optimized(False).find_components,\n }\n tests = [\n make_test(100, 50, 2),\n make_test(1000, 500, 2),\n ]\n print_row('samples', 'features', 'classes', *candidates.keys(), 'answer')\n for samples, features, classes, data, known in tests:\n results = [time_function(f, data.copy(), post_process=int)\n for f in candidates.values()]\n answers = [\n answer\n for answer in [known, *(r[0] for r in results)]\n if answer is not None\n ]\n assert 1 == len(set(answers)), f'1 != len({"; ".join(map(str, answers))})'\n print_row(samples, features, classes, *(r[1] for r in results), results[0][0])\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Prints:</p>\n<pre><code> samples | features | classes | Original | Cleaned | Optimized | answer\n 100| 50| 2| 0.166063| 0.153894| 0.151417| 49\nSO_254392.py:185: RuntimeWarning: overflow encountered in double_scalars\n return log(reduce(mul, (\nTraceback (most recent call last):\n File "SO_254392.py", line 236, in <module>\n main()\n File "SO_254392.py", line 232, in main\n assert 1 == len(set(answers)), f'1 != len({"; ".join(map(str, answers))})'\nAssertionError: 1 != len(499; 499; 1)\n</code></pre>\n<p>or, if we cut out the failed optimization path:</p>\n<pre><code> samples | features | classes | Original | Cleaned | answer\n 100| 50| 2| 0.161394| 0.154552| 49\n 1000| 500| 2| 44.1136| 35.9878| 499\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T21:56:48.580",
"Id": "254719",
"ParentId": "254392",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T19:48:40.813",
"Id": "254392",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"mathematics"
],
"Title": "Algorithm Optimization -- Automatic Dimensionality of PCA"
}
|
254392
|
<p>I wrote a small program in Javascript that, when given a certain number of sides, will draw a polygon with that number of sides (i.e. 3 for a triangle, 5 for a pentagon, 8 for octagon, etc.).</p>
<p>The program is set on an interval that will, every second, increment the number of sides, redraw the canvas, and then draw the new polygon with the new number of sides.</p>
<p>The code works as intended, though I'm not entirely sure if it's working most efficiently. Was wondering if there were better ways to manage variables, draw to the screen, etc.</p>
<p>Here is the <a href="https://jsfiddle.net/SirToadstool/7kyLdxg6/1/" rel="nofollow noreferrer">jsFiddle</a></p>
<p>---HTML---</p>
<pre><code><html>
<head>
<title>Circles</title>
<style>
body * {
margin: 5px;
}
canvas {
border: 2px solid black;
}
</style>
</head>
<body>
<p>Sides: <span id='noSides'></span></p>
<input type='button' class='dir' id='backward' value='BACKWARD' />
<input type='button' class='dir' id='forward' value='FOWARD' />
<input type='button' id='start' value='Start' />
<input type='button' id='stop' value='Stop' />
<input type='button' id='reset' value='Reset' />
<br />
<canvas id='canvas' width='500' height='500'></canvas>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
</code></pre>
<p>---Javascript---</p>
<pre><code>class Vector {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
class Circle {
constructor(x, y, radius) {
this.center = new Vector(x, y);
this.radius = radius;
}
}
const input = document.getElementById("sides");
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const center = {
x: canvas.width / 2,
y: canvas.height / 2
};
const rotateAround = 3 * Math.PI / 2;
drawCanvas();
let reverse = false;
let sides = 0;
let radius = center.y * 0.8;
let shapes = [];
function reset() {
context.rotate(-(3 * Math.PI / 2));
context.translate(-center.y, -center.y);
drawCanvas();
context.translate(center.y, center.y);
context.rotate(3 * Math.PI / 2);
}
function draw() {
reset();
if (reverse) {
if (sides != 0) {
sides -= 1;
}
} else {
sides += 1;
}
document.getElementById('noSides').innerText = sides;
if (sides > 0) {
shapes = [];
for (let i = 0; i < sides; i++) {
shapes.push(new Circle(0, 0, 20));
}
for (let i = 0; i < shapes.length; i++) {
let x1 = radius * Math.cos(Math.PI * (i / (shapes.length / 2)));
let y1 = radius * Math.sin(Math.PI * (i / (shapes.length / 2)));
shapes[i].center.x = x1;
shapes[i].center.y = y1;
}
for (let i = 0; i < shapes.length; i++) {
for (let j = i + 1; j < shapes.length; j++) {
context.beginPath();
context.lineWidth = 0.5;
context.moveTo(shapes[i].center.x, shapes[i].center.y);
context.lineTo(shapes[j].center.x, shapes[j].center.y);
context.stroke();
context.closePath();
}
}
}
}
function drawCanvas() {
context.fillStyle = "lightgrey";
context.fillRect(0, 0, canvas.width, canvas.height);
}
let interval;
let started = false;
function update() {
context.translate(center.y, center.y);
context.rotate(rotateAround);
drawCanvas();
}
update();
document.getElementById('start').onclick = function() {
if (started === false) {
started = true;
interval = setInterval(draw, 1000);
}
}
document.getElementById('stop').onclick = function() {
clearInterval(interval);
started = false;
}
document.getElementById('forward').onclick = function() {
reverse = false;
}
document.getElementById('backward').onclick = function() {
reverse = true;
}
document.getElementById('reset').onclick = function() {
clearInterval(interval);
reset();
sides = 0;
}
</code></pre>
|
[] |
[
{
"body": "<h2><code>closePath</code> is not complement of <code>beginPath</code></h2>\n<p>You are using <code>ctx.closePath()</code> incorrectly. <code>ctx.closePath()</code> is a path function, similar to <code>ctx.moveTo(x, y)</code>. It creates a line from the current position to previous <code>ctx.moveTo(x, y)</code>. It is not the complement of <code>ctx.beginPath()</code>. There is no need to use it in this case.</p>\n<h2>Keep it Simple.</h2>\n<h3><code>Circle</code> & <code>Vector</code></h3>\n<p>You have defined <code>Circle</code>, and <code>Vector</code> objects.</p>\n<p>When you create the circle you pass a <code>x</code>, <code>y</code> coordinate that you use to create a <code>Vector</code> and assign to <code>circle.center</code>.</p>\n<p>Rather pass a <code>Vector</code> to the <code>Circle</code>. eg</p>\n<pre><code>constructor(center, radius) {\n this.center = center;\n ...\n\ncircle = new Circle(new Vector(x, y), 10);\n</code></pre>\n<h3>Just data stores</h3>\n<p>Both the <code>Circle</code> and <code>Vector</code> objects are just data stores, they do nothing else but hold some numbers. You can simplify both to much simpler forms</p>\n<pre><code>const Vector = (x = 0, y = 0) = ({x, y});\nconst Circle = (center = Vector(), radius = 20) = ({center, radius});\n</code></pre>\n<p>This saves you 11 lines of code, without changing the behavior.</p>\n<h3>Irrelevant data.</h3>\n<p>The function <code>draw</code> does some odd things. You create circles yet only ever use centers. As code in Code Review questions is considered to be complete. Using circle is superfluous, just use the vectors.</p>\n<h3>Cache data</h3>\n<p>Your code recalculates all the points each time you redraw, this is a waste of time. You can either</p>\n<ul>\n<li>Store all the points for each shape and use existing path points or create them if they have not yet been created.</li>\n<li>Store the 2D path calls as a Path2D.</li>\n</ul>\n<h2>2D rendering</h2>\n<p>When rendering to 2D canvas context always group path calls that use the same state (color, line width, etc) should be inside the same <code>beginPath</code>. <code>beginPath</code> and <code>stroke</code> require GPU state changes, which is where the rendering bottle neck is, on low end devices this bottle neck is very small making even simple renders slow due to poor state change calls.</p>\n<p>The <code>draw</code> call has too many roles. Setting number of sides, displaying the number of sides, generating the points, all should be part of other functions. <code>draw</code> should only draw nothing more. Create the shape in another function and pass that data to the draw call. Displaying side count, and changing side shape can be done at a higher level.</p>\n<h2>Avoid <code>setInterval</code></h2>\n<p>You should always avoid <code>setInterval</code> as it often makes managing timers more complex. Use <code>setTimeout</code> as there is no need to hold handles as it can be stopped via semaphore.</p>\n<h2>Avoid repetition</h2>\n<p>A lot of the code has very similar parts. Good code has very little repetition. This is done by using functions to do repetitive tasks.</p>\n<p>More often than not the repetitive code will be such over many project. Writing functions for repeated code also creates a resource that can be moved from project to project saving you hours of time typing out the same thing over and over.</p>\n<p>JavaScript supports modules that makes code reuse easy. The rewrite shows some examples, DOM and Maths utils that would normally be in modules and imported. See rewrite comments</p>\n<h2>UI</h2>\n<p>Make the UI smart, buttons that can not or should not be used should be disabled. The disabled status of buttons also give the user feedback as to the state of the app.</p>\n<p>The rewrite maps the buttons to an object called <code>actions</code> which is in effect the interface to the app. Not only can The user call actions, the code also uses actions to <code>reset</code>, and <code>stop</code> (when <code>sides < 1</code>)</p>\n<h2>Rewrite</h2>\n<p>At the top & bottom there is some commented code that shows how the utilities would be imported. The DOM utils are medium level code, if you have questions use the CR comments.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\"; // not required when using modules\nsetTimeout(() => { // timeout only for CR snippet so that code is parse before execution\n // Note I did not indent timeout as there is not much room for snipper \n\n/* To use modules the imports would be. See bottom of snippet */\n// import {query, listener, elements} from \"./DOM/utils.jsm\";\n// import {constants} from \"./Maths/constants.jsm\";\n// import {Vec2} from \"./Maths/constants.jsm\";\n\nconst ctx = query(\"#canvas\").getContext(\"2d\");\nconst center = Vector(ctx.canvas.width / 2, ctx.canvas.height / 2);\n\nconst rotate = - Math.PI / 2;\nconst shapes = [];\nvar sidesStep = 1;\nvar sides = 1;\nvar radius = center.y * 0.8;\nvar started = false;\n\nconst actions = {\n updateBtnStates() {\n btns.start.disabled = started;\n btns.stop.disabled = !started;\n btns.forward.disabled = sidesStep > 0;\n btns.backward.disabled = sidesStep < 0 && sides > 1; \n },\n start() {\n if (!started) {\n started = true;\n update();\n }\n actions.updateBtnStates();\n },\n stop() { \n started = false;\n actions.updateBtnStates();\n },\n reverse() { \n sides -= sidesStep;\n sidesStep = -sidesStep; \n actions.updateBtnStates();\n },\n forward() { actions.reverse() },\n backward() { actions.reverse() },\n reset() { \n sidesStep = 1;\n sides = 1;\n actions.stop();\n update(true);\n }, \n}\nconst btns = elements({\n start: \"#startBtn\",\n stop: \"#stopBtn\",\n forward: \"#forwardBtn\",\n backward: \"#backwardBtn\",\n reset: \"#resetBtn\",\n});\nObject.entries(btns).forEach(([name, el]) => listener(el, \"click\", actions[name]));\n\nactions.reset();\n\nfunction createShape(sides, r = radius) {\n const shape = [];\n var i = sides;\n while (i-- > 0) { \n const ang = (i / sides) * TAU;\n shape.push(Vector(Math.cos(ang) * r, Math.sin(ang) * r));\n }\n return shape;\n}\n \nfunction pathShape(points) {\n const path = new Path2D();\n var i = sides, j, p1, p2;\n while (i-- > 0) { \n j = i;\n p1 = points[i];\n while (j-- > 0) {\n p2 = points[j];\n path.moveTo(p1.x, p1.y);\n path.lineTo(p2.x, p2.y);\n }\n }\n return path;\n}\nfunction drawShape(ctx, path, pos, rotate, lineWidth = 0.5, col = \"#000\") {\n ctx.setTransform(1, 0, 0, 1, pos.x, pos.y);\n ctx.rotate(rotate);\n ctx.lineWidth = lineWidth;\n ctx.strokeStyle = col;\n ctx.stroke(path);\n ctx.setTransform(1, 0, 0, 1, 0, 0); // default\n}\nfunction clearCanvas(color = \"lightgrey\") {\n ctx.fillStyle = \"lightgrey\";\n ctx.fillRect(0, 0, canvas.width, canvas.height);\n} \n\nfunction update(once = false) {\n if (started || once) { \n !once && setTimeout(update, 1000);\n if (!shapes[sides]) { shapes[sides] = pathShape(createShape(sides)) }\n clearCanvas();\n drawShape(ctx, shapes[sides], center, rotate);\n numSidesEl.textContent = sides;\n sides += sidesStep;\n if (sides < 1) { \n sides = 1;\n sidesStep = 1;\n actions.stop();\n }\n }\n}\n},0); // End of timeout\n\n\n\n/* The following would be a Module file /DOM/utils.jsm */\nconst qryEl = qryEl => typeof qryEl === \"string\" ? query(qryEl) : qryEl;\nconst query = (qStr, el = document) => el.querySelector(qStr);\nconst listener = (eq, name, call, opt = {}) => ((eq = qryEl(eq)).addEventListener(name, call, opt), eq);\nconst elements = obj => (Object.entries(obj).forEach(([n, q]) => obj[n] = query(q)), obj);\n// export {query, listener, elements};\n\n/* The following would be a Module file /Maths/constants.jsm */ \n// const constants.TAU = Math.PI * 2;\n// export {constants};\n\n/* The following would be a Module file /Maths/Vec2.jsm */ \n// const Vec2 = (x = 0, y = 0) => ({x, y});\n// export {Vec2};\n\n/* To use modules the imports would be */\n// import {query, listener, elements} from \"./DOM/utils.jsm\";\n// import {constants} from \"./Maths/constants.jsm\";\n// import {Vec2} from \"./Maths/constants.jsm\";\n\n\n/* Replacements for imports constants, Vec2 */\nconst TAU = Math.PI * 2;\nconst Vector = (x = 0, y = 0) => ({x, y});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><p>Sides: <span id='numSidesEl'></span></p>\n <button class='dir' id='backwardBtn'>BACKWARD</button>\n <button class='dir' id='forwardBtn'>FOWARD</button>\n <button id='startBtn'>Start</button>\n <button id='stopBtn'>Stop</button>\n <button id='resetBtn'>Reset</button>\n <br>\n <canvas id='canvas' width='500' height='500'></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Warning Let</h2>\n<p><code>let</code> in global scope is very bad.</p>\n<p>General rule for <code>let</code> is. Only use it inside <code>{</code> blocks <code>}</code>, never use it in global scope.</p>\n<p>Sorry OP the following is a little overly detailed and is in lue of the inevitable comments defending <code>let</code>.</p>\n<p>A <code><script></code> is NOT a block, though obvious (no {}), the general intuition is that it is (who uses global let and puts {} around a script?)</p>\n<p>The counter intuitive behavior of a global <code>let</code>.</p>\n<p>For example a script...</p>\n<pre><code><script > \n let b = {log() { console.log("Hi") }}; // b can not be trusted\n setTimeout(() => b.log(), 200);\n\n</script> \n</code></pre>\n<p>...in 200ms expect "Hi" in console.</p>\n<p>Another (diligent) script will crash</p>\n<pre><code><script>\n "use strict"; // doin the right thing\n let b = 5; // throws "b already declared" What the!!!!\n</script> \n</code></pre>\n<p>Another (sloppy) script can reuse <code>b</code></p>\n<pre><code><script> b = 5 </script> \n</code></pre>\n<p>Not crashing this script, but when the <code>timeout</code> (first script) callback calls <code>b.log</code> which is no longer a function it will throw an error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T09:39:18.403",
"Id": "254410",
"ParentId": "254393",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254410",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T20:41:12.393",
"Id": "254393",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Draw polygons with increasing/decreasing vertices"
}
|
254393
|
<p>note: This is an updated design after a <a href="https://codereview.stackexchange.com/questions/254331/c-callback-multithreaded-can-unregister-itself">previous review round</a>.</p>
<p>I have written a class that handles listeners registering callbacks to receive messages. Registered callbacks can be replaced or removed. Code is multithreaded in that any thread can broadcast to the listeners, and any thread can add, replace or remove listeners.</p>
<p>For this second round, I have made a list of requirements for the class:</p>
<ol>
<li>there may be zero, one or multiple listeners</li>
<li>listeners can be registered or deregistered from different threads</li>
<li>each listener should be called exactly once for each message</li>
<li>all listeners should receive all messages</li>
<li>messages may originate from multiple sources in different threads</li>
<li>each message should be forwarded to all listeners before the next message is processed (messages are not sent in parallel)</li>
<li>each listener should receive the messages in the same order, i.e., the order in which they are provided to the broadcaster (from the view of the broadcaster)</li>
<li>listeners can be removed or replaced</li>
<li>listeners are uniquely identified by a cookie that remains valid if the listener is not deregistered</li>
<li>the cookie remains valid if the listener is replaced</li>
<li>anyone with the cookie should be able to deregister or replace the listener</li>
<li>listeners should never be called again when deregistration completes</li>
<li>the old listener should never be called again when replace completes</li>
<li>listeners should be able to deregister or replace themselves when invoked, listeners do not need to be able to register more callbacks</li>
<li>listeners are noexcept, so code shouldn’t deal with exceptions thrown by listeners</li>
<li>trying to remove or replace the callback associated with an expired cookie is not an error, the operation should simply do nothing, and report to the caller that nothing was done.</li>
<li>adding, replacing and removing listeners happens much less frequently than broadcasting.</li>
</ol>
<p>A further consideration that is not enforced in code:</p>
<ul>
<li>Users are expected to read documentation that states which functions are safe to call from <em>inside</em> a listener, and which <em>must</em> not. (Ideal would be a way to check if a function is called from a listener, so we can error in that case. I can’t figure out a way to do that. How to distinguish the case where the lock in, e.g., add_listener can’t be acquired because we’re calling from the callback (can’t call lock, would deadlock), vs where it can’t be acquired because callbacks are running concurrently (calling lock is correct in that case)?)</li>
</ul>
<h2>Implementation</h2>
<pre><code>#include <vector>
#include <map>
#include <utility>
#include <optional>
#include <mutex>
#include <functional>
#include <type_traits>
// usage notes:
// 1. This class provides no lifetime management of the link, which means
// the user is responsible to ensure that either
// a. the registered callback outlives this broadcaster, or
// b. they revoke their callbacks before destroying any resource it
// points to.
// 2. None of the member functions of this class may be called from
// inside an executing listener, except
// replace_callback_from_inside_callback() and
// remove_listener_from_inside_listener(). Calling them anyway will
// result in deadlock.
// 3. replace_callback_from_inside_callback() and
// remove_listener_from_inside_listener() may _only_ be called from
// inside an executing listener.
template <class... Message>
class Broadcaster
{
public:
using listener = std::function<void(Message...)>;
using cookieType = int32_t;
// should never be called from inside a running listener
template <class F> requires (std::is_nothrow_invocable_r_v<void, F, Message...>)
[[nodiscard]] cookieType add_listener(F&& r_)
{
auto l = lock();
_targets.emplace_back(listener{ std::forward<F>(r_) });
_target_registry[++_lastID] = _targets.size() - 1;
return _lastID;
}
// should never be called from inside a running listener,
// in that case, use replace_listener_from_inside_listener()
template <class F> requires (std::is_nothrow_invocable_r_v<void, F, Message...>)
bool replace_listener(cookieType c_, F&& r_)
{
auto l = lock();
return replace_listener_impl(c_, listener{ std::forward<F>(r_) });
}
// should never be called from inside a running listener,
// in that case, use remove_listener_from_inside_listener()
bool remove_listener(cookieType c_)
{
auto l = lock();
return remove_listener_impl(c_);
}
void notify_all(const Message&... msg_) noexcept
{
auto l = lock();
// invoke all listeners with message
for (const auto& r: _targets)
r(msg_...);
// execute any updates to registered listeners
if (!_mutation_list.empty())
{
for (auto&& [cookie, r] : _mutation_list)
{
if (r.has_value())
replace_listener_impl(cookie, std::move(*r));
else
remove_listener_impl(cookie);
}
_mutation_list.clear();
}
}
// !! should only be called from inside a running listener!
template <class F> requires (std::is_nothrow_invocable_r_v<void, F, Message...>)
void replace_listener_from_inside_listener(cookieType c_, F&& r_)
{
_mutation_list.emplace_back(c_, listener{ std::forward<F>(r_) });
}
// !! should only be called from inside a running listener!
void remove_listener_from_inside_listener(cookieType c_)
{
_mutation_list.emplace_back(c_, std::nullopt);
}
private:
[[nodiscard]] auto lock()
{
return std::unique_lock<std::mutex>(_mut);
}
bool replace_listener_impl(cookieType c_, listener&& r_)
{
auto index = get_target_index(c_);
if (index)
{
// valid slot, update listener stored in it
auto it = _targets.begin() + *index;
*it = std::move(r_);
return true;
}
return false;
}
bool remove_listener_impl(cookieType c_)
{
auto index = get_target_index(c_);
if (index)
{
// valid slot, remove listener stored in it
auto it = _targets.begin() + *index;
_targets.erase(it);
// fixup slot registry, items past deleted one just moved one idx back
for (auto& [cookie, idx]: _target_registry)
{
if (idx > *index)
--idx;
}
// remove entry from slot registry
_target_registry.erase(c_);
return true;
}
return false;
}
std::optional<size_t> get_target_index(cookieType c_) const
{
auto map_it = _target_registry.find(c_);
if (map_it == _target_registry.end())
// cookie not found in registry
return {};
return map_it->second;
}
private:
std::mutex _mut;
std::map<cookieType, size_t> _target_registry;
cookieType _lastID = -1;
std::vector<listener> _targets;
std::vector<std::pair<cookieType, std::optional<listener>>> _mutation_list;
};
</code></pre>
<h2>Example usage</h2>
<pre><code>#include <iostream>
#include <string>
#include <functional>
void freeTestFunction(std::string msg_) noexcept
{
std::cout << "from freeTestFunction: " << msg_ << std::endl;
}
struct test
{
using StringBroadcaster = Broadcaster<std::string>;
void simpleCallback(std::string msg_) noexcept
{
std::cout << "from simpleCallback: " << msg_ << std::endl;
}
void oneShotCallback(std::string msg_) noexcept
{
std::cout << "from oneShotCallback: " << msg_ << std::endl;
_broadcast.remove_listener_from_inside_listener(_cb_oneShot_cookie);
}
void twoStepCallback_step1(std::string msg_) noexcept
{
std::cout << "from twoStepCallback_step1: " << msg_ << std::endl;
// replace callback (so don't request to delete through return argument!)
_broadcast.replace_listener_from_inside_listener(_cb_twostep_cookie, [&](auto fr_) noexcept { twoStepCallback_step2(fr_); });
}
void twoStepCallback_step2(std::string msg_) noexcept
{
std::cout << "from twoStepCallback_step2: " << msg_ << std::endl;
}
void runExample()
{
auto cb_simple_cookie = _broadcast.add_listener([&](auto fr_) noexcept { simpleCallback(fr_); });
_cb_oneShot_cookie = _broadcast.add_listener([&](auto fr_) noexcept { oneShotCallback(fr_); });
_cb_twostep_cookie = _broadcast.add_listener([&](auto fr_) noexcept { twoStepCallback_step1(fr_); });
auto free_func_cookie = _broadcast.add_listener(&freeTestFunction);
_broadcast.notify_all("message 1"); // should be received by simpleCallback, oneShotCallback, twoStepCallback_step1, freeTestFunction
_broadcast.remove_listener(free_func_cookie);
_broadcast.notify_all("message 2"); // should be received by simpleCallback and twoStepCallback_step2
_broadcast.remove_listener(cb_simple_cookie);
_broadcast.notify_all("message 3"); // should be received by twoStepCallback_step2
_broadcast.remove_listener(_cb_twostep_cookie);
_broadcast.notify_all("message 4"); // should be received by none
}
StringBroadcaster _broadcast;
StringBroadcaster::cookieType _cb_oneShot_cookie;
StringBroadcaster::cookieType _cb_twostep_cookie;
};
int main(int argc, char **argv)
{
test t;
t.runExample();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T16:52:13.397",
"Id": "501830",
"Score": "0",
"body": "\"one or multiple listeners\"? Does that mean that there can't be zero listeners, or did you forget to include that in the requirements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T21:05:17.397",
"Id": "501845",
"Score": "1",
"body": "@TobySpeight Ah, right. yes there could also be zero, and that should work fine (it does, was in the test case already). Thanks, i've corrected the text."
}
] |
[
{
"body": "<p>I have just one suggestion but you should evaluate in terms of performance. What I mean is that you should do a performance test with your current code and then with the new changes proposed to see if you gain.</p>\n<p>You are using a lock() function inside the <strong>notify_all</strong> function.</p>\n<pre><code>void notify_all(const Message&... msg_) noexcept\n{\n auto l = lock();\n\n // invoke all listeners with message\n for (const auto& r: _targets)\n r(msg_...);\n\n // execute any updates to registered listeners\n if (!_mutation_list.empty())\n {\n for (auto&& [cookie, r] : _mutation_list)\n {\n if (r.has_value())\n replace_listener_impl(cookie, std::move(*r));\n else\n remove_listener_impl(cookie);\n }\n _mutation_list.clear();\n }\n}\n</code></pre>\n<p>The suggested change is to move the scope of that lock the close to where you need to lock it, for example close to the replace_listener_impl and remove_listener_impl.</p>\n<pre><code>void notify_all(const Message&... msg_) noexcept\n{\n // invoke all listeners with message\n for (const auto& r: _targets)\n r(msg_...);\n\n // execute any updates to registered listeners\n if (!_mutation_list.empty())\n {\n auto l = lock(); // First option\n for (auto&& [cookie, r] : _mutation_list)\n {\n if (r.has_value())\n replace_listener_impl(cookie, std::move(*r));\n else\n remove_listener_impl(cookie);\n }\n _mutation_list.clear();\n }\n}\n</code></pre>\n<p>Another alternative is to move the lock() calls that you have on the functions <strong>replace_listener</strong> and <strong>remove_listener</strong> to the _impl functions.</p>\n<pre><code>template <class F> requires (std::is_nothrow_invocable_r_v<void, F, Message...>)\nbool replace_listener(cookieType c_, F&& r_)\n{\n // Remove auto l = lock(); \n return replace_listener_impl(c_, listener{ std::forward<F>(r_) });\n}\n</code></pre>\n<p>Move it to <strong>replace_listener_impl</strong></p>\n<pre><code>bool replace_listener_impl(cookieType c_, listener&& r_)\n{\n auto l = lock(); // Added\n auto index = get_target_index(c_);\n if (index)\n {\n // valid slot, update listener stored in it\n auto it = _targets.begin() + *index;\n *it = std::move(r_);\n return true;\n }\n return false;\n}\n</code></pre>\n<p>In any of the options that you will choose you should conduct a performance test to see what is more suitable for you, may be is slower or not, so better get the numbers so you have the evidence of what is better for you.</p>\n<p>Hope it helps</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T21:07:37.197",
"Id": "501846",
"Score": "0",
"body": "Thanks for the comment! I can't move the lock, or it wouldn't be safe anymore. That is, if i move the lock down in `notify_all()`, or to the `_impl` function, the vector of listeners could be changed while iterating over it, which would break stuff. Do i see that correctly?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T14:38:09.950",
"Id": "254446",
"ParentId": "254395",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T21:59:51.480",
"Id": "254395",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"callback",
"c++20"
],
"Title": "c++ multithreaded message broadcaster using callbacks"
}
|
254395
|
<p>I created a code where I can add multiple carousels to a page. I did this by storing the carousel in an array and accessing it by clicking on the previous/next arrows.</p>
<p>I was trying to prevent any repetitive coding on JavaScript but I still found myself copying and pasting the code to get the result I wanted.</p>
<p>The first thing I did was store each carousel in an array with <code>var subGroup</code>. I created a for loop on the previous and next arrows so they could function every time I add a new carousel on the page.</p>
<h2>How the carousel is accessed</h2>
<p>I created a switch statement where, for example, if the arrows clicked are on the nth carousel it would move the images only on the nth carousel, which is achieved by accessing the array using index position.</p>
<p>I created an ID for each arrow <code>id="prev0" id="next0" id="prev1"</code> etc. so I could store it in <code>var btnPrevId = parseInt(this.id[this.id.length - 1])</code> in the for loop where it extracts the number from the ID. I then use that variable to index <code>subGroup</code>.</p>
<p><code>console.log(btnPrevId); // Output equals 0, 1, or 2 when clicked </code></p>
<h2>Adding a new case to the switch statement</h2>
<p>The first issue I have is I would have to add a new case if I add a new carousel. I was trying to use an if/else statement where if I clicked on the prev/next arrows on the nth carousel it would then index <code>subGroup[n-1].querySelectorAll(".carousel-cell")</code> but was unsuccessful.</p>
<h2>Moving images by storing the position in a variable</h2>
<p>The second issue I came across is using the left property to adjust the position through multiple carousels using multiple variables instead of one.<br>
<code>var m1 = 0; var m2 = 0; var m3 = 0; </code>
<br>
If I use only one variable for every carousel in the switch statement it will position the images starting where the last data value was set. What I wanted to do instead is position the images where the data value was last set for that specific carousel.</p>
<p>Every time I think I figured it out, I come across another issue that I need to fix which has been quite exciting actually. Working on this carousel has helped me better understand Javascript and although this project is technically done, it could be better. This is my first time getting input on a project. I would really appreciate the feedback</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var subGroup = document.querySelectorAll(".carousel-subgroup");
var nextBtn = document.querySelectorAll(".carousel-btn-next");
var prevBtn = document.querySelectorAll(".carousel-btn-prev");
var x;
var m1 = 0;
var m2 = 0;
var m3 = 0;
// NEXT BUTTON
for (x = 0; x < prevBtn.length; x++) {
prevBtn[x].addEventListener("click", function() {
// Extracted number from the previous buttons id
var btnPrevId = parseInt(this.id[this.id.length - 1]);
switch (btnPrevId) {
case 0:
m1--;
for (var i of subGroup[btnPrevId].querySelectorAll(".carousel-cell")) {
if (m1 == 0) { i.style.left = "0px"; }
if (m1 == 1) { i.style.left = "-495px"; }
if (m1 < 0) { m1 = 0; }
}
break;
case 1:
m2--;
for (var i of subGroup[btnPrevId].querySelectorAll(".carousel-cell")) {
if (m2 == 0) { i.style.left = "0px"; }
if (m2 == 1) { i.style.left = "-495px"; }
if (m2 < 0) { m2 = 0; }
}
break;
case 2:
m3--;
for (var i of subGroup[btnPrevId].querySelectorAll(".carousel-cell")) {
if (m3 == 0) { i.style.left = "0px"; }
if (m3 == 1) { i.style.left = "-495px"; }
if (m3 < 0) { m3 = 0; }
}
break;
default:
}
});
}
// PREVIOUS BUTTON
for (x = 0; x < nextBtn.length; x++) {
nextBtn[x].addEventListener("click", function() {
// Extracted number from the next buttons id
var btnNextId = parseInt(this.id[this.id.length - 1]);
switch (btnNextId) {
case 0:
m1++;
for (var i of subGroup[btnNextId].querySelectorAll(".carousel-cell")) {
if (m1 == 0) { i.style.left = "0px"; }
if (m1 == 1) { i.style.left = "-990px"; }
if (m1 == 2) { i.style.left = "-1480px"; }
if (m1 > 2) { m1 = 2; }
}
break;
case 1:
m2++;
for (var i of subGroup[btnNextId].querySelectorAll(".carousel-cell")) {
if (m2 == 0) { i.style.left = "0px"; }
if (m2 == 1) { i.style.left = "-990px"; }
if (m2 == 2) { i.style.left = "-1480px"; }
if (m2 > 2) { m2 = 2; }
}
break;
case 2:
m3++;
for (var i of subGroup[btnNextId].querySelectorAll(".carousel-cell")) {
if (m3 == 0) { i.style.left = "0px"; }
if (m3 == 1) { i.style.left = "-990px"; }
if (m3 == 2) { i.style.left = "-1480px"; }
if (m3 > 2) { m3 = 2; }
}
break;
default:
}
});
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.carousel-group {
width: 87vw;
margin: 1em auto 3em auto;
}
.carousel-subgroup {
overflow-x: hidden;
position: relative;
}
.carousel-flex {
display: flex;
overflow-x: auto;
}
.carousel-flex::-webkit-scrollbar {
visibility: hidden;
}
.carousel-cell {
Left: 0;
position: relative;
margin-right: 9em;
transition: 0.5s;
}
.carousel-btn {
cursor: pointer;
position: absolute;
top: 56%;
}
.carousel-btn-prev {}
.carousel-btn-next {
left: 99.25%;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://kit.fontawesome.com/66a5def521.js"></script>
<div class="carousel-group">
<div class="carousel-subgroup fade-down">
<h2>Carousel 1</h2>
<div class="carousel-flex">
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=First+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Second+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Third+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Fourth+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Fifth+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Sixth+Text" alt="">
</div>
</div>
<div class="carousel-btn carousel-btn-prev" id="prev0">
<i class="fas fa-chevron-left"></i>
</div>
<div class="carousel-btn carousel-btn-next" id="next0">
<i class="fas fa-chevron-right"></i>
</div>
</div>
<div class="carousel-subgroup fade-down">
<h2>Carousel 2</h2>
<div class="carousel-flex">
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=First+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Second+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Third+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Fourth+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Fifth+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Sixth+Text" alt="">
</div>
</div>
<div class="carousel-btn carousel-btn-prev" id="prev1">
<i class="fas fa-chevron-left"></i>
</div>
<div class="carousel-btn carousel-btn-next" id="next1">
<i class="fas fa-chevron-right"></i>
</div>
</div>
<div class="carousel-subgroup fade-down">
<h2>Carousel 3</h2>
<div class="carousel-flex">
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=First+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Second+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Third+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Fourth+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Fifth+Text" alt="">
</div>
<div class="carousel-cell">
<img src="https://via.placeholder.com/350x200.png?text=Sixth+Text" alt="">
</div>
</div>
<div class="carousel-btn carousel-btn-prev" id="prev2">
<i class="fas fa-chevron-left"></i>
</div>
<div class="carousel-btn carousel-btn-next" id="next2">
<i class="fas fa-chevron-right"></i>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T21:20:43.760",
"Id": "501770",
"Score": "0",
"body": "You can have one function and use a data attribute to know if it is next or previous. You can use an array and use an index so you do not have to have the switch."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T22:46:42.683",
"Id": "254396",
"Score": "1",
"Tags": [
"javascript",
"array",
"html"
],
"Title": "Creating Multiple Carousels by storing them in an Array with JavaScript"
}
|
254396
|
<p>I have a comparison function for use in <code>scandir</code> or <code>qsort</code> to sort an array of <code>struct dirent *</code>s by access date. <code>S</code> is the directory path of the directory whose files are being sorted, and <code>SavesLen</code> is <code>strlen(S)</code>.</p>
<pre><code>static int Q(const struct dirent **const First, const struct dirent **const Second) {
const char *const FirstName = (*First)->d_name, *const SecondName = (*Second)->d_name, *const Name[] = {FirstName, SecondName};
const unsigned short FirstLen = (unsigned short)strlen(FirstName), SecondLen = (unsigned short)strlen(SecondName), Len[] = {FirstLen, SecondLen};
char File[SavesLen+Len[FirstLen < SecondLen]+2], *CurrPtr = memcpy(File, S, SavesLen)+SavesLen;
*CurrPtr++ = '/';
time_t Time[2];
for (unsigned char I = 0; I < 2; I++) {
memcpy(CurrPtr, Name[I], Len[I]);
struct stat Stat;
if (stat(File, &Stat)){
return 0;
}
Time[I] = Stat.st_atimespec.tv_sec;
}
return Time[1]-(*Time);
}
</code></pre>
<p>Sorry for being obsessed with microoptimizations, but I'm looking to improve this.</p>
<p><code>S</code> and <code>SavesLen</code> are both global variables defined and declared and initialized elsewhere. Is there a way to take advantage of local scopes to delete some of the memory earlier? Are there other improvements to be made? Thanks ahead of time.</p>
<p>An answerer pointed out that <code>char File[SavesLen+Len[FirstLen > SecondLen]+2]</code> is extremely hard to read. So here's why I do it that way. There are 2 files, and I need to check the access time of both of them. Rather than creating a path for each one, I'm reusing the same path, to minimize the number of VLA declarations and the number of <code>memcpy()</code> calls. Now let's break it down for you. <code>char File[...]</code> is a VLA declaration. The size is <code>SavesLen</code> plus the larger size of the 2 files, plus 2, for the <code>/</code> and null character. So what the heck is <code>Len[FirstLen > SecondLen]</code>? The reason why it's confusing is because <em><strong>I'm treating booleans like integers,</strong></em> and being weakly typed, C lets me do that. <code>Len</code> is an array so it will either be indexed by 0 or 1 (the 2 boolean values) depending on which one is bigger, because <code>FirstLen > SecondLen</code> will either evaluate to 0 or 1.</p>
<p>It seems the answerer understands, but in case there are others confused. I do agree that there was a bug, and that's because it used to be a ternary and I forgot to switch the values.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T00:00:48.443",
"Id": "501724",
"Score": "1",
"body": "Welcome to the Code Review Community. It would be very helpful to use if you explained what the program is trying to do, and to provide missing pieces of the program such as the definition of the struct `dirent`. Have you profiled your code to know that his is actually a bottleneck?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T00:08:19.617",
"Id": "501725",
"Score": "1",
"body": "@pacmaninbw The purpose of the code is made clear by mentioning `scandir`. `struct dirent` is defined in `<dirent.h>`. I don't think it has to be spelled out here."
}
] |
[
{
"body": "<ul>\n<li><p>One declaration per line, please.</p>\n</li>\n<li><p><code>char File[SavesLen+Len[FirstLen > SecondLen]+2];</code> is extremely hard to read. In fact, I suspect that there is a bug. Correct me if I am wrong, an intention is to allocate enough memory to accomodate the longest pathname. Now, if <code>FirstLen</code> is indeed greater than <code>SecondLen</code>, the condition evaluates to <code>true</code>, which is in this context is <code>1</code>. Now the VLA size becomes <code>SaveLen + Len[1] + 2</code>, that is <code>SaveLen + SecondLen + 2</code>, which is not enough for the longer first name.</p>\n</li>\n<li><p>The loop running just two iterations is better be two calls to a function. Consider</p>\n<pre><code> static time_t get_atime(const char * filename) {\n char path[SavesLen + 1 + strlen(filename) + 1];\n sprintf(path, "%s/%s", S, filename);\n\n struct stat stat; \n stat(path, &stat);\n return stat.st_atimespec.tv_sec;\n }\n\n static int Q(const struct dirent **const First, const struct dirent **const Second) {\n time_t time0 = get_atime((*First)->d_name);\n time_t time1 = get_atime((*Second)->d_name);\n return time1 - time0;\n }\n</code></pre>\n</li>\n<li><p>Of course, <code>Q</code> is not a name for a function. <code>compare_atime</code> perhaps?</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T02:08:48.853",
"Id": "501726",
"Score": "0",
"body": "So you're suggesting to abstract away the process of getting access time? Got it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T02:26:57.387",
"Id": "501727",
"Score": "0",
"body": "Edited my question to reflect this answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T00:11:02.093",
"Id": "254401",
"ParentId": "254398",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-06T23:01:59.910",
"Id": "254398",
"Score": "0",
"Tags": [
"performance",
"c"
],
"Title": "Compare directory entries (sort by access date)"
}
|
254398
|
<p>I am doing C coding practice by reinventing a <code>getline</code> function that works with any streams. Any comments on the overall code quality, including correctness, style and performance, are greatly appreciated.</p>
<p><code>fgetln.h</code>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef FGETLN_H
#define FGETLN_H
#include <stdio.h>
char *fgetln(FILE *fp);
/*
* Read a line from fp, dynamically allocate memory and store it as a string.
* The '\n' at the end of the line and any '\0' before are discarded. Return
* a pointer to the string when successful; return NULL if the line is empty
* or an error occurs.
*
* This function implements the "callee allocates, caller frees" model. You
* should pass the returned pointer to free() when it is no longer needed.
*/
#endif // FGETLN_H
</code></pre>
<p><code>fgetln.c</code>:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#define EXPAND_RATIO 2
// Aggressiveness of memory expansion, must be an integer ≥ 2.
char *fgetln(FILE *fp)
{
signed char c;
// Look for hints of an empty line and discard any '\0' at the start.
while (true) {
c = getc(fp);
if (c == '\0') continue;
if (c == '\n' || c == EOF) return NULL;
break;
}
// If we have reached here, the line has content in it.
ungetc(c, fp);
char *p_tmp, *line = NULL;
size_t arr_size = sizeof(char);
bool end_of_line = false;
unsigned long long i = 0;
p_tmp = realloc(line, arr_size);
if (p_tmp == NULL) goto err_cleanup;
line = p_tmp;
do {
c = getc(fp);
if (c == '\0') continue;
if (c == '\n' || c == EOF) {
end_of_line = true;
c = '\0';
}
if ((i * sizeof(char)) == arr_size) {
if (arr_size == SIZE_MAX) {
if (c != '\0') goto err_cleanup; // Too long
} else {
// Assuming SIZE_MAX % sizeof(char) == 0.
arr_size = arr_size > (SIZE_MAX / EXPAND_RATIO)
? SIZE_MAX
: arr_size * EXPAND_RATIO;
p_tmp = realloc(line, arr_size);
if (p_tmp == NULL) goto err_cleanup;
line = p_tmp;
}
}
line[i++] = c;
} while (!end_of_line);
// Shorten the string to its logical size if available.
size_t logic_size = i * sizeof(char);
if (logic_size < arr_size) {
p_tmp = realloc(line, logic_size);
if (p_tmp == NULL) goto err_cleanup;
line = p_tmp;
}
return line;
err_cleanup:
free(line);
return NULL;
}
#undef EXPAND_RATIO
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T21:49:19.197",
"Id": "501848",
"Score": "0",
"body": "\"The '\\n' at the end of the line and any '\\0' before are discarded.\" deserves clarification. Yes both are _discarded_, yet `'\\0'` does not stop the reading whereas `'\\n'` does. Is that your intent?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T21:53:35.217",
"Id": "501849",
"Score": "0",
"body": "\"... if the line is empty\" would benefit with more info. C line defines _line_ as \"... each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined.\" So a _line_ includes the `'\\n'`. Is your \"line is empty\" is when code reads and get _nothing_, just end-of-file, initially reads a `'\\n'`, and/or something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:49:30.873",
"Id": "501868",
"Score": "0",
"body": "@chux Yes what you described is the intended behavior. What I had in mind is kind of data cleansing. The function reads a __line__ from the stream, where only `\\n` and `EOF` are deemed as line delimiters (the two are also read in as part of the __line__). But if for any reason a `\\0` appears in the middle, I chose to disacrd it and move on because if it's kept mid-array, data behind it becomes inaccessible to `printf(\"%s\")` and some string-handling functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:49:47.990",
"Id": "501869",
"Score": "0",
"body": "@chux Then the processed array, free of `\\0` in the middle, is stored as __a string__, with the `\\n` or `EOF` replaced with a `\\0`. Situations I thought of where the \"line is empty\" include \"[zero or more `\\0`]`EOF`\", \"[zero or more `\\0`]`\\n`\", and __nothing__ at all. Now I see it's conceptually confusing to name the function \"get a line\" while discarding the terminating new-line character. I was bugged by the inconsistency that the tail of the stream may lack an `\\n` at the end while previous lines all have one."
}
] |
[
{
"body": "<p>Excellent comment in the header. It's very important to be clear who owns the returned memory and how to release it. It ought to mention that both newline and <code>\\0</code> are considered as end-of-line characters.</p>\n<p>Good <code>realloc()</code> usage - we don't leak when allocation fails.</p>\n<p>Some small improvements:</p>\n<blockquote>\n<pre><code>#define EXPAND_RATIO 2\n</code></pre>\n</blockquote>\n<p>Why do we need a preprocessor macro for this? I would use a simple <code>static const size_t</code>.</p>\n<blockquote>\n<pre><code>size_t arr_size = sizeof(char);\n</code></pre>\n</blockquote>\n<p><code>sizeof (char)</code> is 1 by definition (since <code>sizeof</code> yields the number of <code>char</code> required for its argument). I wouldn't start with such a small buffer anyway, since almost every line will need several <code>realloc()</code> calls. Start with something sensible, such as 40 (half the width of a standard terminal).</p>\n<blockquote>\n<pre><code>p_tmp = realloc(line, arr_size);\nif (p_tmp == NULL) goto err_cleanup;\nline = p_tmp;\n</code></pre>\n</blockquote>\n<p>Since we know that <code>line</code> is null at this point, we should just use <code>malloc()</code> to be clearer, and eliminate a window where <code>*line</code> is invalid:</p>\n<pre><code>char *line = malloc(arr_size);\nif (!line) return line;\n</code></pre>\n<blockquote>\n<pre><code> if ((i * sizeof(char)) == arr_size) {\n</code></pre>\n</blockquote>\n<p>We can remove the multiplication by 1 from this:</p>\n<pre><code> if (i == arr_size) {\n</code></pre>\n<blockquote>\n<pre><code> if (arr_size == SIZE_MAX) {\n</code></pre>\n</blockquote>\n<p>Ooh, that's very thorough. We're unlikely to have managed to allocate that much memory in a single chunk!</p>\n<blockquote>\n<pre><code> // Assuming SIZE_MAX % sizeof(char) == 0.\n</code></pre>\n</blockquote>\n<p>Again, any number modulo 1 is zero, so that's a truism, not a mere assumption.</p>\n<blockquote>\n<pre><code>#undef EXPAND_RATIO\n</code></pre>\n</blockquote>\n<p>Arguably overkill, given that this is the very end of the translation unit anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T11:20:55.693",
"Id": "501806",
"Score": "2",
"body": "Minor: \"Why do we need a preprocessor macro for this? I would use a simple static const size_t\" --> Then `SIZE_MAX / EXPAND_RATIO` would be a runtime division and not compile time as a `const size_t` object is not _constant_. Some compilers _may_ be understanding though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T11:28:55.367",
"Id": "501807",
"Score": "1",
"body": "\"It ought to mention that both newline and NUL are considered as end-of-line characters.\" is a tad unclear as \"NUL\" is an ASCII code definition (not a C one) and `NULL` is a C one that are often confused with \"NUL\" given their similarity. I'd recommend `'\\0'` or _null character_ or maybe \"NUL\" --> \"ASCII NUL\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T13:27:31.623",
"Id": "254414",
"ParentId": "254404",
"Score": "5"
}
},
{
"body": "<p>Overall, a good and thoughtful effort.</p>\n<p><strong>Bug: Treats character as EOF</strong></p>\n<p>When <code>EOF == -1</code> and code reads a character with the value of 255, the <code>c = getc(fp);</code> likely converts that 255 to -1. Later, the loop incorrectly exits.</p>\n<pre><code>signed char c;\n c = getc(fp);\n if (c == '\\n' || c == EOF) return NULL; // Maybe true for wrong reason\n</code></pre>\n<p>Instead use an <code>int c</code> to well distinguish the 256 (0-255) + 1 (EOF) different responses from <code>getc()</code>.</p>\n<pre><code>// signed char c;\nint c;\n</code></pre>\n<p><strong>Design weakness</strong></p>\n<p>Code should distinguish from reading an empty line and end-of-file. Then the caller can properly distinguish between an empty line and end-of-file. Testing for <code>feof()</code> is insufficient considering the various other reasons for a <code>NULL</code> return.</p>\n<p>OP's design returns <code>NULL</code> for both.</p>\n<pre><code> if (c == '\\n' || c == EOF) return NULL;\n</code></pre>\n<p>Pseudo-code alternative (memory management not shown)</p>\n<pre><code> Read input until \\n of EOF\n if loop end due to EOF and nothing read (or input error), return NULL\n Append \\0\n ...\n</code></pre>\n<p>More: Code returns <code>NULL</code> for 5 conditions (I recommend 3 with a mod):</p>\n<ul>\n<li>Immediate <code>'\\n'</code>. This I recommend to not return <code>NULL</code>.</li>\n<li>Immediate end-of-file: OK</li>\n<li>Immediate input error: I recommend to always return <code>NULL</code> on input error.</li>\n<li>Out of memory (growing): OK</li>\n<li>Out of memory (shrinking): I recommend to return the original pointer - see below.</li>\n</ul>\n<p><strong>Missing include</strong></p>\n<p><code>fgetln.c</code> fails to include <code>fgetln.h</code>. This is important to test for consistency and makefile auto dependency generation. I recommend to include it first before other <code><></code> in this file.</p>\n<p><a href=\"https://codereview.stackexchange.com/questions/254404/beginner-c-fgetline-implementation#comment501870_254427\">Test needed</a> with code using OP's algorithm.</p>\n<p><strong>Minor: Questionable type</strong></p>\n<p><code>unsigned long long i</code> is sufficient as <code>size_t i</code></p>\n<p><strong>Minor: Error exit not needed</strong></p>\n<p>If a memory re-allocation fails when shrinking, code could simply continue.</p>\n<pre><code>if (logic_size < arr_size) {\n p_tmp = realloc(line, logic_size);\n //if (p_tmp == NULL) goto err_cleanup;\n //line = p_tmp;\n if (p_tmp) line = p_tmp;\n}\n</code></pre>\n<p><strong>Non-ASCII code</strong></p>\n<p>Consider using only ASCII for maximum compliance.</p>\n<pre><code>// ... must be an integer ≥ 2.\n... must be an integer >= 2.\n</code></pre>\n<p><strong>Minor: <code>sizeof(type)</code> vs. <code>sizeof(refenced pointer)</code></strong></p>\n<p><code>sizeof(char)</code> is always 1. If code wants to emphasize the size of the referenced pointer, use it directly and avoid the effort to manually match the type.</p>\n<pre><code>char *line = NULL;\n// size_t arr_size = sizeof(char);\nsize_t arr_size = sizeof *line;\n</code></pre>\n<p>This is easier to maintain, should one move code to say <code>wchar_t *line = NULL;</code></p>\n<p><strong>Pedantic: missing check</strong></p>\n<p>Check return of <code>ungetc(c, fp);</code>.</p>\n<p>... or, IMO better, re-write code to not need <code>ungetc()</code>. It is there mainly convenience of the loop.</p>\n<p><strong>Reasonable use of <code>goto</code></strong></p>\n<hr />\n<p>Some sample alternative code. Memory management details only stubbed in.</p>\n<pre><code>void* realloc_grow(size_t *sz, void *s);\nvoid realloc_shrink(size_t *sz, void *s);\n\nchar* fgetln(FILE *fp) {\n unsigned char *s = NULL;\n size_t i = 0;\n size_t sz = 0;\n int ch;\n\n while ((ch = fgetc(fp)) != EOF) {\n if (ch == '\\0') {\n continue;\n }\n if (i + 1 >= sz) {\n if (realloc_grow(&sz, &s) == NULL) {\n free(s);\n return NULL; // OOM\n }\n }\n if (ch == '\\n')\n break;\n s[i++] = (unsigned char) ch;\n }\n\n if (ch == EOF) {\n if (feof(fp)) {\n if (sz == 0) {\n return NULL; // end-of-file with no input\n }\n } else {\n free(s);\n return NULL; // input error\n }\n }\n\n s[i++] = '\\0';\n realloc_shrink(&i, &s);\n return (char*) s;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:47:26.937",
"Id": "501865",
"Score": "0",
"body": "Thank you very much for the detailed comments and sample code! After changing the type of `c` to `int`, a character with the value 255 is able to pass the first `while` loop. But if it would've caused `char` type overflow at the first `while` loop, I figure it will still overflow when being stored because `line` has the type `char *` too and is accordingly `realloc()`ed? Should I change the type of `p_tmp` and `line` to `unsigned char *`, or maybe avoid character types altogether in favor of integer types?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:55:33.807",
"Id": "501870",
"Score": "0",
"body": "As for the __unneeded test__ part, I was thinking of the edge case that the array can only accommodate one more character before its size exceeds `SIZE_MAX`. If `c` happens to be a line delimiter (`\\n` or `EOF`), it is replaced with `\\0` and put in that last slot to form a string. If `c` is anything else (won't be `\\0`, or the loop would've `continue`ed before the replacement), the array cannot both hold it and form a string without exceeding `SIZE_MAX`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:55:40.560",
"Id": "501871",
"Score": "0",
"body": "But now I've noticed the bug in this conditional test. If `i == arr_size == SIZE_MAX`, writing to `line[i]` leads to buffer overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:57:12.057",
"Id": "501872",
"Score": "1",
"body": "@UM-Li \"I figure it will still overflow when being stored because line has the type char * too\" --> _Conversion_, not _overflow_ is your concern here. The issue existed before with `signed char c; ... c = getc(fp);` and reading character 255 and assigning it to a `signed char`. That is the same situation with `line[i++] = c;` (c == 255, `char` is _signed_). When conversion is out of range to a signed integer, the result is implementation defined (ID). Fortunately that is usually simple wrap around and no trouble. To avoid this ID behavior, use `unsigned char` as in my sample code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T02:00:25.957",
"Id": "501874",
"Score": "0",
"body": "@UM-Li ... the re-allocation is not an concern here as the issue is not one of buffer overflow, but out-of-range to char` conversions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T02:01:48.970",
"Id": "501876",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/118231/discussion-between-chux-reinstate-monica-and-um-li)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T23:55:44.700",
"Id": "254427",
"ParentId": "254404",
"Score": "4"
}
},
{
"body": "<p>Overall this isn't a bad effort. I can't see any problems, aside from clobbering the EOF, mostly it's stylistic choices. So good job .</p>\n<h1>Comments go above</h1>\n<p>It's much more common for the comment in a header to be ABOVE the function, rather than below it. This is ok for now as there's only one function, but when you have more it will confuse people.</p>\n<p>If you're going to continue to put it below then you should at least put the function signature in the comment, so that people know which function you're talking about. i.e.</p>\n<pre><code>char *fgetln(FILE *fp);\n/* \n * fgetln:\n * Read a line from fp, dynamically allocate memory and store it as a string.\n</code></pre>\n<p>This is also true for:</p>\n<pre><code>#define EXPAND_RATIO 2\n// Aggressiveness of memory expansion, must be an integer ≥ 2.\n</code></pre>\n<h1>Be precise in your documentation</h1>\n<pre><code>/* \n * Read a line from fp, dynamically allocate memory and store it as a string.\n * The '\\n' at the end of the line and any '\\0' before are discarded. Return\n * a pointer to the string when successful; return NULL if the line is empty\n * or an error occurs.\n *\n * This function implements the "callee allocates, caller frees" model. You\n * should pass the returned pointer to free() when it is no longer needed.\n */\n</code></pre>\n<p>This reads as saying the <code>\\0</code> BEFORE the start of the line are discarded. The actual code discards <em>all</em> <code>\\0</code>!\nThis will confuse some people who expect inner <code>\\0</code> to be preserved.</p>\n<pre><code>/* \n * fgetln:\n * Read from fp until '\\n' or EOF and store it in dynamically allocate memory as a zero-terminated string.\n *\n * The '\\n' at the end of the line is discarded, as are any '\\0' read before the end of the line.\n \n * Return a pointer to the string when successful; \n * Return NULL if the line is empty or an error occurs.\n *\n * This function implements the "callee allocates, caller frees" model. You\n * should pass the returned pointer to free() when it is no longer needed.\n */\n</code></pre>\n<h1>Reading an empty line</h1>\n<pre><code> * a pointer to the string when successful; return NULL if the line is empty\n * or an error occurs.\n \n</code></pre>\n<p>How does a client using your code differentiate between and empty line and an error?\nWhy do you consider an empty line to be so bad? :) Have you considered returning an empty string instead? i.e. <code>return "";</code>?</p>\n<h1>Use the correct return type from standard functions</h1>\n<pre><code>signed char c;\nc = getc(fp);\n</code></pre>\n<p><code>getc</code> is defined as returning an int. You're losing the ability to check for EOF here, as the manual specifically says it returns a char cast as int <strong>or</strong> EOF.</p>\n<p>Also, why specify that the <code>char</code> is <code>signed</code>? What use is that to you in this code? I can't see any checks that rely on the value of <code>c</code> being < 0.</p>\n<pre><code>unsigned long long i = 0;\n</code></pre>\n<p>This should be a <code>size_t</code>, as</p>\n<ol>\n<li>you're using it to hold the sizes of allocations</li>\n<li>you're using it in conjunction with <code>sizeof</code>, which returns <code>size_t</code></li>\n<li>unsigned long long is MASSIVE and probably bigger than <code>size_t</code>, and therefore any valid allocation</li>\n</ol>\n<h1>ungetc</h1>\n<pre><code>// If we have reached here, the line has content in it.\nungetc(c, fp);\n</code></pre>\n<p>Not all streams handle ungetc too well. It's usually better to handle the buffering of the last value yourself. (i.e. invert your loop so that it reads a char at the end of it, and the top of the loop expects a buffered char)</p>\n<p>(Also, the manual for ungetc specifically points out it's going to cast the <code>int</code> into an <code>unsigned char</code>, furthering my confusion about your choice of <code>signed char</code>)</p>\n<h1>Appropriate length variable names</h1>\n<p><code>i</code> is far too short for a variable that:</p>\n<ol>\n<li>Isn't directly a loop counter</li>\n<li>Has a scope that spans 50 lines of code</li>\n</ol>\n<p>Also, <code>i</code> is misleading as it isn't a loop counter, it's a LENGTH. Therefore it should be named <code>length</code> or <code>count</code> or something.</p>\n<h1>Declare variables where they're needed and with the smallest scope</h1>\n<p>This:</p>\n<pre><code>char *p_tmp, *line = NULL;\nsize_t arr_size = sizeof(char);\nbool end_of_line = false;\nunsigned long long i = 0;\n\np_tmp = realloc(line, arr_size);\nif (p_tmp == NULL) goto err_cleanup;\nline = p_tmp;\n</code></pre>\n<p>is better as:</p>\n<pre><code>size_t arr_size = sizeof(char);\nbool end_of_line = false;\nunsigned long long i = 0;\n\nchar *line = NULL;\nchar *p_tmp = realloc(line, arr_size);\nif (p_tmp == NULL) goto err_cleanup;\nline = p_tmp;\n</code></pre>\n<p>This way the p_tmp and line variables are correctly scoped (i.e. they exist for as little as possible) and <em>always</em> have a valid value.</p>\n<p>I would go so far as to say that an even better route is:</p>\n<pre><code>char *p_tmp = realloc(line, arr_size);\nif (p_tmp == NULL) goto err_cleanup_noline; //or just return NULL here\nchar *line = p_tmp;\n</code></pre>\n<p>This way avoids line existing as a null pointer for a while. Thus we can now rememebr that line is ALWAYS non-null.</p>\n<p>Or even just use <code>malloc</code> to begin with, as <code>realloc</code> for a non-existing pointer to a know size is a bit of obfuscation.</p>\n<p>The same goes for <code>c</code>. It's better to declare individual <code>c</code> variables inside each scope rather than a single function-spanning <code>c</code>. This way ensures that no stale data is accidentally used.</p>\n<h1>DRY:</h1>\n<p>Don't repeat yourself</p>\n<pre><code> c = getc(fp);\n if (c == '\\0') continue;\n if (c == '\\n' || c == EOF) {\n end_of_line = true;\n c = '\\0';\n }\n</code></pre>\n<p>This code is identical to the previous block, except that it sets a boolean. This could easily be refactored into a function such as this:</p>\n<pre><code>char strip_until_next_char(bool *end_of_line) {\n while (true) {\n int c = getc(fp);\n if (c == '\\0') continue;\n if (c == '\\n' || c == EOF) {\n *end_of_line = true;\n return '\\0';\n }\n *end_of_line = false;\n return (char) c;\n }\n}\n</code></pre>\n<p>or:</p>\n<pre><code>bool strip_until_next_char(char *out_c) {\n while (true) {\n int c = getc(fp);\n if (c == '\\0') continue;\n if (c == '\\n' || c == EOF) {\n *out_c = '\\0';\n return true;\n }\n *out_c = (char) c;\n return false;\n }\n}\n</code></pre>\n<h1>Spare me the details</h1>\n<p>Ideally, code would read like flowing English. That means it's easy to see what it does at an algorithmic level and we don't have to worry about which bits move where. It also means it's easy to adjust and spot the flaws in it. To do that we can refactor the code into functions that say what they do. Thus:</p>\n<pre><code>do {\n char c;\n end_of_line = strip_until_next_char(&c);\n \n bool ok = ensure_allocation_fits(string_length, &line, &arr_size, end_of_line);\n if (!ok) {\n goto err_cleanup;\n }\n\n line[i++] = c;\n} while (!end_of_line);\n</code></pre>\n<h1>sizeof(char)</h1>\n<p>sizeof returns multiples of char, thus sizeof(char) is defined as being <code>1</code>. It's nice that you're being explicit about the contents of your allocations, but if so I think it'd be best if you did this:</p>\n<pre><code>size_t arr_size = 1 * sizeof(char);\n</code></pre>\n<h1>average case</h1>\n<p>How often do you expect to do strings of size 1?</p>\n<p>Currently you'll go 1, 2, 4, 8. So you'll do 4 reallocs just to get to an average length of a short string. Give that you do a shrink-realloc at the end of your program you might save yourself some time and simply start with an allocation of 100 or something.</p>\n<h1>undef</h1>\n<pre><code>#undef EXPAND_RATIO\n</code></pre>\n<p>This is commendable, but also kind of pointless. Unless you expect the code to be included into something? Importantly though: it's not idiomatic. Most people only <code>undef</code> something when they want to immediately <code>define</code> it again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T18:15:21.527",
"Id": "501832",
"Score": "0",
"body": "Thank you for the review. What type `i` should be still bugs me. My intention was that `i` acts purely as an array **i**ndex as in `line[i++] = c;`. I figured `i` doesn't represent size itself, thus the integer type and occurrences of `i * sizeof(char)` despite it's just \"×1\". Should `i` still be defined as a `size_t`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T02:12:28.357",
"Id": "501877",
"Score": "0",
"body": "\"You're losing the ability to check for EOF here, as the manual specifically says it returns a char cast as int or EOF.\" --> A problem for a different reason. `EOF` is very often -1 and assigning `signed char c = getc(fp);` is not a problem when end-of-file/input error occurs. OTOH reading character 255 likely also results in a -1 saved - losing differentiation from `EOF`. IAC, agree with conclusion: use `int c`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T13:36:40.543",
"Id": "501918",
"Score": "0",
"body": "The function uses an int to represent all chars and EOF. The cast to char is truncation, so you're technically losing the EOF, as that's out of range of the char. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T13:45:31.677",
"Id": "501919",
"Score": "1",
"body": "@UM-Li: a big pain point for me when using C, especially with the POSIX API, is \"which integer should this be??\". There's so many of them and they all need to be used together! Why `size_t` in this case? Imagine if `i` was SIZE_MAX + 1. What would that mean for your program? Is it something you'd want it to be? Note that C will promote SIZE_MAX to unsigned long long in that equality check."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T12:53:57.927",
"Id": "254442",
"ParentId": "254404",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T03:51:36.427",
"Id": "254404",
"Score": "6",
"Tags": [
"beginner",
"c",
"reinventing-the-wheel",
"stream"
],
"Title": "Beginner C fgetline() implementation"
}
|
254404
|
<p>I'm working on a piece of code that remaps a set of signals (1-D integer arrays) onto a set of multi channel samples. I hope the typedefs and the remapping clearifies what I mean. If not, please let me know.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdint.h>
#define SIGNAL_LENGTH 1024
/**
* Multiple linear input signals as read by a previous input stage
*/
typedef struct {
// Mics inside
int32_t micInside0[SIGNAL_LENGTH];
int32_t micInside1[SIGNAL_LENGTH];
int32_t micInside2[SIGNAL_LENGTH];
int32_t micInside3[SIGNAL_LENGTH];
// Mics aux
int32_t micAux0[SIGNAL_LENGTH];
int32_t micAux1[SIGNAL_LENGTH];
int32_t micAux2[SIGNAL_LENGTH];
int32_t micAux3[SIGNAL_LENGTH];
} InputSignals_t;
/**
* Single input struct to be passed to the following filtering stage
*/
typedef struct {
// Mic inside 0
int32_t micInside0a;
int32_t micInside0b;
int32_t micInside0Select;
// Mic inside 1
int32_t micInside1a;
int32_t micInside1b;
int32_t micInside1Select;
// Mic inside 2
int32_t micInside2a;
int32_t micInside2b;
int32_t micInside2Select;
// Mic inside 3
int32_t micInside3a;
int32_t micInside3b;
int32_t micInside3Select;
} FilterSample_t;
/**
* Map the linear input signals to interleved multi-channel filter input signals.
*/
void mapMicFilters(InputSignals_t *inputSignals, FilterSample_t filterSamples[SIGNAL_LENGTH]) {
for(int i = 0; i < SIGNAL_LENGTH; i++) {
FilterSample_t *filterSample = &filterSamples[i];
// I am rather unhappy with the look of the following
// code section where the mapping is done.
// Mic inside 0
filterSample->micInside0a = inputSignals->micInside0[i];
filterSample->micInside0b = 0;
filterSample->micInside0Select = 1;
// Mic inside 1
filterSample->micInside1a = inputSignals->micInside0[i];
filterSample->micInside1b = 0;
filterSample->micInside1Select = 1;
// Mic inside 2
filterSample->micInside2a = inputSignals->micInside0[i];
filterSample->micInside2b = 0;
filterSample->micInside2Select = 1;
// Mic inside 3
filterSample->micInside3a = inputSignals->micInside0[i];
filterSample->micInside3b = 0;
filterSample->micInside3Select = 1;
}
}
</code></pre>
<p>I am rather unhappy with the look of the code section where the mapping is done.The reason for this is that the lines become very long when the signal names become more specific (therefore longer). But a line break within the statements would really mess up the readability:</p>
<pre><code>filterSample->micInside0a =
inputSignals->micInside0[i];
filterSample->micInside0b =
0;
filterSample->micInside0Select =
1;
</code></pre>
<p>Do you have any suggestions on how to format the code? In dynamic languages I would just take a hashmap with the variable names and loop through it. But I have (and want) to use C.</p>
<p>Thank you!</p>
|
[] |
[
{
"body": "<p>Whenever I see (e.g.):</p>\n<pre><code>int foo0, foo1, foo2, foo3, ..., fooN;\n</code></pre>\n<p>I think that can be replaced more cleanly with an <em>array</em>. So, I'd rather have:</p>\n<pre><code>int foo[N];\n</code></pre>\n<p>Thus, I'd change:</p>\n<pre><code>int32_t micInside0[SIGNAL_LENGTH];\n</code></pre>\n<p>(et. al.) into:</p>\n<pre><code>int32_t micInside[4][SIGNAL_LENGTH];\n</code></pre>\n<p>That sort of thing occurs in several more places for different variables as well.</p>\n<hr />\n<p>A good style rule is to use shorter names for argument names and stack/automatic variables [that have shorter scope/duration] and longer names for globals.</p>\n<p>For example: <code>FilterSample_t filterSamples[SIGNAL_LENGTH]</code> is a bit redundant and could be shortened to (e.g.) <code>FilterSample_t fslist[SIGNAL_LENGTH]</code></p>\n<p>Likewise, <code>FilterSample_t *filterSample = &filterSamples[i];</code> is a bit long and could be shortened to: <code>FilterSample_t *fscur = &fslist[i];</code></p>\n<p>To me, the longer names are "too much eye candy".</p>\n<p>Also, with the shorter names, the lines will be shorter, so they're <em>less</em> likely to need to be wrapped to multiple lines [with the indenting].</p>\n<hr />\n<p>If you add an additional <code>struct</code>, you can reorganize/simplify <code>micInside*</code> and <code>micAux*</code>.</p>\n<hr />\n<p>As to the indenting of the second [wrapped] line that <em>you</em> didn't like, personally, I do that 10 times / day. I've found that to be very clean. But, I've been doing that for 20+ years, so I'm used to it.</p>\n<hr />\n<p>Note that you did [for all "X", where "X" is one of 0,1,2,3]:</p>\n<pre><code>filterSample->micInsideXa = inputSignals->micInside0[i];\n</code></pre>\n<p>But, I <em>think</em> that was a <em>typo</em> and you meant to do:</p>\n<pre><code>filterSample->micInsideXa = inputSignals->micInsideX[i];\n</code></pre>\n<hr />\n<p>I realize that school classes teach the use of <code>i</code>, <code>j</code>, etc. But, I've found that more descriptive names can make the code clearer.</p>\n<hr />\n<p>Anyway, I've refactored your code incorporating these ideas.</p>\n<p><em>Caveat:</em> I had some difficulty with the remapping to arrays and I had to guess a bit about some of the relationships. (e.g.) <code>CHANMAX</code> for "max # of channels" was a guess, based on my experience with video and audio processing and seeing "mic" (as in "microphone") and "aux" (as in "auxiliary audio").</p>\n<p>And I may have messed this up by transposing the array indexes, but it should give you an idea of what I'm driving at:</p>\n<pre><code>#include <stdint.h>\n\n#define SIGNAL_LENGTH 1024\n\n#define CHANMAX 4\n\n/**\n* Multiple linear input signals as read by a previous input stage\n*/\ntypedef struct {\n // Mics inside\n int32_t micInside[CHANMAX][SIGNAL_LENGTH];\n\n // Mics aux\n int32_t micAux[CHANMAX][SIGNAL_LENGTH];\n} InputSignals_t;\n\ntypedef struct {\n int32_t mic_a;\n int32_t mic_b;\n int32_t mic_select;\n} micfilter_t;\n\n/**\n* Single input struct to be passed to the following filtering stage\n*/\ntypedef struct {\n micfilter_t filt_micinside[CHANMAX];\n} FilterSample_t;\n\n/**\n* Map the linear input signals to interleved multi-channel filter input signals.\n*/\nvoid\nmapMicFilters(InputSignals_t *inputSignals, FilterSample_t fslist[SIGNAL_LENGTH])\n{\n for (int isamp = 0; isamp < SIGNAL_LENGTH; isamp++) {\n FilterSample_t *fscur = &fslist[isamp];\n InputSignals_t *inpbase = &inputSignals[isamp];\n\n // I am rather unhappy with the look of the following\n // code section where the mapping is done.\n\n for (int ichan = 0; ichan < CHANMAX; ++ichan) {\n micfilter_t *fchan = &fscur->filt_micinside[ichan];\n int32_t *inpcur = inpbase->micInside[ichan];\n fchan->mic_a = inpcur[isamp];\n fchan->mic_b = 0;\n fchan->mic_select = 0;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T10:06:51.477",
"Id": "502322",
"Score": "0",
"body": "I like the loop-y thing. The problem with the indexing is that the numbers do not exactly represent my actual code. I might have abstracted it a bit to generically. There are actual names representing the fixed position of the mics. My guess is, the only way to achieve a loop is an extra relation-datastructure that says something like `{{.from=MIC_ABC, .to=CHANNEL_XYZ}, {.from=MIC_123, .to=CHANNEL_456}}`. That's what I meant by using a hashmap. Maybe I should just give it a try :D Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T06:07:55.313",
"Id": "254686",
"ParentId": "254415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254686",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T13:58:02.563",
"Id": "254415",
"Score": "0",
"Tags": [
"c"
],
"Title": "Remapping of arrays on structs (code style)"
}
|
254415
|
<p>The idea of the code is to count how many elements in testy_L2 are the same with those on testy. So for example, in the first row of conf_matrix we have that 17 elements on testy_L2 are 0., one element is 1., and two elements are 2., so we have 17 correct numbers and 3 wrong numbers for 0. in testy_L2.</p>
<p>What do you think of this code? Is there another way to make it simpler/more elegant?</p>
<pre><code>list_0 = []
a,b,c = 0,0,0
for j in indexes_0[0]:
if testy_L2[j] == 0.0:
a += 1
if testy_L2[j] == 1.0:
b += 1
if testy_L2[j] == 2.0:
c += 1
list_0.append(a)
list_0.append(b)
list_0.append(c)
list_1 = []
a,b,c = 0,0,0
for j in indexes_1[0]:
if testy_L2[j] == 0.0:
a += 1
if testy_L2[j] == 1.0:
b += 1
if testy_L2[j] == 2.0:
c += 1
list_1.append(a)
list_1.append(b)
list_1.append(c)
list_2 = []
a,b,c = 0,0,0
for j in indexes_2[0]:
if testy_L2[j] == 0.0:
a += 1
if testy_L2[j] == 1.0:
b += 1
if testy_L2[j] == 2.0:
c += 1
list_2.append(a)
list_2.append(b)
list_2.append(c)
</code></pre>
<p>Inputs:</p>
<p>testy:</p>
<pre><code>array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
2., 2., 2., 2., 2., 2., 2., 2., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
</code></pre>
<p>testy_L2:</p>
<pre><code>array([0., 0., 0., 1., 1., 0., 1., 0., 0., 1., 0., 1., 0., 0., 1., 1., 1.,
0., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,
2., 2., 2., 2., 2., 2., 2., 2., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 2., 0., 2., 0., 0., 0., 0., 0.])
</code></pre>
<p>Indexes_0, Indexes_1, Indexes_2:</p>
<pre><code>for i in range(len(testy)):
indexes_0, indexes_1, indexes_2 = np.where(testy == 0.0), np.where(testy == 1.0), np.where(testy == 2.0)
</code></pre>
<p>Output:</p>
<p>conf_matrix:</p>
<pre><code>conf_matrix = np.array([list_0,list_1,list_2])
array([[17, 1, 2],
[10, 10, 0],
[ 0, 0, 22]])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T21:12:04.903",
"Id": "501768",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>You have essentially one chunk of code that's duplicated three times:</p>\n<pre><code>list_N = []\na,b,c = 0,0,0\nfor j in indexes_N[0]:\n if testy_L2[j] == 0.0:\n a += 1\n if testy_L2[j] == 1.0:\n b += 1\n if testy_L2[j] == 2.0:\n c += 1\nlist_N.append(a)\nlist_N.append(b)\nlist_N.append(c)\n</code></pre>\n<p>This could be easily wrapped in a function:</p>\n<pre><code>def process_the_stuff(indexes):\n acc = []\n a,b,c = 0,0,0\n for j in indexes[0]:\n if testy_L2[j] == 0.0:\n a += 1\n if testy_L2[j] == 1.0:\n b += 1\n if testy_L2[j] == 2.0:\n c += 1\n acc.append(a)\n acc.append(b)\n acc.append(c)\n return acc\n</code></pre>\n<p>Then just:</p>\n<pre><code>list_0 = process_the_stuff(indexes_0)\nlist_1 = process_the_stuff(indexes_1)\nlist_2 = process_the_stuff(indexes_2)\n</code></pre>\n<hr />\n<p>I'd clean up some other stuff though:</p>\n<ul>\n<li>I'm not a fan of assigning multiple variables on a line in the vast majority of cases. I think <code>a</code>, <code>b</code>, and <code>c</code> should be initially assigned on separate lines.</li>\n<li>The three <code>append</code> calls at the bottom could be cleaned up a bit by using <code>extend</code>, or just simply returning a tuple/list directly.</li>\n<li>All three <code>if</code> checks are necessarily exclusive of each other (since <code>testy_L2[j]</code> can't be equal to <code>0</code>, <code>1</code>, and <code>2</code> at the same time). Those should be <code>elif</code>s instead so that once one is true, the others aren't checked.</li>\n</ul>\n<p>After fixing these things, you'd be left with:</p>\n<pre><code>def process_the_stuff(indexes):\n a = 0\n b = 0\n c = 0\n for j in indexes[0]:\n if testy_L2[j] == 0.0:\n a += 1\n elif testy_L2[j] == 1.0:\n b += 1\n elif testy_L2[j] == 2.0:\n c += 1\n return [a, b, c] # May make more sense to return a tuple instead unless you need a list\n\nlist_0 = process_the_stuff(indexes_0)\nlist_1 = process_the_stuff(indexes_1)\nlist_2 = process_the_stuff(indexes_2)\n</code></pre>\n<hr />\n<p>Minor, but "indexes" should be "indices" for the plural of "index".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T21:54:06.487",
"Id": "501773",
"Score": "0",
"body": "Thank you! Really helpful. And sorry for the 'indexes' for I'm not native english speaker."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T20:06:49.417",
"Id": "254419",
"ParentId": "254417",
"Score": "4"
}
},
{
"body": "<p>Here's code from a well tested library that accomplishes the same thing.</p>\n<p><a href=\"https://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html\" rel=\"nofollow noreferrer\">Documentation</a></p>\n<pre><code>from sklearn.metrics import confusion_matrix\nconf_matrix = confusion_matrix(testy,testy_L2)\n</code></pre>\n<h1>Inline Implementation</h1>\n<p>Without more imports, this can still be achieved with very little code.</p>\n<pre><code>def confusion_matrix(Y_true, Y_predicted):\n matrix = np.zeros((3,3),dtype=int)\n for y_true,y_predicted in zip(\n Y_true.astype('int'), \n Y_predicted.astype('int')\n ):\n matrix[y_true,y_predicted] += 1\n return matrix\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T15:32:34.847",
"Id": "501923",
"Score": "0",
"body": "Thank you, but the idea was to make up with a code to it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T22:52:02.800",
"Id": "254424",
"ParentId": "254417",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254419",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T19:11:42.217",
"Id": "254417",
"Score": "2",
"Tags": [
"python"
],
"Title": "Code to classify elements on np.array on lists"
}
|
254417
|
<p>After reading that <a href="https://refactoring.guru/smells/data-class" rel="nofollow noreferrer">Data Classes can be considered a code smell</a>, I am shifting from a pattern with many data classes and a single manager class that handles all the instantiation of the classes, to a pattern where each data class becomes more like a model and sets its own properties based on sproc calls.</p>
<p>The code as I have written works, but my questions are about:</p>
<ol>
<li><p><code>GetReportDetails()</code> - Is returning an instance of the parent class through a member method problematic for any reason? I know this is used in a Singleton, but this is not a singleton.</p>
</li>
<li><p>The base class exposes only two properties, both of which are connection strings, since I am pulling data from two databases. Is there a better way to handle this?</p>
</li>
<li><p>Any other feedback?</p>
</li>
</ol>
<pre><code>public class ReportDetails : ReportBase
{
private readonly IConfiguration config;
public int CustomReportId { get; private set; }
public int FolderId { get; private set; }
public string FolderName { get; private set; }
public int? ReportTemplateId { get; private set; }
public int PimsUserId { get; private set; }
public string Name { get; private set; }
public string Description { get; private set; }
public bool Active { get; private set; }
public string ProjectName { get; private set; }
public int ProjectId { get; private set; }
public List<AssociatedModule> AssociatedModules { get; private set; }
public AssociatedModule SelectedAssociatedModule { get; private set; }
public List<ReportTemplateName> TemplateNames { get; private set; }
public ReportTemplateName SelectedTemplateName { get; private set; }
public List<ReportFolder> ReportFolders { get; private set; }
public ReportDetails(IConfiguration config) : base(config)
{
this.config = config;
}
public ReportDetails GetReportDetails(int customReportId, int? projectId, string projectName)
{
var inparams = new sproc_CustomReportGetDetailsModifiedVersion_Wrapper.In_Type();
inparams.CustomReportId = customReportId;
var sp = new sproc_CustomReportGetDetailsModifiedVersion_Wrapper(inparams);
_ = DBClient.ExecOn(this.ProjectDBConnectionString).SpCall(sp);
var outrecord = sp.Out.Records[0];
Active = outrecord.Active;
CustomReportId = outrecord.CustomReportId;
Description = outrecord.Description;
FolderId = outrecord.FolderId;
FolderName = outrecord.FolderName;
Name = outrecord.Name;
PimsUserId = outrecord.PimsUserId;
ReportTemplateId = outrecord.ReportTemplateId;
ProjectName = projectName;
ProjectId = Convert.ToInt32(projectId);
AssociatedModules = GetAssociatedModules();
SelectedAssociatedModule = GetSelectedModule();
TemplateNames = GetTemplateNames();
SelectedTemplateName = GetSelectedTemplateName();
ReportFolders = GetReportFolders();
return this;
}
private ReportTemplateName GetSelectedTemplateName()
{
//NOTE: TemplateNames uses "ReportId" as a synonym for ReportTemplateId.
return TemplateNames.Single(e=>e.ReportId == ReportTemplateId);
}
private List<ReportTemplateName> GetTemplateNames()
{
return new ReportTemplateName(config).GetReportTemplateNames(SelectedAssociatedModule.AssociatedModuleId);
}
private AssociatedModule GetSelectedModule()
{
var inparams = new sproc_ReportDetailsGet_Wrapper.In_Type()
{
//NOTE: AssociatedModules uses "ReportID" as a synonym for ReportTemplateId.
ReportId = ReportTemplateId,
};
var sp = new sproc_ReportDetailsGet_Wrapper(inparams);
_ = DBClient.ExecOn(base.ReportDBConnectionString).SpCall(sp);
int assModuleId = sp.Out.Records[0].AssociatedModuleId;
return AssociatedModules.Single(e => e.AssociatedModuleId == assModuleId);
}
private List<AssociatedModule> GetAssociatedModules()
{
return new AssociatedModule(config).GetModuleList();
}
private List<ReportFolder> GetReportFolders()
{
return new ReportFolder(config).GetReportFolderList();
}
}
</code></pre>
<p>The base class is very thin.</p>
<pre><code>public abstract class ReportBase
{
public string ProjectDBConnectionString { get; private set; }
public string ReportDBConnectionString { get; private set; }
public ReportBase(IConfiguration config)
{
ProjectDBConnectionString = config.GetConnectionString("CLIENT_DB");
ReportDBConnectionString = config.GetConnectionString("REPORTING");
}
}
</code></pre>
<p>Previously, a class may look something like this. Note there is no functionality - it is just a collection of properties, I think this is known as a Data Class, and according to the link above, it is generally considered a code smell:</p>
<pre><code>public class ReportDetails
{
public int CustomReportId { get; set; }
public int FolderId { get; set; }
public string FolderName { get; set; }
public int? ReportTemplateId { get; set; }
public int PimsUserId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public bool Active { get; set; }
public string ProjectName { get; set; }
public int ProjectId { get; set; }
public List<AssociatedModule> AssociatedModules { get; set; }
public AssociatedModule SelectedAssociatedModule { get; set; }
public List<ReportTemplateName> TemplateNames { get; set; }
public ReportTemplateName SelectedTemplateName { get; set; }
public List<ReportFolder> ReportFolders { get; set; }
}
</code></pre>
<p>And there would be a manager that would operate on the data class, something like this:</p>
<pre><code> public class ReportDetailsManager
{
public List<ReportDetails> GetReportDetails()
{
// Build and return list of ReportDetails
}
public ReportDetails GetReportDetails(int reportDetailId)
{
ReportDetails reportDetails = new ReportDetails();
// Go to the DB and assign properites
return reportDetails;
}
}
</code></pre>
<p>The crux of the refactor was to move the manager methods into what was formerly just a data class.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T01:56:17.663",
"Id": "501784",
"Score": "2",
"body": "maybe including the old pattern (that you've shifted from) would be helpful to give more helpful thoughts on how much you've gained, and what you can do better. Also, include the base class as well."
}
] |
[
{
"body": "<p>I don't see any code smell in the previous version as data model. The provided article seems to consider data models code smell because it's not enforcing OOP principles, which I understand. However, in real-world code scenarios, data models are very useful and widely used in all programming languages not only in <code>C#</code>. Without them, it will be hard to work with DBMS (database management system), flatten objects, and many other useful scenarios where using data models would add more maintainability to the objects.</p>\n<p>You can take a look on <code>.NET</code> reference code, you will find many data class models that have been used under the hood, and they are maintained by either parent class or another classes.</p>\n<p>In the end, I would say that the previous version is much better in handling than the new one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T15:04:10.597",
"Id": "254486",
"ParentId": "254418",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T19:58:27.327",
"Id": "254418",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"inheritance"
],
"Title": "Builiding a Model from Stored Procedures"
}
|
254418
|
<p>I need some help with the graph and Dijkstra's algorithm in Python 3. I tested this code (look below) at one site and it says to me that the code took too long. Can anybody suggest how to solve that? I don't know how to speed up this code. I read many sites but I didn't find normal examples...</p>
<p>P.S. this is a new code version with deque and something like this, but it's still too slow.</p>
<pre><code>from collections import deque
class node:
def __init__(self, name, neighbors, distance, visited):
self.neighbors = neighbors
self.distance = distance
self.visited = visited
self.name = name
def addNeighbor(self, neighbor_name, dist): # adding new neighbor and length to him
if neighbor_name not in self.neighbors:
self.neighbors.append(neighbor_name)
self.distance.append(dist)
class graph:
def __init__(self):
self.graphStructure = {} # vocabulary with information in format: node_name, [neighbors], [length to every neighbor], visited_status
def addNode(self, index): # adding new node to graph structure
if self.graphStructure.get(index) is None:
self.graphStructure[index] = node(index, [], [], False)
def addConnection(self, node0_name, node1_name, length): # adding connection between 2 nodes
n0 = self.graphStructure.get(node0_name)
n0.addNeighbor(node1_name, length)
n1 = self.graphStructure.get(node1_name)
n1.addNeighbor(node0_name, length)
def returnGraph(self): # printing graph nodes and connections
print('')
for i in range(len(self.graphStructure)):
nodeInfo = self.graphStructure.get(i + 1)
print('name =', nodeInfo.name, ' neighborns =', nodeInfo.neighbors, ' length to neighborns =', nodeInfo.distance)
def bfs(self, index): # bfs method of searching (also used Dijkstra's algorithm)
distanceToNodes = [float('inf')] * len(self.graphStructure)
distanceToNodes[index - 1] = 0
currentNode = self.graphStructure.get(index)
queue = deque()
for i in range(len(currentNode.neighbors)):
n = currentNode.neighbors[i]
distanceToNodes[n - 1] = currentNode.distance[i]
queue.append(n)
while len(queue) > 0: # creating queue and visition all nodes
u = queue.popleft()
node_u = self.graphStructure.get(u)
node_u.visited = True
for v in range(len(node_u.neighbors)):
node_v = self.graphStructure.get(node_u.neighbors[v])
distanceToNodes[node_u.neighbors[v] - 1] = min(distanceToNodes[node_u.neighbors[v] - 1], distanceToNodes[u - 1] + node_u.distance[v]) # update minimal length to node
if not node_v.visited:
queue.append(node_u.neighbors[v])
return distanceToNodes
def readInputToGraph(graph): # reading input data and write to graph datatbase
node0, node1, length = map(int, input().split())
graph.addNode(node0)
graph.addNode(node1)
graph.addConnection(node0, node1, length)
def main():
newGraph = graph()
countOfNodes, countOfPairs = map(int, input().split())
if countOfPairs == 0:
print('0')
exit()
for _ in range(countOfPairs): # reading input data for n(countOfPairs) rows
readInputToGraph(newGraph)
# newGraph.returnGraph() # printing information
print(sum(newGraph.bfs(1))) # starting bfs from start position
main()
</code></pre>
<p>The input graph structure may look like this:</p>
<pre><code>15 17
3 7 2
7 5 1
7 11 5
11 5 1
11 1 2
1 12 1
1 13 3
12 10 1
12 4 3
12 15 1
12 13 4
1 2 1
2 8 2
8 14 1
14 6 3
6 9 1
13 9 2
</code></pre>
<p>I'm only learning python so I think I may be doing something wrong.</p>
|
[] |
[
{
"body": "<ol>\n<li><p>Making an <strong>str</strong>(which makes a string from an object) for the node class which would simplify the graph return method<br />\nthe <strong>str</strong> converts an object to a string type</p>\n</li>\n<li><p>is this a dense graph or sparse graph?\nSparse Graphs have a lot less edges between vertices\nSparse Graphs can be efficently used as adjency lists\nDense Graphs can be efficnetly represented with an adjency matrix (2d list of bool)\nNote: if you are familar with binary, you can use an int to set and get bits in Python (more space efficent than 2d list)</p>\n</li>\n<li><p>I would suggest a new class for what to do when the algorithm reaches a node (such as NodeVisit)\nThis new class can a function called <strong>call</strong>(node) and run as object(the_node)\nThis allows diffrent code to run on node such as print out or add distances along a path</p>\n</li>\n<li><p>Dijkstra's algorithm has a lower Big O with a min priority que\nMin priority ques are similar to real life lines with priority levels and tasks\nThis can be made from a list where left_row is 2 * row and right_row is (2 * row) + 1</p>\n</li>\n<li><p>Make a seperate function or even class for Dijkstra's algorithm\nDijkstra's algorithm can be done using parallel lists for vertex, distance, prev vertex\nLooking up the wikipedia article for Dijkstra's Algorithm shows its psudo code</p>\n<ol start=\"6\">\n<li>If you plan to use node anywhere else then make self.visited a parallel array and not inside the node class\nAnother situation where int and binary can be used for space efficency</li>\n</ol>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T07:52:28.147",
"Id": "501798",
"Score": "0",
"body": "Hello! Thanks for the answer) I'll look for all problems you described )\n3.I'll look at how to do that) But can l print a node name in the loop instead of the new function?\nI will change the code looking at your answer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T17:35:06.543",
"Id": "501931",
"Score": "0",
"body": "print(str(the_node))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T19:07:36.153",
"Id": "501933",
"Score": "0",
"body": "str(node) calls the __str__ function on the node class. print(str(node)) outputs that str to the command line."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T23:43:09.513",
"Id": "254426",
"ParentId": "254420",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T20:24:28.857",
"Id": "254420",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"graph"
],
"Title": "Dijkstra's algorithm in graph (Python)"
}
|
254420
|
<p>While working on a much more complicated audio application, I was thinking about <a href="https://en.wikipedia.org/wiki/Modular_synthesizer" rel="noreferrer">modular synthesizers</a>, and whether it could be made simple to build a C++ application that implemented a modular synthesizer in a way that feels just as easy as connecting the various modules of a real modular synthesizer. The basic trick I used is that almost everything derives from a base class <code>Module</code>, which registers the object in a global registry. Every class that derives from <code>Module</code> must also implement a function <code>update()</code> that will update all its output values.</p>
<p>There is a class <code>Speaker</code> that, when updated, will in effect cause samples to be written to the sound card. I'm using <a href="https://www.libsdl.org/" rel="noreferrer">SDL</a> to handle audio in a platform independent way, and it also requires surprisingly little code to get going.</p>
<p>Apart from that, there are modules for <a href="https://en.wikipedia.org/wiki/Voltage-controlled_oscillator" rel="noreferrer">VCOs</a>, <a href="https://en.wikipedia.org/wiki/Variable-gain_amplifier" rel="noreferrer">VCAs</a> and <a href="https://en.wikipedia.org/wiki/Voltage-controlled_filter" rel="noreferrer">VCFs</a> (although instead of voltage controlled I guess they are "value controlled"), an <a href="https://en.wikipedia.org/wiki/Envelope_(music)" rel="noreferrer">envelope generator</a> and a very basic <a href="https://en.wikipedia.org/wiki/Music_sequencer" rel="noreferrer">sequencer</a>.</p>
<p>In the code below I have two ways of "wiring" the modules:</p>
<ol>
<li>The synthesizer itself is a <code>Module</code> consisting of several submodules, the latter are implemented as member variables. The <code>update()</code> function implements the wires, by just copying values from outputs of the various submodules to inputs of other modules.</li>
<li>There is a <code>class Wire</code> that is a <code>Module</code> itself, the parameters are two references, and in its <code>update()</code> function it just copies from one reference to another.</li>
</ol>
<p>I do know that the code is very inefficient, that is largely a consequence of the design. However I am interested in hearing whether any performance improvements are possible without requiring large changes in the design.</p>
<p>I am also interested whether you think this code is good from an educational perspective: is it fun to create something with this code? Does it teach you good and/or bad things about modular synthesizers and about C++?</p>
<p>The code is very basic, it could be made more robust by creating separate classes for input values and output values, perhaps also distinguishing between values that represent amplitudes, frequencies, trigger signals and so on. On the other hand, with modular synthesizers all jacks are also the same shape and the cables don't care what they connect to.</p>
<p>The code below can also be found on <a href="https://github.com/gsliepen/modsynth" rel="noreferrer">GitHub</a> and <a href="https://gitlab.com/gsliepen/modsynth" rel="noreferrer">GitLab</a>.</p>
<p>example.cpp:</p>
<pre><code>#include "modsynth.h"
#include <iostream>
using namespace ModSynth;
static struct Example: Module {
// Components
VCO clock{4};
Sequencer sequencer{
"C4", "E4", "G4", "C5",
"D4", "F4", "A4", "D5",
"Bb3", "D4", "F4", "Bb4",
"F5", "C5", "A4", "F4",
};
VCO vco;
Envelope envelope{0.01, 1, 0.1};
VCA vca;
Speaker speaker;
// Routing signals using the update() function
void update() {
sequencer.clock_in = clock.square_out;
envelope.gate_in = sequencer.gate_out;
vco.frequency = sequencer.frequency_out;
vca.amplitude = envelope.amplitude_out;
vca.audio_in = vco.triangle_out;
speaker.left_in = vca.audio_out;
speaker.right_in = vca.audio_out;
}
} example;
int main() {
// Components
VCO clock{1};
Sequencer sequencer{"C2", "D2", "Bb1", "F1"};
VCO vco;
VCF vcf{0, 3};
VCA vca{2000};
Envelope envelope{0.1, 1, 0.1};
Speaker speaker;
// Routing signals using Wire objects
Wire wires[]{
{sequencer.clock_in, clock.square_out},
{envelope.gate_in, sequencer.gate_out},
{vco.frequency, sequencer.frequency_out},
{vca.audio_in, envelope.amplitude_out},
{vcf.cutoff, vca.audio_out},
{vcf.audio_in, vco.sawtooth_out},
{speaker.left_in, vcf.lowpass_out},
{speaker.right_in, vcf.lowpass_out},
};
std::cout << "Press enter to exit...\n";
std::cin.get();
}
</code></pre>
<p>modsynth.h:</p>
<pre><code>#pragma once
#include <initializer_list>
#include <string>
#include <vector>
namespace ModSynth {
// Base class for all modules
struct Module {
Module();
Module(const Module &other) = delete;
Module(Module &&other) = delete;
virtual ~Module();
virtual void update() = 0;
};
// Sources
struct VCO: Module {
// Parameters
float frequency{}; // Hz
// Audio output
float sawtooth_out{-1}; // -1..1 output
float sine_out{};
float square_out{1};
float triangle_out{};
VCO() = default;
VCO(float frequency): frequency(frequency) {}
void update();
};
struct Envelope: Module {
// Trigger input
float gate_in{}; // > 0 triggers attack
// Parameters
float attack{}; // seconds
float decay{}; // seconds/halving
float release{}; // seconds/halving
// Output
float amplitude_out{}; // 0..1
Envelope() = default;
Envelope(float attack, float decay, float release): attack(attack), decay(decay), release(release) {}
void update();
private:
// Internal state
enum {
ATTACK,
DECAY,
RELEASE,
} state;
};
// Modifiers
struct VCA: Module {
// Audio input
float audio_in{};
// Parameters
float amplitude{};
// Audio output
float audio_out{};
VCA() = default;
VCA(float amplitude): amplitude(amplitude) {}
void update();
};
struct VCF: Module {
// Audio input
float audio_in{};
// Parameters
float cutoff{}; // Hz
float resonance{}; // dimensionless,
// Audio output
float lowpass_out{};
float bandpass_out{};
float highpass_out{};
VCF() = default;
VCF(float cutoff, float resonance): cutoff(cutoff), resonance(resonance) {}
void update();
};
// Sequencer
struct Sequencer: Module {
// Trigger input
float clock_in{}; // > 0 triggers next note
// Parameters
std::vector<float> frequencies; // Hz
// Output
float frequency_out; // Hz
float gate_out;
Sequencer(std::initializer_list<std::string> notes);
void update();
private:
// Internal state
std::size_t index;
};
// Sinks
struct Speaker: Module {
// Audio input
float left_in{};
float right_in{};
void update();
};
// Connections
struct Wire: Module {
// Value input
float &input;
// Value output
float &output;
Wire(float &output, float &input): input(input), output(output) {}
void update();
};
}
</code></pre>
<p>modsynth.cpp:</p>
<pre><code>#include "modsynth.h"
#include <algorithm>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include <mutex>
#include <SDL2/SDL.h>
namespace ModSynth {
// Module registry
static std::vector<Module *> modules;
static std::mutex mutex;
Module::Module() {
std::lock_guard<std::mutex> lock(mutex);
modules.push_back(this);
}
Module::~Module() {
std::lock_guard<std::mutex> lock(mutex);
modules.erase(std::find(modules.begin(), modules.end(), this));
}
// Audio output
static struct Audio {
static float left;
static float right;
static void callback(void *userdata, uint8_t *stream, int len) {
std::lock_guard<std::mutex> lock(mutex);
float *ptr = reinterpret_cast<float *>(stream);
for (size_t i = 0; i < len / sizeof ptr; i++) {
left = 0;
right = 0;
for (auto mod: modules) {
mod->update();
}
// Make the output a bit softer so we don't immediately clip
*ptr++ = left * 0.1;
*ptr++ = right * 0.1;
}
}
Audio() {
SDL_Init(SDL_INIT_AUDIO);
SDL_AudioSpec desired{};
desired.freq = 48000;
desired.format = AUDIO_F32;
desired.channels = 2;
desired.samples = 128;
desired.callback = callback;
if (SDL_OpenAudio(&desired, nullptr) != 0) {
throw std::runtime_error(SDL_GetError());
}
SDL_PauseAudio(0);
}
} audio;
float Audio::left;
float Audio::right;
const float dt = 1.0f / 48000;
const float pi = 4.0f * std::atan(1.0f);
// Sources
void VCO::update() {
float phase = sawtooth_out * 0.5f - 0.5f;
phase += frequency * dt;
phase -= std::floor(phase);
sawtooth_out = phase * 2.0f - 1.0f;
sine_out = std::sin(phase * 2.0f * pi);
square_out = std::rint(phase) * -2.0f + 1.0f;
triangle_out = std::abs(phase - 0.5f) * 4.0f - 1.0f;
}
void Envelope::update() {
if (gate_in <= 0.0f) {
state = RELEASE;
} else if (state == RELEASE) {
state = ATTACK;
}
switch (state) {
case ATTACK:
amplitude_out += dt / attack;
if (amplitude_out >= 1.0f) {
amplitude_out = 1.0f;
state = DECAY;
}
break;
case DECAY:
amplitude_out *= std::exp2(-dt / decay);
break;
case RELEASE:
amplitude_out *= std::exp2(-dt / release);
break;
}
}
// Modifiers
void VCA::update() {
audio_out = audio_in * amplitude;
}
void VCF::update() {
float f = 2.0f * std::sin(std::min(pi * cutoff * dt, std::asin(0.5f)));
float q = 1.0f / resonance;
lowpass_out += f * bandpass_out;
highpass_out = audio_in - q * bandpass_out - lowpass_out;
bandpass_out += f * highpass_out;
}
// Sequencer
Sequencer::Sequencer(std::initializer_list<std::string> notes) {
static const std::map<std::string, int> base_notes = {
{"Cb", -1}, {"C", 0}, {"C#", 1},
{"Db", 1}, {"D", 2}, {"D#", 3},
{"Eb", 3}, {"E", 4}, {"E#", 5},
{"Fb", 4}, {"F", 5}, {"F#", 6},
{"Gb", 6}, {"G", 7}, {"G#", 8},
{"Ab", 8}, {"A", 9}, {"A#", 10},
{"Bb", 10}, {"B", 11}, {"B#", 12},
};
for (auto &note: notes) {
auto octave_pos = note.find_first_of("0123456789");
auto base_note = base_notes.at(note.substr(0, octave_pos));
auto octave = std::stoi(note.substr(octave_pos));
frequencies.push_back(440.0f * std::exp2((base_note - 9) / 12.0f + octave - 4));
}
index = frequencies.size() - 1;
}
void Sequencer::update() {
if (clock_in > 0 && !gate_out) {
index++;
index %= frequencies.size();
}
frequency_out = frequencies[index];
gate_out = clock_in > 0;
}
// Sinks
void Speaker::update() {
audio.left += left_in;
audio.right += right_in;
}
// Connections
void Wire::update() {
output = input;
}
}
</code></pre>
<p>This can be compiled using this command on most operating systems, assuming the SDL2 library and headers are installed:</p>
<pre><code>c++ -o example example.cpp modsynth.cpp -lSDL2
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T20:39:23.423",
"Id": "501968",
"Score": "0",
"body": "I think only you can answer _is it fun to create something with this code_."
}
] |
[
{
"body": "<p>This was fun code to play with and to review. I haven't played with a modular synth for about forty years. Here are some things that may help you improve your code.</p>\n<h2>Consider hiding data</h2>\n<p>Right now everything's public in every <code>Module</code> but it's not clear that's a good thing. For example, any 70's vintage synth should have a <code>Phaser</code> so I implemented this one:</p>\n<pre><code>struct Phaser: Module {\n // Audio input\n float audio_in{};\n \n // Parameters\n unsigned limit{};\n\n // Audio output\n float audio_out{};\n\n Phaser() = default;\n Phaser(unsigned limit): limit(limit) {}\n void update();\n\nprivate:\n // internal structure\n std::deque<float> delay;\n};\n\nvoid Phaser::update() {\n delay.push_back(audio_in);\n audio_out = audio_in + delay.front();\n if (delay.size() >= limit) {\n delay.pop_front();\n } \n}\n</code></pre>\n<p>I made the delay line <code>private</code> because there's typically no input directly into the delay line of such a component. It's possible that other <code>Module</code>s may also benefit from that.</p>\n<h2>Use all required <code>#include</code>s</h2>\n<p>The code uses <code>std::exp2</code> so it should have <code>#include <cmath></code>.</p>\n<h2>Consider using templates</h2>\n<p>A <code>float</code> is probably fine for this purpose, but one could imaging implementing this on, say, an 8-bit microcontroller in which an <code>int</code> might be more appropriate (if lower fidelity!). Templating that parameter would be a simple way to accommodate either.</p>\n<h2>Use <code>override</code> where appropriate</h2>\n<p>The <code>update()</code> function is very important for all modules. I'd be inclined to mark that function <code>override</code> to help the compiler identify if anyone inadvertently declared an <code>update()</code> function with the wrong prototype.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef MODSYNTH_H\n#define MODSYNTH_H\n// file contents go here\n#endif // MODSYNTH_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n<h2>Consider a more granular approach</h2>\n<p>I don't know about your speakers but mine are single channel devices. That is I have a left channel and a right channel, but they go to two different physical devices. I'd suggest making the <code>Speaker</code> a mono object, so you don't limit to stereo. You might want <a href=\"https://en.wikipedia.org/wiki/5.1_surround_sound\" rel=\"nofollow noreferrer\">5.1 surround sound</a> for example. Also, I would consider creating separate classes for <code>VCO_sine</code>, <code>VCO_square</code>, etc. to make the system even more modular.</p>\n<h2>Consider abstracting out a musical note class</h2>\n<p>I'd suggest that rather than burying it within the <code>Sequencer</code> class, the notion of mapping from a note to a frequency is sufficiently central to most music that it warrants a separate class. Further, judicious use of a <a href=\"https://en.cppreference.com/w/cpp/language/user_literal\" rel=\"nofollow noreferrer\">user defined literal</a> would allow you to freely intermix frequency in Hertz or musical notation and have all functions use frequency in Hertz.</p>\n<p>Here's a <code>constexpr</code> implementation of a user-defined literal for this purpose:</p>\n<pre><code>constexpr float operator "" _note(const char *ch, std::size_t ) {\n int base_note{0};\n switch (*ch++) {\n case 'C':\n base_note = -9;\n break;\n case 'D':\n base_note = -7;\n break;\n case 'E':\n base_note = -5;\n break;\n case 'F':\n base_note = -4;\n break;\n case 'G':\n base_note = -2;\n break;\n case 'A':\n base_note = 0;\n break;\n case 'B':\n base_note = 2;\n break;\n default:\n throw std::range_error("Note must be within A-G inclusive");\n }\n if (*ch == 'b') {\n --base_note;\n ++ch;\n } else if (*ch == '#') {\n ++base_note;\n ++ch;\n }\n auto octave{std::atoi(ch)};\n return 440.0f * std::exp2(base_note / 12.0f + octave - 4);\n}\n</code></pre>\n<p>This greatly simplifies the <code>Sequencer</code> constructor:</p>\n<pre><code>Sequencer::Sequencer(std::initializer_list<float> notes) \n : frequencies{notes}\n , index{frequencies.size() - 1}\n{}\n</code></pre>\n<p>Example use within <code>main</code>:</p>\n<pre><code>Sequencer sequencer{"C3"_note, "D3"_note, "Bb2"_note, "F2"_note};\n</code></pre>\n<h2>Eliminate unused data</h2>\n<p>I understand that the <code>userdata</code> parameter of the <code>Audio::callback</code> function is actually specified by the SDL library, but at the moment, it just generates an annoying compiler warning about an unused parameter. I'd suggest omitting the name until/unless you actually use the parameter. This may still generate a warning from picky compilers, but at least it would be apparent that the omission is deliberate.</p>\n<h2>Wire we here? (Sorry for the terrible pun!)</h2>\n<p>Since you've asked, the <code>Wire</code> class seems a bit contrived. Also, there's not much use in instantiating a module unless it actually eventually gets wired to a speaker output. If you further decided to break things into more modular chunks as I've suggested above, perhaps the <code><<</code> operator could be abused for this purpose. You might write:</p>\n<pre><code>left_speaker << phaser << sawtooth << sequencer;\n</code></pre>\n<p>This very clearly shows the connections and would be quite natural in style. I realize that some devices (like the sequencer) have multiple inputs and outputs, but it's not a huge leap to imagine how one might write that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T18:49:21.340",
"Id": "501833",
"Score": "0",
"body": "Thanks for the review, glad you had fun :) One question though, what felt better to wire the module together? The `update()` method or the `Wire` class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T18:52:19.883",
"Id": "501834",
"Score": "0",
"body": "For me, both the `update()` and `Wire` classes seemed a bit awkward (not least because I'd reverse the order of the latter so that it reads `{from, to}` but an obvious extension of this would be to make a GUI representation so a `Wire` class might be more appropriate if that's the direction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T18:55:33.263",
"Id": "501835",
"Score": "0",
"body": "I don't think I will go the GUI route with this. The goal was to make it as easy as possible to *program* a modular synth in C++. Do you think there is a better or less awkward way to write the modules together (besides fixing the order of the constructor parameters)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T19:04:44.317",
"Id": "501836",
"Score": "1",
"body": "I've updated my answer to try to address that."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T18:36:55.117",
"Id": "254459",
"ParentId": "254421",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "254459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T22:03:14.593",
"Id": "254421",
"Score": "7",
"Tags": [
"c++",
"c++11",
"audio",
"sdl"
],
"Title": "Modular synthesizer framework for C++"
}
|
254421
|
<p>I know the following code are horrible, so I'd like a review. Criticism are welcome. I want to know what went wrong, and how I can avoid the same mistake in the future.</p>
<hr />
<p>Version 1</p>
<pre><code>const unsigned int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
for (int i = 1; i < argc; ++i) {
unsigned long tmp;
try { tmp = std::stoul(argv[i], nullptr, 10); }
catch (std::invalid_argument) { std::cerr << "Invalid base! Conversion failed.\n"; return -2; }
catch (std::out_of_range) { std::cerr << "Invalid base! Too large.\n"; return -2; }
if (tmp > std::numeric_limits<unsigned int>::max()) { std::cerr << "Invalid base! Too large.\n"; return -2; }
if (tmp < 2) { std::cerr << "Invalid base! Must at least be 2.\n"; return -2; }
if (tmp > set_max) { std::cerr << "Invalid base! Must be within " << set_max << ".\n"; return -2; }
base.push_back(static_cast<unsigned int>(tmp));
}
</code></pre>
<hr />
<p>Version 2</p>
<pre><code>const int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
try { for (int i = 1; i < argc; ++i) {
unsigned long tmp; try { tmp = std::stoul(argv[i], nullptr, 0); }
catch (std::invalid_argument ) { throw std::string("Conversion failed" ); }
catch (std::out_of_range ) { throw std::string("Too large" ); }
if (tmp > std::numeric_limits<unsigned int>::max()) { throw std::string("Too large" ); }
if (tmp < 2 ) { throw std::string("Must at least be 2" ); }
if (tmp > set_max ) { throw std::string("Must be within " + std::to_string(set_max)); }
base.push_back(static_cast<unsigned int>(tmp));
} } catch (std::string &err_msg) { std::cerr << "Invalid base! " << err_msg << ".\n"; return -2; }
</code></pre>
<hr />
<p>Version 3</p>
<pre><code>const int set_max {32};
std::vector<unsigned int> base;
base.reserve(argc-1);
for (int i = 1; i < argc; ++i) {
unsigned long tmp;
try {
try {
tmp = std::stoul(argv[i], nullptr, 0);
}
catch (std::invalid_argument) {
throw std::string("Conversion failed");
}
catch (std::out_of_range) {
throw std::string("Too large");
}
if (tmp > std::numeric_limits<unsigned int>::max()) {
throw std::string("Too large");
}
if (tmp < 2) {
throw std::string("Must at least be 2");
}
if (tmp > set_max) {
throw std::string("Must be within " + std::to_string(set_max));
}
}
catch (std::string &err_msg) {
std::cerr << "Invalid base! " << err_msg << ".\n";
return -2;
}
base.push_back(static_cast<unsigned int>(tmp));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T22:27:42.587",
"Id": "501777",
"Score": "3",
"body": "It looks like this code is part of a function, maybe include the whole function instead of just (part of) the function body? What is the code supposed to do exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T22:33:12.550",
"Id": "501778",
"Score": "0",
"body": "@G.Sliepen It's part of the main function. It is parsing arguments given to the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T22:40:00.133",
"Id": "501779",
"Score": "0",
"body": "There isn't really anything else right now in my main function body. These code are literally taken as is, just without the function head and the end curly bracket."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T12:21:22.670",
"Id": "501813",
"Score": "2",
"body": "Please include the entire main function with the header files. Does the code work as expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T11:26:52.760",
"Id": "501903",
"Score": "0",
"body": "`I want to know what went wrong` have mercy on the maintenance programmer."
}
] |
[
{
"body": "<h2>Readability</h2>\n<ul>\n<li><p>Version 1:<br />\nThis is unreadable. If you presented that me in a professional context I would literally fire you (for real).</p>\n</li>\n<li><p>Version 2:<br />\nThis is arguably readable. But you are making it hard for yourself and other people. You are probably going to be breaking your companies coding guidelines and I can see your colleagues complain. But its all subjective. I would not like you if we were working on the same code base.</p>\n</li>\n<li><p>Version 3:<br />\nThis is a reasonable readable version.</p>\n</li>\n</ul>\n<h2>Code Review</h2>\n<p>Your use of exceptions is a bit much. Exceptions are great when you can not correct the problem at the point of the error and need to transfer control to a higher level context and thus can take a reasonable action based on context.</p>\n<p>Here you are throwing exceptions and catching them in the same function (i.e you are not moving to a higher context). It's not terrible, but you can achieve the same effect with error codes (and the error codes do not cross an interface boundary so are OK). I am not going to argue for error codes or against them. In this case that is a style thing and how your team likes to handle the situation.</p>\n<p>The only issue I have is that exception that are throw can potentially change over time, and you don't catch the any (<code>catch (...)</code>) and thus can potentially have an accidental application termination with no error message.</p>\n<p>I don't know how many arguments this takes. But it exits on the first parameter error. You may want to check all the parameters and generate more errors (if possible). This potentially will allow the user to fix all the parameters at once rather than having to run the application multiple times fixing one parameter at a time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T03:17:49.477",
"Id": "502384",
"Score": "0",
"body": "Thank you for your detailed walkthrough. Sorry for the late reply."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T18:33:04.530",
"Id": "254458",
"ParentId": "254422",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T22:08:08.880",
"Id": "254422",
"Score": "0",
"Tags": [
"c++",
"c++11",
"error-handling"
],
"Title": "C++ Error/exception handling"
}
|
254422
|
<p>I created an algorithm to solve in synthetic geometry. This problem states that these points are a scalar (real) number. The goal is to first make the possible triangles from the line segments. Then sum up the points within the triangles. For this question, ordering does not matter within the triangle.</p>
<p>I would like to know if there are any improvements possible on the algorithm. For example, if there is a Las Vegas Algorithm for it.</p>
<p>Also, I would like to know if I should make classes or is this even less maintainable than using built-in data structures.</p>
<pre><code>
"""
Triangle sums module
module fn
make_triangles(the_lines: [(float, float)]) -> [(float, float, float)]
total_triangles(the_triangles: [(float, float, float)]) -> [float]
user_output(the_sums: [float]) -> None
"""
"""
Problem
Given:
Our points are made of a single float
These points are made into tuples within a list
Find:
the triangles within the points
The sum of the points on the triangle
Note: the triangles have no distinct ordering in the points
"""
def make_triangles(the_lines: [(float, float)]) -> [(float, float, float)]:
"""
:param the_lines: the lines to make triangles from
:return: the triangles
time: O(len(the_lines) * len(the_lines)
space: O(len(the_lines) * len(the_lines))
"""
the_triangles: [(float, float, float)] = []
for pair_a in the_lines:
for pair_b in the_lines:
if pair_a == pair_b:
continue
if pair_a[0] == pair_b[0]:
the_triangles.append((pair_a[0], pair_a[1], pair_b[1]))
elif pair_a[0] == pair_b[1]:
the_triangles.append((pair_a[0], pair_a[1], pair_b[0]))
return the_triangles
def total_triangles(the_triangles: [(float, float, float)]) -> [float]:
"""
:param the_triangles: the triangles of points to add up
:return: a list of the totals
time: O(len(the_triangles))
space: O(len(the_triangles))
"""
vec: [float] = [0.0] * len(the_triangles)
for row in range(len(vec)):
vec[row] = the_triangles[row][0] + the_triangles[row][1] + the_triangles[row][2]
return vec
def user_output(the_sums: [float]) -> None:
"""
:param the_sums: the calculated sums
:return: None
Output: std output
"""
row = 0
for number in the_sums:
if row % 3 == 0:
print('', end='\n')
print(str(number), end=" ")
row = row + 1
print('\n', end='')
def main() -> None:
"""
Entry point for script
:return: None
Input: None
Output: std output
"""
the_lines = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]
the_triangles = make_triangles(the_lines)
the_sums = total_triangles(the_triangles)
user_output(the_sums)
if __name__ == "__main__":
main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Here's my attempt at trimming it down. Note that there's no real reason to prefix variables with <code>the_</code>. Also list comprehensions can help with making code more concise, removing the need for <code>total_triangles()</code> entirely.</p>\n<pre><code>def make_triangles(lines: [(float, float)]) -> [(float, float, float)]:\n """\n :param lines: the lines to make triangles from\n :return: the triangles\n time: O(len(lines) * len(lines)\n space: O(len(lines) * len(lines))\n """\n triangles: [(float, float, float)] = []\n for ax, ay in lines:\n for bx, by in lines:\n if ax == bx and ay != by:\n triangles.append((ax, ay, by))\n if ax == by and ax != bx:\n triangles.append((ax, ay, bx))\n return triangles\n\n\ndef print_sums(sums: [float]) -> None:\n """\n :param the_sums: the calculated sums\n :return: None\n Output: std output\n """\n row = 0\n for number in sums:\n if row % 3 == 0:\n print('', end='\\n')\n print(str(number), end=" ")\n row = row + 1\n print('\\n', end='')\n\n\ndef main() -> None:\n """\n Entry point for script\n :return: None\n Input: None\n Output: std output\n """\n lines = [(0.0, 1.0), (1.0, 2.0), (2.0, 3.0)]\n triangles = make_triangles(lines)\n sums = [ sum(triangle) for triangle in triangles ]\n print_sums(sums)\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T00:01:27.813",
"Id": "254428",
"ParentId": "254423",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254428",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-07T22:40:22.020",
"Id": "254423",
"Score": "2",
"Tags": [
"algorithm",
"python-3.x"
],
"Title": "Combinatorial Geometry Algorithm (synthetic)"
}
|
254423
|
<p>Small Calculator I made for myself while trying to learn COBOL for fun. Compiler used is GNUCOBOL. Just asks for input and will either do multiplication, subtraction, or addition. Completes run after input is asked.</p>
<pre><code>MATH
IDENTIFICATION DIVISION.
PROGRAM-ID. MATH.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 INP PIC A(14).
01 NUM1 PIC 9(7).
01 NUM2 PIC A(2).
88 PLU VALUE "+".
88 AIDS VALUE "-".
88 MULT VALUE "*".
01 NUM3 PIC 9(15).
01 ANS PIC 9(8).
PROCEDURE DIVISION.
DISPLAY "Input: "
ACCEPT INP.
UNSTRING INP DELIMITED BY SPACE
INTO NUM1, NUM2, NUM3
END-UNSTRING.
IF NUM2 = "+" THEN
ADD NUM1 NUM3 GIVING ANS
ELSE
IF NUM2 = "-" THEN
SUBTRACT NUM1 FROM NUM3 GIVING ANS
ELSE
IF NUM2 = "*" THEN
MULTIPLY NUM1 BY NUM3 GIVING ANS
END-IF.
DISPLAY ANS.
STOP RUN.
</code></pre>
<p>COBOL documentation isn't as great compares to languages like C++ or Javascript, so I struggled a bit.</p>
|
[] |
[
{
"body": "<p>First off, you don't verify the data entered by the user. This is an absolute <em>must</em>, IMHO.</p>\n<p>I'm no COBOL programmer, but do have some basic COBOL knowledge. Others may suggest better solutions. Anyway, here are my thoughts:</p>\n<p>You define data item <code>01 INP PIC A(14)</code> but the user needs to input numbers and operators. Picture character <code>A</code> means *letter of the Latin alphabet or a space", You should use <code>X</code>, because you cannot tell what the user will enter, and that is why you need to add code to verify.</p>\n<p>You define the data items to hold the input numbers as <code>PIC 9(7)</code>, and <code>PIC 9(15)</code>, resp., and the data item to hold the operation result as <code>PIC 9(8)</code>. How did you come up with these lengths? Make sure the result fits into the corresponding data item.</p>\n<p>You define the data item to hold the math operator as <code>PIC A(2)</code>, but the operators are only one character (and not of type <code>A</code>). Again <code>PIC X</code> would be appropriate.</p>\n<p>You're defining <em>condition names</em> for the operators, which is a good idea.</p>\n<pre><code> 01 NUM2 PIC A(2).\n 88 PLU VALUE "+".\n 88 AIDS VALUE "-".\n 88 MULT VALUE "*".\n</code></pre>\n<p>However, you don't make user of them. You can use them in your <code>IF</code> statements, and in the (missing) logic to verify the input. So instead of</p>\n<pre><code> IF NUM2 = "+" THEN\n ADD NUM1 NUM3 GIVING ANS\n ELSE ...\n</code></pre>\n<p>you could code</p>\n<pre><code> IF PLU THEN \n ADD NUM1 NUM3 GIVING ANS\n ELSE ...\n</code></pre>\n<p>Instead of coding nested <em>IF</em> statements use other constructs the language of choice offers. In COBOL, you could make use of the <code>EVALUATE</code> statement as follows:</p>\n<pre><code> EVALUATE TRUE \n WHEN PLU \n ADD NUM1 NUM3 GIVING ANS \n WHEN AIDS \n SUBTRACT NUM1 FROM NUM3 GIVING ANS \n WHEN MULT \n MULTIPLY NUM1 BY NUM3 GIVING ANS \n WHEN OTHER\n some error processing here....\n END-EVALUATE.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T15:21:54.530",
"Id": "502024",
"Score": "0",
"body": "I was confused about the rightest number in the Data section, given I mostly work in js and bash right now. I just used random digits, but i will fix that. How do you verify? Thank you for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T18:01:08.107",
"Id": "502033",
"Score": "1",
"body": "Not sure what you mean by *„I was confused about the rightest number in the Data section“*? Also, what do you want to verify? As for the data items in your calculator (NUM1 & NUM3) you have to make a decision, and then make sure what the user enters fits, or reject with an appropriate message. The data item for the result must be able to hold the result of multiplications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T18:19:10.237",
"Id": "502034",
"Score": "0",
"body": "the 2 in `01 NUM2 PIC A(2).` i had no clue what it meant, and i thought it was some sort of identifier, but i was incorrect. just a dumb mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T19:38:32.597",
"Id": "502038",
"Score": "0",
"body": "I see. PICTURE (or PIC) is followed by a sequence of *picture characters* that describe the data item. E.g. ```PIC AA``` (two bytes), or ```PIC AAAAA``` (fife bytes). The later may be abbreviated as ```PIC A(5)```. So the number in parenthesis is a *repeat factor* for the picture character. You can use it multiple times in a single data item, e.g. ```01 DECNUM PIC 9(9)V9(4)```"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T21:47:56.960",
"Id": "254504",
"ParentId": "254430",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254504",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T02:27:34.357",
"Id": "254430",
"Score": "2",
"Tags": [
"calculator",
"cobol"
],
"Title": "Basic COBOL Calculator"
}
|
254430
|
<p>For my job I was tasked with writing a faster version of Arduino's <a href="https://www.arduino.cc/reference/en/language/functions/math/map/" rel="nofollow noreferrer">map</a>. The requirements were only use addition and subtraction, since these are cheap operations on our board.</p>
<p>For reference, here is Arduino's implementation:</p>
<pre><code>long map(long x, long in_min, long in_max, long out_min, long out_max) {
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
</code></pre>
<p>And here's what I wrote</p>
<pre><code>long fasterMap(long value, long fromLow, long fromHigh, long toLow, long toHigh) {
long first = value - fromLow;
long second = toHigh - toLow;
long combined = 0;
while (second != 0) { // Avoid usage of * operator
combined = combined + first;
second = second - 1;
}
long third = fromHigh - fromLow;
long count = 0;
while (combined >= third) { // Avoid usage of / operator
combined = combined - third;
count = count + 1;
}
count = count + toLow;
return count;
}
</code></pre>
<p>Is there any more performance or micro-optimizations I can make to have this function calculate even faster? Thanks!</p>
<p>Note: Because this is running on an Arduino, answers in pure <code>c++</code> are greatly encouraged.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T04:27:13.440",
"Id": "501788",
"Score": "3",
"body": "Does your implementation outperform the reference one?"
}
] |
[
{
"body": "<p>Well, I don't speak c++ but checked the provided link to Arduino's <code>map()</code> method and there it states</p>\n<blockquote>\n<p>The function also handles negative numbers well, so that this example</p>\n<p>y = map(x, 1, 50, 50, -100);</p>\n<p>is also valid and works well.</p>\n</blockquote>\n<p>which your method wouldn't handle well, because with having <code>toHigh = -100</code> of the <code>fasterMap()</code> method would result in some really long running <code>while</code> loop because <code>second</code> in <code>long second = toHigh - toLow;</code> would result in <code>long second = -100 - 50</code> and therfor <code>while(second != 0)</code> would never evaluate to true.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T04:56:56.450",
"Id": "254432",
"ParentId": "254431",
"Score": "2"
}
},
{
"body": "<p>We have no detection of integer overflow (in either the reference implementation or the replacement). Given that we're using a signed type, any overflow would be Undefined Behaviour.</p>\n<p>I'm surprised that your implementation turns out faster than the reference. If your compiler can't implement multiplication at least as fast as repeated addition, or division as fast as repeated subtraction, you need a better compiler.</p>\n<p>A faster (and less overflow-prone) technique may be to use one of the standard straight-line-drawing algorithms, since we can visualise the rescaling operation as line-graph lookup.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T20:02:44.713",
"Id": "501839",
"Score": "2",
"body": "On Arduinos with an AVR CPU, it generates a `call _mulsi3` for the multiplication and `call _divmodsi4` for the division (see https://godbolt.org/z/ebdPTW). Funnily enough, the compiler sees that the first `while`-loop in `fasterMap()` is a multiplication and replaces it by `call _mulsi3`. It doesn't do so for the division. Possibly because OP's code doesn't handle division by zero, and as @Heslacher mentioned, it doesn't handle negative numbers very well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T09:28:59.510",
"Id": "254437",
"ParentId": "254431",
"Score": "1"
}
},
{
"body": "<p>Faster very much depends on the use case. In any case, measure! You may even implement different strategies depending on your parameters.</p>\n<h1>mapping completely generic over the whole <code>long</code> range</h1>\n<p>do a recursive bisect instead of your plain loop</p>\n<pre><code>long bisect_map(long x, long in_min, long in_max, long out_min, long out_max) {\n if (in_min > in_max)\n return bisect_map(x, in_max, in_min, out_max, out_min);\n if (out_min == out_max)\n return out_min;\n const long in_mid = (in_min + in_max) >> 1;\n const long out_mid = (out_min + out_max) >> 1;\n if (in_min == in_mid)\n return out_mid;\n if (x <= in_mid)\n return bisect_map(x, in_min, in_mid, out_min, out_mid);\n else\n return bisect_map(x, in_mid + 1, in_max, out_mid, out_max);\n}\n</code></pre>\n<p>On all algorithms - use fixed point arithmetic to avoid precision loss</p>\n<h1>mapping different values on the same ranges</h1>\n<p>Precompute the division. Multiplication remains during runtime</p>\n<pre><code>class Mapper\n{\npublic:\n Mapper(long in_min, long in_max, long out_min, long out_max, long fp_length = 8)\n : in_min(in_min)\n , out_min(out_min)\n , fp_length(fp_length)\n , factor(((out_max - out_min) << fp_length) / (in_max - in_min)) { }\n\n long operator()(long x) {\n return ((((x - in_min) * factor) >> fp_length) + out_min);\n }\n\nprivate:\n long in_min;\n long out_min;\n long fp_length;\n long factor;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-05T11:46:35.850",
"Id": "269766",
"ParentId": "254431",
"Score": "2"
}
},
{
"body": "<p>The division is the real killer since the simple CPU doesn't have a divide instruction. Even in CPUs that do, it is very slow.</p>\n<p>If the denominator is known at compile time, the compiler can transform it into a multiplication or otherwise use tricks for that specific value (e.g. powers of two are just a shift).</p>\n<p>You want all the in/out parameters to be known at compile time, and only <code>x</code> is the real run-time parameter.</p>\n<p>This is done using templates.</p>\n<pre><code>template <long in_min, long in_max, long out_min, long out_max>\nstruct map {\n long operator()(long x) const {\n return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;\n }\n}\n</code></pre>\n<p>Now you can use it like this:</p>\n<pre><code>map<12,42, 0,100> pbar_mapper;\n ⋮\nlong output = pbar_mapper(input);\n</code></pre>\n<p>That is, let the compiler figure out the fast trick for multiplying and dividing by these specific constants. With optimizations turned on, it should be at least as fast as any hand-written tricks.</p>\n<h1>update</h1>\n<p>Apparently, the compiler for Arduino doesn't replace division with reciprocal multiplication. Only divisions where the denominator is a power of 2 are replaced with simple operations.</p>\n<p>The template form <em>does</em> cause the compiler to pre-compute the subexpressions <code>out_max-out_min</code> and <code>in_max-in_min</code>. A big improvement in generated code was seen by using <code>int</code> instead of <code>long</code>. See: <a href=\"https://godbolt.org/z/PPYTWvqff\" rel=\"nofollow noreferrer\">https://godbolt.org/z/PPYTWvqff</a></p>\n<p>If <code>int</code> is 16 bits, and you know the values you are interested in will fit in this range, that will be the best benefit. So define the template using <code>int</code> and add a <code>static_assert</code> that <code>(in_max-in_min)*(out_max-out_min)</code> does not exceed the size of an <code>int</code>.</p>\n<p>Better yet, detect that case and automatically do the intermediate calculation using <code>long</code> and let the compiler know when it's multiplying two <code>int</code> to get a <code>long</code> and when it's dividing a <code>long</code> by an <code>int</code>, and hopefully it generates simpler code for the multiply and calls a faster form of the divide?</p>\n<p>If you can choose the output range to be a power of two, that would eliminate the division.</p>\n<p>Hmm and I notice that the "max" values in the original code shown are apparently meant to be <em>exclusive</em>, or the math is a little off and it just seems to work OK if the <code>input</code> value is equal to <code>in_max</code>. Since it's not doing rounding but truncation, a little imprecision might not be noticed.</p>\n<p>Anyway, a range of 128 would correspond to parameters of <code>0,128</code> or <code>1,129</code>. If you're mapping to a nice range to pass along to other code, a range that's a power of two would be perfectly natural.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-05T16:54:03.653",
"Id": "532388",
"Score": "0",
"body": "Nice trick making use of the compiler optimisation which is replacing the division by a multiplication with the reciprocal. This optimisation is available for most platforms, unfortunately it is not available for Arduino."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-05T20:38:36.653",
"Id": "532415",
"Score": "0",
"body": "@stefan Yipes, I wonder why not? Playing with Compiler Explorer, I see it only optimizes/inlines when dividing by powers of two. I see multiplication does have a built-in instruction, and the compiler replaces it for some values and I guess it knows when the built-in is faster (having only single-bit shifts slows it down so `x*15` is not replaced). So, I wonder if you could manually generate the equivalent reciprocal multiplication expression? I'm guessing that maybe the double-width arithmetic is slow and that's why it's not helpful."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-05T14:46:43.867",
"Id": "269775",
"ParentId": "254431",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254432",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T02:33:22.980",
"Id": "254431",
"Score": "0",
"Tags": [
"c++",
"performance",
"arduino"
],
"Title": "Faster map function"
}
|
254431
|
<p>I am learning swift and I came across this problem.
Converting each start letter to capitalized form if it's lowercase.</p>
<pre><code>func upperCaseFirstCharacter(str:String){
let myArr = str.components(separatedBy: " ")
var finalStr :String=""
for word in myArr {
let myStr = word.replacingCharacters(in: ...str.startIndex, with: word.first?.uppercased() ?? "")
finalStr.append(myStr)
if myArr.last != word{
finalStr.append(" ")
}
}
print(finalStr)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T14:53:14.400",
"Id": "501819",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>There's certainly different ways to do this problem in Swift. Here's an example:</p>\n<pre><code>extension Comparable {\n func clamped(to limits: ClosedRange<Self>) -> Self {\n min(max(self, limits.lowerBound), limits.upperBound)\n }\n}\n\nextension Int {\n var nonNegative: Int {\n clamped(to: 0...Int.max)\n }\n}\n\nextension Collection {\n var tailLength: Int {\n (count - 1).nonNegative\n }\n\n var head: SubSequence { prefix(1) }\n var tail: SubSequence { suffix(tailLength) }\n}\n\nextension String {\n var uppercaseFirst: String {\n head.localizedUppercase + tail\n }\n \n var words: [String] {\n components(separatedBy: " ")\n }\n \n var uppercaseFirstWords: String {\n words\n .map(\\.uppercaseFirst)\n .joined(separator: " ")\n }\n \n}\n\nlet example = "upper case the first letters please"\nprint(example.uppercaseFirstWords)\n</code></pre>\n<p>Now is that shorter than your code? No.\nIs it better? It's definitely different, so why might we prefer one or the other?</p>\n<p>One reason to avoid the for loop and mutation is that it's difficult for people to think about how the dynamic runtime behaviour is, when they just read the code, i.e. the magic vs the spell. Generally it's ok to begin with and then you end up drowning in mutation the more you build it up.</p>\n<p>The for-loop imperative style has the focus on all the details about the how to do something, (the reader has to follow all that through when reading the code) where the functional style is about what to do. The detail can get in the way, like temporary variables: "let myArr =". Your brain has to work through how all the mutation will work, compare that with something like</p>\n<pre><code>words.map(\\.uppercaseFirst).joined(separator: " ")\n</code></pre>\n<p>is more like the description of what is wanted - take the words in the string, uppercase their first letters, then join them up with spaces. Hopefully simple to read.</p>\n<p>On the other hand the functional style has a learning curve to it, for loops are easier to get started with. But the state juggling can result in things like:</p>\n<pre><code>if myArr.last != word\n</code></pre>\n<p>Which I guess has to do with avoiding a dangling " " - though it's not clear, so time has to be spent to understand that and make sure it's right.</p>\n<p>Another advantage would be breaking up the pieces into having more reusable parts, so for example having the 'words' computed property on String means you can reuse it for other things - perhaps it would be useful to have an array of words from a string, let's say to work with the last word, or to count the words:</p>\n<pre><code>example.words.count\nexample.words.suffix(1)\nexample.words.suffix(1).map(\\.uppercaseFirst)\nexample.words.randomElement().map { $0 + "!" }\n</code></pre>\n<p>Be wary about writing functions that bake in a 'side-effect' like printing its result. That means if you want to use it as part of some other processing, you can't. Consider changing the function signature:</p>\n<pre><code>func upperCaseFirstCharacter(_ str: String) -> String\n</code></pre>\n<p>Think carefully about the function names too, does it uppercase the first character of the string passed in?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T11:06:39.007",
"Id": "501901",
"Score": "2",
"body": "Note that `var tail: SubSequence { dropFirst() }` would be simpler *and* more efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T12:25:50.173",
"Id": "501909",
"Score": "0",
"body": "Thanks, and to OP: coding this as a Swift language-learning exercise is different to coding it in real life, for that @MartinR has the right answer about not reinventing the wheel - leveraging Foundation etc"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T11:17:53.657",
"Id": "254441",
"ParentId": "254436",
"Score": "2"
}
},
{
"body": "<p>A few observations on improving the code snippet, but using the same basic logic:</p>\n<ol>\n<li>If you split the string with <code>components</code>, you can use <code>joined</code> to put them back together.</li>\n<li>The <code>...str.startIndex</code> syntax will crash if you supply a zero length string. I would suggest using <code>prefix</code> and <code>dropFirst</code> to simplify the code.</li>\n<li>When writing routines like this, I’d generally suggest using <code>StringProtocol</code> so that it works for both string and substrings. In this case, I would make it an extension of <code>StringProtocol</code>.</li>\n<li>This method of capitalizing the first character of every word (regardless of part of speech) is sometimes called “start case” or “proper case”. I would suggest renaming the method accordingly.</li>\n</ol>\n<p>Thus:</p>\n<pre><code>extension StringProtocol {\n func startcased() -> String {\n components(separatedBy: " ")\n .map { $0.prefix(1).uppercased() + $0.dropFirst() }\n .joined(separator: " ")\n }\n}\n\nlet string = "this is a test"\nprint(string.startcased()) // This Is A Test\n</code></pre>\n<hr />\n<p>If the in the intent was to achieve “title case”, we often wouldn't capitalize certain parts of speech, e.g., articles and conjunctions. The <code>NaturalLanguage</code> library can be used for more refined capitalization logic:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>import NaturalLanguage\n\nextension StringProtocol {\n func titlecased() -> String {\n var capitalizeWordRanges: [Range<String.Index>] = []\n\n var result = String(self)\n\n // find words other than conjunctions and determiners\n\n let tagger = NLTagger(tagSchemes: [.lexicalClass])\n tagger.string = result\n let options: NLTagger.Options = [.omitWhitespace, .joinContractions]\n var isStartOfSentence = true\n\n tagger.enumerateTags(in: startIndex..<endIndex, unit: .word, scheme: .lexicalClass, options: options) { tag, range in\n guard let tag = tag else { return true }\n\n print(tag.rawValue, self[range])\n\n switch tag {\n case .sentenceTerminator: // see if we're potentially starting a new sentence\n isStartOfSentence = true\n return true\n\n case .punctuation, .openQuote, .closeQuote, .openParenthesis, .closeParenthesis:\n return true\n\n case .conjunction where self[range].count < 4,\n .determiner where self[range].count < 4,\n .preposition where self[range].count < 4: // only capitalize conjunctions or articles at the start of a sentence\n if isStartOfSentence { fallthrough }\n\n default:\n capitalizeWordRanges.append(range) // otherwise, add this to the array of ranges to t\n }\n\n isStartOfSentence = false\n\n return true\n }\n\n // loop through, doing replacements; do it in reverse order because sometimes the capitalized string isn't the same length, e.g. German ß -> SS\n\n for range in capitalizeWordRanges.reversed() {\n result.replaceSubrange(range.lowerBound...range.lowerBound, with: result[range.lowerBound].uppercased())\n }\n\n return result\n }\n}\n\nlet string2 = "this is a test"\nprint(string2.titlecased()) // This Is a Test\n\nlet string3 = #"The sign said, "don't feed the animals.""#\nprint(string3.titlecased()) // The Sign Said, "Don't Feed the Animals."\n\nlet string4 = "¿donde está la biblioteca?"\nprint(string4.titlecased()) // ¿Donde Está la Biblioteca?\n\n</code></pre>\n<p>Note, enumerating through the words solves another problem, namely situations where words may not preceded immediately by a space, but rather, perhaps punctuation, such as the quotation marks before “don't” in <code>string3</code>, above. Just splitting and joining by spaces will only work in the simplest of scenarios. Also, some languages have punctuation at the start of a sentence, e.g. the Spanish “¡Ay, caramba!” or “¿Donde está la biblioteca?” If you iterate through the actual words, rather than relying on spaces, you solve that problem.</p>\n<p>This admittedly is not perfect “title case” logic. E.g. it is taking care of the capitalizing of the first character, but not shifting the rest of the word to lowercase (e.g., if the input string was entirely in uppercase). But if you are only worried about the first letter, this is probably better than the naive start/proper capitalization routine. And if you want to implement a richer title case rendition, this routine might be a good starting point.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T03:28:27.633",
"Id": "501880",
"Score": "1",
"body": "There is also [`capitalized`](https://developer.apple.com/documentation/foundation/nsstring/1416784-capitalized) which apparently handles quotation marks and punctuation correctly, but has no special treatment of articles and conjunctions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T04:41:54.133",
"Id": "501883",
"Score": "0",
"body": "Well, now _that_ is the right answer. I was sitting here all smug and happy with my simple solution that eliminated a lot of the kruft, and you politely posted the overlooked one-liner! You should post that as an answer! I’d upvote it. Sure, my “title case” solution is a fine over-engineered answer to a question that wasn’t asked, but `capitalized` is the correct answer to the original question, IMHO."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T15:47:11.063",
"Id": "254448",
"ParentId": "254436",
"Score": "4"
}
},
{
"body": "<h3>Another bug</h3>\n<p>The detection whether to insert a separator or not</p>\n<pre><code>if myArr.last != word{\n finalStr.append(" ")\n}\n</code></pre>\n<p>does not work if the string contains multiple instances of the last word:</p>\n<pre><code>let s = "foo bar foo"\nupperCaseFirstCharacter(str: s) // FooBar Foo\n</code></pre>\n<p>You would have to check for the last <em>index</em> instead, or better, use <code>map</code> and <code>joined</code> as already suggested in the other answers.</p>\n<h3>Why reinvent the wheel?</h3>\n<p>If the intention is to change the initial character of each word to uppercase, and all remaining characters of a word to lowercase, then you can simply use <a href=\"https://developer.apple.com/documentation/foundation/nsstring/1416784-capitalized\" rel=\"nofollow noreferrer\"><code>capitalized</code></a> from the Foundation framework:</p>\n<pre><code>import Foundation\n\nlet s = "foo bar FOO"\nprint(s.capitalized) // Foo Bar Foo\n</code></pre>\n<p>This also handles words surrounded by quotation marks or other punctuation correctly (examples taken from Rob's answer):</p>\n<pre><code>let s2 = #"The sign said, "don't feed the animals.""#\nprint(s2.capitalized) // The Sign Said, "Don't Feed The Animals."\n\nlet s3 = "¿donde está la biblioteca?"\nprint(s3.capitalized) // ¿Donde Está La Biblioteca?\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T09:14:31.587",
"Id": "254481",
"ParentId": "254436",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254441",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T08:19:30.163",
"Id": "254436",
"Score": "1",
"Tags": [
"strings",
"swift"
],
"Title": "Convert first letter of every word to uppercase"
}
|
254436
|
<p>I made this python script to create dated folders within a directory. This is my first practical automation project and I don't want to cement any bad habits so I was wondering if there is anything I can improve in the code I have written here. Any feedback will be appreciated!</p>
<p>The main challenge I had was to account for months with different day ranges, and then to reset the counts properly for all the variables. I feel like this is more complicated than it probably needs to be but I don't know if there are some python libraries I am unaware of that could help simplify it more.</p>
<p>I thought about having a predefined end date as well but that would require the user to open up a calendar and find 2 dates. I figured by just asking for a start date and how many folders they want, I could make things simpler for the end user but I'm not even sure that that is actually the case.</p>
<p>I also don't know if I've used classes correctly here. At first I had everything thrown into the while statement. I also considered using a for loop instead of while but went with while instead. Again, this is my first real project so any help with other decisions I could have made will be appreciated!</p>
<pre><code>import os
import pathlib
directory = "/Users/myName/Box Sync/SAFAC/Budget Requests/2020-2021/Weekly/"
# directory = input("Enter the path where you would like to create files: ")
date = input("Enter the starting date in mm-dd-yyyy format: ")
period = int(input("Enter the period between each date folder: "))
instances = int(input("How many folders do you want? "))
Folders = []
arguments = date.split("-")
dayArgument = arguments[1]
monthArgument = arguments[0]
yearArgument = arguments[2]
init = instances - instances
elapse = period - period
seperator = "-"
month = int(monthArgument)
day = int(dayArgument) + int(elapse)
def make_directories(input_list):
for folderName in input_list:
dirpath = os.path.join(directory, folderName[0:],'Documentation')
try:
os.makedirs(dirpath)
except FileExistsError:
print('Directory {} already exists'.format(dirpath))
else:
print('Directory {} created'.format(dirpath))
def add_folder_to_list(month,day,year,extra):
full_name_constructor = (month,day,year,extra)
# full_name_constructor = (str(month),str('0'+str(day)),yearArgument,"Budgets")
fullName = seperator.join(full_name_constructor)
Folders.append(fullName)
def format_and_append_folder_name():
if day < 10 and month >= 10:
add_folder_to_list(str(month),str('0'+str(day)),yearArgument,"Budgets")
elif day >= 10 and month < 10:
add_folder_to_list(str('0'+str(month)),str(day),yearArgument,"Budgets")
elif day < 10 and month < 10:
add_folder_to_list(str('0'+str(month)),str('0'+str(day)),yearArgument,"Budgets")
else:
add_folder_to_list(str(month),str(day),yearArgument,"Budgets")
def check_month():
global maxDays
if (month % 2 ) == 0 and month != 2 : # if even but not February
maxDays = 30
elif month == 2 :
maxDays = 28 #if February
else :
maxDays = 31 # if odd
while init < instances :
check_month()
format_and_append_folder_name()
make_directories(Folders)
# print(Folders[init]) # for debugging
init += 1
elapse += period
day = int(dayArgument) + int(elapse)
if day > maxDays :
month += 1
day -= maxDays # reset days
dayArgument = day # recalibrate the new zero point for the day to be the date in the new month
elapse = 0 # recalibrate elapse point to 0 so it can reiterate the period again
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T16:01:08.620",
"Id": "501825",
"Score": "0",
"body": "Excellent question, particularly for a newcomer to the site."
}
] |
[
{
"body": "<p>OK let's look at your code.</p>\n<h2>Unused Imports</h2>\n<p><code>pathlib</code> was imported but I don't see any use of it in the codebase, I understand that this might be as a result of testing out approaches to a problem. <code>pylint</code> can help mitigate this by catching unused modules. It also catches some PEP guidelines which your code breaks.</p>\n<h2>Avoid Globals</h2>\n<p>You have lots of global variables. A common approach whenever you want to use a global is asking yourself some questions; "How do I express myself with code whilst avoiding this global variable". When in doubt, prefer objects that holds <code>state</code> to global variables.</p>\n<h2>Code Review</h2>\n<p>On first glance, I can see you are manually parsing dates. This doesn't look good, you introduce bugs when reinventing the wheel. Right now, your code contains a bug, it accepts invalid dates, I can easily create a date like this\n<code>date = "12-03-202022"</code>\nThe above code generates no error, this can be disastrous.\nA common alternative is using python <code>datetime</code> module. This simplify everything, we can move the dates by periods easily, creating directories becomes quite easy.</p>\n<p>NOTE: datetime module checks for invalid dates.</p>\n<p>A simple way of creating a date from a string is given as</p>\n<pre><code>from datetime import datetime\ndate = datetime.strptime(start_date, "%d/%m/%y")\n</code></pre>\n<p>This simple line of code simplifies everything, the full code can then be written as</p>\n<pre><code>"""Directory creating program"""\n\nimport os\nfrom datetime import datetime, timedelta\n\ndef next_date(date, period):\n """Increase the date by timedelta\n date: datetime object\n period: timedelta to increase our date by\n """\n new_date = date + timedelta(days=period)\n return '/'.join((str(new_date.day), str(new_date.month), str(new_date.year))), new_date\n\ndef make_directories(home_dir, start_date, instances, period):\n """Create sub directories in the home_dir\n\n home_dir: base directory\n start_date: date to append to directories created\n instances: number of directories to create\n period: difference between two dates\n """\n date = datetime.strptime(start_date, "%d/%m/%y")\n\n for i in range(instances):\n start_date = start_date.replace('/', '-')\n dirpath = os.path.join(directory, start_date,'Documentation')\n try:\n os.makedirs(dirpath)\n except FileExistsError:\n print('Directory {} already exists'.format(dirpath))\n else:\n print('Directory {} created'.format(dirpath))\n\n start_date, date = next_date(date, period)\n\nif __name__ == "__main__":\n directory = "/Users/myName/Box Sync/SAFAC/Budget Requests/2020-2021/Weekly/"\n make_directories(directory, '3/1/20', 10, 5)\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T16:18:26.150",
"Id": "254451",
"ParentId": "254438",
"Score": "3"
}
},
{
"body": "<h2>Hard-coded paths</h2>\n<p>It looks like you started off asking for this:</p>\n<pre><code>directory = input("Enter the path where you would like to create files: ")\n</code></pre>\n<p>but then changed your mind:</p>\n<pre><code>directory = "/Users/myName/Box Sync/SAFAC/Budget Requests/2020-2021/Weekly/"\n</code></pre>\n<p>The latter style of hard-coded directories should be avoided. Accept the directory via <code>input</code>, or (more likely) via <code>argparse</code>.</p>\n<h2>Unit specificity</h2>\n<pre><code>Enter the period between each date folder\n</code></pre>\n<p>is not specific enough. Period in days, months, years? A combined timedelta format? Based on your code it looks like days, but your prompt should specify.</p>\n<h2>Datetime parsing</h2>\n<p>Don't do <code>split</code>-based date parsing like this:</p>\n<pre><code>dayArgument = arguments[1]\nmonthArgument = arguments[0]\nyearArgument = arguments[2]\n</code></pre>\n<p>Instead, call into one of the parsing routines in <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime\" rel=\"nofollow noreferrer\">datetime</a>. Beyond that, <code>mm-dd-yyyy</code> is both non-standard and non-sortable. Strongly consider using <code>yyyy-mm-dd</code> instead.</p>\n<p>Likewise, rather than</p>\n<pre><code>def add_folder_to_list(month,day,year,extra):\n full_name_constructor = (month,day,year,extra)\n # full_name_constructor = (str(month),str('0'+str(day)),yearArgument,"Budgets")\n fullName = seperator.join(full_name_constructor)\n</code></pre>\n<p>just use the built-in <code>datetime</code> format routines.</p>\n<h2>Pathlib</h2>\n<p>You import it, but you don't use it here:</p>\n<pre><code> dirpath = os.path.join(directory, folderName[0:],'Documentation')\n</code></pre>\n<p>Best to replace your <code>join</code> with a <code>/</code> operator on a <code>Path</code> instance.</p>\n<h2>Spelling</h2>\n<p><code>seperator</code> -> <code>separator</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T16:26:33.453",
"Id": "254452",
"ParentId": "254438",
"Score": "2"
}
},
{
"body": "<h3>Bugs</h3>\n<p>There are a few (potential) bugs in you program: <code>check_month()</code> doesn't handle leap years and the code doesn't handle roll over at the end of a year.</p>\n<h3><code>datetime</code></h3>\n<p>Using <code>datetime</code> from the standard library can fix these bugs and simplify the code. <code>datetime.date()</code> provides methods for parsing and formating date strings. And <code>datetime.timedelta()</code> for adding an interval or period to a date.</p>\n<p>Using the library, your code can be simplified to something like:</p>\n<pre><code>from datetime import date, timedelta\nfrom pathlib import Path\n\ntemplate = input(f"Enter a directory template (use DD for day, MM for month, YYYY for year): ")\ntemplate = template.replace('YYYY', '{0:%Y}').replace('MM', '{0:%m}').replace('DD', '{0:%d}')\n\nstart = input(f"Enter a start date (yyyy-mm-dd): ")\ncurrent_date = date.fromisoformat(start)\n\nperiod = input("Enter the number of days between each date folder: ")\nperiod = timedelta(days=int(period))\n\ncount = int(input(f"Enter the number of folders to create: "))\n \nfor _ in range(count):\n path = Path(template.format(current_date))\n\n try:\n path.mkdir(parents=True)\n\n except FileExistsError:\n print(f'Directory {path} already exists.')\n\n else:\n print(f'Directory {path} created.')\n \n current_date += period\n</code></pre>\n<p>Using a template provides some flexibility in telling the code what directories to create. The template gets turned into a format string by replacing codes in the template with formatting codes for the components of a date. For example, 'YYYY' in the template gets replaced with '{0:%Y}'. When the format string is used to format a date, the <code>{0:%Y}</code> gets replaced with the 4-digit year. 'DD' and 'MM' are use for the day and month respectively. Letting the user enter a code like 'YYYY' and then replacing it with the format code is just to sanitize the user input.</p>\n<p>The <code>date.fromisoformat()</code> parses a date in the YYYY-MM-DD format and returns a date object. If you really need to use DD-MM-YYYY format, also import <code>datetime</code> from the <code>datetime</code> library and use <code>start = datetime.strptime(start, "%d-%m-%Y").date()</code>.</p>\n<p>I prefer using <code>pathlib</code>, so I used that in the code. <code>os.path</code> would work just as well.</p>\n<h3>User experience (UX)</h3>\n<p>With some additional effort, the user experience can be improved. For example, default values can be provided for some inputs. As another, a stop date can be used instead of a number of periods (quick: how many weeks are there between 2021-01-08 and 2021-08-01?).</p>\n<pre><code>from datetime import date, timedelta\nfrom pathlib import Path\n\nDEFAULT_TEMPLATE = "/Users/myName/Box Sync/SAFAC/Budget Requests/2020-2021/Weekly/DD-MM-YYYY-Budgets/Documentation"\nDEFAULT_START = dt.date.today()\nDEFAULT_PERIOD = 7 # days\nDEFAULT_COUNT = 1 # a str\n\nprint("Enter the following (defaults are in [])")\n\ntemplate = input(f" Directory template (use DD for day, MM for month, YYYY for year)\\n[{DEFAULT_TEMPLATE}]: ")\nif template == '':\n template = DEFAULT_TEMPLATE\ntemplate = template.replace('YYYY', '{0:%Y}').replace('MM', '{0:%m}').replace('DD', '{0:%d}')\n\nstart = input(f" Start date (yyyy-mm-dd) [{DEFAULT_START}]: ")\nif start:\n date = dt.date.fromisoformat(start)\nelse:\n date = DEFAULT_START\n\nperiod = input(f" Number of days between each date folder [{DEFAULT_PERIOD}]: ")\nif period == '':\n period = DEFAULT_PERIOD\nperiod = dt.timedelta(days=int(period))\n\nend = input(f" Number of folders or a stop date (yyyy-mm-dd) [{DEFAULT_COUNT}]: ")\nif end == '':\n end = date + period * DEFAULT_COUNT\n \nelif '-' in end:\n end_date = dt.date.fromisoformat(end)\n \nelse:\n end_date = date + period * int(end)\n\n \nwhile date < end_date:\n path = Path(template.format(date))\n \n try:\n path.mkdir(parents=True)\n\n except FileExistsError:\n print(f'Directory {path} already exists.')\n\n else:\n print(f'Directory {path} created.')\n\n date += period\n</code></pre>\n<p>In the code, the prompts include the default value in '[]'. If the user just hits ENTER, the default values get used. The code for determining the <code>end_date</code> uses the default number of periods if the user doesn't enter anything. Otherwise, it checks to see if the user entered a date or a count and does the appropriate conversion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:03:02.717",
"Id": "254468",
"ParentId": "254438",
"Score": "1"
}
},
{
"body": "<p>I agree with most if not all the points made by other answers thus far so I won't rehash their answers. Here are some additional points.</p>\n<ul>\n<li>Use type hints. They will save you (or the next person who has to look at this script) in the long run.</li>\n<li>Using Clean Code principles, break down responsibility into smaller functions.</li>\n<li>Check to see if the file that already exists is indeed a folder.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code># Trying to make a folder and catching the exception when it already exists \n# is a good idea except when the thing that already exists is a FILE not a FOLDER.\ndef make_directory(value: str):\n try:\n os.makedirs(value)\n except OSError as e:\n if e.errno == errno.EEXIST and os.path.isdir(value):\n pass\n else:\n raise\n</code></pre>\n<ul>\n<li>Avoid unnecessary actions. Use <code>init = 0</code> instead of <code>init = instances - instances</code></li>\n<li><code>if day < 10 and month >= 10:</code> can be written as <code>if day < 10 <= month:</code></li>\n<li>If you're using globals, it's a good sign you should create a class.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:52:52.487",
"Id": "254611",
"ParentId": "254438",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T10:32:49.600",
"Id": "254438",
"Score": "5",
"Tags": [
"python"
],
"Title": "Creates a series of folders from a given starting date"
}
|
254438
|
<p>I'm writing my own expression tree system, just for fun, but I have a few doubts about my code.<br>
My goal here is to create an abstract layer of expressions, and allow different <em>"languages"</em> to extend it.
<br>
For example, those are my base components :</p>
<pre class="lang-cs prettyprint-override"><code>//Base expression class for all expressions in every domain
public abstract class Expression
{
public void Accept(Visitor visitor)
{
visitor.Visit(this);
}
}
//Base left-right (binary) expression class for all binary expressions in every domain
public abstract class BinaryExpression : Expression
{
protected BinaryExpression(Expression left,Expression right)
{
Left = left;
Right = right;
}
public Expression Left { get; }
public Expression Right { get; }
}
//Base assignment expression (x <= y) class for all assignment expressions in every domain
public abstract class AssignmentExpression : BinaryExpression
{
protected AssignmentExpression(Expression destination,Expression source)
: base(destination,source)
{
Destination = destination;
Source = source;
}
public Expression Destination { get; }
public Expression Source { get; }
}
//The visitor class who can visit expressions
public abstract class Visitor
{
public abstract void Visit(Expression expression);
}
</code></pre>
<p>And I have two languages using the definitions above.
Language A :</p>
<pre class="lang-cs prettyprint-override"><code>//The LangA visitor
public class LangAVisitor : Visitor
{
public void Visit(LangAMoveExpression expression)
{
Debug.WriteLine("LangAMoveExpression");
}
public override void Visit(Expression expression)
{
Debug.WriteLine("LangAExpression");
Visit((dynamic)expression);
}
}
//Language A assignment expression (known for this language as move)
public class LangAMoveExpression : AssignmentExpression
{
public LangAMoveExpression(Expression destination,Expression source)
: base(destination,source)
{
}
}
//Just an empty expression
public class LangAEmptyExpression : Expression
{
}
</code></pre>
<p>And Language B :</p>
<pre class="lang-cs prettyprint-override"><code>//The LangB visitor
public class LangBVisitor : Visitor
{
public void Visit(LangBStoreExpression expression)
{
Debug.WriteLine("LangBStoreExpression");
}
public override void Visit(Expression expression)
{
Debug.WriteLine("LangBExpression");
Visit((dynamic)expression);
}
}
//Language B assignment expression (known for this language as store)
public class LangBStoreExpression : AssignmentExpression
{
public LangBStoreExpression(Expression destination,Expression source)
: base(destination,source)
{
}
}
//Just an empty expression
public class LangBEmptyExpression : Expression
{
}
</code></pre>
<p>Execution Example :</p>
<pre class="lang-cs prettyprint-override"><code>void Main()
{
Execute(new LangAVisitor(),new LangAMoveExpression(new LangAEmptyExpression(),new LangAEmptyExpression()));
Execute(new LangBVisitor(),new LangBStoreExpression(new LangBEmptyExpression(),new LangBEmptyExpression()));
}
void Execute(Visitor visitor,params Expression[] expressions)
{
foreach(var expression in expressions)
{
expression.Accept(visitor);
}
}
</code></pre>
<ol>
<li>I am able to get the desired output I want thanks to the code supplied, but I really don't like the <code>dynamic</code> casting approach, is there any way I can implement this better?
<br>Also, i need to keep the executing as generic as possible.</li>
<li>Many doubts came to me when placing the <code>public void Accept(Visitor visitor)</code> in the base <code>Expression</code> class, should it even be there?</li>
<li>How extensible is this code ?<br>Is it well architecture for any upcoming extensions ?</li>
</ol>
<p>Thanks in advance !</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T07:38:25.370",
"Id": "501802",
"Score": "1",
"body": "With the traditional Visitor pattern, the Expression types are not very extensible (visitor is more suitable when you have a fixed set of expressions), but you can easily add different languages (you just create another Visitor derivative). I've written a bit about this in an [answer](https://softwareengineering.stackexchange.com/a/412392/275536) to a different question, it will help you understand what Visitor is actually about. 1/2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T07:38:30.010",
"Id": "501803",
"Score": "1",
"body": "Traditionally, the Visitor base class would actually have a separate Visit method for each direct child of Expression - these would be differentiated either by name, or by the type signature (relying on overload resolution) - see [this Wikipedia article](https://en.wikipedia.org/wiki/Visitor_pattern). The whole thing with `dynamic` here doesn't seem to really solve anything (at first glance), it just adds unnecessary complexity while appearing helpful. It has the same constraint - if you add a new type of Expression, you'd still need to update all the Language classes. 2/2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T09:42:41.047",
"Id": "501804",
"Score": "0",
"body": "Sorry for nitpicking, in Visitor pattern _**Visitor** lets you define a new operation without changing the classes of the elements on which it operates_ or in another words _Represents an operation to be performed on elements of an object structure_ - in your implementation, I assume an `Expression` is an operation which is \"visiting\" an object(\"host\")."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T10:09:15.107",
"Id": "501805",
"Score": "0",
"body": "@Fabio - \"I assume an Expression is an operation\" - I'm not sure, but I think Expression is just used to represent an abstract syntax tree (so, not an executable operation, just data representing some code/expression, like something a compiler would produce). If so, then it fits the role of a traversable tree of elements that visitors act upon, and Visitor derivatives like OP's \"languages\" could actually be operations like \"interpret\". One reason why I suspect this is the case is because that particular example is often used (most notably, the Go4 book uses an AST to motivate the pattern)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T02:08:42.643",
"Id": "254439",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"visitor-pattern"
],
"Title": "Visitor pattern, Extensible visitor for custom implementation"
}
|
254439
|
<p><strong>Could anyone review my code for a calculator using tkinter?</strong></p>
<p>I'm attempting to use two classes, one with the functions of the calculator and a second which creates the GUI.</p>
<p>It seems to work fine (although I'd like to add keyboard functionality), so I'd like to ask if there is anything that I could have done better. The code is based on a tutorial I found online. The algorithm for <code>evaluate</code> is also found online, but I modified it to work with the program.</p>
<p>My program about 400 lines, so I really think there might be some way to improve it?</p>
<p><em>The tutorial is <a href="https://www.geeksforgeeks.org/python-simple-gui-calculator-using-tkinter/" rel="nofollow noreferrer">here</a></em></p>
<p><em>The original evaluation code is <a href="https://www.geeksforgeeks.org/expression-evaluation/" rel="nofollow noreferrer">here</a></em></p>
<p>Here's my code..</p>
<pre><code>import tkinter as tk # Import tkinter library
import math # Import math lib
import re # Import this thing too
class Calculator:
"""
A class used to implement the functions of a calculator
"""
def __init__(self):
self.answer = tk.StringVar()
self.equation = tk.StringVar()
self.expression = ""
self.paren = False
self.prev_expression = []
self.itr = ""
def set_prev_expr(self):
"""
Stores all changes to the expression in a list
"""
self.prev_expression.append(self.expression)
def get_prev_expr(self):
try:
print("Getting last entry")
self.expression = self.prev_expression.pop()
self.equation.set(self.expression)
except IndexError:
print("No values in undo")
self.answer.set("Can't undo")
def clear(self):
"""
Resets Variables used to defaults
"""
self.set_prev_expr()
print("Clearing")
self.paren = False
self.expression = ""
self.answer.set(self.expression)
self.equation.set(self.expression)
self.itr = ""
print("Clearing complete")
def insert_paren(self):
"""
Inserts paren into equation
"""
self.set_prev_expr()
if not self.paren:
self.expression += "("
self.equation.set(self.expression)
self.paren = True # Keeps track of paren orientation
print(self.expression)
else:
self.expression += ")"
self.paren = False
self.equation.set(self.expression)
print(self.expression)
def percent(self):
"""
divides expression by 100
"""
self.set_prev_expr()
self.expression += " / 100"
self.evaluate(self.expression)
def square(self):
self.set_prev_expr()
if True: # If the last number is in paren applies to entire paren block
match = re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+', self.expression)
print(match)
try:
last = float(self.evaluate(match.pop(-1)))
self.expression = " ".join(match) + " " + str(math.pow(last, 2)) # Always pos, no chance of dash causing error
print(self.expression)
self.evaluate(self.expression)
except: # Any errors should be picked up by evaluate function so no need to print to screen
print("Error")
self.answer.set("Cannot Calculate Ans")
def press(self, num: str):
self.set_prev_expr()
if num in ["*", "/", "+", "-"]: # Adds spaces either side of operators. Special operators are handled separately
self.expression = str(self.expression) + " " + str(num) + " "
else: # Negative is included here
self.expression = str(self.expression) + str(num)
self.equation.set(self.expression)
print(self.expression)
def square_root(self):
self.set_prev_expr()
if True: # If the last number is in paren applies to entire paren block
match = re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+', self.expression)
print(match)
try:
last = float(self.evaluate(match.pop(-1)))
self.expression = " ".join(match) + " " + str(math.sqrt(last))
print(self.expression)
self.evaluate(self.expression)
except ValueError: # Should be called if try negative num
print("Error")
self.answer.set("Imaginary Answer")
def backspace(self):
self.set_prev_expr()
if self.expression[-1] == ")": # If you delete a paren re-add paren flag
self.paren = True
self.expression = self.expression[:-1]
print(self.expression)
self.equation.set(self.expression)
# Function to find weight
# of operators.
def _weight(self, op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
return 0
# Function to perform arithmetic
# operations.
def _arith(self, a, b, op):
try:
if op == '+':
return a + b
elif op == '-':
return a - b
elif op == '*':
return a * b
elif op == '/':
return a / b
else:
return None
except ZeroDivisionError:
print("Invalid Operation: Div by Zero")
self.answer.set("ZeroDivisionError")
return "ZeroDiv"
# Function that returns value of
# expression after evaluation.
def evaluate(self, tokens: str):
self.set_prev_expr()
# adds support for negative numbers by adding a valid equation
token_lst = tokens.split(" ")
#print(token_lst)
for index, elem in enumerate(token_lst):
if "—" in elem:
token_lst[index] = elem.replace("—", "(0 -") + ")"
#print(token_lst)
tokens = " ".join(token_lst)
print(tokens)
# stack to store integer values.
values = []
# stack to store operators.
ops = []
i = 0
while i < len(tokens):
# Current token is a whitespace,
# skip it.
if tokens[i] == ' ':
i += 1
continue
# Current token is an opening
# brace, push it to 'ops'
elif tokens[i] == '(':
ops.append(tokens[i])
# Current token is a number or decimal point, push
# it to stack for numbers.
elif (tokens[i].isdigit()) or (tokens[i] == "."):
val = ""
# There may be more than one
# digits in the number.
while (i < len(tokens) and
(tokens[i].isdigit() or tokens[i] == ".")):
val += str(tokens[i])
i += 1
val = float(val)
values.append(val)
# right now the i points to
# the character next to the digit,
# since the for loop also increases
# the i, we would skip one
# token position; we need to
# decrease the value of i by 1 to
# correct the offset.
i -= 1
# Closing brace encountered,
# solve entire brace.
elif tokens[i] == ')':
while len(ops) != 0 and ops[-1] != '(':
try:
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
except IndexError:
print("Syntax Error")
self.answer.set("Syntax Error")
self.get_prev_expr()
self.get_prev_expr() # Returns expr to previous state
return None
values.append(self._arith(val1, val2, op))
if values[-1] == "ZeroDiv":
return None
# pop opening brace.
ops.pop()
# Current token is an operator.
else:
# While top of 'ops' has same or
# greater _weight to current
# token, which is an operator.
# Apply operator on top of 'ops'
# to top two elements in values stack.
while (len(ops) != 0 and
self._weight(ops[-1]) >=
self._weight(tokens[i])):
try:
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
except IndexError:
print("Syntax Error")
self.answer.set("Syntax Error")
self.get_prev_expr() # Returns expr to previous state
self.get_prev_expr()
return None
values.append(self._arith(val1, val2, op))
if values[-1] == "ZeroDiv":
return None
# Push current token to 'ops'.
ops.append(tokens[i])
i += 1
# Entire expression has been parsed
# at this point, apply remaining ops
# to remaining values.
while len(ops) != 0:
try:
val2 = values.pop()
val1 = values.pop()
op = ops.pop()
except IndexError:
print("Syntax Error")
self.answer.set("Syntax Error")
self.get_prev_expr() # Returns expr to previous state
self.get_prev_expr()
return None
values.append(self._arith(val1, val2, op))
if values[-1] == "ZeroDiv":
return None
# Top of 'values' contains result,
# return it.
try:
if (values[-1] % 1 == 0): # Checks if the value has decimal
values[-1] = int(values[-1])
if (values[-1] >= 9.9e+8) or (values[-1] <= -9.9e+8):
raise OverflowError
values[-1] = round(values[-1], 10) # rounds a decimal number to 10 digits (max on screen is 20)
self.expression = str(values[-1])
self.expression = self.expression.replace("-", "—") # If the answer starts with a dash replace with neg marker
self.equation.set(self.expression)
self.answer.set(self.expression)
return values[-1]
except SyntaxError:
print("Syntax Error")
self.answer.set("Syntax Error")
return None
except OverflowError:
print("Overflow")
self.answer.set("Overflow")
self.get_prev_expr() #Returns to previous state (for special funct) deletes extra step in normal ops
self.get_prev_expr()
return None
class CalcGui(Calculator):
BOX_HEIGHT = 2
BOX_WIDTH = 8
CLEAR_COLOR = "#c2b2b2"
SPECIAL_BUTTONS_COLOR = "#b1b1b1"
OPERATOR_COLOR = "dark grey"
NUM_COLOR = "#cfcaca"
def __init__(self, main_win: object):
self.main_win = main_win
Calculator.__init__(self)
self.create_text_canvas()
self.create_button_canvas()
def create_text_canvas(self):
entry_canv = tk.Canvas(bg="blue") # Contains the output screens
entry1 = tk.Entry(entry_canv,
text=self.equation,
textvariable=self.equation,
width=20
)
entry1.pack()
ans_box = tk.Label(entry_canv,
textvariable=self.answer,
width=20
)
ans_box.pack()
entry_canv.pack()
def create_button_canvas(self):
self.buttons = [ # List of all button info
#chr. x y color command
("clear", 0, 0, self.CLEAR_COLOR , self.clear ),
("↺" , 1, 0, self.SPECIAL_BUTTONS_COLOR, self.get_prev_expr ),
("x²" , 2, 0, self.SPECIAL_BUTTONS_COLOR, self.square ),
("√x" , 3, 0, self.SPECIAL_BUTTONS_COLOR, self.square_root ),
("—" , 0, 1, self.SPECIAL_BUTTONS_COLOR, lambda: self.press("—")),
("()" , 1, 1, self.SPECIAL_BUTTONS_COLOR, self.insert_paren ),
("%" , 2, 1, self.SPECIAL_BUTTONS_COLOR, self.percent ),
("÷" , 3, 1, self.OPERATOR_COLOR , lambda: self.press("/")),
("7" , 0, 2, self.NUM_COLOR , lambda: self.press("7")),
("8" , 1, 2, self.NUM_COLOR , lambda: self.press("8")),
("9" , 2, 2, self.NUM_COLOR , lambda: self.press("9")),
("x" , 3, 2, self.OPERATOR_COLOR , lambda: self.press("*")),
("4" , 0, 3, self.NUM_COLOR , lambda: self.press("4")),
("5" , 1, 3, self.NUM_COLOR , lambda: self.press("5")),
("6" , 2, 3, self.NUM_COLOR , lambda: self.press("6")),
("-" , 3, 3, self.OPERATOR_COLOR , lambda: self.press("-")),
("1" , 0, 4, self.NUM_COLOR , lambda: self.press("1")),
("2" , 1, 4, self.NUM_COLOR , lambda: self.press("2")),
("3" , 2, 4, self.NUM_COLOR , lambda: self.press("3")),
("+" , 3, 4, self.OPERATOR_COLOR , lambda: self.press("+")),
("⌫" , 0, 5, self.NUM_COLOR , self.backspace ),
("0" , 1, 5, self.NUM_COLOR , lambda: self.press("0")),
("." , 2, 5, self.NUM_COLOR , lambda: self.press(".")),
("=" , 3, 5, "orange" , lambda: self.evaluate(self.expression)),
]
button_canv = tk.Canvas(bg="red") # Contains Input buttons
for (character, x, y, color, command) in self.buttons:
button = tk.Button(button_canv, text= character, bg= color, # Unique
relief= tk.RAISED, height= self.BOX_HEIGHT, width= self.BOX_WIDTH) # Defaults
button.grid(row= y, column= x)
button.configure(command= command)
button_canv.pack(padx=5, pady=5)
def main():
main_win = tk.Tk()
main_win.configure(background="light blue")
main_win.title("Calculator")
main_win.resizable(False, False) # Becomes ugly if you resize it
calculator = CalcGui(main_win)
main_win.mainloop()
if __name__ == "__main__":
main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Separation of business from presentation</h2>\n<p>It's mostly good; <code>Calculator</code> is effectively your business layer. The one thing that creeps me out a little is using a <code>tk.StringVar</code> in it. One way to have a "pure" <code>Calculator</code> that has zero requirements on tk is to accept bound function references to <code>answer.set</code> and <code>equation.set</code> as arguments to your constructor. The class will be calling into those methods but won't need to know that they're tied to tk.</p>\n<h2>Unit test</h2>\n<p><code>Calculator</code> is a good candidate for being unit-tested; you probably don't even need to mock anything out. So try your hand at that.</p>\n<h2>Finding the last match</h2>\n<p>This:</p>\n<pre><code> match = re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|\\"[^\\"]*\\"|\\S+', self.expression)\n print(match)\n try:\n last = float(self.evaluate(match.pop(-1)))\n</code></pre>\n<p>needs to be re-thought. You certainly should not be calling <code>findall</code> and then choosing the last match - that defeats the purpose of regular expressions. Add a <code>$</code> and whatever other intervening characters you need, and this will match to the end of the string.</p>\n<h2>Set membership tests</h2>\n<p>Try changing</p>\n<pre><code>if num in ["*", "/", "+", "-"]\n</code></pre>\n<p>to</p>\n<pre><code>if num in {"*", "/", "+", "-"}\n</code></pre>\n<p>and maybe storing that set as a class static.</p>\n<h2>Formatting</h2>\n<pre><code>str(self.expression) + " " + str(num) + " "\n</code></pre>\n<p>can be</p>\n<pre><code>f'{self.expression} {num} '\n</code></pre>\n<h2>Specific type hints</h2>\n<pre><code>main_win: object\n</code></pre>\n<p>isn't helpful. Put a breakpoint here and check your debugger to see what the actual tk widget type is.</p>\n<h2>Resizing</h2>\n<pre><code>main_win.resizable(False, False) # Becomes ugly if you resize it\n</code></pre>\n<p>No kidding. This suggests not that you should disable resizing, but that your layout is incorrectly expressed. That's not surprising since these are hard-coded:</p>\n<pre><code>BOX_HEIGHT = 2\nBOX_WIDTH = 8\n</code></pre>\n<p>I encourage you to do some research on how tk represents a proportionate-resizeable grid layout.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T21:31:12.000",
"Id": "502043",
"Score": "0",
"body": "After spending some time trying to understand the re syntax, and then failing and browsing stack exchange I changed the matching statement I used to.\n ```for match in re.finditer(r'\\([^\\)]*\\)|\\S+$', self.expression): # gets last match \n pass\n rem_expression = self.expression[:match.span()[0]] + self.expression[match.span()[1]:]\n match = match.group()```\nIs this a better way to use regular expressions? I could not really find a way for it to only hit the last match, it always showed all occurrences."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T22:19:47.127",
"Id": "502045",
"Score": "0",
"body": "Can you show an example string that that regex is trying to parse?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T00:23:10.013",
"Id": "502051",
"Score": "0",
"body": "Something like this `\"2 + (2 * 4) / (3 + 1)''` and it would capture the `\"(3 + 1)\"`\nor `\"2 + 34\"` and it would capture \"34\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T13:36:01.877",
"Id": "502101",
"Score": "1",
"body": "I think I figured it out after a nights sleep. I needed a `$` before the OR because the one I had only applied to the last part of the expression..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T15:56:30.293",
"Id": "254449",
"ParentId": "254447",
"Score": "7"
}
},
{
"body": "<p>There'sa bug in your <code>square</code> and <code>square_root</code> functions:</p>\n<pre><code> def square(self):\n self.set_prev_expr()\n if True: # If the last number is in paren applies to entire paren block\n match = re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|\\"[^\\"]*\\"|\\S+', self.expression)\n print(match)\n try:\n last = float(self.evaluate(match.pop(-1)))\n self.expression = " ".join(match) + " " + str(math.pow(last, 2)) # Always pos, no chance of dash causing error\n print(self.expression)\n self.evaluate(self.expression)\n except: # Any errors should be picked up by evaluate function so no need to print to screen\n print("Error")\n self.answer.set("Cannot Calculate Ans")\n\n</code></pre>\n<p>and</p>\n<pre><code> def square_root(self):\n self.set_prev_expr()\n if True: # If the last number is in paren applies to entire paren block\n match = re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|\\"[^\\"]*\\"|\\S+', self.expression)\n print(match)\n try:\n last = float(self.evaluate(match.pop(-1)))\n self.expression = " ".join(match) + " " + str(math.sqrt(last))\n print(self.expression)\n self.evaluate(self.expression)\n except ValueError: # Should be called if try negative num\n print("Error")\n self.answer.set("Imaginary Answer")\n</code></pre>\n<p>You see, <code>if True</code> statements are pointless, because <code>True</code> is <em>always</em> <code>True</code>,\nhence the block will be executed regardless of the value of <code>self.set_prev_expr()</code>.</p>\n<p>Instead of concatenating string, you can use a formatted string, which will allow you to directly insert non-string values into a string.</p>\n<p>So they would be the equivalent of just</p>\n<pre><code> def square(self):\n self.set_prev_expr()\n match = re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|\\"[^\\"]*\\"|\\S+', self.expression)\n print(match)\n try:\n last = float(self.evaluate(match.pop(-1)))\n self.expression = f'{" ".join(match)} {math.pow(last, 2)}' # Always pos, no chance of dash causing error\n print(self.expression)\n self.evaluate(self.expression)\n except: # Any errors should be picked up by evaluate function so no need to print to screen\n print("Error")\n self.answer.set("Cannot Calculate Ans")\n\n</code></pre>\n<p>and</p>\n<pre><code> def square_root(self):\n self.set_prev_expr()\n match = re.findall('\\[[^\\]]*\\]|\\([^\\)]*\\)|\\"[^\\"]*\\"|\\S+', self.expression)\n print(match)\n try:\n last = float(self.evaluate(match.pop(-1)))\n self.expression = f'{" ".join(match)} {math.sqrt(last)}'\n print(self.expression)\n self.evaluate(self.expression)\n except ValueError: # Should be called if try negative num\n print("Error")\n self.answer.set("Imaginary Answer")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T16:37:01.843",
"Id": "501828",
"Score": "0",
"body": "Thanks for answering this question. I'll try to use more formatted strings in my programs, I honestly didn't know that you could use them in such a way '.'"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T16:03:58.023",
"Id": "254450",
"ParentId": "254447",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254449",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T15:14:53.607",
"Id": "254447",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"tkinter"
],
"Title": "Basic python GUI Calculator using tkinter"
}
|
254447
|
<p>first allow me to explain the what the purpose of this program is:
a "barcode" as I'm calling it consists of three parts:</p>
<ol>
<li><strong>plant_id</strong>=['ATX','HOU','CHS']</li>
<li><strong>Serial Number</strong>: a string of 9-digits</li>
<li><strong>mod 10 digit</strong>: A digit (as a chr()) between 0-9 that is assigned randomly to the end of a barcode.</li>
</ol>
<p>So a full barcode would look like this:</p>
<p><strong>'ATX9784634072'</strong>: (ATX=plan_id, '978463407'=serial_number, and '2' is the mod 10 digit)</p>
<p><strong>Note:</strong> for each serial number there can only be one barcode. So in this case there are no other barcodes with the serial number 978463407. The plant ID simply indicates the plant that manufactured the item. Thus for each serial number there are 3*10=30 possible barcodes and only one is valid.</p>
<p>Any other barcode with serial number 978463407 will be invalid regardless of it's pland_id value or its mod_10 digit value.</p>
<p>Thus far I have an iterator class called BarcodeIterator that only iterates over the serial numbers in a given range (start and stop arguments).</p>
<p>Then I have a generator function bar_code_generator, that takes an instance of BarcodeIterator() as a parameter to generate the full bar codes.</p>
<pre><code>## Let me begin by explaining the structure of the barcodes in question
## The barcode is made up of three parts. The Plant ID,
## The serial number, then a mod_10 digit. (For purposes of this
## code, I'm going to assume this is a random number between 1 and 10
## Example: 'ATX9784634068',
Plants=['ATX','HOU','DFW']
s_num0='978463406'
s_num1='978463407'
s_num2='978463408'
class BarcodeIterator:
def __init__(self,barcode,start,stop,
plant_ID=['ATX','HOU','CHS']):
self.plant=barcode[:3]
self.serial_number=barcode[3:12]
self.mod_10=barcode[-1]
self.start = int(self.serial_number)-start-1
self.stop = int(self.serial_number)+stop
self.plant_ID=plant_ID
def __next__(self):
self.start+=1
if self.start>self.stop:
raise StopIteration
else:
start_string=str(self.start)
result=start_string.zfill(9)
return result
def __iter__(self):
return self
def bar_code_generator(iterObj,plant_ID=['ATX','HOU','CHS']):
for bc in iterObj:
for p_id in plant_ID:
def get_mod():
x0='0'
while x0<='9':
yield x0
x0=chr(ord(x0)+1)
for digit in get_mod():
barcode_tuple=(p_id,bc,digit)
barcode_string=''.join(barcode_tuple)
yield barcode_string
##class Barcode:
'''going to be my iterable class'''
## def __init__(self, barcode):
## self.barcode = barcode
## self.plant_id=barcode[:3]
## ....
##
## def __iter__(self):
## return BarcodeIterator(
if __name__=='__main__':
bc_iter=BarcodeIterator(s_num0,1,1)
bc_gen=bar_code_generator(bc_iter)
bc_list=[bc for bc in bc_gen]
print(bc_list)
and the result is this:
['ATX0004634050', 'ATX0004634051', 'ATX0004634052', 'ATX0004634053'
, 'ATX0004634054', 'ATX0004634055', 'ATX0004634056', 'ATX0004634057'
, 'ATX0004634058', 'ATX0004634059', 'HOU0004634050', 'HOU0004634051'
, 'HOU0004634052', 'HOU0004634053', 'HOU0004634054', 'HOU0004634055'
, 'HOU0004634056', 'HOU0004634057', 'HOU0004634058', 'HOU0004634059'
, 'CHS0004634050', 'CHS0004634051', 'CHS0004634052', 'CHS0004634053', . . . it continues
</code></pre>
<p>Finally, my question (or plea for help) is this:</p>
<p>I want to:</p>
<p>clean this code up a lot: I would really like to have a BarcodeIterator() object and a Barcode() object (the iterable). So that each time I call an instance of Barcode() it returns the next valid Barcode... which brings me to my second question</p>
<p>As I have mentioned twice. There is only one valid barcode per serial number (hence, 30 possible barcodes). I haven't put an isValid() function in the scrip because I don't know where it would go.</p>
<p>I want to see each time the Barcode() object is called, it yields the next valid barcode without having to create a new object (if possible).</p>
<p>I hope this was clear. Any help will be greatly appreciated.</p>
<p>Please post here, but if you have vast experience in python and want to work with me on this you are more than welcome to pm me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T19:33:17.003",
"Id": "501837",
"Score": "0",
"body": "What determines which barcode is valid?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T21:03:12.353",
"Id": "501844",
"Score": "1",
"body": "There is *`plant_id`, plan_id, plant ID*, and *pland_id* above."
}
] |
[
{
"body": "<p>Why would a barcode be in charge of finding more barcodes? That seems really strange.</p>\n<p>Beyond that, there seems to be a lot of unecessary juggling betwen iterators, generators, and the barcode class here.</p>\n<pre><code>def serial_strings(start, count):\n return (\n str(serial_num).zfill(9)\n for serial_num in range(start, start+count)\n )\n\ndef barcodes(serial_start=0, serial_count=1, plants=['ATX','HOU','CHS']):\n return (\n plant+serial+str(digit)\n for serial in serial_strings(serial_start,serial_count)\n for plant in plants\n for digit in range(10)\n )\n\nif __name__=='__main__':\n print(list(barcodes(463405)))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T20:12:48.527",
"Id": "501840",
"Score": "0",
"body": "I'll get back to you in a second. with that. It's a microcosm of a real problem that I don't want to discuss online. But yes. Given a barcode I want to find the other items that were manufacture right before and right after. The serial numbers are assigned sequentially with respect to time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:06:21.487",
"Id": "501856",
"Score": "0",
"body": "So, the serial number part of the barcode is sequential with respect to time. So, barcode: ATX4634051019 (Plant: ATX; serial: 463405101; mod_10: 9) may have been made 2 seconds before HOU4634051027(Plant: HOU; serial: 463405102; mod_10: 7) and so on.\n\nSo, if I want to find the items made around the same time as mine, I need to scan 30 possible bar codes for one bar code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T19:34:46.373",
"Id": "254461",
"ParentId": "254460",
"Score": "0"
}
},
{
"body": "<p>I'm a little too tired to make any ambitious suggestions, but I thought I'd recommend a few minor improvements.</p>\n<p>Your <code>BarcodeIterator</code> class could be significantly neater by just using a generator function. Unless you have a complicated object state used in multiple different ways that also needs to be iterable (like if you're writing a data structure), I've found manually writing iterator classes to have a tendency to convolute code. Even then, the last structure I wrote had its <code>__iter__</code> method as a generator function for simplicity. Instead, I'd use (after removing the un-used bits):</p>\n<pre><code>from typing import Iterator\n\ndef barcode_iterator(barcode: str, start: int, stop: int) -> Iterator[str]:\n serial_number = barcode[3:12]\n start = int(serial_number) - start\n stop = int(serial_number) + stop\n\n while start <= stop:\n start_string = str(start)\n result = start_string.zfill(9)\n yield result\n start += 1\n</code></pre>\n<p>This does away with needing to set up the state in the initializer, just to use it in the one method. This also prevents you from needing to manually throw a <code>StopIteration</code>.</p>\n<p>If you want to have a <code>Barcode</code> class that's iterable and returns only valid results, its <code>__iter__</code> method could look something like this:</p>\n<pre><code>class Barcode:\n def __iter__(self):\n return (code\n for code in barcode_iterator(...)\n if is_valid(code)) # Assuming the existence of an is_valid function\n</code></pre>\n<hr />\n<p><code>get_mod</code> is odd. It being nested inside of the function suggests that it's using something in the enclosing scope. That isn't the case though; it simply returns a list of stringified numbers. The numbers also never change, so it doesn't make much sense as a function. I think this is one of the rare cases where <code>map</code> is actually the most appropriate tool:</p>\n<pre><code>def bar_code_generator(iterObj, plant_ID=['ATX', 'HOU', 'CHS']):\n for bc in iterObj:\n for p_id in plant_ID:\n for digit in map(str, range(10)): # essentially (str(n) for n in range(10))\n barcode_tuple = (p_id, bc, digit)\n barcode_string = ''.join(barcode_tuple)\n yield barcode_string\n</code></pre>\n<hr />\n<p>I also <a href=\"https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument\">wouldn't use <code>['ATX','HOU','CHS']</code> as a default value in the functions</a>. Swap it to using a tuple instead:</p>\n<pre><code>def bar_code_generator(iterObj, plant_ID=('ATX', 'HOU', 'CHS')):\n</code></pre>\n<p>It's a small change, and you likely won't get bitten here, but if you do ever accidentally mutate <code>plant_ID</code>, you'll get very confusing behavior using lists.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:26:53.013",
"Id": "501858",
"Score": "0",
"body": "I love the map suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T00:02:15.520",
"Id": "501860",
"Score": "0",
"body": "Ok I like those two functions!\n\nI want to put them in the BarcodeIterator() class and use the in the __next__() function. Check if the barcodes are valid, if so return the in the __next__() function.\nThen I want to return the BarcodeIterator object in the __iter__() function of the Barcode() object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T00:09:54.510",
"Id": "501862",
"Score": "0",
"body": "@MatthewDoughty The first function I showed replaces the `BarcodeIterator` class (or at least that was my intent). Then, instead of filtering in `__next__`, I'd just use a generator expression and do something like `valid_codes = (code for code in barcode_iterator(...) if is_valid(code))`. I'd produce the unfiltered results from one generator, then have a second generator consume the first and filter as needed. With that, the `__iter__` method of `Barcode` could be just `def __iter__(self): return (code for code in barcode_iterator(...) if is_valid(code)`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:07:01.153",
"Id": "254469",
"ParentId": "254460",
"Score": "2"
}
},
{
"body": "<p>So, the serial number part of the barcode is sequential with respect to time. So, barcode: ATX4634051019 (Plant: ATX; serial: 463405101; mod_10: 9) may have been made 2 seconds before HOU4634051027(Plant: HOU; serial: 463405102; mod_10: 7) and so on. The next serial number would be 463405103, 463405104, 463405105, 463405106, 463405107...</p>\n<p>I don't know what their respective mod_10 digit's are nor their plant_id.</p>\n<p>I want an iterator object that generates the potential barcodes. This is BarcodeIterator():\nIt's next function should checks if each generated barcode is valid, if it is, it returns it and skips to the next serial number. (it doesn't keep checking barcodes with that same serial number)</p>\n<p>The next object Barcode():</p>\n<p>should be the iterable. It should have the <strong>iter</strong>() method and return the next valid barcode when iterated over</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:17:01.683",
"Id": "254470",
"ParentId": "254460",
"Score": "-1"
}
},
{
"body": "<p>Something like this would generate all possible barcodes "near" the given barcode:</p>\n<pre><code>import itertools as it\n\ndef barcode_generator(barcode, start, stop, plants=['ATX','HOU','CHS']):\n serial_number=int(barcode[3:12])\n start = serial_number - start\n stop = serial_number + stop\n\n for serial, plant, suffix in it.product(range(start, stop), plants, range(10)):\n yield f"{plant}{serial:09}{suffix}"\n</code></pre>\n<p>It can be used like this:</p>\n<pre><code>for bcode in barcode_generator('HOU1234567890', 1, 1):\n print(bcode)\n</code></pre>\n<p>Or, if you need the generator object:</p>\n<pre><code>bcgen = barcode_generator('HOU1234567890', 1, 1)\nprint(next(bcgen))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T00:22:59.927",
"Id": "254475",
"ParentId": "254460",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T18:43:06.597",
"Id": "254460",
"Score": "3",
"Tags": [
"python",
"object-oriented"
],
"Title": "Generates barcodes using iterator objects and an iterable objects"
}
|
254460
|
<p>I have written this code that reads a JSON and CSV files compares them and outputs to a text file This output file will contains the association that my program has created in the following format
<CSV_SENSOR_ID>:<JSON_SENSOR_ID>. If a flying object was only picked up by one of the sensors, the
other sensor’s ID should be reported as -1. If the distance between two readings is below 100 then we can assume that both IDs match.</p>
<p>I understand that the bulk of my code is in the checkJSON function and the distance calculations, I was wondering if anyone has ideas to improve the speed and space requirements for this program and task!</p>
<pre><code>#include <vector>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
//using namespace std;
std::string filenameA = "input.csv";
std::string filenameB = "input.json";
/*
* utlity function that converts degrees to radians
* code
* @param degree: angle in degrees
*/
long double toRadians(const long double degree)
{
// cmath library in C++
// defines the constant
// M_PI as the value of
// pi accurate to 1e-30
long double one_deg = (M_PI) / 180;
return (one_deg * degree);
}
/**
* function that calculates the distance give longitudes and latitudes
* code obtained from: https://www.geeksforgeeks.org/program-distance-two-points-earth/
*/
long double distance(long double lat1, long double long1,
long double lat2, long double long2)
{
// Convert the latitudes
// and longitudes
// from degree to radians.
lat1 = toRadians(lat1);
long1 = toRadians(long1);
lat2 = toRadians(lat2);
long2 = toRadians(long2);
// Haversine Formula
long double dlong = long2 - long1;
long double dlat = lat2 - lat1;
long double ans = pow(sin(dlat / 2), 2) +
cos(lat1) * cos(lat2) *
pow(sin(dlong / 2), 2);
ans = 2 * asin(sqrt(ans));
// Radius of Earth in
// Kilometers, R = 6371
// Use R = 3956 for miles
long double R = 6371;
// Calculate the result
ans = ans * R*1000; //answer in metres
return ans;
}
/*
* creating a structure of type SensorData that
* holds the values for the ID, latitude and longitude
*/
struct SensorData {
int id;
std::string latitude;
std::string longitude;
};
std::vector<SensorData> csvData; //creating an array of type sensor data
std::vector<std::string> outputData; // creating an output dataArray that is going to be used to write to file
/**
* function that reads the CSV file and
* stores the data read into the csvData array
*
* @param filename: the name of the input file that is going to be reads
*/
void readCSV(std::string filename){
std::ifstream file(filename);
std::string input;
std::getline(file, input);
while(std::getline(file, input)){
std::stringstream ss(input);
std::vector<std::string> data;
while(ss.good()){
std::string sub;
std::getline(ss, sub, ',');
data.push_back(sub);
}
if(data.size() == 3) {
SensorData locData = {std::stoi(data[0]), data[1], data[2]};
csvData.push_back(locData);
}
}
}
/**
* function that reads the JSON file and
* compares the longitude and latitude to the CSV file and places the matching IDs in an output vector
* also matches the flying objects detected by only the JSON "sensor" to -1.
* @param filename: the name of the input file that is going to be reads
*/
void checkJSON(std::string filename){
std::ifstream file(filename);
while(file){
std::string input;
std::getline(file, input, '}');
if(input.size() < 6)
continue;
std::stringstream ss(input.substr(6));
std::vector<std::string> data;
while(ss.good()){
std::string sub;
std::getline(ss, sub, ',');
sub = sub.substr(sub.find_first_not_of(" \t\n\r\v\f"));
if(sub[1] == 'I')
data.push_back(sub.substr(7, sub.size() - 8));
else if(sub[2] == 'a')
data.push_back(sub.substr(12, sub.size() - 1));
else
data.push_back(sub.substr(13, sub.size() - 1));
}
bool found = false;
for(auto i = csvData.begin(); i != csvData.end(); ++i){
if((data[1] == i->latitude && data[2] == i->longitude) || distance(stold(data[1]), stold(data[2]), stold(i->latitude), stold(i->longitude))<=100)
{
std::string output = std::to_string(i->id);
output += ":";
output += data[0];
output += "\n";
outputData.push_back(output);
csvData.erase(i);
found = true;
break;
}
}
if(!found){
std::string output = "-1:";
output += data[0];
output += "\n";
outputData.push_back(output);
}
}
file.close();
}
/**
* function that writes to an output text file. It also
* matches flying objects picked up by only the CSV "sensor" file to -1.
*/
void writeFile(){
std::string output = "output";
output += filenameA[7];
output += ".txt";
std::ofstream file(output);
if (!file)
{
std::cerr << "Error opening file for writing" << std::endl;
return;
}
for(auto i : outputData){
std::cout << i;
file << i;
}
if(csvData.size() != 0){
for(auto i : csvData){
std::string output = std::to_string(i.id);
output += ":-1\n";
std::cout << output;
file << output;
}
}
file.close();
}
int main(int argc, char * argv[]){
if(argc != 1 && argc != 3){
std::cerr << "Invalid arguments" << std::endl;
exit(1);
}
if(argc == 3){
filenameA = argv[1];
filenameB = argv[2];
}
readCSV(filenameA);
checkJSON(filenameB);
writeFile();
}
</code></pre>
|
[] |
[
{
"body": "<h1>General advice</h1>\n<h2>Use proper types</h2>\n<p>One of the best things you can do to make C++ code better and—<em>usually</em>—faster (either compiling faster, running faster, or both) is to make proper types. C++ is a strongly-typed language, probably <em>the</em> most strongly-type language in popular use. Lean into that. Take advantage of it. Reap the rewards.</p>\n<p>For example…</p>\n<p>Your program is working a lot with numbers. All kinds of numbers, which can easily get mixed up. For this, it might be a good idea to use a units library. The state of the art is <a href=\"https://mpusz.github.io/units/\" rel=\"nofollow noreferrer\">mp-units</a>. (There’s also <a href=\"https://www.boost.org/doc/libs/release/doc/html/boost_units.html\" rel=\"nofollow noreferrer\">Boost.Units</a> if you’re already using Boost.)</p>\n<p>To see why a units library can help, look at this bit of your code:</p>\n<pre><code>// Radius of Earth in \n// Kilometers, R = 6371 \n// Use R = 3956 for miles \nlong double R = 6371; \n \n// Calculate the result \nans = ans * R*1000; //answer in metres\n</code></pre>\n<p>If someone who actually wants the result in US customary units, if they make the mistake of merely replacing <code>long double R = 6371;</code> with <code>long double R = 3956;</code>… they’re going to get the answer in “milli-miles”.</p>\n<p>With a units library, you could define your constants like so:</p>\n<pre><code>#include <units/physical/si/si.h>\n#include <units/physical/si/us/us.h>\n\nusing namespace units::physical::si::literals;\n\nconstexpr auto radius_of_earth = 6371_q_km;\n// if someone would rather work with us units, then they could just replace\n// the above line with:\nconstexpr auto radius_of_earth = 3956_q_mi_us;\n// and the program would still work correctly.\n</code></pre>\n<p>But even without a units library, using proper types could net you <em>massive</em> gains in speed, safety, and flexibility.</p>\n<p>One place where you would probably see a lot of gains is your <code>SensorData</code> type. As it’s currently written, you keep the ID as an <code>int</code>… but the latitude and longitude as strings. Then in <code>checkJSON()</code>, you first try a string comparison which… not a great idea, really… and then fallback on converting everything to <code>long double</code> to do the distance comparison. The upshot of this is that <code>SensorData</code> is a <em>lot</em> bigger than it needs to be (strings are <em>much</em> bigger than <code>long double</code>s on any platform I’ve ever heard of), and a <em>lot</em> slower when comparing with other data (string comparisons are a <em>lot</em> slower than comparing doubles—even with an epsilon (more on that shortly)).</p>\n<p>So if you made a <em>proper</em> class for the sensor data:</p>\n<pre><code>class SensorData\n{\n int id;\n double latitude;\n double longitude;\n\n // proper inserter function:\n friend auto operator>>(std::istream& in, SensorData& data) -> std::istream&\n {\n auto temp = sensor_data{};\n auto comma = char{};\n\n in >> temp.id;\n in >> comma; // optional: confirm that comma is a comma\n // even better, you could write a manipulator that\n // checks for a comma, then ignores it\n in >> temp.d1;\n in >> comma;\n in >> temp.d2;\n\n // ignore rest of line (which should be nothing but a newline char)\n // if you want, you can confirm this, or just assume it's always\n // true and skip this line\n if (in.ignore(std::numeric_limits<std::streamsize>::max(), '\\n'))\n // only if the input isn't bad or fail, save the result\n data = std::move(temp);\n\n return in;\n }\n};\n</code></pre>\n<p>Now, watch what that does to just <code>readCSV()</code> for example:</p>\n<pre><code>auto readCSV(std::filesystem::path const& path)\n{\n auto file = std::ifstream{path};\n \n // you should usually, if not always, do this\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n // turn off locale stuff so numbers parse properly\n // you should *always* do this unless you want locale stuff\n file.imbue(std::locale::classic());\n\n // Looks like we need to ignore one line (a header line?)\n file.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\n return std::vector(\n std::istream_iterator<SensorData>{file},\n std::istream_iterator<SensorData>{}\n );\n}\n</code></pre>\n<p>Yup, that’s it. That’s literally it. And not only will your data vector be <em>much</em> smaller—possibly nearly a third of the size—the whole read function will probably be <em>hundreds</em>, if not <em><strong>THOUSANDS</strong></em> of times faster due to not needing a new string stream and vector for each data point. In addition, everything else involving the CSV data will be faster too, because, since each data point is now so much smaller, more of them will fit in cache.</p>\n<p>And, really, you should have types for the IDs, too, so they don't get fuggered up when being printed. (For example, you wouldn’t want IDs converted to hex… that makes no sense.) But for a tiny, one-off program, it’s probably not worth it.</p>\n<p>I always teach this mantra to my students: In C++, if you get the <em>types</em> right, everything else just magically falls into place. It’s worth it.</p>\n<h2>Don’t use <code>long double</code></h2>\n<p><code>long double</code> is some bullshit. There, I said it.</p>\n<p>On any platform you’re likely to be running this code on, <code>double</code> will give you ~15–16 digits of precision, while <code>long double</code> <em>MAY</em> (more on that in a sec) give you ~19 (at most ~34 on, like 64-bit ARM). Are you <em>really</em> in a situation where you absolutely cannot tolerate an error of 0.00000000000001… but an error of 0.000000000000000001 is okay? I mean, are you seriously concerned about 0.00000000000001°… which is roughly 0.000000000111 metres, or 111 <em>pico</em>metres <em>in the worst case</em>? Are you trying to distinguish between individual atoms at the equator?</p>\n<p>Because, here’s the thing: the <em>cost</em> of those extra 3–4 digits of precision is <em>high</em>. Not only are you paying for 2 more bytes <em>per value</em>, you’re often also paying for extra padding bytes for alignment to keep <code>double</code>s on 64-bit address boundaries. Yikes. All that extra space costs big by bumping data out of cache.</p>\n<p>Also, the larger size of <code>long double</code> means it’s harder for them to be vectorized. You may shrug at the <em>size</em> difference—<code>double</code>s are 8 bytes, <code>long doubles</code> are 10, and meh, what’s 2 piddly bytes… but simple operations like adding two values can be like 4 or 8 times faster with <code>double</code>s than with <code>long double</code>s due to better vectorization. SSE can work with 2 <code>double</code>s at a time, AVX can do 4, and AVX-512 can do 8. For example, with AVX, those 4 lines at the start of <code>distance()</code> can basically be done simultaneously. Even old-school SSE can do two at a time.</p>\n<p>In fact, and this may come as a shock to you, if you’re using MSVC… then there <em>is</em> no <code>long double</code>. <a href=\"https://docs.microsoft.com/en-us/cpp/cpp/data-type-ranges?view=msvc-160\" rel=\"nofollow noreferrer\"><code>long double</code> just maps to <code>double</code></a>. Why? Because <code>long double</code> doesn’t work with SSE. (GCC still uses an 80-bit <code>long double</code>, though.)</p>\n<p>Just use <code>double</code>. Not only is it less typing, it’s smaller, faster, and you may already be using it anyway.</p>\n<h1>Code review</h1>\n<pre><code>std::string filenameA = "input.csv";\nstd::string filenameB = "input.json";\n</code></pre>\n<p>Your code uses several globals, which is never a great idea, and in this case, there are no real benefits. These variables could be local to <code>main()</code>.</p>\n<p>Also, these are paths. Rather than using naked strings, you should use the proper type: <code>std::filesystem::path</code>.</p>\n<pre><code>long double toRadians(const long double degree) \n{ \n // cmath library in C++ \n // defines the constant \n // M_PI as the value of \n // pi accurate to 1e-30 \n long double one_deg = (M_PI) / 180; \n return (one_deg * degree); \n}\n</code></pre>\n<p>No, sorry, the <code><cmath></code> library does no such thing. <code>M_PI</code> is not part of C++ (or C for that matter), though it’s a common extension. And as for it being accurate to 30 decimal places… that’s just absurd. GCC only defines it with ~20 digits (which is already way more digits than necessary).</p>\n<p>Math constants are available in C++20. If you have a recent compiler, you can include <code><numbers></code>, and then π is <code>std::numbers::pi</code>.</p>\n<p>If you don’t have C++20, then you have to do things the bad old way:</p>\n<pre><code>#ifndef M_PI\n# define M_PI 3.14159265358979323846\n#endif\n</code></pre>\n<p>Either way, you should use a <code>constexpr</code> constant:</p>\n<pre><code>auto toRadians(double degrees)\n{\n constexpr auto degrees_to_radians = std::numbers::pi / 180.0;\n\n return degrees * degress_to_radians;\n}\n</code></pre>\n<p>That constant isn’t really useful outside of that function, so you might as well keep it there.</p>\n<p>In <code>distance()</code>:</p>\n<pre><code>long double distance(long double lat1, long double long1, \n long double lat2, long double long2) \n{ \n // Convert the latitudes \n // and longitudes \n // from degree to radians. \n lat1 = toRadians(lat1); \n long1 = toRadians(long1); \n lat2 = toRadians(lat2); \n long2 = toRadians(long2); \n \n // Haversine Formula \n long double dlong = long2 - long1; \n long double dlat = lat2 - lat1; \n \n long double ans = pow(sin(dlat / 2), 2) + \n cos(lat1) * cos(lat2) * \n pow(sin(dlong / 2), 2); \n \n ans = 2 * asin(sqrt(ans)); \n \n // Radius of Earth in \n // Kilometers, R = 6371 \n // Use R = 3956 for miles \n long double R = 6371; \n \n // Calculate the result \n ans = ans * R*1000; //answer in metres\n \n return ans; \n} \n</code></pre>\n<p>You’re missing <em>several</em> <code>std::</code> for all the math functions.</p>\n<p>I don’t recommend relying on operator precedence for things to work. So when calculating <code>ans</code>, you probably want to put some parentheses around the last three terms.</p>\n<p>As for the constant <code>R</code>, you should never use all uppercase names for anything but preprocessor definitions. In any case, the radius of the Earth is a useful constant that might change (you might make it more precise, for example). For that reason, you should probably pull it out of the function and give it a proper name:</p>\n<pre><code>constexpr auto mean_radius_of_earth = 6371.0; // radius of Earth in km\n</code></pre>\n<p>Now, if you’re going to work in one unit, and you’re not using a units library, you’re better off sticking to that one unit. You want the distance in metres, so:</p>\n<pre><code>constexpr auto mean_radius_of_earth = 6'371'008.8 ; // radius of Earth in m\n</code></pre>\n<p>If you want to use miles or feet or whatever instead, you just need to change this one constant.</p>\n<pre><code>/*\n * creating a structure of type SensorData that \n * holds the values for the ID, latitude and longitude\n */\nstruct SensorData {\n int id;\n std::string latitude;\n std::string longitude;\n};\n\nstd::vector<SensorData> csvData; //creating an array of type sensor data\nstd::vector<std::string> outputData; // creating an output dataArray that is going to be used to write to file\n</code></pre>\n<p>I’ve already shown how you can improve <code>SensorData</code>, and both of those globals shouldn’t be globals.</p>\n<pre><code>void readCSV(std::string filename){\n std::ifstream file(filename);\n std::string input;\n std::getline(file, input);\n while(std::getline(file, input)){\n std::stringstream ss(input);\n std::vector<std::string> data;\n while(ss.good()){\n std::string sub;\n std::getline(ss, sub, ',');\n data.push_back(sub);\n }\n if(data.size() == 3) {\n SensorData locData = {std::stoi(data[0]), data[1], data[2]};\n csvData.push_back(locData);\n }\n }\n}\n</code></pre>\n<p>I’ve already shown how <code>readCSV()</code> can be improved if you improve <code>SensorData</code>, but I’ll dig into this function anyway.</p>\n<p>First, you don’t want to be taking the function argument by value. That creates a copy of the string… and there’s no point. If you’re just going to be looking at its value, you should take the argument by <code>const&</code>. (It won’t make a practical difference, because most likely your filenames are short enough for the small string optimization, and anyway it’s just one copy in the whole program, so it won’t matter.)</p>\n<p>The first thing you do in the function is create the input stream… good. And then you create a string to hold the current line… also good, though you should probably give this a better name. Like <code>line</code>, because that’s what it is. Then you get a line and discard it… no problem, I guess it’s a header line, right? Then you start the loop, checking the state of the file after each <code>getline()</code>… all good.</p>\n<p>Inside the loop is where your troubles begin. First you create a string stream… not great, but… well, I mean, you need a fresh string stream each loop iteration, so, meh. (You should also imbue the classic locale, because you’re parsing numbers. But that’s no big deal either.)</p>\n<p>However, the <em>next</em> line creates a vector… <em>in every loop iteration</em>. <em>THAT</em> is going to slow you down. And it’s especially wasteful because you reuse the vector over and over, and it will (should!) be the same size every time. By putting the vector inside the loop, you’re paying for reallocation over and over and over. Worse, you’re not even using the fact that you know it will (should!) be 3 elements long, and pre-allocating, so it’s <em>possible</em> (though not likely) that each call to <code>push_back()</code>—which is happening 3 times <em>per loop</em>—is allocating memory.</p>\n<p>So let’s start by pulling the vector out of the loop… and give it a better name than “data”:</p>\n<pre><code>auto readCSV(std::filesystem::path const& path)\n{\n std::vector<SensorData> csv_data;\n\n std::ifstream file{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n std::string line;\n std::vector<std::string> line_parts;\n line_parts.reserve(3); // we expect 3 parts on each line\n\n // skip the header line?\n std::getline(file, line);\n\n while (std::getline(file, line))\n {\n std::istringstream ss{line};\n ss.imbue(std::locale::classic());\n\n // ... [snip] ...\n\n // clear the line parts for the next loop iteration\n // this shouldn't actually free the memory, though, so it can be\n // reused\n line_parts.clear()\n }\n\n return csv_data;\n}\n</code></pre>\n<p>Now the next thing you do is read “lines” from the string stream, using commas as the “end-of-line” delimiter, and store them in the <code>line_part</code> vector. But that requires another string, which is being created again and again each time through the loop. <em>Hopefully</em> each string is small enough that it doesn’t require allocation… but I don’t know what your data looks like. To be safe, you should pull the string out of the loop:</p>\n<pre><code>auto readCSV(std::filesystem::path const& path)\n{\n std::vector<SensorData> csv_data;\n\n std::ifstream file{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n std::string line;\n std::string line_part;\n std::vector<std::string> line_parts;\n line_parts.reserve(3);\n\n // skip the header line?\n std::getline(file, line);\n\n while (std::getline(file, line))\n {\n std::istringstream ss{line};\n ss.imbue(std::locale::classic());\n\n while (std::getline(ss, line_part, ','))\n line_parts.push_back(line_part); // !!!\n\n // ... [snip] ...\n\n line_parts.clear()\n }\n\n return csv_data;\n}\n</code></pre>\n<p>But there’s still a problem. On that line marked with <code>!!!</code>, you’re <em>copying</em> <code>line_part</code> into <code>line_parts</code> every time. You <em>could</em> change that to a move, but… then we lose all the benefits of having <code>line_part</code> outside of the loop; the memory is no longer being re-used each time through the loop, because we’re moving it away each time, so each new time through it has to be re-allocated.</p>\n<p>Let’s rethink.</p>\n<p>Here’s an interesting idea. What if we tried reading each line part <em>directly</em> into the <code>line_parts</code> vector. The catch is, we’d need one extra element in order to account for that last, failed read. But that’s okay, because if all the memory is allocated at the start, it costs us nothing to have one extra string there each loop.</p>\n<p>So we could do this:</p>\n<pre><code>auto readCSV(std::filesystem::path const& path)\n{\n std::vector<SensorData> csv_data;\n\n std::ifstream file{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n std::string line;\n std::vector<std::string> line_parts;\n line_parts.reserve(4); // expect 3 parts + 1 space for the last attempted read\n\n // skip the header line?\n std::getline(file, line);\n\n while (std::getline(file, line))\n {\n std::istringstream ss{line};\n ss.imbue(std::locale::classic());\n\n while (true)\n {\n // make space for the next part\n //\n // so long as this loop is run no more than 4 times, it should\n // never allocate, because we reserved 4 (3 + 1) spaces\n line_parts.emplace_back();\n\n // try to read a part\n if (not std::getline(ss, line_parts.back(), ','))\n {\n // failed to read a part, so remove the space we made, and\n // then quit the loop\n line_parts.pop_back();\n\n break;\n }\n }\n\n // ... [snip] ...\n\n line_parts.clear()\n }\n\n return csv_data;\n}\n</code></pre>\n<p>Not bad! Now all you need to do is parse what was read:</p>\n<pre><code>auto readCSV(std::filesystem::path const& path)\n{\n std::vector<SensorData> csv_data;\n\n std::ifstream file{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n std::string line;\n std::vector<std::string> line_parts;\n line_parts.reserve(4);\n\n // skip the header line?\n std::getline(file, line);\n\n while (std::getline(file, line))\n {\n std::istringstream ss{line};\n ss.imbue(std::locale::classic());\n\n while (true)\n {\n line_parts.emplace_back();\n\n if (not std::getline(ss, line_parts.back(), ','))\n {\n line_parts.pop_back();\n\n break;\n }\n }\n\n if (line_parts.size() == 3)\n {\n csv_data.emplace_back(\n std::stoi(line_parts[0]),\n std::stod(line_parts[1]),\n std::stod(line_parts[2]));\n }\n else\n {\n // maybe throw an exception? to detect malformed data?\n throw std::runtime_error{"malformed CSV line: " + line};\n }\n\n line_parts.clear()\n }\n\n return csv_data;\n}\n</code></pre>\n<p>This isn’t bad already. With most of the variables hoisted outside the loop, memory can be reused from one loop iteration to the next. That alone should make this function <em>MUCH</em> faster.</p>\n<p>Can we do even better?</p>\n<p>Maybe!</p>\n<p>Do we really need to put the three parts of each line in a vector? What if we parsed each one as we went along?</p>\n<pre><code>// IOstreams manipulator\nclass ignore_char\n{\n char _c;\n\npublic:\n explicit constexpr ignore_char(char c) noexcept : _c{c} {}\n\n friend auto operator>>(std::istream& in, ignore_char ic) -> std::istream&\n {\n // read in one character as a formatted input read\n if (auto c = char{}; in >> c)\n {\n // if the char read isn't what was expected, signal failure\n if (c != ic._c)\n in.setstate(std::ios_base::failbit);\n }\n \n return in;\n }\n};\n\nauto readCSV(std::filesystem::path const& path)\n{\n std::vector<SensorData> csv_data;\n\n std::ifstream file{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n std::string line;\n\n // skip the header line?\n std::getline(file, line);\n\n while (std::getline(file, line))\n {\n std::istringstream ss{line};\n ss.imbue(std::locale::classic());\n\n auto id = int{};\n auto latitude = double{};\n auto longitude = double{};\n\n ss >> id >> ignore_char(',')\n >> latitude >> ignore_char(',')\n >> longitude;\n\n // the rest of ss should be empty\n // if you want, you can confirm, maybe via another manipulator\n\n // if all the reads above were good, then save the data point\n if (ss)\n {\n csv_data.emplace_back(id, latitude, longitude);\n }\n else\n {\n // maybe throw an exception? to detect malformed data?\n throw std::runtime_error{"malformed CSV line: " + line};\n }\n }\n\n return csv_data;\n}\n</code></pre>\n<p>But once you’ve done that, you don’t really need the string stream:</p>\n<pre><code>auto readCSV(std::filesystem::path const& path)\n{\n std::vector<SensorData> csv_data;\n\n std::ifstream file{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.imbue(std::locale::classic());\n\n // skip the header line?\n file.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\n auto id = int{};\n auto latitude = double{};\n auto longitude = double{};\n\n while (file >> id >> ignore_char(',') >> latitude >> ignore_char(',') >> longitude)\n {\n csv_data.emplace_back(id, latitude, longitude);\n }\n\n // you can check if file.eof() is true, to make sure everything was read\n // and if not, throw an error\n\n return csv_data;\n}\n</code></pre>\n<p>Which is basically the same code as the version from earlier, where <code>SensorData</code> had its own extractor function.</p>\n<p>The next function is <code>checkJSON()</code>, and it’s a whopper. It does at least 3 things:</p>\n<ol>\n<li>It loops through the file, and for each block of JSON data:\n<ol>\n<li>It parses the block, basically, <code>SensorData</code>.</li>\n<li>It searches <code>csvData</code> for a matching object.\n<ul>\n<li>If a match is found:\n<ol>\n<li>It records the matched pair of IDs.</li>\n<li>It removes the matched item from <code>csvData</code></li>\n</ol>\n</li>\n<li>Otherwise:\n<ol>\n<li>It records the unmatched ID.</li>\n</ol>\n</li>\n</ul>\n</li>\n</ol>\n</li>\n</ol>\n<p>That’s a lot of work for one function, so one of the first things you need to do to bring this function under control is break some of this business out into other functions.</p>\n<p>To start with, let’s extract the parsing.</p>\n<pre><code>auto parse_json_sensor_data(std::istream& in, sensor_data& data) -> std::istream&\n{\n // basically, everything between:\n \n // std::string input;\n // std::getline(file, input, '}');\n // ...\n // \n // else\n // data.push_back(sub.substr(13, sub.size() - 1));\n // }\n\n // and then:\n \n // data.id = std::stoi(data[0]);\n // data.latitude = std::stod(data[1]);\n // data.longitude = std::stod(data[2]);\n //\n // return in;\n}\n\nauto checkJSON(std::filesystem::path const& path)\n{\n auto file = std::ifstream{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n auto data = sensor_data{};\n while (parse_json_sensor_data(file, data))\n {\n // ... [snip] ...\n }\n}\n</code></pre>\n<p>Now I didn’t actually fill in <code>parse_json_sensor_data()</code>, because I can’t. You didn’t give any information about the file format. I might be able to reverse engineer parts of it from your existing code… but that would only give me an incomplete picture, and I wouldn’t be able to offer any suggestions for improving the algorithm, because I would only have the algorithm… not the data. All I could do is suggest ways to make the existing algorithm prettier; without knowing what the data looks like, I have no idea if there’s a better algorithm, or even if the existing code is wrong.</p>\n<p>So I can’t help you with the parsing. But hopefully you can take some of the tips for parsing the CSV and apply them, such as: avoid that vector of strings, and try parsing directly from the stream rather than creating a separate string stream and parsing from that. In any case, now that the JSON parsing is its own function, you can optimize the hell of out that separately from the rest of <code>checkJSON()</code>.</p>\n<p>Anywho, once you’ve got the data parsed, you need to find if it’s in <code>csvData</code>. Okay, first of all, you shouldn’t use a global for this, so you should add an argument to the function:</p>\n<pre><code>auto checkJSON(std::filesystem::path const& path, std::vector<SensorData> csvData)\n{\n auto file = std::ifstream{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n\n auto data = sensor_data{};\n while (parse_json_sensor_data(file, data))\n {\n // ... [snip] ...\n }\n}\n</code></pre>\n<p>Note we can take it by value because we’re not just reading it, we’re also modifying it.</p>\n<p>Now, you have a bug in your code:</p>\n<pre><code>for(auto i = csvData.begin(); i != csvData.end(); ++i){\n // ... [snip] ...\n csvData.erase(i);\n // ... [snip] ...\n}\n</code></pre>\n<p>Never, ever modify a container while iterating over it. In this case, when you erase the element, you invalidate the iterators… which means your whole loop is now borked. You probably got lucky because your stdlib’s vector iterators are ultimately just simple pointers, and erasing doesn’t reallocate, so it just <em>appears</em> to work. On the other hand… it might be skipping data! Have you checked?</p>\n<p>Let’s think about what’s really going on here. You have two containers: <code>csvData</code> and <code>outputData</code>. You want to find an element in <code>csvData</code>, and <em>if</em> you find it, remove it (after taking its data and put it in <code>outputData</code>. If you <em>don’t</em> find it, you just want to put other data in <code>outputData</code>.</p>\n<p>What this sounds like is <code>std::remove_if()</code> (plus you need to use <a href=\"https://en.wikipedia.org/wiki/Erase-remove_idiom\" rel=\"nofollow noreferrer\">the erase-remove idiom</a>):</p>\n<pre><code>csvData.erase(\n std::remove_if(csvData.begin(), csvData.end(),\n [&json_data, &output](auto&& csv_data)\n {\n if ((data[1] == i->latitude && // etc.... (will fix shortly)\n {\n // add csv_data.id and json_data.id to output\n return true; // remove the item from csvData\n }\n else\n {\n // add -1 and json_data.id to output\n return false; // DON'T remove the item from csvData\n }\n }),\n csvData.end()\n);\n</code></pre>\n<p>Now, the way you check the distance is like this:</p>\n<pre><code>(data[1] == i->latitude && data[2] == i->longitude) || distance(stold(data[1]), stold(data[2]), stold(i->latitude), stold(i->longitude))<=100\n</code></pre>\n<p>Now, comparing strings is… not a great idea. String comparisons are <em>SLOW</em>, compared to <code>double</code> comparisons. If you’ve converted <code>SensorData</code> to use <code>double</code>s instead of strings, then you should already see a <em>significant</em> speedup.</p>\n<p><em>HOWEVER</em>, you shouldn’t really compare floating-point numbers with <code>==</code>. Instead, you should use an epsilon. Basically, you take the two numbers, and subtract them, and if the absolute value of their difference is greater than your epsilon, they are not equal. For example:</p>\n<pre><code>constexpr auto epsilon = 0.0000001; // seven decimal places of accuracy should be okay\n\nauto values_are_equal(double v1, double v2)\n{\n return std::abs(v1 - v2) < epsilon;\n}\n</code></pre>\n<p>So now the test is:</p>\n<pre><code>constexpr auto min_distance = 100.0;\n\nif ((values_are_equal(csv_data.latitude, json_data.latitude) and values_are_equal(csv_data.longitude, json_data.longitude))\n or distance(csv_data.latitude, csv_data.longitude, json_data.latitude, json_data.longitude) <= min_distance)\n</code></pre>\n<p>And of course you could save some typing by using functions to make all that much shorter.</p>\n<p>All this should make <code>checkJSON()</code> thousands of times faster.</p>\n<p>But… maybe we can do better!</p>\n<h1>Alternative design</h1>\n<p>Okay, let's start with getting the types right. First we want a type representing the ID and position data that’s being read from both the CSV and JSON files:</p>\n<pre><code>struct sensor_data\n{\n int id;\n double latitude;\n double longitude;\n\n // should really use std::expected instead of std::optional... but don't\n // have that yet.\n static auto read_csv_format(std::istream& in) -> std::optional<sensor_data>;\n static auto read_json_format(std::istream& in) -> std::optional<sensor_data>;\n};\n\nauto sensor_data::read_csv_format(std::istream& in) -> std::optional<sensor_data>\n{\n auto id = int{};\n auto latitude = double{};\n auto longitude = double{};\n\n if (file >> id >> ignore_char(',') >> latitude >> ignore_char(',') >> longitude)\n return sensor_data{id, latitude, longitude};\n else\n return std::nullopt;\n}\n\nauto sensor_data::read_json_format(std::istream& in) -> std::optional<sensor_data>\n{\n // i don't know how to write this function\n}\n</code></pre>\n<p>Now, what you currently do is read all the CSV data into a vector… then read all the JSON data in, comparing it to the CSV data as you go, and so on. The final result you want is a pair of IDs. What if we skip the middleman. You don’t really need that vector of CSV data. It’s not the final result you want. What if, instead, we made a type for the final data:</p>\n<pre><code>struct result_t\n{\n int csv_id = -1;\n int json_id = -1;\n double latitude;\n double longitude;\n}\n</code></pre>\n<p>Now when you read in the CSV data, you save it in a vector of <code>result_t</code>:</p>\n<pre><code>auto read_csv_data(std::filesystem::path const& path)\n{\n auto file = std::ifstream{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.imbue(std::locale::classic());\n\n // header line?\n file.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n\n auto data = std::vector<result_t>{};\n\n while (true)\n {\n if (auto [ok, d] = sensor_data::read_csv_format(file); ok)\n data.emplace_back({.csv_id = d.id, .latitude = d.latitude, .longitude = d.longitude});\n else\n break;\n }\n\n return data;\n}\n</code></pre>\n<p>So, after calling this function, you have a vector of entries, where each entry has a <code>csv_id</code>, <code>latitude</code>, and <code>longitude</code>, and a <code>json_id</code> of <code>-1</code>.</p>\n<p>Now you pass that data into the JSON function:</p>\n<pre><code>auto read_json_data(std::filesystem::path const& path, std::vector<result_t> result_data)\n{\n auto file = std::ifstream{path};\n file.exceptions(std::ifstream::failbit | std::ifstream::badbit);\n file.imbue(std::locale::classic());\n\n while (true)\n {\n if (auto [ok, d] = sensor_data::read_json_format(file); ok)\n {\n auto is_close = [&d](auto&& csv_data)\n {\n return (values_are_equal(csv_data.latitude, d.latitude) and values_are_equal(csv_data.longitude, d.longitude))\n or distance(csv_data.latitude, csv_data.longitude, d.latitude, d.longitude) <= min_distance;\n }\n\n // If you find a data point in the existing result_data that is\n // close, then set its json_id. Since the csv_id is already set,\n // that means the entry now has both IDs set.\n //\n // Otherwise, if you don't find one, add the new json data with\n // a csv_id of -1.\n\n if (auto p = std::find_if(result_data.begin(), result_data.end(), is_close); p != result_data.end())\n p->json_id = d.id;\n else\n result_data.emplace_back({.json_id = d.id, .latitude = d.latitude, .longitude = d.longitude});\n }\n else\n {\n break;\n }\n }\n\n // At this point, any point in result set that was in both the CSV and\n // JSON will have both IDs set.\n //\n // Any point found in the JSON that wasn't in the CSV was added with the\n // CSV ID as -1.\n //\n // And any point that was in the CSV but for which no JSON match was\n // found, it will still have the JSON ID as -1 from read_csv_data().\n\n return result_data;\n}\n</code></pre>\n<p>And of course, writing the output is trivial:</p>\n<pre><code>auto write_results(std::ostream& out, std::vector<result_t> const& data)\n{\n std::for_each(data.begin(), data.end(), [&out](auto&& d)\n {\n out << d.csv_id << ':' << d.json_id << '\\n';\n });\n}\n</code></pre>\n<p>And you main function is also trivial:</p>\n<pre><code>auto const default_csv_path = std::filesystem::path{input.csv"};\nauto const default_json_path = std::filesystem::path{input.json"};\n\nauto main(int argc, char* argv[]) -> int\n{\n if (argc != 1 && argc != 3)\n {\n std::cerr << "Invalid arguments" << std::endl;\n // exit(1); // NEVER use exit() in C++. It doesnt't call destructors.\n\n return EXIT_FAILURE;\n }\n\n auto csv_path = default_csv_path;\n auto json_path = default_json_path;\n\n if (argc == 3)\n {\n csv_path = argv[1];\n json_path = argv[2];\n }\n\n auto data = read_csv_data(csv_path);\n\n data = read_json_data(json_path, std::move(data));\n\n write_result(std::cout, data);\n}\n</code></pre>\n<p>That’s it!</p>\n<h1>Summary</h1>\n<p>Get the types right. That will make a HUGE difference. It makes code easier to read, and it can make large differences in performance, too. You should’t really be trucking longitude and latitude around as strings… because they’re not strings, they’re numeric values.</p>\n<p>Avoid allocations in loops. You also need to be aware of when functions are probably going to be called in loops. For example, a stream extractor for sensor data is pretty likely to be used in a loop that reads sensor data in from a file. Don’t prematurely optimize, but do ask yourself questions like: “do I <em>need</em> to make a vector of strings to parse this data… why can’t I just read the <code>double</code> values directly from the stream into the desired output type”?</p>\n<p>Generally, consider what you really want. Do you want a vector of sensor data? Or… are you really after a collection of CSV IDs and JSON IDs? If the latter, perhaps there’s a way to get the best of both worlds, so you don’t need two large collections of data when you can get away with one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T01:00:13.070",
"Id": "254538",
"ParentId": "254462",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254538",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T20:09:39.807",
"Id": "254462",
"Score": "2",
"Tags": [
"c++",
"performance",
"algorithm"
],
"Title": "Optimizing code that reads a JSON file and a CSV file and compares them and outputs to a file"
}
|
254462
|
<p>I am working with a data set that has many variables. Currently I am storing the data in many indented dictionaries in the following way:</p>
<pre><code>import numpy as np
X_POSITIONS = [0,1.5,1]
Y_POSITIONS = [0,1,2]
CHANNELS = ['left pad', 'right pad', 'top pad', 'bottom pad']
data = {}
for x in X_POSITIONS:
data[x] = {}
for y in Y_POSITIONS:
data[x][y] = {}
for ch in CHANNELS:
data[x][y][ch] = np.random.rand() # Here I would place my data.
</code></pre>
<p>This works fine, but it is cumbersome if by some reason I need to change the order of the keys. Consider the following function:</p>
<pre><code>def do_something_with_single_channel(data_from_one_channel):
for x in data_from_one_channel:
for y in data_from_one_channel[x]:
print(f'x = {x}, y = {y}, data[x][y] = {data_from_one_channel[x][y]}')
</code></pre>
<p>Before calling this function the whole <code>data</code> object has to be rearranged:</p>
<pre><code>new_data = {}
for ch in CHANNELS:
new_data[ch] = {}
for x in X_POSITIONS:
new_data[ch][x] = {}
for y in Y_POSITIONS:
new_data[ch][x][y] = data[x][y][ch]
do_something_with_single_channel(new_data['left pad'])
</code></pre>
<p>Since this seems to be a very common thing to do, I am sure that there must already exist something better than dictionaries for this purpose. Ideally I imagine something that can be accessed in the same way as the arguments of a function by giving names to the variables and forgetting about the order, for example something of the form</p>
<pre><code>do_something_with_single_channel(data[channel='left pad'])
</code></pre>
<p>Does something like this exists? What's the name?</p>
|
[] |
[
{
"body": "<p>Consider a nested dictionary comprehension:</p>\n<pre class=\"lang-py prettyprint-override\"><code>data = {x:{y:{ch: np.random.rand()\n for ch in CHANNELS}\n for y in Y_POSITIONS}\n for x in X_POSITIONS}\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>pprint.pprint(data)\n\n{0: {0: {'bottom pad': 0.4563182938806024,\n 'left pad': 0.7109389987303294,\n 'right pad': 0.04972926343584316,\n 'top pad': 0.49018200203439044},\n 1: {'bottom pad': 0.9197368747212471,\n 'left pad': 0.49675239597387033,\n 'right pad': 0.8846734838851381,\n 'top pad': 0.2536908682927299},\n 2: {'bottom pad': 0.19202917332705682,\n 'left pad': 0.4680743827356374,\n 'right pad': 0.9824888617543756,\n 'top pad': 0.7871922090543111}},\n 1: {0: {'bottom pad': 0.532524614137474,\n 'left pad': 0.5500941768186839,\n 'right pad': 0.046363378683273115,\n 'top pad': 0.507924966038481},\n 1: {'bottom pad': 0.18606527132423667,\n 'left pad': 0.2926470569818338,\n 'right pad': 0.4542221348696881,\n 'top pad': 0.07304292627461106},\n 2: {'bottom pad': 0.255962925458759,\n 'left pad': 0.8206558157675303,\n 'right pad': 0.028156806394849743,\n 'top pad': 0.4617476628686388}},\n 1.5: {0: {'bottom pad': 0.5537703566924752,\n 'left pad': 0.14192043274483335,\n 'right pad': 0.04030969407542717,\n 'top pad': 0.4145838174513119},\n 1: {'bottom pad': 0.10519991606894175,\n 'left pad': 0.33471726599841756,\n 'right pad': 0.10389744180143101,\n 'top pad': 0.3927574328293768},\n 2: {'bottom pad': 0.2950323578101469,\n 'left pad': 0.9335998766267041,\n 'right pad': 0.9337763647877098,\n 'top pad': 0.6591832120994695}}}\n</code></pre>\n<hr />\n<p>However, to retain data of disparate types for later analyses, use <code>pandas</code> Data Frames which are essentially equal length Pandas Series (or 1-D Numpy arrays). And using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"noreferrer\"><code>itertools.product</code></a>, you can return all possible combinations from multiple iterables:</p>\n<pre><code>from itertools import product \n\nimport numpy as np\nimport pandas as pd\n\ndata = list(product(X_POSITIONS, Y_POSITIONS, CHANNELS))\n\n# CAST LIST OF VALUES INTO DATA FRAME AND ASSIGN COLUMN OF RANDOM NUMs\ndf = (pd.DataFrame(data, columns=['X_POSITIONS', 'Y_POSITIONS', 'CHANNELS'])\n .assign(value = np.random.rand(len(data), 1)))\n</code></pre>\n<p><strong>Output</strong> <em>(N=36 for 3 * 3 * 4 product)</em></p>\n<pre class=\"lang-py prettyprint-override\"><code>print(df)\n\n# X_POSITIONS Y_POSITIONS CHANNELS value\n# 0 0.0 0 left pad 0.761372\n# 1 0.0 0 right pad 0.440973\n# 2 0.0 0 top pad 0.182679\n# 3 0.0 0 bottom pad 0.564203\n# 4 0.0 1 left pad 0.954728\n# 5 0.0 1 right pad 0.539686\n# 6 0.0 1 top pad 0.957724\n# 7 0.0 1 bottom pad 0.232217\n# 8 0.0 2 left pad 0.488761\n# 9 0.0 2 right pad 0.883579\n# 10 0.0 2 top pad 0.010666\n# 11 0.0 2 bottom pad 0.022114\n# 12 1.5 0 left pad 0.129402\n# 13 1.5 0 right pad 0.763472\n# 14 1.5 0 top pad 0.475217\n# 15 1.5 0 bottom pad 0.160637\n# 16 1.5 1 left pad 0.521797\n# 17 1.5 1 right pad 0.865391\n# 18 1.5 1 top pad 0.263130\n# 19 1.5 1 bottom pad 0.576295\n# 20 1.5 2 left pad 0.004636\n# 21 1.5 2 right pad 0.137856\n# 22 1.5 2 top pad 0.156635\n# 23 1.5 2 bottom pad 0.198684\n# 24 1.0 0 left pad 0.143598\n# 25 1.0 0 right pad 0.660144\n# 26 1.0 0 top pad 0.588416\n# 27 1.0 0 bottom pad 0.294899\n# 28 1.0 1 left pad 0.915973\n# 29 1.0 1 right pad 0.348533\n# 30 1.0 1 top pad 0.391135\n# 31 1.0 1 bottom pad 0.951016\n# 32 1.0 2 left pad 0.015479\n# 33 1.0 2 right pad 0.719314\n# 34 1.0 2 top pad 0.976324\n# 35 1.0 2 bottom pad 0.191481\n</code></pre>\n<p>To subset data frame by your indicator values:</p>\n<pre class=\"lang-py prettyprint-override\"><code>print(df[df['CHANNELS'] == 'right pad'])\n\n# X_POSITIONS Y_POSITIONS CHANNELS value\n# 1 0.0 0 right pad 0.988888\n# 5 0.0 1 right pad 0.091176\n# 9 0.0 2 right pad 0.334674\n# 13 1.5 0 right pad 0.706215\n# 17 1.5 1 right pad 0.032422\n# 21 1.5 2 right pad 0.024871\n# 25 1.0 0 right pad 0.554525\n# 29 1.0 1 right pad 0.790112\n# 33 1.0 2 right pad 0.650198\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T22:09:41.787",
"Id": "501850",
"Score": "0",
"body": "Thanks, this looks better with data frames!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T22:26:44.267",
"Id": "501943",
"Score": "0",
"body": "I have implemented my code with ```pandas.DataFrame``` and it works, but accessing single elements is incredibly slow. My ```df``` has about 1.5e6 rows and later I need to group the elements according to the values of some of the columns, for example ```df[(df['x']=1)&(df['y']=2)&(df['channel']='left pad')]```. I need to do this for each value of ```x``` and ```y``` and ```channel``` and this takes a considerable amount of time, with the indented dictionaries implementation is super fast (however a bit too rigid)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T22:49:04.347",
"Id": "501944",
"Score": "0",
"body": "According to a time measurement using ```time.time()``` with the data frame it takes about 150 s while with the dictionaries it takes 20 s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T06:10:27.790",
"Id": "501947",
"Score": "0",
"body": "There are *many* `pandas` methods for calculations. Pandas works best in sets not scalar values, especially vectorized calculations. It is not clear what exactly you need to do. Look into `groupby` to run calculations across *all* groups: `df.groupby(['x','y','channel'])['value'].agg(['sum','mean','median','min','max'])`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T21:56:03.397",
"Id": "254465",
"ParentId": "254463",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254465",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T20:10:15.533",
"Id": "254463",
"Score": "4",
"Tags": [
"python",
"hash-map",
"collections"
],
"Title": "Data set with many variables in Python, many indented dictionaries?"
}
|
254463
|
<p>I seem to have taught myself the basics of c++ living off grig in the woods of Alaska.
Most of this has been done on my android phone using cpp droid.
This is the first time anyone has seen any of my code and I am curious what you think of it.
There no error checking and the style may look a little strange on a normal computer.
I do have a laptop, but limited power and a dead battery it makes it hard to use.
I use Linux Mint 18 on it, I am not impressed with Windows or Mac.</p>
<p>This is my attempt at a feedforward backprop neural network with little knowledge of calculus.
I am using only std libraries so it should be platform compatible.</p>
<p>After several attempts trying to follow Pdfs that I could never get to work I created my own.
Some where several thousand lines of code.
I'm hoping I created a program that runs as fast as possible. I am passing almost no parameters in my function and use the variables directly instead of methods.
I think that using the Layers as a derived class of Neuron does not break encapsulation?</p>
<p>I had to comment out the <code>protected:</code> line in Neuron because it was giving me an error.
Do I have to derive Layer by saying <code>:protected</code> instead of <code>:public</code>?
My output layer only holds one neuron so I have not created a vector for it.
I would have used the hand written number detection to test but I could not figure out how to read the file.
There is something about flipping the bits in the header. I do know how to use fstream but it does not work with cpp droid.
I came up with the idea of teaching it to add two numbers but could not figure out how to add whole numbers so decimals it was.
I have yet for it to give a correct answer. It seems to know that .1 +.1 is less than .8+.1.</p>
<p>I understand that this is a naieve way to accomplish a neural network but I believe it would work with a little tweaking. I'll have to take my windows,YUK, laptop out and put a copiler on it to improve this program more.</p>
<p>My goal was to create a net for NLP. I found a list of 366,00 words and put them in a map numbered 1 through 366,000. as the key.
If I understand neural networks that would be too many inputs for a net. How many would be too many.
I tried to use n->weights[c] but it was giving incorrect values so I was forced to use layers[r][c].weights[w]
I believe I am not creating my neurons right.</p>
<p>I am curious to see what you think about my code. Thank you in advance for you time and input. I may take a few days for me to check back in.</p>
<pre><code>/*
This creates an implicitly connected feed forward
backward propagated deep neural network
this program has two inputs and one output
It is attempting to learn how to add two decimals together
*/
#include<iostream>
#include<vector>
#include<cmath>
#include<random>
#include <cassert>
using namespace std;
//Neurons hold the values
class Neuron {
public:
Neuron();
virtual ~Neuron() {}
void setValue(double val) {
_value =val;
}
void setTestValue(double val) {
_testValue = val;
}
//protected:
double derivative =0;
double _gradient =0;
double _delta =0;
double _testValue =0;
double _value =0;
double _bias =0;
vector<double> _weight;
};
Neuron::Neuron() {
//cout << "Making a neuron!" << endl;
}
//The layer class manipulates the values of neurons
class Layer :public Neuron {
public:
Layer() {}
Layer( vector<double>entry) {}
Layer(vector<int> topology, vector<double> input, vector<double> test);
~Layer() {}
void createNet();
void train();
void feed();
void predict(vector<double> entry);
void backward();
void printOutput();
double randNum();
double sigmoid(double x) {
return x/(1+abs(x));//Is this right?
}
double getError();
private:
double _momentum=.05;
double _mFactor =.05;
double _learn =.5;
double netError =0;
double _error =0;
double _rms =0;
double _answer =0;
// Neuron * n = new Neuron;
vector<Neuron> layer;
vector<vector<Neuron> > layers;
vector<int> topology;
};
Layer::Layer(vector<int> topology, vector<double> input, vector<double> test) {
this->topology=topology;
//r stands for row
for(unsigned r=0; r<topology.size(); r++) {
if(r==0) {
for(unsigned c=0; c< input.size(); c++) {// c stands for collum
Neuron i;
i.setValue(input.at(c));
layer.push_back(i);
}
} else if(r==topology.size()-1) {//output layer
for(int c=0; c<topology[r]; c++) {
Neuron o;
o._bias = 1;//= randNum();//would work either way to set neuron bias i think
//w stands for weight
for(auto w=0; w < topology[r-1]; w++) {//took away i-1
double weight = randNum();
o._weight.push_back(weight);
}
o.setTestValue(test.at(c));
layer.push_back(o);
o._weight.clear();
}
} else {//This creates the hidden layers
for (int c =0; c<topology[r]; c++) {
Neuron h;
h._bias = 1;
for(int w=0; w<topology[ r+1]; w++) {
double weight=randNum();
h._weight.push_back(weight);
}
layer.push_back(h);
h._weight.clear();
}
}
layers.push_back(layer);
layer.clear();
}
}
void Layer::createNet() {
vector<int> topology;
vector<double> input;
vector<double> test;
topology.push_back(2);//input layer
//There is no limit on the number of hidden layers
topology.push_back(10);//hidden layer
topology.push_back(10);//hidden layer
topology.push_back(1);//output layer
input.push_back(0.09);
input.push_back(.08);
test.push_back(.17);
Layer layer(topology, input, test);
int laps=0;
double entry=0;
vector<double>entries;
layer.feed();
layer.train();
layer.predict(entries);
}
void Layer::train() {
int lap=0;
int totalTrain=1000;
double sum=0;
double temp=0;
double avg=0;
double total=0;
while(lap<totalTrain) {
lap++;
sum=0;
//cout<<"-----LAP----- "<<lap<<endl;
for(auto r=0; r<layers.size(); r++) {
if(r==0) {
sum=0;
for(int c=0; c<layers[r].size(); c++) {
temp=randNum();
sum+=temp;
layers[r][c].setValue(temp);
}
}
if(r==layers.size()-1)
layers[r][0].setTestValue(sigmoid(sum));
}
double epoch=0;
double count=10;
// actual train loop
while(epoch<count) {
epoch++;
if(getError()<.001) {
//cout<<"BREAK on epoch "<<epoch<<endl;
temp+=epoch;
break;
} else {
temp+=epoch;
}
feed();
backward();
//cout<<getError()<<endl;
}
//here I'm trying to come up with overall net error
avg+= temp;
temp=0;
avg/=count;
total+=avg;
// cout<<"average "<<avg<<endl;
avg=0;
}
total/=totalTrain;
// cout<<"average training total "<<total<<endl;
//total=0;
}
void Layer::predict(vector<double> entry) {
double answer=0;
string response="y";
while(response=="y") {
for(auto r=0; r<layers.size(); r++) {
if(r==0) {
answer=0;
for(int c=0; c<layers[r].size(); c++) {
double temp=0;
cout<<"Enter a decimal number like .1 or .4 the total needs to be less than 1.0 "<<endl;
cin>>temp;
answer+=temp;
layers[r][c].setValue(temp);
//cout<<"value "<<layers[r][c]._value<<endl;
}
layers[layers.size()-1][0].setTestValue(answer);
}
}
feed();
printOutput();
cout<<"Do you want to continue (y/n)"<<endl;
cin>>response;
}
}
void Layer::feed() {
// cout << "********** FORWARD **********" << endl;
double sum=0;
for(unsigned r=1; r<layers.size(); r++) {
if(r == layers.size()-1) { //This is the output layer
for(unsigned c=0; c<layers[r].size(); c++) {
double sum=0;
// cout<<"Feed neron sum "<<layers[r][c]._value<<endl;
for(unsigned w=0; w < layers[r][c]._weight.size(); w++) {//size of weights should match previous number of neurons in previous layer
double pValue = layers[r-1][w]._value;
double weight = layers[r][c]._weight[w];
sum +=pValue * weight;
}
sum+=layers[r][c]._bias;
layers[r][c].setValue(sigmoid(sum));
//cout<<"Neuron Value " << layers[r][c]._value<<endl;
}
} else { //1st hidden layer of however many are made
for(unsigned c=0; c<layers[r].size(); c++) {
sum=0;
for(unsigned w=0; w < layers[r][c]._weight.size(); w++) {//size of weights should match previous number of neurons in previous layer
double pValue = layers[r-1][w]._value;
double weight = layers[r][c]._weight[w];
sum +=pValue * weight;
}
sum+=layers[r][c]._bias;
layers[r][c].setValue(sigmoid(sum));
}
}
}
}
void Layer::backward() {
double derivative=0;
double sum=0;
// cout << "********** Calculating gradients **********" << endl;
//AKA calculating SLOPE?
for(unsigned r=layers.size()-1; r>0; r--) {
if(r == layers.size()-1) {//output layer
for(unsigned c=0; c<layers[r].size(); c++) {
double val = layers[r][c]._value;
double test = layers[r][c]._testValue;
derivative=(1-val)*val;
double gradient=layers[r][c]._gradient=derivative*(test-val);
}
} else { //hidden row
for(unsigned c=0; c<layers[r].size(); c++) {
double val = layers[r][c]._value;
//derivative=(1-val)*(1+val);//used on tanf
derivative=(1-val)*val;
sum=0;
for(unsigned g=0; g < layers[r+1].size(); g++) {//gradients and weights are same size
sum +=layers[r+1][g]._gradient * layers[r][c]._weight[g];
layers[r][c]._gradient=derivative*sum;
}
}
}
}
// cout << "********** Updating Weights**********<<endl;
for(unsigned r=layers.size()-1; r >0; r--) {
if(r==layers.size()-1) {
for(unsigned c=0; c<layers[r].size(); c++) {
for(unsigned w=0; w<layers[r][c]._weight.size(); w++) {
double weight=layers[r][c]._weight[w];
//double val=layers[r-1][w]._value;
double cVal=layers[r-1][c]._value;
double grad=layers[r][c]._gradient;
double delta=layers[r][c]._delta;
double bias=layers[r][c]._bias;
double oldDelta=delta;
delta=_learn*grad*cVal;
//cout<<"Output weight adjust delta "<<delta<<" row "<<r<<" col "<<c<<endl;
weight+=delta;
_mFactor = _momentum*oldDelta;
layers[r][c]._weight[w]+=_mFactor;
//----------------now adjust neuron bias-----------------
delta =_learn*grad;
//cout<<"delta "<<delta<<endl;
bias+=delta;
_mFactor=_momentum*oldDelta;
layers[r][c]._bias=bias+=_mFactor;
}
}
} else {//adjust hidden weights
for(unsigned c =0; c< layers[r].size(); c++) {
double val = 0;
double grad =layers[r+1][c]._gradient;
double delta=layers[r][c]._delta;
double bias=layers[r][c]._bias;
for(unsigned w=0; w< layers[r][c]._weight.size(); w++) {
double weight=layers[r][c]._weight[w];
val = layers[r-1][c]._testValue;
double oldDelta=delta;
//cout<<"hidden weight adjust delta "<<delta<<" row "<<r<<" col "<<c<<endl;
// cout<<" weight "<<w<<endl;
delta=_learn*grad*val;
weight+=delta;
layers[r][c]._weight[w]+=_momentum*oldDelta;
//now adjust neuron bias
delta =_learn*grad;
bias+=delta;
//_mFactor=_momentum*oldDelta;
layers[r][c]._bias=bias+=_momentum*oldDelta;
}
}
}
}
}
void Layer::printOutput() {
for(auto r=0; r<layers.size(); r++) {
for(auto c=0; c<layers[r].size(); c++) {
if(r==layers.size()-1) {
cout<<"NEURON value "<<layers[r][c]._value<<endl;
cout<<"NEURON test answer "<<layers[r][c]._testValue<<endl;
}
}
}
}
double Layer::randNum() {
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> urd(0,1);
return urd(gen);
}
double Layer::getError() {
for(unsigned r=layers.size()-1; r>layers.size()-2; r--) {
double error=0;
double size=layers[r].size();
for(unsigned c=0; c<layers[r].size(); c++) {
double val=layers[r][c]._value;
double test=layers[r][c]._testValue;
error+=test-val;
}
error*=error;
error=error/size;
error=sigmoid(error);
return error;
}
}
int main() {
Layer layer;
layer.createNet();
cout << "##########FINISHED!!!!##########" << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:28:59.863",
"Id": "501859",
"Score": "0",
"body": "Is there a way to add a c++tag to this question? I got in a hurry standing outside."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T01:12:26.297",
"Id": "501864",
"Score": "0",
"body": "Welcome to Code Review! I have added the c++ tag and updated a few other formatting issues. If you mean to separate sentences into individual paragraphs, then use two line breaks instead of just one."
}
] |
[
{
"body": "<ol>\n<li>Never use using namespace std in a header (until you have a good reason for it, I know no one a priori)! Even in cpp files within a more global scope, this can become buggy as hell in doubt, even without exotic building schemes like UnityBuilds for instance.</li>\n<li>"I had to comment out the protected: line in Neuron because it was giving me an error. ": Sorry for the question within an answer but what error did you get? Semantically, it's totally fine to have them protected. If they should yield read-only character for derived classes, then you could consider protected getters for them and make them private in doubt.</li>\n<li>For better testing, try to introduce interfaces for your classes (if performance is not a critical issue).</li>\n<li>Rather try to move general mathematical stuff to extra places. See for instance the sigmoid function (btw: can you ensure, you are never divide by zero there?).</li>\n<li>At least your Layer::backward() routine is too large. Try to make that one smarter with sub routines!</li>\n<li>Try to abstract input and output, again especially for testing in the first place. cin and cout should then be concrete 'specializations'.</li>\n<li>Multiple times, you're doing that to local Neuron objects: <code>h._weight.clear()</code>; right before they go out of scope anyways. Only apply <code>layer.push_back(std::move(h));</code> here instead as the last operation within those scopes.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T23:15:43.090",
"Id": "502478",
"Score": "1",
"body": "Wow thank you. Instead of using namespace stand I should typename to something like ```typename double myVector=using std::vector;```I've been eye-balling the size of the backprop my self. You definitely have given good advice. I thought of train the neural net on Black Jack instead of teaching it to add."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T23:19:29.587",
"Id": "502480",
"Score": "0",
"body": "Commenting out the private access was I believe a problem with CodingC++ It was saying that the varible was private. I declare it a child of neuron as public:"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T20:41:40.660",
"Id": "254716",
"ParentId": "254466",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T22:34:59.153",
"Id": "254466",
"Score": "1",
"Tags": [
"c++",
"neural-network"
],
"Title": "Does this feedforward neural network work like i think it works?"
}
|
254466
|
<p>Please make code review for command line utility for user data migration from MUBI.com to letterboxd.com.
Utility makes Get HTTP request downloads json-data, parses it and saves as CSV-file.</p>
<p>Can be found at <a href="https://github.com/hextriclosan/mubi2letterboxd" rel="nofollow noreferrer">github</a></p>
<pre><code>// mubi2letterboxd is a simple command line utility for user data migration from MUBI to letterboxd.
// With the utility, you can create a .csv file suitable for manual import to Letterboxd.
//
// inspired by the reddit entry by jcunews1
// https://www.reddit.com/r/learnjavascript/comments/auwynr/export_mubi_data/ehcx2zf/
package main
import (
"bufio"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
type MovieRecord struct {
Id int `json:"id"`
Review string `json:"body"`
WatchedAt int64 `json:"updated_at"`
Rating int `json:"overall"`
Film struct {
Title string `json:"title"`
Year int `json:"year"`
Directors []struct {
Name string `json:"name"`
} `json:"directors"`
} `json:"film"`
}
const (
url = "https://mubi.com/services/api/ratings"
perPage = "1000"
letterboxdCsvFileName = "letterboxd.csv"
)
func main() {
fmt.Print("Input MUBI userID and press Enter: ")
var mubiUserId string
if _, err := fmt.Scanf("%s", &mubiUserId); err == nil {
if _, err := strconv.ParseUint(mubiUserId, 10, 64); err == nil {
if err := process(mubiUserId); err != nil {
fmt.Fprintf(os.Stderr, "Error occurred: %s\n", err)
}
} else {
fmt.Fprintf(os.Stderr,"%q is not a valid UserId\n", mubiUserId)
}
} else {
fmt.Fprintf(os.Stderr, "Error reading UserID: %s\n", err)
}
fmt.Print("Press Enter to exit")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
func process(mubiUserId string) error {
var movieRecords []MovieRecord
var csvRows [][]string
client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
query := req.URL.Query()
query.Set("user_id", mubiUserId)
query.Set("per_page", perPage)
fmt.Printf("Data for UserID %s will be requested from MUBI server\n", mubiUserId)
for i := 1; ; i++ {
fmt.Printf("Requesting for chunk #%d... ", i)
query.Set("page", strconv.Itoa(i))
req.URL.RawQuery = query.Encode()
response, err := client.Do(req)
if err != nil {
return err
}
if response.StatusCode != http.StatusOK {
return errors.New(fmt.Sprintf("Server returned status code %d", response.StatusCode))
}
jsonFile, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
if err := json.Unmarshal(jsonFile, &movieRecords); err != nil {
return err
}
fmt.Printf("downloaded %d records\n", len(movieRecords))
if len(movieRecords) == 0 {
break
}
for _, item := range movieRecords {
csvRows = append(csvRows, generateCsvRow(item))
}
}
if len(csvRows) == 0 {
fmt.Printf("\nNo records found at MUBI server for UserID %s\n", mubiUserId)
return nil
}
outFile, err := os.Create(letterboxdCsvFileName)
if err != nil {
return err
}
defer func() {
err := outFile.Close()
if err != nil {
log.Fatal(err)
}
}()
csvwriter := csv.NewWriter(outFile)
defer csvwriter.Flush()
if err := csvwriter.Write([]string{"tmdbID", "Title", "Year", "Directors", "Rating", "WatchedDate", "Review"}); err != nil {
return err
}
if err := csvwriter.WriteAll(csvRows); err != nil {
return err
}
absPath, err := filepath.Abs(outFile.Name())
if err != nil {
return err
}
fmt.Printf("\n%d records are saved to %q\n", len(csvRows), absPath)
return outFile.Sync()
}
func generateCsvRow(r MovieRecord) []string {
idOut := strconv.Itoa(r.Id)
titleOut := r.Film.Title
yearOut := strconv.Itoa(r.Film.Year)
directors := make([]string, len(r.Film.Directors))
for i, director := range r.Film.Directors {
directors[i] = director.Name
}
directorsOut := strings.Join(directors, ", ")
ratingOut := strconv.Itoa(r.Rating)
timeOut := time.Unix(r.WatchedAt, 0).Format("2006-01-02")
reviewOut := r.Review
return []string{idOut, titleOut, yearOut, directorsOut, ratingOut, timeOut, reviewOut}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T23:57:56.353",
"Id": "254472",
"Score": "1",
"Tags": [
"json",
"csv",
"go",
"http"
],
"Title": "Command line utility for user data migration from MUBI.com to letterboxd.com"
}
|
254472
|
<p>I am fairly new to Python and have tried to create a tic tac toe game that is completely automatic, where you can see if a <code>player1</code> has an advantage if you let it start in the middle and I would love some feedback on it and improvement areas. That is, is it something that looks crazy, something that I do wrong or something that I should clarify regarding the structure and coding?</p>
<p>I ask because I'm so new to python that I have a hard time seeing where I should settle and where I should spend more time improving the code. I will also address where I think my code is weak below and would love to hear your input on this comment.</p>
<p>Briefly about how it works is that you start by calling <code>main()</code> and decide how many games you would like to play by answering the first question, then you have to decide how big playing surface you would like out of 3, 5 and 7 by answering the second question and last you pick your scenario (1 or 2) by answering the last question. 1 is the scenario when all moves are automatic and 2 is the scenario where player1 put its first move in the middle. Then you will get a plot with the statistic from all game rounds.</p>
<p>My biggest concern about it is that the error messages if you call the wrong value to board_size, games or scenario appears after you have answered all the questions and not immediately - what do you think about that? I have tried to specify the error messages to compensate that though I didn't find a way to have them appear straight away.</p>
<pre><code>import numpy as np
import random
import matplotlib.pyplot as plt
# creating an empty board
def create_board(board_size):
return np.zeros((board_size,board_size), dtype=int)
def find_placement_scenario_one(board):
lst = []
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
lst.append((i, j))
return(lst)
def random_placeout_scenario_one(board, player):
selection = find_placement_scenario_one(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)
def find_placement_scenario_two(board, board_size):
l=[]
for i in range(len(board)):
for j in range(len(board)):
if board_size == 3:
if board[i][j] == 0:
l.append((1, 1))
if board_size == 5:
if board[i][j] == 0:
l.append((2, 2))
if board_size == 7:
if board[i][j] == 0:
l.append((3, 3))
return(l)
def placeout_scenario_two(board, player, board_size):
player = 1
selection = find_placement_scenario_two(board, board_size)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)
def check_row(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
def check_column(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[y][x] != player:
win = False
continue
if win == True:
return(win)
return(win)
def check_diagonal(board, player):
win = True
y = 0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win
def evaluate(board):
winner = 0
for player in [1, 2]:
if (check_row(board, player) or
check_column(board,player) or
check_diagonal(board,player)):
winner = player
if np.all(board != 0) and winner == 0:
winner = -1
return winner
def choose_scenario(scenario, board_size):
if board_size ==3 or board_size == 5 or board_size == 7:
if scenario == 1 or scenario == 2:
board, winner, counter = create_board(board_size), 0, 1
if scenario == 1:
while winner == 0:
for player in [1, 2]:
board = random_placeout_scenario_one(board, player)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
board, winner, counter = create_board(board_size), 0, 1
if scenario == 2:
board, winner, counter = create_board(board_size), 0, 1
while winner == 0:
for player in [2, 1]:
board = placeout_scenario_two(board, player, board_size)
board = random_placeout_scenario_one(board, player)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)
else:
print('Playing surface does not exist, try again')
def save_stats(games, scenario, board_size):
player1wins=0
player2wins=0
ties=0
for game in range(games):
result=choose_scenario(scenario, board_size)
if result==-1: ties+=1
elif result==1: player1wins+=1
else: player2wins+=1
return [player1wins, player2wins, ties] # for returning
def print_and_save_stats(games, scenario, board_size):
if board_size ==3 or board_size == 5 or board_size == 7:
if scenario == 1 or scenario == 2:
player1wins, player2wins, ties = save_stats(games, scenario, board_size)
print('Player 1 wins:',player1wins)
print('Player 2 wins:',player2wins)
print('Tie:',ties)
# Fake dataset
height = [player1wins, player2wins, ties]
bars = ('Player 1', 'Player 2', 'Tie')
y_pos = np.arange(len(bars))
# Create bars and choose color
plt.bar(y_pos, height, color = (0.5,0.1,0.5,0.6))
# Add title and axis names
plt.title('My title')
plt.xlabel('')
plt.ylabel('')
# Limits for the Y axis
plt.ylim(0,games)
# Create names
plt.xticks(y_pos, bars)
# Show graphic
plt.show()
else:
print('Scenario does not exist')
def main():
try:
games = int(input("How many games do you want to simulate? "))
board_size = int(input("How big playing surface (3/5/7)? "))
scenario = int(input('What scenario (1/2)? '))
choose_scenario(scenario, board_size)
print_and_save_stats(games, scenario, board_size)
except ValueError:
print('You have to answer all the question to start the game, try again')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T14:35:47.583",
"Id": "501921",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T17:14:04.473",
"Id": "501929",
"Score": "0",
"body": "Thank you @SᴀᴍOnᴇᴌᴀ, I have now edited the question title and I hope it clarifies what I'm asking for and adheres to the standard of the site."
}
] |
[
{
"body": "<p>This looks good.</p>\n<pre><code># creating an empty board\ndef create_board(board_size):\n return np.zeros((board_size,board_size), dtype=int)\n</code></pre>\n<p><code>find_placement_scenario_one</code> is both a noisy name and could be simplified. I'd write it like this.</p>\n<pre><code>def available_spaces(board): \n return np.argwhere(board==0)\n</code></pre>\n<p><code>random_placeout_scenario_one</code> is another odd name. The return statement is also odd, as you are mutating the original board anyway. I'd leave out the return, as this makes it very clear the that the original board is being modified.</p>\n<pre><code>def make_random_move(board, player): \n spaces = available_spaces(board) \n space = random.choice(spaces)\n board[space] = player \n</code></pre>\n<p>The row and diagonal checks could be simplified with numpy.</p>\n<pre><code>def is_winning_by_row(board, player):\n return any(\n all(row == player)\n for row in board\n )\n\ndef is_winning_by_col(board, player):\n return is_winning_by_row(board.transpose(), player)\n\ndef is_winning_by_diag(board, player):\n return any(\n all(np.diag(board_rotation) == player)\n for board_rotation in [board, np.fliplr(board)]\n ) \n\ndef is_winning(board, player):\n return (\n is_winning_by_row(board, player) or\n is_winning_by_col(board, player) or\n is_winning_by_diag(board, player)\n )\n</code></pre>\n<p>You could reduce mutation in <code>save_stats()</code>.</p>\n<pre><code>def save_stats(games, scenario, board_size): \n game_results = [\n play_game(scenario, board_size) # formerly choose_scenario\n for _ in range(games)\n ]\n\n player1wins = game_results.count(1)\n player2wins = game_results.count(2)\n ties = game_results.count(-1)\n\n return player1wins, player2wins, ties\n</code></pre>\n<h1>Other</h1>\n<p>The board size checks are silly. If there is an invalid size, raise an exception as early as possible. Checking this criteria multiple times introduces noise into your code.</p>\n<p>Also your random placement for situation 2 appears to only ever place moves in the middle, seems pretty broken.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T21:40:58.550",
"Id": "254502",
"ParentId": "254473",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T00:03:43.027",
"Id": "254473",
"Score": "1",
"Tags": [
"python",
"numpy",
"tic-tac-toe",
"matplotlib"
],
"Title": "TicTacToe: If an error messages do not appear straight away"
}
|
254473
|
<p>I need help to optimise the code as it becomes slow with a large dataset. I have an exchange simulation program that takes in market prices from a csv and then allows the user to place bids and offers for the products (currencies) that are up for trade.</p>
<p>OrderBookEntry.cpp contains the constructors</p>
<pre><code>#include "OrderBookEntry.h"
OrderBookEntry::OrderBookEntry( double _price,
double _amount,
std::string _timestamp,
std::string _product,
OrderBookType _orderType,
std::string _username)
: price(_price),
amount(_amount),
timestamp(_timestamp),
product(_product),
orderType(_orderType),
username(_username)
{
}
OrderBookType OrderBookEntry::stringToOrderBookType(std::string s)
{
if (s == "ask")
{
return OrderBookType::ask;
}
if (s == "bid")
{
return OrderBookType::bid;
}
return OrderBookType::unknown;
}
</code></pre>
<p>OrderBook.cpp processes bids and offers</p>
<pre><code>#include <map>
#include <algorithm>
#include <iostream>
#include "OrderBook.h"
#include "CSVReader.h"
/** construct, reading a csv data file */
/* R1A: Retrieve the live order book from the Merklerex exchange simulation */
OrderBook::OrderBook(std::string filename)
{
orders = CSVReader::readCSV(filename);
}
/** return vector of all known products in the dataset*/
std::vector<std::string> OrderBook::getKnownProducts()
{
std::vector<std::string> products;
std::map<std::string,bool> prodMap;
for (OrderBookEntry& e : orders)
{
prodMap[e.product] = true;
}
// now flatten the map to a vector of strings
for (auto const& e : prodMap)
{
products.push_back(e.first);
}
return products;
}
/** return vector of Orders according to the sent filters*/
std::vector<OrderBookEntry> OrderBook::getOrders(OrderBookType type,
std::string product,
std::string timestamp)
{
std::vector<OrderBookEntry> orders_sub;
for (OrderBookEntry& e : orders)
{
if (e.orderType == type &&
e.product == product &&
e.timestamp == timestamp )
{
orders_sub.push_back(e);
}
}
return orders_sub;
}
void OrderBook::insertOrder(OrderBookEntry& order)
{
orders.push_back(order);
std::sort(orders.begin(), orders.end(), OrderBookEntry::compareByTimestamp);
}
/* R2D: Using the live order book from the exchange, decide if it should withdraw its bids at any point in time */
/* R3D: Using the live order book from the exchange, decide if it should withdraw its offers at any point in time */
void OrderBook::withdrawOrder(std::string time)
{
for (std::size_t i = orders.size() - 1; i < orders.size(); --i)
{
if(orders[i].timestamp == time && orders[i].username == "simuser")
{
orders.erase(orders.begin() + i);
}
}
}
std::vector<OrderBookEntry> OrderBook::matchAsksToBids(std::string product, std::string timestamp)
{
// asks = orderbook.asks
std::vector<OrderBookEntry> asks = getOrders(OrderBookType::ask,
product,
timestamp);
// bids = orderbook.bids
std::vector<OrderBookEntry> bids = getOrders(OrderBookType::bid,
product,
timestamp);
// sales = []
std::vector<OrderBookEntry> sales;
// I put in a little check to ensure we have bids and asks
// to process.
if (asks.size() == 0 || bids.size() == 0)
{
std::cout << " OrderBook::matchAsksToBids no bids or asks" << std::endl;
return sales;
}
// sort asks lowest first
std::sort(asks.begin(), asks.end(), OrderBookEntry::compareByPriceAsc);
// sort bids highest first
std::sort(bids.begin(), bids.end(), OrderBookEntry::compareByPriceDesc);
// for ask in asks:
std::cout << "max ask " << asks[asks.size()-1].price << std::endl;
std::cout << "min ask " << asks[0].price << std::endl;
std::cout << "max bid " << bids[0].price << std::endl;
std::cout << "min bid " << bids[bids.size()-1].price << std::endl;
for (OrderBookEntry& ask : asks)
{
// for bid in bids:
for (OrderBookEntry& bid : bids)
{
// if bid.price >= ask.price # we have a match
if (bid.price >= ask.price)
{
// sale = new order()
// sale.price = ask.price
OrderBookEntry sale{ask.price, 0, timestamp,
product,
OrderBookType::asksale};
if (bid.username == "simuser")
{
sale.username = "simuser";
sale.orderType = OrderBookType::bidsale;
}
if (ask.username == "simuser")
{
sale.username = "simuser";
sale.orderType = OrderBookType::asksale;
}
// # now work out how much was sold and
// # create new bids and asks covering
// # anything that was not sold
// if bid.amount == ask.amount: # bid completely clears ask
if (bid.amount == ask.amount)
{
// sale.amount = ask.amount
sale.amount = ask.amount;
// sales.append(sale)
sales.push_back(sale);
// bid.amount = 0 # make sure the bid is not processed again
bid.amount = 0;
// # can do no more with this ask
// # go onto the next ask
// break
break;
}
// if bid.amount > ask.amount: # ask is completely gone slice the bid
if (bid.amount > ask.amount)
{
// sale.amount = ask.amount
sale.amount = ask.amount;
// sales.append(sale)
sales.push_back(sale);
// # we adjust the bid in place
// # so it can be used to process the next ask
// bid.amount = bid.amount - ask.amount
bid.amount = bid.amount - ask.amount;
// # ask is completely gone, so go to next ask
// break
break;
}
// if bid.amount < ask.amount # bid is completely gone, slice the ask
if (bid.amount < ask.amount &&
bid.amount > 0)
{
// sale.amount = bid.amount
sale.amount = bid.amount;
// sales.append(sale)
sales.push_back(sale);
// # update the ask
// # and allow further bids to process the remaining amount
// ask.amount = ask.amount - bid.amount
ask.amount = ask.amount - bid.amount;
// bid.amount = 0 # make sure the bid is not processed again
bid.amount = 0;
// # some ask remains so go to the next bid
// continue
continue;
}
}
}
}
return sales;
}
</code></pre>
<p>functions to place bids and asks in main</p>
<pre><code>void MerkelMain::enterAsk()
{
std::cout << "Make an ask - enter the amount: product, price, amount, eg. ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);
std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
if (tokens.size() != 3)
{
std::cout << "MerkelMain::enterAsk Bad input! " << input << std::endl;
}
else {
try {
OrderBookEntry obe = CSVReader::stringsToOBE(
tokens[1],
tokens[2],
currentTime,
tokens[0],
OrderBookType::ask
);
obe.username = "simuser";
if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
std::cout << " MerkelMain::enterAsk Bad input " << std::endl;
}
}
}
void MerkelMain::enterBid()
{
std::cout << "Make a bid - enter the amount: product, price, amount, eg. ETH/BTC,200,0.5" << std::endl;
std::string input;
std::getline(std::cin, input);
std::vector<std::string> tokens = CSVReader::tokenise(input, ',');
if (tokens.size() != 3)
{
std::cout << "MerkelMain::enterBid Bad input! " << input << std::endl;
}
else {
try {
OrderBookEntry obe = CSVReader::stringsToOBE(
tokens[1],
tokens[2],
currentTime,
tokens[0],
OrderBookType::bid
);
obe.username = "simuser";
if (wallet.canFulfillOrder(obe))
{
std::cout << "Wallet looks good. " << std::endl;
orderBook.insertOrder(obe);
}
else {
std::cout << "Wallet has insufficient funds . " << std::endl;
}
}catch (const std::exception& e)
{
std::cout << " MerkelMain::enterBid Bad input " << std::endl;
}
}
}
</code></pre>
<p>CSVReader.cpp</p>
<pre><code>#include <iostream>
#include <fstream>
#include "CSVReader.h"
CSVReader::CSVReader()
{
}
std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFilename)
{
std::vector<OrderBookEntry> entries;
std::ifstream csvFile{csvFilename};
std::string line;
if (csvFile.is_open())
{
while(std::getline(csvFile, line))
{
try {
OrderBookEntry obe = stringsToOBE(tokenise(line, ','));
entries.push_back(obe);
}catch(const std::exception& e)
{
std::cout << "CSVReader::readCSV bad data" << std::endl;
}
}// end of while
}
std::cout << "CSVReader::readCSV read " << entries.size() << " entries" << std::endl;
return entries;
}
std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator)
{
std::vector<std::string> tokens;
signed int start, end;
std::string token;
start = csvLine.find_first_not_of(separator, 0);
do{
end = csvLine.find_first_of(separator, start);
if (start == csvLine.length() || start == end) break;
if (end >= 0) token = csvLine.substr(start, end - start);
else token = csvLine.substr(start, csvLine.length() - start);
tokens.push_back(token);
start = end + 1;
}while(end > 0);
return tokens;
}
OrderBookEntry CSVReader::stringsToOBE(std::vector<std::string> tokens)
{
double price, amount;
if (tokens.size() != 5) // bad
{
std::cout << "Bad line " << std::endl;
throw std::exception{};
}
// we have 5 tokens
try {
price = std::stod(tokens[3]);
amount = std::stod(tokens[4]);
}catch(const std::exception& e){
std::cout << "CSVReader::stringsToOBE Bad float! " << tokens[3]<< std::endl;
std::cout << "CSVReader::stringsToOBE Bad float! " << tokens[4]<< std::endl;
throw;
}
OrderBookEntry obe{price,
amount,
tokens[0],
tokens[1],
OrderBookEntry::stringToOrderBookType(tokens[2])};
return obe;
}
OrderBookEntry CSVReader::stringsToOBE(std::string priceString,
std::string amountString,
std::string timestamp,
std::string product,
OrderBookType orderType)
{
double price, amount;
try {
price = std::stod(priceString);
amount = std::stod(amountString);
}catch(const std::exception& e){
std::cout << "CSVReader::stringsToOBE Bad float! " << priceString<< std::endl;
std::cout << "CSVReader::stringsToOBE Bad float! " << amountString<< std::endl;
throw;
}
OrderBookEntry obe{price,
amount,
timestamp,
product,
orderType};
return obe;
}
</code></pre>
<p>Some data from the csv. 1st part is the date, 2nd part is the product, 3rd part is the OrderBookType (asks or bids), 4th part is the price and 5th part is the amount. When placing bids or asks, users do not need to enter the date but need to key in a value for everything else.</p>
<pre><code>2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187308,7.44564869
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187307,3.467434
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187305,6.85567013
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.0218732,1.
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187163,0.03322569
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02187008,0.21
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186299,0.1
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186251,0.0091
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186053,0.58
2020/03/17 17:01:24.884492,ETH/BTC,bid,0.02186052,0.05
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T03:44:10.127",
"Id": "501881",
"Score": "0",
"body": "Have you determined which part is slow? The CSV reader? Matching asks to bids?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T03:55:33.900",
"Id": "501882",
"Score": "0",
"body": "@1201ProgramAlarm it should be matching asks to bids but how do I confirm which function is slow? Do I need to measure the function's execution time?"
}
] |
[
{
"body": "<p>Erasing from the middle of a vector can be slow.</p>\n<blockquote>\n<pre><code>void OrderBook::withdrawOrder(std::string time)\n{\n for (std::size_t i = orders.size() - 1; i < orders.size(); --i)\n {\n if(orders[i].timestamp == time && orders[i].username == "simuser")\n { \n orders.erase(orders.begin() + i);\n }\n }\n}\n</code></pre>\n</blockquote>\n<p>It's better to <code>std::remove()</code> the unwanted elements, then remove them in one go:</p>\n<pre><code>void OrderBook::withdrawOrder(const std::string& time)\n{\n orders.erase(std::remove(orders.begin(), orders.end(),\n [&time](auto order){ return order.timestamp == time && order.username == "simuser"; }),\n orders.end());\n}\n</code></pre>\n<hr />\n<p>This code is a poor way to keep a container sorted:</p>\n<blockquote>\n<pre><code>void OrderBook::insertOrder(OrderBookEntry& order)\n{\n orders.push_back(order);\n std::sort(orders.begin(), orders.end(), OrderBookEntry::compareByTimestamp);\n}\n</code></pre>\n</blockquote>\n<p>If we sort once when we create <code>orders</code>, then we should just be able to binary-search and <code>insert()</code> at the correct location, instead of causing a full sort every time. It looks like we might be better off changing to a different container (e.g. <code>std::multiset</code>) to maintain our desired order more efficiently.</p>\n<hr />\n<p>Look at this logic:</p>\n<blockquote>\n<pre><code>std::sort(asks.begin(), asks.end(), OrderBookEntry::compareByPriceAsc);\nstd::sort(bids.begin(), bids.end(), OrderBookEntry::compareByPriceDesc);\n\nfor (OrderBookEntry& ask : asks) {\n for (OrderBookEntry& bid : bids) {\n if (bid.price >= ask.price)\n {\n //...\n }\n }\n}\n</code></pre>\n</blockquote>\n<p>If the bid price is less than the ask price, then all of the later bids will also be less (since we sorted according to price). So there's no need to continue the loop when we reach that point:</p>\n<pre><code>std::sort(asks.begin(), asks.end(), OrderBookEntry::compareByPriceAsc);\nstd::sort(bids.begin(), bids.end(), OrderBookEntry::compareByPriceDesc);\n\nfor (OrderBookEntry& ask : asks) {\n for (OrderBookEntry& bid : bids) {\n if (bid.price < ask.price) { break; }\n \n //...\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T15:49:33.390",
"Id": "254489",
"ParentId": "254478",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254489",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T03:20:11.177",
"Id": "254478",
"Score": "2",
"Tags": [
"c++",
"performance"
],
"Title": "Exchange simulation that trades between currencies"
}
|
254478
|
<p><a href="https://github.com/LocalInsomniac/ProjectNightmare/pull/12" rel="nofollow noreferrer">A link to the pull request in question.</a></p>
<p>I maintain a C++ DLL / Game Maker library that constructs an environment that allows one to call any game maker script/function from within the C++ dll directly. It does this by placing all DLL function calls in a second thread that then communicates function calls to the original thread at which point game maker executes the calls and sends back any return values.</p>
<p>The main thorn this resulted in was a plethora of wrapper functions and other boilerplate. Every time I added support for a game maker function, I would have to go and write a header declaration, write a function to import the Game Maker function ID, and write the actual function declaration which is a somewhat confusing call to add a function call struct to the thread communications. Similarly there were other wrappers to export data for the ACTUAL DLL calls and then call them in the DLL thread when the message was received.</p>
<p>This was all just background to my problem that my recent code changes have solved. I don’t expect anyone to review that DLL interfacing code (though I am always open to improvements!).</p>
<p>To solve this problem I wrote a program called “dynamicWrapperGeneration.c” that when ran parses various headers that used to contain all that boilerplate but now contain nothing but function declarations. It then generates the needed boilerplate files. This file specifically is the one I would like reviewed.</p>
<p>Normally I wouldn’t post here for a small-ish task like this (not gonna lie at one point I considered posting the entire 3000 line library here at one point), but this executable is the first of its kind for me. I have never written anything like this before, so I don’t even know what to <em>call</em> this thing let alone whether my methods are overly crude and clumsy. At some point this executable will actually be expanded to generate the Game Maker side scripts as well, so I want to make sure I am going down a good path with what I currently made so that way I can start to steer myself in a good direction.</p>
<p>Another thing to mention is that the person who primarily owns the repo I am pull requesting this to knows no C++ whatsoever, so anything that might help to make the code friendlier looking to a beginner to C++ software would be appreciated.</p>
<p>I have done code reviews in the past at previous and current jobs in software engineering with fellow devs on the same project, but I have never done one with random people unfamiliar with a project before. So I apologize in advance if I’m either over or under sharing.</p>
<pre><code>#include <stdio.h>
#include <malloc.h>
#include <string.h>
//rs
int walk_function(FILE* inputFile, FILE* outputFile, FILE* outputFile2)
{
int began = 0;
int ended = 0;
int c = fgetc(inputFile);
while (!ended && c != EOF)
{
if (c == ' ')
{
ended = began;
began = 1;
}
c = fgetc(inputFile);
}
if (c == EOF)
return c == EOF;
began = 0;
ended = 0;
char* functionName = (char*)malloc(sizeof(char));
functionName[0] = 0;
int functionNameLength = 0;
while (!ended && c != EOF)
{
if (c == '(')
{
ended = 1;
} else
{
char* tempFunctionName = (char*)malloc((functionNameLength+2)*sizeof(char));
strcpy(tempFunctionName, functionName);
tempFunctionName[functionNameLength] = c;
tempFunctionName[functionNameLength+1] = 0;
free(functionName);
functionName = tempFunctionName;
functionNameLength++;
}
c = fgetc(inputFile);
}
fprintf(outputFile, "GMEXPORT double get_%s()\n", functionName);
fprintf(outputFile, "{\n");
fprintf(outputFile, " return (double)(int)%s;\n", functionName);
fprintf(outputFile, "}\n");
fprintf(outputFile2, "if (function_to_call == (void*)%s)\n", functionName);
fprintf(outputFile2, " function_return_value = %s(", functionName);
int argumentCount = 0;
int waitingTillComma = 0;
ended = 0;
while (!ended && c != EOF)
{
if (c == ')')
{
ended = 1;
} else if (c == 'd' && !waitingTillComma)
{
fprintf(outputFile2, "dll_input[%u].number", argumentCount);
waitingTillComma = 1;
argumentCount++;
} else if (c == 'c' && !waitingTillComma)
{
fprintf(outputFile2, "dll_input[%u].text", argumentCount);
waitingTillComma = 1;
argumentCount++;
} else if (c == ',' && waitingTillComma)
{
fprintf(outputFile2, ", ");
waitingTillComma = 0;
}
c = fgetc(inputFile);
}
fprintf(outputFile2, ");\n");
return c == EOF;
}
int walk_GML_function(FILE* inputFile, FILE* outputFile, FILE* outputFile2)
{
int ended = 0;
int functionType = 2;
int c = fgetc(inputFile);
while (!ended && c != EOF)
{
if (c == ' ')
{
ended = 1;
} else if (c == 'v' && functionType == 2)
{
functionType = 0;
} else if (c == 'd' && functionType == 2)
{
functionType = 1;
}
c = fgetc(inputFile);
}
if (c == EOF)
return c == EOF;
ended = 0;
char* functionName = (char*)malloc(sizeof(char));
functionName[0] = 0;
int functionNameLength = 0;
while (!ended && c != EOF)
{
if (c == '(')
{
ended = 1;
} else
{
char* tempFunctionName = (char*)malloc((functionNameLength+2)*sizeof(char));
strcpy(tempFunctionName, functionName);
tempFunctionName[functionNameLength] = c;
tempFunctionName[functionNameLength+1] = 0;
free(functionName);
functionName = tempFunctionName;
functionNameLength++;
}
c = fgetc(inputFile);
}
fprintf(outputFile, "ADD_FUNCTION(%s)\n", functionName);
int argumentCount = 0;
int* argumentType = NULL;
int waitingTillComma = 0;
ended = 0;
while (!ended && c != EOF)
{
if (c == ')')
{
ended = 1;
} else if (c == 'd' && !waitingTillComma)
{
int* argumentTypeTemp = (int*)malloc((argumentCount+1)*sizeof(int));
memcpy(argumentTypeTemp, argumentType, argumentCount*sizeof(int));
argumentTypeTemp[argumentCount] = 0;
free(argumentType);
argumentType = argumentTypeTemp;
waitingTillComma = 1;
argumentCount++;
} else if (c == 'c' && !waitingTillComma)
{
int* argumentTypeTemp = (int*)malloc((argumentCount+1)*sizeof(int));
memcpy(argumentTypeTemp, argumentType, argumentCount*sizeof(int));
argumentTypeTemp[argumentCount] = 1;
free(argumentType);
argumentType = argumentTypeTemp;
argumentCount++;
} else if (c == ',' && waitingTillComma)
{
waitingTillComma = 0;
}
c = fgetc(inputFile);
}
if (functionType == 0)
{
fprintf(outputFile2, "void %s(", functionName);
} else if (functionType == 1)
{
fprintf(outputFile2, "double %s(", functionName);
}
for (int i = 0; i < argumentCount; i++)
{
if (argumentType[i] == 0)
{
fprintf(outputFile2, "double input%u", i);
} else if (argumentType[i] == 1)
{
fprintf(outputFile2, "const char* input%u", i);
}
if (i+1 < argumentCount)
{
fprintf(outputFile2, ", ");
}
}
fprintf(outputFile2, ")\n");
fprintf(outputFile2, "{\n");
if (functionType == 0)
{
fprintf(outputFile2, " addDelayedFunctionCall(FP_%s, 0", functionName);
} else if (functionType == 1)
{
fprintf(outputFile2, " return addDelayedFunctionCall(FP_%s, 1", functionName);
}
for (int i = 0; i < argumentCount; i++)
{
fprintf(outputFile2, ", input%u", i);
}
fprintf(outputFile2, ");\n");
fprintf(outputFile2, "}\n");
return c == EOF;
}
void parse_GML_header(FILE* outputFile, char* inputFileName)
{
FILE* inputFile = fopen(inputFileName, "r");
while (1)
{
if (walk_GML_function(inputFile, outputFile, outputFile))
{
return;
}
}
}
void parse_GML_libraries()
{
char* outputFileName = "gameMakerGenLibrary.hpp";
FILE* outputFile = fopen(outputFileName, "w");
parse_GML_header(outputFile, "gameMakerFunctions\\3DGraphics\\d3d_model.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\3DGraphics\\d3d_primitive.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\3DGraphics\\d3d_shape.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\3DGraphics\\d3d_transform.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\gameGraphics\\fontsAndText.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\userInteraction\\mouse.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\userInteraction\\keyboard.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\userInteraction\\joystick.hpp");
parse_GML_header(outputFile, "gameMakerFunctions\\gamePlay\\rooms.hpp");
}
int main()
{
char* inputFileName = "gameLoop.hpp";
FILE* inputFile = fopen(inputFileName, "r");
char* outputFileName = "getGameLoop.hpp";
FILE* outputFile = fopen(outputFileName, "w");
char* outputFileName2 = "callGameLoop.hpp";
FILE* outputFile2 = fopen(outputFileName2, "w");
while (1)
{
if (walk_function(inputFile, outputFile, outputFile2))
{
break;
}
}
parse_GML_libraries();
}
</code></pre>
<h2>Example Input</h2>
<p>Example GameLoop.hpp:</p>
<pre><code>GMEXPORT double gameLoopInit(char* program_directory);
GMEXPORT double gameLoopStep();
GMEXPORT double gameLoopDraw();
</code></pre>
<p>Example gameMakerFunctions\3DGraphics\d3d_model.hpp:</p>
<pre><code>double d3d_model_create();
void d3d_model_destroy(double ind);
void d3d_model_load(double ind, const char* fname);
void d3d_model_draw(double ind, double x, double y, double z, double texid);
void d3d_model_primitive_begin(double ind, double kind);
void d3d_model_vertex_texture(double ind, double x, double y, double z, double xtex, double ytex);
void d3d_model_primitive_end(double ind);
</code></pre>
<h2>Example Output</h2>
<p>Example GetGameLoop.hpp:</p>
<pre><code>GMEXPORT double get_gameLoopInit()
{
return (double)(int)gameLoopInit;
}
GMEXPORT double get_gameLoopStep()
{
return (double)(int)gameLoopStep;
}
GMEXPORT double get_gameLoopDraw()
{
return (double)(int)gameLoopDraw;
}
</code></pre>
<p>Example callGameLoop.hpp:</p>
<pre><code>if (function_to_call == (void*)gameLoopInit)
function_return_value = gameLoopInit(dll_input[0].text);
if (function_to_call == (void*)gameLoopStep)
function_return_value = gameLoopStep();
if (function_to_call == (void*)gameLoopDraw)
function_return_value = gameLoopDraw();
</code></pre>
<p>Example gameMakerGenLibrary.hpp:</p>
<pre><code>ADD_FUNCTION(d3d_model_create)
double d3d_model_create()
{
return addDelayedFunctionCall(FP_d3d_model_create, 1);
}
ADD_FUNCTION(d3d_model_destroy)
void d3d_model_destroy(double input0)
{
addDelayedFunctionCall(FP_d3d_model_destroy, 0, input0);
}
ADD_FUNCTION(d3d_model_load)
void d3d_model_load(double input0, const char* input1, const char* input2)
{
addDelayedFunctionCall(FP_d3d_model_load, 0, input0, input1, input2);
}
ADD_FUNCTION(d3d_model_draw)
void d3d_model_draw(double input0, double input1, double input2, double input3, double input4)
{
addDelayedFunctionCall(FP_d3d_model_draw, 0, input0, input1, input2, input3, input4);
}
ADD_FUNCTION(d3d_model_primitive_begin)
void d3d_model_primitive_begin(double input0, double input1)
{
addDelayedFunctionCall(FP_d3d_model_primitive_begin, 0, input0, input1);
}
ADD_FUNCTION(d3d_model_vertex_texture)
void d3d_model_vertex_texture(double input0, double input1, double input2, double input3, double input4, double input5)
{
addDelayedFunctionCall(FP_d3d_model_vertex_texture, 0, input0, input1, input2, input3, input4, input5);
}
ADD_FUNCTION(d3d_model_primitive_end)
void d3d_model_primitive_end(double input0)
{
addDelayedFunctionCall(FP_d3d_model_primitive_end, 0, input0);
}
</code></pre>
<p>Assume that any files not included are either empty or nothing but whitespace. I didn't design for files to be omitted, but the other "gameMakerFunctions*.hpp" headers are utilized identically.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T05:03:05.003",
"Id": "501884",
"Score": "0",
"body": "I’m not new to the stack exchange network. I don’t get why new contributor is still a thing.... I guess it’s a glitch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T06:29:08.253",
"Id": "501885",
"Score": "1",
"body": "This is not C++. This is C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T07:00:41.313",
"Id": "501887",
"Score": "0",
"body": "@indi there is no mistake. This is a C++ file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T07:28:27.097",
"Id": "501888",
"Score": "1",
"body": "No, that is not C++. It won’t compile on compilers that don’t allow you to use non-`const` `char` pointers for a `const` `char` array. (Some do allow that as an extension. GCC does, but warns `warning: ISO C++ forbids converting a string constant to 'char*'`.) That is C code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T07:42:52.023",
"Id": "501889",
"Score": "0",
"body": "@indi the file name is “dynamicWrapperGeneration.cpp”. It is a C++ file. I did not mistype/misclick the tags on the post. Thanks for asking if there was a mistake. No mistake. This is a C++ file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T07:48:26.630",
"Id": "501890",
"Score": "1",
"body": "You can name the file whatever you want; filenames are irrelevant to a C++ compiler. You can name it `dynamicWrapperGeneration.java` if you want, and still run it through a C++ compiler. It doesn’t matter what the file name is, what matters is what the code is, and that is *not* C++. That is C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T07:53:37.337",
"Id": "501891",
"Score": "0",
"body": "@indi I don’t know what the point your comment is trying to make here or asking me to do. It is literally being compiled with a C++ compiled as C++ code. Are you asking me to use a C compiler instead? This is a completely functional C++ program..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T07:59:37.490",
"Id": "501892",
"Score": "2",
"body": "I can’t make my point any clearer: This. Is. Not. C++. It literally is not C++. Your C++ compiler may have let it pass (because most C++ compilers are also C compilers), but it is not legal C++. (Didn’t you see a message in your compiler output telling you that?) It *is* legal C. If you want it reviewed, you should be asking for C reviewers, not C++ reviewers. If you *really* want it reviewed by C++ reviewers… well, you’re not going to like what they have to say. (It’ll probably just be: “throw it all out and rewrite it in C++”.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T08:11:53.863",
"Id": "501894",
"Score": "0",
"body": "@indi I mean I can do that and probably will, but will the mods sanction me for lying since my code repo clearly shows it documented as C++ code? I don’t know if I’m allowed to do that, but I guess I shall."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T08:14:27.803",
"Id": "501895",
"Score": "0",
"body": "@indi “Didn’t you see a message in your compiler output telling you that?” Not that I recall, but I also have a gajillion warnings from “dead code” in my templates, so it’s hard to say really. If it’s there it is buried at the core of the earth."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T18:50:19.500",
"Id": "501932",
"Score": "0",
"body": "@G.Sliepen unsure exactly what you mean. There is no command line input. Everything is done by loading files (my C++ project files in fact which are located on the github). Are you just preferring I move them here instead? Before I do that I should warn you that there’s about 10 files being loaded... would it be better to attach a zip?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T21:33:56.967",
"Id": "501937",
"Score": "0",
"body": "@G.Sliepen I will add two example momentarily. The program won’t run without every file (because they are hard coded file paths), but I suppose a small sample should be enough to make it interpretable even if not runnable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T21:56:15.227",
"Id": "501942",
"Score": "1",
"body": "@G.Sliepen added them. Let me know if you have any further questions. Thank you. :)"
}
] |
[
{
"body": "<ul>\n<li><p><strong>DRY</strong></p>\n<p>The block</p>\n<pre><code> while (!ended && c != EOF) \n { \n if (c == '(') \n { \n ended = 1; \n } else \n { \n char* tempFunctionName = (char*)malloc((functionNameLength+2)*sizeof(char)); \n strcpy(tempFunctionName, functionName); \n tempFunctionName[functionNameLength] = c; \n tempFunctionName[functionNameLength+1] = 0; \n free(functionName); \n functionName = tempFunctionName; \n functionNameLength++; \n } \n c = fgetc(inputFile);\n } \n</code></pre>\n<p>is repeated twice. Factor it out into a function.</p>\n</li>\n<li><p><strong>No naked loops</strong>. To augment the above bullet point, every loop implements an important job, which deserves a name. For example, the above block is in fact <code>char * parse_function_name()</code>, isn't it? Similarly, it is quite hard to understand what this block is doing:</p>\n<pre><code> while (!ended && c != EOF)\n { \n if (c == ' ')\n {\n ended = began;\n began = 1;\n }\n c = fgetc(inputFile);\n }\n</code></pre>\n<p>It looks like it is skipping everything until (and including) the very first space. Why? Is it <code>void parse_and_discard_type_declaration()</code>?</p>\n<p>Ditto for parsing arguments.</p>\n</li>\n<li><p><strong>Right tools for the right job</strong>. The code assumes a very rigid source file format. You'd be in much better shape taking a <code>flex</code>/<code>bison</code> route.</p>\n</li>\n<li><p><strong>Misc</strong></p>\n<ul>\n<li>Do not cast what <code>malloc</code> returns. Doing it may lead to mysterious crashes.</li>\n<li>Always test what <code>malloc</code> returns.</li>\n<li>I strongly recommend to <code>realloc</code>, rather than manually copy the contents.</li>\n<li>Along the same line, grow the allocated size "geometrically" (<code>allocated_size *= 2</code>). This would drastically reduce the number of calls to <code>malloc</code> and <code>strcpy</code>.</li>\n<li><code>sizeof(char)</code> is guaranteed to be 1. In any case prefer <code>sizeof(variable)</code>, as in <code>sizeof(*tempFunctionName)</code>. This avoids a double-maintenance problem: if you'd want to switch to another type (say, <code>wchar_t</code>), there'll be just one place to edit.</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T20:48:06.123",
"Id": "254498",
"ParentId": "254479",
"Score": "2"
}
},
{
"body": "<p><strong><code>malloc</code> vs. <code>realloc</code></strong></p>\n<p>Rather than allocate, copy, append ...\n... consider re-allocate, append.</p>\n<pre><code>// char* tempFunctionName = (char*)malloc((functionNameLength+2)*sizeof(char));\n// strcpy(tempFunctionName, functionName);\n// tempFunctionName[functionNameLength] = c;\n// tempFunctionName[functionNameLength+1] = 0;\n// free(functionName);\n// functionName = tempFunctionName;\n// functionNameLength++;\n\nfunctionName = realloc(functionName, functionNameLength + 2);\nfunctionName[functionNameLength++] = c;\nfunctionName[functionNameLength] = '\\0';\n\n// Or better, test allocation success\n\nchar* tempFunctionName = realloc(functionName, functionNameLength + 2);\nif (tempFunctionName == NULL) Handle_OutOfMemory_TBD_code();\nfunctionName = tempFunctionName;\nfunctionName[functionNameLength++] = c;\nfunctionName[functionNameLength] = '\\0';\n</code></pre>\n<p>Consider growing the re-allocation is bigger chunks than 1.</p>\n<hr />\n<p><strong>Rather than size by type, size by the referenced variable</strong></p>\n<pre><code>// ptr = malloc(n * sizeof(type_of_what_p_points_to));\nptr = malloc(sizeof *ptr * n);\n</code></pre>\n<p>Easier to code right, review and maintain. No need to hunt for the type of object <code>ptr</code> points to.</p>\n<p>Starting the multiplication with <code>sizeof *ptr</code> insure at least <code>size_t</code> math is used. Useful with more complex calculations.</p>\n<p>In C, the cast is not needed. Code as needed if code is also meant for C++.</p>\n<hr />\n<p><strong>Alterative <code>while</code></strong></p>\n<p>Use 1 <code>fgetc()</code></p>\n<pre><code>// int c = fgetc(inputFile);\n// while (!ended && c != EOF) {\n// ...\n// c = fgetc(inputFile);\n//}\n\nint c;\nwhile ((c = fgetc(inputFile)) != EOF && !ended) {\n ...\n}\n</code></pre>\n<p><strong><code>bool</code> vs. <code>int</code></strong></p>\n<p><code>bool</code> makes sense here</p>\n<pre><code>#include <stdbool.h>\n\n//int began = 0;\n//int ended = 0;\nbool began = false;\nbool ended = false;\n</code></pre>\n<hr />\n<p><strong>Maybe <code>fscanf()</code></strong></p>\n<p>Code looks like it is seeking 2 <code>' '</code>:</p>\n<pre><code>//int began = 0;\n//int ended = 0;\n//int c = fgetc(inputFile);\n//while (!ended && c != EOF) {\n// if (c == ' ') {\n// ended = began;\n// began = 1;\n// }\n// c = fgetc(inputFile);\n//}\n//if (c == EOF) return c == EOF;\n\n// Replaceable with\n// vvvvvv 1 or more non-spaces \nif (fscanf(inputFile, "%*[^ ])" == EOF) return EOF;\n// vvvvv 1 space\nif (fscanf(inputFile, "%1[ ]%*[^ ])" == EOF) return EOF;\nif (fgetc(inputFile) != ' ') return EOF;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T21:41:10.643",
"Id": "254503",
"ParentId": "254479",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254503",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T04:59:46.703",
"Id": "254479",
"Score": "1",
"Tags": [
"c",
"parsing"
],
"Title": "Parse Certain C++ Headers and Dynamically Generate Other Headers Containing Boilerplate Code"
}
|
254479
|
<p>I don't know if anyone is intrested but I'll give it a chans. I have some basic experiance in coding Python now and if anyone would be intrested to see how my code looks and if there is any suggestions on writing better code to improove myself.</p>
<p>There is no need for writing code for me, just if you guys have any tips on how to do it better that would be awesome.
This script is a attempt on building a backtesting machinery for me to backtest som Algo trading strategies. It's made up of 3 files thoug I try to make it sort of clean (it's not very cleen anyway)</p>
<p>This is the main one:</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime as dt
import pandas_datareader as web
import bs4 as bs
import urllib.request
#from strategies import strategies
from scan import Scanner
from dateutil.relativedelta import relativedelta
scan = False
saveScan = True
showProgress = False
showPlot = False
long = True
short = True
perYear = False
plt.style.use('ggplot')
mpl.use('TkAgg')
resaults_list = []
souce = urllib.request.urlopen('https://stockmarketmba.com/listofetfsforanindexprovider.php?s=5')
soup = bs.BeautifulSoup(souce, 'lxml')
tickers = []
if scan:
for a in soup.find_all('a', href=True):
if "analyze.php?s=" in a['href'] and "/" not in a['href']:
newticker = a['href'].replace("analyze.php?s=", "")
tickers.append(newticker)
else:
# Tickers = , 'FLGE', 'FLRG'
tickers = ['FAS', 'REM']
start = dt.datetime(2015, 1, 1)
end = dt.datetime.now()
rdelta = relativedelta(end, start)
rdelta = rdelta.years
for i in range(3):
for ticker in tickers:
df = web.DataReader(ticker, 'yahoo', start, end)
df.drop(['High', 'Low', 'Open', 'Adj Close'], axis=1, inplace=True)
#Opening the scanner with allt the inputs
scanner = Scanner(df, ticker, scan, saveScan, showProgress, showPlot, long, short, resaults_list, i, rdelta, perYear)
resaults_list = scanner.heart()
#Loopling trough Long-Short, Long and Short
if long:
long = False
elif short:
long = True
short = False
#Saving the results from the Dataframe to excel
if scan or saveScan:
df2 = pd.DataFrame(resaults_list)
df2.columns = ['Rev','LongShort','Ticker', 'Wallet Mean', 'Wallet', 'Wallet increase', 'Plus', 'Minus']
#df2 = df2.sort_values(by=['Wallet'], ascending=False)
now = dt.datetime.now()
df2.to_excel(f'data/{now.strftime("%Y%m%d_%H%M")}_scan.xlsx',
index=False)
</code></pre>
<p>And this is scan.py</p>
<pre><code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from strategies import strategies
import datetime as dt
class Scanner:
def __init__(self, df, ticker, scan, saveScan, showProgress, showPlot, long, short, resaults_list, rev, rdelta, perYear):
self.df = df
self.ticker = ticker
self.df = df
self.ticker = ticker
self.scan = scan
self.saveScan = saveScan
self.showProgress = showProgress
self.showPlot = showPlot
self.long = long
self.short = short
self.resaults_list = resaults_list
self.rev = rev
self.rdelta = rdelta
self.perYear = perYear
def heart(self):
df = self.df
ticker = self.ticker
scan = self.scan
saveScan = self.saveScan
showProgress = self.showProgress
showPlot = self.showPlot
long = self.long
short = self.short
resaults_list = self.resaults_list
rev = self.rev
rdelta = self.rdelta
perYear = self.perYear
ema12 = df.Close.ewm(span=12, adjust=False).mean()
ema26 = df.Close.ewm(span=26, adjust=False).mean()
ema200 = df.Close.ewm(span=200, adjust=False).mean()
macd = ema12 - ema26
ema6 = macd.ewm(span=6, adjust=False).mean()
df['macd'] = macd
df['signal'] = ema6
df['ema200'] = ema200
increase = []
olong = []
clong = []
oshort = []
cshort = []
wallet = []
buyandhold = []
bought = False
sold = False
longClose = 0
shortClose = 0
poss = 0
neg = 0
sell_possetive = 0
wallet_increase = 0
wallet_value = 1000
buyandhold_wallet = 1000
old_price = -1
tomorrow = "tomt"
for i in range(0, len(df)):
strategie = strategies(df['macd'][i], df['signal'][i], df['Close'][i], df['ema200'][i], bought, sold)
close = df['Close'][i]
if tomorrow == "ol":
longClose = df['Close'][i]
increase.append(np.nan)
olong.append(df['Close'][i])
clong.append(np.nan)
oshort.append(np.nan)
cshort.append(np.nan)
wallet.append(wallet_value)
bought = True
tomorrow = "tomt"
elif tomorrow == "cl":
increase.append(df['Close'][i] - longClose)
olong.append(np.nan)
clong.append(df['Close'][i])
oshort.append(np.nan)
cshort.append(np.nan)
wallet_value = ((wallet_value / longClose) * df['Close'][i])
wallet.append(wallet_value)
bought = False
tomorrow = "tomt"
if df['Close'][i] - longClose > 0:
poss += 1
elif df['Close'][i] - longClose < 0:
neg += 1
elif tomorrow == "os":
shortClose = df['Close'][i]
increase.append(np.nan)
oshort.append(df['Close'][i])
cshort.append(np.nan)
olong.append(np.nan)
clong.append(np.nan)
wallet.append(wallet_value)
sold = True
tomorrow = "tomt"
elif tomorrow == "cs":
increase.append(shortClose - df['Close'][i])
cshort.append(df['Close'][i])
oshort.append(np.nan)
olong.append(np.nan)
clong.append(np.nan)
wallet_value = ((wallet_value / df['Close'][i]) * shortClose)
wallet.append(wallet_value)
sold = False
tomorrow = "tomt"
if df['Close'][i] - shortClose > 0:
poss += 1
elif df['Close'][i] - shortClose < 0:
neg += 1
else:
increase.append(np.nan)
oshort.append(np.nan)
cshort.append(np.nan)
olong.append(np.nan)
clong.append(np.nan)
wallet.append(wallet_value)
if strategie.olongMacd() and long:
tomorrow = "ol"
elif strategie.clongMacd() and long:
tomorrow = "cl"
elif strategie.oshortMacd() and short:
tomorrow = "os"
elif strategie.cshortMacd() and short:
tomorrow = "cs"
if old_price < 0:
old_price = df['Close'][i]
buyandhold_wallet = (buyandhold_wallet / old_price) * df['Close'][i]
buyandhold.append(buyandhold_wallet)
old_price = df['Close'][i]
df['increase'] = increase
df['Open Long'] = olong
df['Close Long'] = clong
df['Open Short'] = oshort
df['Close Short'] = cshort
df['wallet'] = wallet
df['buyandhold'] = buyandhold
print(str(rev), "", ticker)
if showProgress:
print("Mean ", df['increase'].mean())
print("Plus: ", poss)
print("Minus: ", neg)
longshort1 = ' Long ' if long else ''
longshort2 = ' Short ' if short else ''
wal_increase = ((df['wallet'].iloc[-1] - df['wallet'][0]) / df['wallet'][0]) * 100
if perYear:
resaults_list.append(["Y " + str(rev), longshort1 + longshort2, ticker, int(df['wallet'].mean()), int(df['wallet'].iloc[-1]), int(wal_increase / rdelta), int(poss / rdelta), int(neg / rdelta)])
else:
resaults_list.append(["T " + str(rev), longshort1 + longshort2, ticker, int(df['wallet'].mean()), int(df['wallet'].iloc[-1]), int(wal_increase), int(poss), int(neg)])
if showPlot:
ax1 = plt.subplot2grid((12, 1), (0, 0), rowspan=4, colspan=1, title=ticker)
ax2 = plt.subplot2grid((12, 1), (5, 0), rowspan=4, colspan=1, title='Macd', sharex=ax1)
ax3 = plt.subplot2grid((12, 1), (9, 0), rowspan=4, colspan=1, title='Wallet', sharex=ax1)
ax1.plot(df.index, df['Close'], color='black', label='Close')
ax1.plot(df.index, df['ema200'], color='blue', label='ema200')
ax1.scatter(df.index, df['Open Long'], color='green', label='Open long', marker='^', alpha=1)
ax1.scatter(df.index, df['Close Long'], color='red', label='Close long', marker='v', alpha=1)
ax1.scatter(df.index, df['Open Short'], color='blue', label='Open short', marker='v', alpha=1)
ax1.scatter(df.index, df['Close Short'], color='black', label='Close short', marker='^', alpha=1)
ax1.legend(fontsize='x-small')
ax2.plot(df.index, df['signal'], color='red', label='signal')
ax2.plot(df.index, df['macd'], color='green', label='macd')
ax2.axhline(0, linestyle='-.', color='black')
ax2.legend(fontsize='x-small')
ax3.plot(df.index, df['wallet'], color='red', label='wallet')
ax3.plot(df.index, df['buyandhold'], color='green', label='Buy and hold')
ax3.axhline(0, linestyle='-.', color='black')
ax3.legend(fontsize='x-small')
plt.show()
if not scan:
df.to_excel('data/{}.xlsx'.format(ticker), index=False)
return resaults_list
</code></pre>
<p>And this is the strategies.py</p>
<pre><code>class strategies():
def __init__(self, macd, signal, close, ema200, bought, sold):
self.macd = macd
self.signal = signal
self.close = close
self.ema200 = ema200
self.bought = bought
self.sold = sold
def olongMacd(self):
s1 = self.macd > self.signal
s2 = self.close > self.ema200
s3 = 0 > self.macd
s4 = not self.bought and not self.sold
output = s1 and s2 and s3 and s4
return output
def clongMacd(self):
s1 = self.signal > self.macd
s2 = self.bought
output = s1 and s2
return output
def oshortMacd(self):
s1 = self.signal > self.macd
s2 = self.ema200 > self.close
s3 = self.macd > 0
s4 = not self.bought and not self.sold
output = s1 and s2 and s3 and s4
return output
def cshortMacd(self):
s1 = self.macd > self.signal
s2 = self.sold
output = s1 and s2
return output
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T15:50:14.270",
"Id": "501924",
"Score": "2",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T15:58:25.387",
"Id": "501926",
"Score": "2",
"body": "I see you've edited the title - but it still doesn't say what the code _does_. On Code Review, the title always states the purpose of the code - the implied question is always, \"How can this be improved?\" and it doesn't need stating."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T15:37:01.777",
"Id": "254487",
"Score": "0",
"Tags": [
"python"
],
"Title": "AlgoTrading backtesting. Can I make this code leener and more flexible?"
}
|
254487
|
<p>I programmed a calculator with int operations. The calculator stores functions in a dictionary. Also, the calculator stores how many arguments the function takes in a dictionary.</p>
<p>The input format is arguments followed by module and function name. These are split by lines and spaces. Input lines that start with a # are comments and are ignored by the calculator.</p>
<p>In order to use a value from the previous functions, an argument can be skipped and will be inserted in the front of the functions arguments.</p>
<p>The code is in three modules: fn (stores the functions), int_ops (int arthmatic operations), and run.py (grabs user input and outputs answer).</p>
<pre><code>import fn
from fn import key, plugin_function
from int_ops import divide, multiply, subtract, add
"""
Run Module
__fn__:
key(module_name: str, fn_name: str) -> str
plugin_function(module_name: str, fn_name: str, number_of_args: int, func) -> None:
main() -> None
"""
def main() -> None:
fn.plugin_function(add, "Int", "add", 2)
fn.plugin_function(subtract, "Int", "subtract", 2)
fn.plugin_function(multiply, "Int", "multiply", 2)
fn.plugin_function(divide, "Int", "divide", 2)
lines = ["2 2 Int add", "1 Int add"]
stack = []
split = ""
for line in lines:
split = line.split(" ")
if split[0] == "#":
continue
"""
ignore extra spaces and extra tabs in input
"""
for e in split:
e = e.replace(" ", "")
e = e.replace("\t", "")
"""
module name and function name are not args passed to call
"""
num_current_args = len(split) - 2
needed_num_of_args = fn.num_args[key(split[-2], split[-1])]
"""
add args from the stack for args not stated in input
"""
for row in range(needed_num_of_args - num_current_args):
split.insert(0, stack[row])
del stack[row]
function = fn.function[key(split[-2], split[-1])]
output = str(function(split))
stack.append(output)
print(stack)
if __name__ == "__main__":
main()
"""
Int Module
fn
divide(parts: [str]) -> int
multiply(parts: [str]) -> int
subtract(parts: [str]) -> int
add(parts: [str]) -> int
"""
def divide(parts: [str]) -> int:
"""
:param parts: parts of divide_int cmd
Output: 0 if divsor is 0, int division otherwise
"""
a = int(parts[0])
b = int(parts[0])
if b == 0:
return 0
return a // b
def multiply(parts :[str]) -> int:
"""
:param parts: parts of the multiply_int cmd, ends with this name
Output: scalar multiplication of ints
"""
a = int(parts[0])
b = int(parts[1])
return a * b
def subtract(parts:[str]) -> int:
"""
:param parts: parts of the subract_int cmd
Output: subtraction of two
"""
a = int(parts[0])
b = int(parts[1])
return a - b
def add(parts :[str]) -> int:
"""
:param parts: parts of the add_int cmd, ends with this name
Output: sum as int of both number
"""
a = int(parts[0])
b = int(parts[1])
return a + b
"""
Module containing the functions that can be run
This file has the mathmatical functions of the calculator
fn
key(module_name: str, fn_name: str) -> str
function(module_name: str, fn_name: str)
num_args(module_name: str, fn_name)
plugin_function(func, module_name: str, fn_name: str, number_of_args: int) -> None
"""
__fn__ = {}
__num_args__ = {}
def key(module_name: str, fn_name: str) -> str:
"""
:param module_name: name of the module
:param fn_name: name of the function
Key used for this module
"""
return module_name + " " + fn_name
def function(module_name: str, fn_name: str):
"""
:param module_name: module the function is in
:param fn_name: the name of the function
Output: function
"""
return __fn__[key(module_name, fn_name)]
def num_args(module_name: str, fn_name: str) -> int:
"""
:param module_name: module of the function
:param fn_name: name of the function
Output: Number of parameters such as x and y (2) that the function takes
"""
return __num_args__[key(module_name, fn_name)]
def plugin_function(func, module_name: str, fn_name: str, number_of_args: int) -> None:
"""
:param module_name: name of the module
:param fn_name: name of the function
:param number_of_args: number of args the function takes (required to be str)
:param func: the function to run
Output: None
"""
global __fn__
global __num_args__
__fn__[key(module_name, fn_name)] = func
__num_args__[key(module_name, fn_name)] = number_of_args
</code></pre>
|
[] |
[
{
"body": "<p>I think you overengineered this solution. Below is a barebones implementation in one file. The focus here is on keeping the runtime logic as simple as possible. That is, if you wanted a more robust system for adding operations, it should ideally still compile into a simple structure like a dictionary of operations before the calculator even begins.</p>\n<pre><code>from collections import namedtuple\n\nOperation = namedtuple('Operation',['func','num_params'])\n\nOPERATIONS = {\n 'Int add': Operation(\n lambda a,b: int(a)+int(b),\n 2\n )\n}\n\ndef main() -> None:\n lines = ["2 2 Int add", "1 Int add"]\n stack = []\n for line in lines:\n tokens = [\n token.strip()\n for token in line.split()\n ]\n *args, dtype, operator = tokens\n operation = OPERATIONS[f'{dtype} {operator}']\n\n stack_args_needed = operation.num_params - len(args)\n for _ in range(stack_args_needed):\n args.append(stack.pop())\n\n result = operation.func(*args)\n stack.append(result)\n print(stack)\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T22:15:01.693",
"Id": "254505",
"ParentId": "254491",
"Score": "1"
}
},
{
"body": "<p>Unless I missed a major announcement regarding very new versions of Python, this isn't a proper type hint:</p>\n<pre><code>def divide(parts: [str]) -> int:\n</code></pre>\n<p>To type-hint a list, you need one of:</p>\n<pre><code>from typing import List\n\ndef divide(parts: List[str]) -> int: # Python 3.5+ \n\n\ndef divide(parts: list[str]) -> int: # Python 3.9+\n</code></pre>\n<hr />\n<p>You have another bug as well:</p>\n<pre><code>for e in split:\n e = e.replace(" ", "")\n e = e.replace("\\t", "")\n</code></pre>\n<p>This will not change <code>split</code>. This puts the string returned by <code>replace</code> into <code>e</code>, then <code>e</code> is overwritten on the next iteration and the replaced data is lost. You'd need something like this instead:</p>\n<pre><code>replaced_split = [e.replace(" ", "").replace("\\t", "")\n for e in split]\n</code></pre>\n<p>Then, used <code>replaced_split</code> instead of <code>split</code>.</p>\n<hr />\n<pre><code>split.insert(0, stack[row])\n</code></pre>\n<p>You should really never insert into the front of a list, unless you have 0 performance requirements. When you insert into the front, it needs to shift every other element in the list to make room at the front (<code>O(n)</code>; where <code>n</code> is the size of the list). It's much better to add to the end using <code>append</code>, which is amortized <code>O(1)</code> iirc. If it's too messy adding to the end, switch to using a <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>dequeue</code></a> which allows for constant-time inserts at both ends.</p>\n<hr />\n<p>Another bug:</p>\n<pre><code>a = int(parts[0])\nb = int(parts[0])\n</code></pre>\n<p><code>b</code> should be the element at index <code>1</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T16:14:47.543",
"Id": "254525",
"ParentId": "254491",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254525",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T17:48:08.687",
"Id": "254491",
"Score": "0",
"Tags": [
"python-3.x",
"calculator"
],
"Title": "Stack based Calculator in Python"
}
|
254491
|
<p>For an interview, I had to create a card game called <code>match</code>. The rules were the following:</p>
<p>Players can choose a number of packs of playing cards and combine them into a single deck. The deck can be shuffled.</p>
<p>Cards are played sequentially from the top of the deck into the pile,</p>
<p>If two cards played sequentially match, the first player to declare "Match" takes all the cards in the pile.</p>
<p>(For the purpose of the simulation the program should randomly choose a player to have declared "Match" first).</p>
<p>The play then continues with the next card in the deck, starting a new pile. The game ends no more cards can be drawn from the deck and no player can declare "Match!".</p>
<p>The player that has taken the most cards is the winner. The game may end in a draw.</p>
<p>The match condition can be the following</p>
<pre><code>The suits of two cards must match
Example: "3 of hearts" and "5 of hearts" match because they are both hearts.
The values of two cards must match
Example: "7 of hearts" and "7 of clubs" match because they both have the value 7.
Both suit and value must match
Example: "Jack of spades" only matches another "Jack of spades"
The program
As input, the program should ask:
how many packs of cards to use for the deck
which match condition to use
It should then simulate the game.
The program should output the results by either declaring the winner, or a draw.
</code></pre>
<p>I had a timebox of 90 minutes to complete this task but I ran out of time. My approach was to basically eventually have a front end plugged into this so wrote the code with that approach. After I submitted I realized I didn't add the check for a draw.</p>
<p>Here is <code>deck.js</code></p>
<pre><code>const suits = ["♠", "♥", "♣", "♦"];
const values = [
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"J,",
"Q",
"K",
"A",
];
class Deck {
constructor(packs = 1) {
this.packs = packs;
this.deck = [];
}
newDeck() {
let counter = this.packs;
while (counter) {
for (let suit of suits) {
for (let value of values) {
this.deck.push(new Card(value, suit));
}
}
counter--;
}
return this.deck;
}
get deckSize() {
return this.deck.length;
}
shuffle() {
let counter = this.deckSize,
temp,
i;
while (counter) {
i = Math.floor(Math.random() * counter--);
temp = this.deck[counter];
this.deck[counter] = this.deck[i];
this.deck[i] = temp;
}
return this.deck;
}
deal() {
let hand = [];
while (hand.length < 2) {
hand.push(this.deck.shift());
}
return hand;
}
}
class Card {
constructor(value, suit) {
this.value = value;
this.suit = suit;
}
}
module.exports = {Deck, Card}
</code></pre>
<p>here is my app.js</p>
<pre><code>const { Deck } = require("./deck.js");
const MatchCondition = Object.freeze({ suits: 1, values: 2, both: 3 });
const players = ["playerOne", "playerTwo"];
const playerScores = {
playerOne: 3,
playerTwo: 4,
};
let deck;
let cards = {};
let result = "";
const cardsAreEqual = (card1, card2) => {
Object.keys(card1).length === Object.keys(card2).length &&
Object.keys(card1).every((p) => card1[p] === card2[p]);
};
const matchCondition = (cards, condition) => {
//Need to add some error handling for when the conditions
//Does not match a MatchCondition
let result = "";
if (condition === MatchCondition.suits) {
if (cards[0].suit === cards[1].suit) {
result = `The Suits MATCH !!!`;
}
}
if (condition === MatchCondition.value) {
if (cards[0].value === cards[1].value) {
result = `The Values MATCH !!!`;
}
}
if (condition === MatchCondition.both) {
if (cardsAreEqual(cards[0], cards[1])) {
result = `The Cards MATCH !!!`;
}
}
return result;
};
const winningScore = (playerObj) => {
const [key, value] = Object.entries(playerObj).reduce((r, e) =>
e[1] > r[1] ? e : r
);
return { [key]: value };
};
const startGame = (numOfPacks, condition) => {
const randomPlayer = Math.floor(Math.random() * players.length);
deck = new Deck(numOfPacks);
deck.newDeck();
deck.shuffle();
if (deck.deckSize !== 0) {
cards = deck.deal();
result = matchCondition(cards, condition);
if (result !== "") {
playerScores[players[randomPlayer]]++;
return `${players[randomPlayer]} shouted ${result}`;
}
} else {
return winningScore(playerScores);
}
};
startGame(2, MatchCondition.suits);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T01:39:15.537",
"Id": "504910",
"Score": "1",
"body": "Code building technique and structuring is the basis for continual progress and consistent quality. Algorithmic insights cannot overcome code that is perpetually 80% complete, so to speak. So I ask: What broke the time limit? Where/how was time spent? Sticking points? How was the code constructed; what was written in what order? How was functionality built up? How much bugginess was popping up as code evolved? For example did a \"use case\" bug seem to be threaded across multiple objects and/or functions? Was new code just using/calling existing code or forcing internal change?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T08:11:02.470",
"Id": "504931",
"Score": "0",
"body": "@radarbob I think what broke the time limit was I underestimated what was required. My initial mistake was trying to create this project in a way that would also have a frontend. I think I should have focussed more on getting the basic functionality to work before thinking of the front end"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T08:19:03.627",
"Id": "504932",
"Score": "1",
"body": "*trying to create this project in a way that would also have a frontend* -- there IS a front end. It's the console. Note the last bit of code in the answers below. The game is instantiated, executed, and output displayed all from the console. A GUI would be doing exactly the same thing but with buttons and such. Also random pretty flashy thingies to convince folks to buy this game."
}
] |
[
{
"body": "<h1>deck.js</h1>\n<p>The <code>Card</code> class can be removed entirely by writing <code>newDeck()</code> like so.</p>\n<pre><code> newDeck() {\n this.cards = [];\n for (let i=0;i<this.packs;++i) {\n for (const suit of suits) {\n for (const value of values) {\n this.cards.push({value,suit});\n }\n }\n }\n\n return this.cards;\n }\n</code></pre>\n<p>Shuffling logic can be separated from class.</p>\n<pre><code>function shuffle(array) {\n for (let i=0;i<array.length;++i) {\n let j = array.length -1 - Math.floor(Math.random()*i);\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n }\n}\n\nclass Deck{\n // ...\n shuffle() {\n shuffle(this.cards);\n }\n}\n</code></pre>\n<h1>app.js</h1>\n<p>It seems weird to be checking which match condition to use while simulating a game. Grabbing a condition on init would be more suited ♠.</p>\n<pre><code>const MatchCondition = {\n 'suits': ([a,b]) => \n a.suit === b.suit,\n 'value': ([a,b]) =>\n a.value === b.value,\n 'both': ([a,b]) => \n MatchCondition.suits(a,b) && MatchCondition.value(a,b)\n}\n</code></pre>\n<p>Your start game function seems to actually simulate the entire game, so a rename would be appropriate.</p>\n<pre><code>const maxEntryFromDict = (dict) => {\n const [key, value] = Object.entries(dict).reduce(\n (r, e) => e[1] > r[1] ? e : r\n );\n return { [key]: value };\n};\n\nconst randomChoice = (items) =>\n items[Math.floor(Math.random()*items.length)]\n\nconst playGame = (numOfPacks, condition) => {\n const scores = {\n playerOne: 3,\n playerTwo: 4,\n };\n const randomPlayer = randomChoice(Object.keys(scores));\n const deck = new Deck(numOfPacks);\n deck.newDeck();\n deck.shuffle();\n\n while (deck.cards.length > 0) {\n const cards = deck.deal();\n console.log(cards);\n\n if (condition(cards)) {\n scores[randomPlayer]++;\n console.log(`${randomPlayer} shouted Match!`);\n }\n }\n return maxEntryFromDict(scores);\n};\n\nconst game_result = playGame(2, MatchCondition.suits);\nconsole.log(game_result);\n</code></pre>\n<p>There's definitely some incorrect behaviours remaining including the fact that piles are not kept track of at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T19:56:45.350",
"Id": "254496",
"ParentId": "254493",
"Score": "0"
}
},
{
"body": "<h2>Only what is needed</h2>\n<p>Programming is a creative process and things like time pressure have a negative effect on the whole project (even little 90min projects). That said software development is a business that must be profitable. Time is a limited resource so there will always be time pressure.</p>\n<p>As a coder you must write efficiently, spending time on details not required puts pressure on you. The result is you don't think it through, you make mistakes and the quality of the code suffers.</p>\n<p>There is not much to review as most of the code is superfluous, and what counts (the output) is incomplete and thus does not work.</p>\n<h2>What was the task?</h2>\n<p>Your question outlines the task, but your code suggests a much more complex brief.</p>\n<p>If taken at face value (outline in question) you have overcooked the solutions.</p>\n<p>Task Return highest score or <code>"draw"</code> of the card game <a href=\"https://en.wikipedia.org/wiki/Snap_(card_game)\" rel=\"nofollow noreferrer\">"Snap"</a> (variation there of) for 2 or more players playing with 1 or more decks.</p>\n<h3>Interpretation of rules of "Snap"</h3>\n<p>I don't think that there are 3 different rules, a match is any of 3 different conditions. Same suit, save value, or same suit And value. (the last is not needed)</p>\n<h2>Focus on the task.</h2>\n<p>An application is just a function where all you know about its behavior is down to what the function returns.</p>\n<h3>Don't code for unrelated content</h3>\n<p>There is no output with cards, or which player wins, only a number or a string.</p>\n<p>Why bother with players and player names, only the player scores matter. That can be done with an array of values.</p>\n<p>Why bother with the cards, the card only represent the number of hands dealt.</p>\n<p>Then its the odds of a match per card dealt that determines if a random player wins the stack. There is a 1 in 4 odds that suits will match and 1 in 13 that the values will match. The odds of a match is the sum of (1 / 13 + 1 / 4)</p>\n<p>To account for the end game (number of cards not collected when there is no match on last hand) I reduced the odds per card by 1/52</p>\n<p>Thus you could have written</p>\n<pre><code>function Snap(decks, players) {\n const match = () => Math.random() <= (1 / 4 + 1 / 13 - 1 / 52);\n const scores = new Array(players).fill(0);\n var stack = 1, best = 0, cards = decks * 52 - 1;\n function play() {\n cards --;\n if (match()) {\n best = Math.max(scores[Math.random() * players | 0] += stack + 1, best);\n stack = 0;\n cards --;\n }\n stack ++;\n } \n return Object.freeze({\n play,\n get gameOver() { return cards <= 0 },\n bestScore: () => { \n 1 === scores.reduce((c, pts)=> c + (pts === best ? 1 : 0), 0)? best: "Draw"; \n },\n });\n}\nconst game = Snap(2, 2); \nwhile (!game.gameOver) { game.play() }\nconst result = game.bestScore();\n</code></pre>\n<p>Total time to write ~15 min.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T16:09:47.160",
"Id": "254524",
"ParentId": "254493",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254524",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T18:37:51.137",
"Id": "254493",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"game"
],
"Title": "Create a Card game called match"
}
|
254493
|
<p>I am trying to implement a tiny text file read / write class <code>FileIO</code> in order to make the operations of reading / writing pure text files easily. The usage is like:</p>
<pre><code>FileIO.Instance.FileWrite("TextFile1.txt", "This is a test1.");
FileIO.Instance.FileWrite("TextFile2.txt", "This is a test2.");
Console.WriteLine(FileIO.Instance.ReadTxTFile("TextFile1.txt", System.Text.Encoding.Default));
Console.WriteLine(FileIO.Instance.ReadTxTFile("TextFile2.txt", System.Text.Encoding.Default));
</code></pre>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>FileIO</code> class is as below.</p>
<pre><code>class FileIO
{
public readonly static FileIO Instance = new FileIO();
public void FileWrite(string filename, string inputString)
{
FileStream file_stream = new FileStream(filename, FileMode.Append);
byte[] Input_data = System.Text.Encoding.Default.GetBytes(inputString);
file_stream.Write(Input_data, 0, Input_data.Length);
file_stream.Flush();
file_stream.Close();
}
public void FileWrite(string filename, string inputString, FileMode fileMode)
{
FileStream file_stream = new FileStream(filename, fileMode);
byte[] Input_data = System.Text.Encoding.Default.GetBytes(inputString);
file_stream.Write(Input_data, 0, Input_data.Length);
file_stream.Flush();
file_stream.Close();
}
public void FileWrite(string filename, string inputString, FileMode fileMode, Encoding encoding)
{
FileStream file_stream = new FileStream(filename, fileMode);
byte[] Input_data = encoding.GetBytes(inputString);
file_stream.Write(Input_data, 0, Input_data.Length);
file_stream.Flush();
file_stream.Close();
}
public string ReadTxTFile(string filename, Encoding encoding)
{
System.IO.StreamReader textreader;
string inputString;
inputString = "";
try
{
textreader = new System.IO.StreamReader(filename, encoding);
}
catch (Exception)
{
return "";
throw;
}
inputString = textreader.ReadToEnd();
textreader.Close();
return inputString;
}
}
</code></pre>
<p>If there is any possible improvement about:</p>
<ul>
<li><p>Performance: including data reading/writing speed things</p>
</li>
<li><p>The naming and readability</p>
</li>
<li><p>Potential drawbacks of the implemented methods</p>
</li>
</ul>
<p>, please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T21:36:54.513",
"Id": "501938",
"Score": "3",
"body": "Why not use `File.ReadAllText` and `File.WriteAllText`? Also, you use classes that implement `IDisposable` yet you don't `Dispose()` of them. And why aren't you encapsulating their uses in a `using`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T00:29:26.187",
"Id": "501981",
"Score": "0",
"body": "@BCdotWEB Thank you for the comments. Do you mean that `Dispose()` method should be added? May I update the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T01:14:58.583",
"Id": "501984",
"Score": "1",
"body": "Don't edit the code in the question but consider that fix to apply. [Using objects that implement IDisposable](https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects). And yes, methods `File.ReadAllText` and `File.WriteAllText` are already exist in .NET. Thus you don't need the code you wrote. [Learn what the `File` class can](https://docs.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T07:54:57.353",
"Id": "501992",
"Score": "0",
"body": "@aepot OK, I see. Thank you for the suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T09:53:42.327",
"Id": "502000",
"Score": "0",
"body": "AFAIK the code in the question can be updated as long as there isn't a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T09:56:40.997",
"Id": "502001",
"Score": "1",
"body": "@JimmyHu Whether or not an explicit call to `Dispose()` is needed depends on the case. The best approach is to use a `using`: https://stackoverflow.com/questions/17357258/does-using-statement-always-dispose-the-object"
}
] |
[
{
"body": "<h3>Naming</h3>\n<ul>\n<li><code>FileIO</code>: The <code>File</code> class resides inside the <code>System.IO</code> namespace. <code>FileIO</code> is quite a misfortune chose of name. <code>TextFileWrapper</code>, <code>TextFileUtil</code> or <code>TextFileManager</code> would be a more appropriate name for this in my opinion.</li>\n<li><code>FileWrite</code>: The general guidance is to start your methods with a verb. So, <code>WriteFile</code> would be a better name for this.</li>\n<li><code>ReadTxtFile</code>: This name is a bit misleading. <code>txt</code> can be considered as a file extension, so the caller may no specify the filename as you expect.</li>\n<li><code>inputString</code>: Please try to avoid <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a>.</li>\n</ul>\n<p>Please try to chase consistency (or symmetry).<br />\nTry to name your Read-Write method pair in the same fashion:</p>\n<ul>\n<li><code>ReadTextFile</code>, <code>WriteTextFile</code></li>\n<li><code>ReadFile</code>, <code>WriteFile</code></li>\n<li>or simply just <code>Read</code> and <code>Write</code></li>\n</ul>\n<p>Stuttering:</p>\n<ul>\n<li>Maybe it's just for me, but <strong>File</strong>IO.Instance.<strong>File</strong>Write seems too repetitive.</li>\n<li><code>TextFileManager.Write</code> seems way more natural for me.</li>\n</ul>\n<h3>Robustness</h3>\n<p>Your implementation is quite naive. It does not deal with a lot of different cases:</p>\n<ul>\n<li>What if the <code>fileName</code> points to a non-existing file?</li>\n<li>What if the <code>inputString</code> is enormously large?</li>\n<li>What if one of the parameters is <code>null</code>?</li>\n<li>What if the file has been opened by another method and has not been closed yet?</li>\n</ul>\n<p>Your implementation also relies on <code>Encoding.Default</code>, which is <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.default\" rel=\"nofollow noreferrer\">computer specific</a>.<br />\nWhich means you can end up in the following situation:</p>\n<ul>\n<li><code>FileA.txt</code> has been written to the disk on MachineA</li>\n<li><code>FileA.txt</code> has been copied from MachineA to MachineB\n<ul>\n<li>where the default encoding is different</li>\n</ul>\n</li>\n<li>MachineB could not read <code>FileA.txt</code></li>\n</ul>\n<h3>Thread-safety</h3>\n<ul>\n<li>Your <code>instance</code> property does not make your class a singleton.\n<ul>\n<li>Please read thoroughly <a href=\"https://csharpindepth.com/articles/singleton\" rel=\"nofollow noreferrer\">Jon Skeet's guidance</a>.</li>\n</ul>\n</li>\n<li>If you make your class a singleton you have to make sure that your operations are thread-safe.\n<ul>\n<li>Reading and writing the same file from different threads are handled in a proper way.</li>\n</ul>\n</li>\n<li>As pointed out by others you have to do some clean-up as well.\n<ul>\n<li>To make sure that if something goes wrong then your file handles are closed properly.</li>\n</ul>\n</li>\n</ul>\n<h3>Performance</h3>\n<ul>\n<li>Try to take advantage of <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/io/asynchronous-file-i-o\" rel=\"nofollow noreferrer\">async I/O</a></li>\n<li>Try to take advantage of <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1?view=net-5.0\" rel=\"nofollow noreferrer\">ArrayPool</a> when you are calling the GetBytes method.\n<ul>\n<li>It has an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.getbytes?view=net-5.0#System_Text_Encoding_GetBytes_System_Char___System_Int32_System_Int32_System_Byte___System_Int32_\" rel=\"nofollow noreferrer\">overload which accepts a byte array</a></li>\n</ul>\n</li>\n<li>As always, measure, measure and measure.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T11:32:44.233",
"Id": "254549",
"ParentId": "254494",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254549",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T18:56:37.750",
"Id": "254494",
"Score": "1",
"Tags": [
"c#",
"performance",
"strings",
"file",
"stream"
],
"Title": "A Tiny Text File Read/Write class Implementation in C#"
}
|
254494
|
<p>I wanted to make a React hook that allowed me to use the React Component Class lifecycle calls. So I could use the named version instead of just having useEffect.</p>
<p>For example, I want to be able to do this.</p>
<pre><code>useEffectWithName.componentDidMount(callback);
</code></pre>
<p>Here is the code that I put together with help from the following question.
"https://stackoverflow.com/questions/53464595/how-to-use-componentwillmount-in-react-hooks".</p>
<p>My question is did I implement the React Class Lifecycle functions in a hook properly?
Or do you see an issue with how I did this.</p>
<p>Thanks in advance. Note I am using typescript.</p>
<pre><code>import {
useEffect,
EffectCallback,
memo,
PropsWithChildren,
FunctionComponent
} from 'react';
const useEffectWithName = (() => {
const componentDidMount = (cb: EffectCallback) => {
useEffect(cb, []);
}
const componentDidUpdate = (cb: EffectCallback) => {
useEffect(cb);
}
interface shouldComponentUpdate<P> {
Component: FunctionComponent<P>;
condition: (
prevProps: Readonly<PropsWithChildren<P>>,
nextProps: Readonly<PropsWithChildren<P>>
) => boolean;
}
const shouldComponentUpdate = <P>({ Component, condition }: shouldComponentUpdate<P>) => {
memo(Component, condition);
}
const componentWillUnmount = (cb: EffectCallback) => {
useEffect(() => {
return () => {
cb()
};
}, []);
}
return {
componentDidMount: componentDidMount,
componentDidUpdate: componentDidUpdate,
shouldComponentUpdate: shouldComponentUpdate,
componentWillUnmount: componentWillUnmount
};
})();
export default useEffectWithName;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T18:32:12.317",
"Id": "503298",
"Score": "0",
"body": ".... but why? :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T19:11:32.173",
"Id": "503414",
"Score": "0",
"body": "Makes it more readable. So when you look at it you know what it does. Instead of doing a trick and having to think about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T19:12:26.453",
"Id": "503415",
"Score": "1",
"body": "Go check this out, it's maybe something you'll like https://github.com/streamich/react-use"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T20:16:08.140",
"Id": "254497",
"Score": "0",
"Tags": [
"javascript",
"react.js"
],
"Title": "React hook to wrap useEffect and mimic React component class lifecycle calls"
}
|
254497
|
<p>I devised a new primality test <strong>isPrimeNumber()</strong> below which determines if 1000000007 is prime.
It works fine but the code looks unprofessional in my opinion. Is there any way to refactor it to make it more readable? Maybe inline the recursive gcd() function so everything is self-contained in the <strong>isPrimeNumber()</strong> function etc.,...? Any tips? Thanks!</p>
<pre><code>// Primality Test
// Every n is prime if all lattice points on x+y=n are visible from the origin.
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#define NOT_PRIME_NUMBER 0
#define PRIME_NUMBER 1
uint64_t gcd(uint64_t a, uint64_t b)
{
return (b != 0) ? gcd(b, a % b) : a;
}
int isPrimeNumber(uint64_t n)
{
if (n == 2 || n == 3 || n == 5)
{
return PRIME_NUMBER;
}
uint64_t m = n % 10;
if (m == 1 || m == 3 || m == 7 || m == 9)
{
uint64_t x, y;
uint64_t step = 0, maxStep = sqrt(n) / 2;
// Start near line x=y.
x = (n / 2) + 2;
y = n - x;
do {
// Check lattice point visibility...
if (gcd(x, y) != 1)
{
return NOT_PRIME_NUMBER;
}
x++; y--; step++;
} while (step < maxStep);
}
else
{
return NOT_PRIME_NUMBER;
}
return PRIME_NUMBER;
}
int main(int argc, char* argv)
{
uint64_t n = 1000000007;
if (isPrimeNumber(n) == PRIME_NUMBER)
{
printf("%llu prime.", n);
}
else
{
printf("%llu not prime.", n);
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>m</code> digit checking can be simplified and your do while loop can be replaced with the simpler for loop. The constants also seem excessive given that non-zero truthiness is baked into C.</p>\n<pre><code>int isPrimeNumber(uint64_t n)\n{\n if (n==2 || n==3) return 1;\n if (n%2==0) return 0;\n \n // Start near line x=y.\n uint64_t x = (n / 2) + 2;\n uint64_t y = n - x;\n\n uint64_t count = sqrt(n) / 2;\n for (uint64_t i=0;i<count;++i) {\n // Check lattice point visibility...\n if (gcd(x, y) != 1) return 0;\n\n x++; y--;\n }\n\n return 1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T13:00:13.390",
"Id": "501954",
"Score": "1",
"body": "Looks great! The only missing case is when n=1. Maybe we could add a check here: \n if (n == 1) return 0;\n if (n == 2 || n == 3) return 1;\n if (n % 2 == 0) return 0; .... or maybe somekind of c-ternary-operator?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T08:52:29.917",
"Id": "254519",
"ParentId": "254508",
"Score": "2"
}
},
{
"body": "<p><strong>Avoid FP functions for integer problems.</strong></p>\n<p><code>sqrt(n)</code> problems include potential inexact roots for perfect squares (it is a FP function, not an integer one) and rounding of the <code>double</code> argument when <code>n</code> > 2<sup>54</sup> or so.</p>\n<p>Sample alternative; <a href=\"https://en.wikipedia.org/wiki/Integer_square_root#Example_implementation_in_C\" rel=\"nofollow noreferrer\">int_sqrt in C</a></p>\n<hr />\n<p>Other: Only small stuff:</p>\n<p><strong>Minor: OK for a narrower type</strong></p>\n<pre><code>//uint64_t m = n % 10;\nunsigned m = n % 10u;\nif (m == 1 || m == 3 || m == 7 || m == 9)\n</code></pre>\n<p><strong>Minor: Streamline first test</strong></p>\n<p>Rather than 3 initial tests that are rarely true, maybe one.</p>\n<pre><code>//if (n == 2 || n == 3 || n == 5) {\n// return PRIME_NUMBER;\n//}\nif (n <= 6) {\n return (n == 2 || n == 3 || n == 5) ? PRIME_NUMBER : NOT_PRIME_NUMBER;\n</code></pre>\n<p><strong>Minor: potential mis-matched type and specifier</strong></p>\n<p><code>"%llu"</code> matches a <code>unsigned long long</code>.</p>\n<p><code>"%" PRIu64</code> (from <code><inttypes.h></code>) matches a <code>uint64_t</code>.</p>\n<p>Today, it is common <code>unsigned long long</code> and <code>uint64_t</code> are the same type. But that is not specified. <code>unsigned long long</code> may be wider.</p>\n<p>Alternative:</p>\n<pre><code>int main(void) {\n uint64_t n = 1000000007;\n if (isPrimeNumber(n) == PRIME_NUMBER) {\n // printf("%llu prime.", n);\n printf("%llu prime.", (unsigned long long) n);\n // OR\n printf("%" PRIu64 " prime.", n);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T22:45:00.827",
"Id": "254536",
"ParentId": "254508",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254519",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T00:06:03.170",
"Id": "254508",
"Score": "4",
"Tags": [
"c",
"recursion",
"primes"
],
"Title": "Primality Test Refactoring"
}
|
254508
|
<p>I wrote this to go in my simple static site generator. it takes any plaintext file (but meant for html) and injects the specified file contents and other data at matching tags. This is my first "big" JavaScript project, and most of my knowledge has come from several-year-old posts on StackExchange, YouTube, and Medium, so I cannot guarantee that I have followed modern conventions.</p>
<p>I have included test code, and It should run as-is however it does require a single index.html file in the same dir to test <code>fileInject()</code>.</p>
<pre><code>const fs = require('fs');
var test = `<!-- template:one -->
<!-- template:two -->
<!-- template:three -->
<!-- template:index.html -->
<!-- template:five -->`;
var data = [['one','apple'],['three','orange'],['five','banana']];
// Grab tags from template files. Does not return duplicates.
const getTags = (template) => {
const regex = /\<\!\-\- template:(?<label>(?:(?!\<\!\-\-).)+) \-\-\>/g;
var match, matches = [];
while(match = regex.exec(template)) {
if(!matches.includes(match)) {
matches.push([match.groups.label, match[0]]);
}
}
return matches;
}
// Inject data at matching tags. Tag object format: [['key','value'], ...]
// Silent on failure, but mostly because I do not know how to check if template.replace() succeeds or fails.
const dataInject = (template, tags) => {
for(let tag of tags) {
const regex = new RegExp(`\<\!\-\- template:${tag[0]} \-\-\>`, 'g');
template = template.replace(regex, tag[1]);
}
return template;
}
// Find and inject file contents at matching tags.
// Logs errors on failure.
const fileInject = (template) => {
const tags = getTags(template);
for(let tag of tags) {
try{
fs.accessSync(tag[0]);
const partial = fs.readFileSync(tag[0]).toString();
template = template.replace(tag[1], partial);
} catch(e) { console.log(`error injecting file '${tag[0]}'`) }
}
return template;
}
// Individual tests
//console.log(dataInject(test, data));
//console.log(fileInject(test));
//combined tests. Both work, however (if combined) dataInject() should be called first as fileInject() will finish quicker encounter fewer failures.
//console.log(dataInject(fileInject(test), data));
console.log(fileInject(dataInject(test, data)));
</code></pre>
|
[] |
[
{
"body": "<p>Here's a few pointers to help out:</p>\n<ul>\n<li>I see you're using both let and var in there - be consistent and just choose one.</li>\n<li>You're escaping a lot of regular expression characters that don't need to be escaped - it makes the regex less readable. i.e. <code>/\\<\\!\\-\\- template:(?<label>(?:(?!\\<\\!\\-\\-).)+) \\-\\-\\>/g</code> could be written as <code>/<!-- template:(?<label>(?:(?!<!--).)+) -->/g</code></li>\n<li>Often it's good to name functions as verbs. i.e. just rename dataInject to injectData and fileInject to injectFile, it reads better.</li>\n<li>Right now, if there was an error reading the template file, you'll always get the same message logged: <code>error injecting file '<file name>'</code>. It doesn't matter if node didn't have permission to access it, or if the file did not exist, you won't get any more information besides that log message. What's worse, you don't rethrow any error, so the program will continue trying to run even though the template has issues. I would just take out the try-catch completely, the original error usually has the most useful information to help debug problems.</li>\n<li>I assume this injection logic is meant to be used by a server. With that use case in mind, you don't want to use the sync versions of the file-system functions - it means the server is unable to handle any other request while it's doing a file operation. Instead of <code>fs.readFileSync()</code>, use <code>fs.readFile()</code>, or even better, <code>fs.promises.readFile()</code>.</li>\n<li>The <code>if (!matches.includes(match))</code> line isn't doing anything. matches is an array of arrays while match is a match object, match will never be inside matches.</li>\n<li>Any reason why <code>data</code> is a list of lists and not an object (or a Map)? Why not just have data equal <code>{ one: 'apple', three: 'orange', ... }</code>. If some function needs it in the list-of-list format, it can just call <a href=\"https://developer.mozilla.org/en-us/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"nofollow noreferrer\"><code>Object.entries()</code></a> on it.</li>\n<li>Finally, I just want to warn against re-inventing the wheel. There's plenty of great templating systems already out there (i.e. handlebars.js) that come with plenty of great features and built-in XSS protection. If your codebase only needs templates in one or two places, then I can understand preferring to throw together something simple instead of adding a new dependency, but if you're going to be using these templates a lot, it might be better to use a pre-built solution instead of maintaining your own.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-02T01:35:23.540",
"Id": "255484",
"ParentId": "254509",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T00:45:38.273",
"Id": "254509",
"Score": "0",
"Tags": [
"javascript",
"template"
],
"Title": "Html Templating for a WIP static site generator, written in Javascript"
}
|
254509
|
<p>My code works as intended. <strong>CategoryController</strong> class has <strong>getAllCategories</strong> method, which tells <strong>ContentOrderMap</strong> class to map differently ordered categories to their respective OrderType enum.</p>
<p>The intention is whenever <code>@RequestParam(defaultValue = "DEFAULT") OrderType categoriesOrderType</code> changes from <strong>DEFAULT</strong>, to lets say, <strong>POST_COUNT_DESC</strong>, I would get differently ordered categories in my view.</p>
<p>My concern is if this is an efficient way of dealing with multiple ways of ordering my content. Previously I had a bunch of if statements in my controller and they would take care of getting and assigning information to model based on request param. This didn't seem very scalable since my controller method would get very big and would contain logic, which I think should not be there.</p>
<p>I'm having trouble correctly wording my problem and issues since I am new to this, if anything is not clear enough, I will gladly reword or explain.</p>
<p><strong>Controller:</strong></p>
<pre><code>@Controller
@RequestMapping("/categories")
public class CategoryController {
private CategoryService categoryService;
private ContentOrderMap orderMap;
public CategoryController(CategoryService categoryService, ContentOrderMap orderMap) {
this.categoryService = categoryService;
this.orderMap = orderMap;
}
@GetMapping("/all")
public String getAllCategories(@RequestParam(defaultValue = "0") int pageNumber, Model model, @RequestParam(defaultValue = "DEFAULT") OrderType categoriesOrderType) {
orderMap.mapCategoriesToOrderType(pageNumber);
Page<Category> categories = orderMap.categoriesByOrderType.get(categoriesOrderType);
int pageCount = categoryService.getAllCategories(pageNumber).getTotalPages();
model.addAttribute("orderType", categoriesOrderType);
model.addAttribute("categories", categories.getContent());
model.addAttribute("pageNumber", pageNumber);
model.addAttribute("hasNextPage", categories.hasNext());
model.addAttribute("pageCount", pageCount);
return "categories";
}
}
</code></pre>
<p><strong>ContentOrderMap</strong> class</p>
<pre><code>public Map<OrderType, Page<Category>> categoriesByOrderType = new HashMap<>();
</code></pre>
<pre><code>public void mapCategoriesToOrderType(int pageNumber) {
categoriesByOrderType.put(OrderType.DEFAULT, categoryService.getAllCategories(pageNumber));
categoriesByOrderType.put(OrderType.POST_COUNT_DESC, categoryService.getAllCategoriesByPostCountDesc(pageNumber));
categoriesByOrderType.put(OrderType.POST_COUNT_ASC, categoryService.getAllCategoriesByPostCountAsc(pageNumber));
categoriesByOrderType.put(OrderType.FOLLOWER_COUNT_DESC, categoryService.getAllCategoriesByFollowersCountDesc(pageNumber));
categoriesByOrderType.put(OrderType.FOLLOWER_COUNT_ASC, categoryService.getAllCategoriesByFollowersCountAsc(pageNumber));
categoriesByOrderType.put(OrderType.POST_DATE_DESC, categoryService.getAllCategoriesByNewestPost(pageNumber));
categoriesByOrderType.put(OrderType.POST_DATE_ASC, categoryService.getAllCategoriesByOldestPost(pageNumber));
}
</code></pre>
<p><strong>CategoryService</strong></p>
<p>all of the methods seen above are more or less identical in service class, they only differ in their naming, so I am going to add only one of them for brevity's sake</p>
<pre><code>public Page<Category> getAllCategoriesByPostCountDesc(int pageNumber) {
Pageable pageable = PageRequest.of(pageNumber, 4);
return categoryRepository.findAllOrderByPostCountDesc(pageable);
}
</code></pre>
<p>In case its needed, I add an example of how <strong>categoryRepository</strong> looks</p>
<pre><code>@Query(value = "SELECT c.* FROM category c LEFT JOIN review r ON c.id = r.category_id GROUP BY c.id ORDER BY COUNT(*) DESC",
countQuery = "SELECT COUNT(*) FROM CATEGORY",
nativeQuery = true)
Page<Category> findAllOrderByPostCountDesc(Pageable pageable);
</code></pre>
|
[] |
[
{
"body": "<p>Well, you found a workable solution.</p>\n<p>One thing that strikes out at me is, that you expose the inner structure of your\nContentOrderMap by accessing <code>orderMap.categoriesByOrderType.get(categoriesOrderType)</code> directly.\nThe inner map <code>categoriesByOrderType</code> is an implementation detail, which you should not make\nknown in the public interface. Rather give <code>ContentOrderMap</code> a direct method which returns the page (and while we are at it: change the name, as nobody should care about the class being or containing a map.)</p>\n<p>A problem remains, which is: changes will not be local at one place. When you add a new <code>OrderType</code>,\nyou have to extend the <code>OrderType</code> enum <em>and</em> the <code>ContentOrderMap</code> <em>and</em> the <code>CategoryRepository</code>.</p>\n<p>Frankly, you'll not find a way to solve this problem in a 100% clean way, as it concerns the interface\n(i.e. the REST service), <em>and</em> the database, so if you assemble your actual definition of a type <em>and</em>\nthe data storage effect it has in one place, you will have mixed responsibilities in that place.</p>\n<p>However, if you think this mixing of responsibilities is bearable (everything is a tradeoff in software\nengineering ;-)) you might think about harnessing the power of the java enum, which can implement an\ninterface. Something along the lines of:</p>\n<pre><code>public enum OrderType {\n DEFAULT("select c.* from whatever order by whatever"),\n POST_COUNT_DESC("select c.* from whatever order by something else"),\n ....;\n \n private final String query;\n \n private OrderType(String query) {\n this.query = query;\n }\n \n public String getQuery() {\n return query;\n }\n}\n</code></pre>\n<p>This way, you only have to extend the enum, pass the constant on into your repository, and then do\nwhatever you need to do with the contained query.</p>\n<p>Another alternative is, using your container. I'm not using spring, but there must be something along\nthe lines of a CDI <code>Instance<></code>, which gives you a list of all implementations of a given interface.</p>\n<p>In a CDI world, you could declare an interface:</p>\n<pre><code>public interface OrderHandler {\n public boolean handlesType(String orderType); // no enum, in the end REST sends you a string anyway\n public Page<Category> getResult(Pageable pageable);\n}\n</code></pre>\n<p>Then write your different implementations of these interfaces, and get all of them via:</p>\n<pre><code>@Inject\nInstance<OrderHandler> orderHandlers;\n\n...\n\nfor (OrderHandler orderHandler : orderHandlers) {\n if (orderHandler.handlesType(myParameter)) {\n orderHandler.getResult(...);\n }\n}\n</code></pre>\n<p>As I said, there must be something equivalent in spring.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T08:06:00.660",
"Id": "254516",
"ParentId": "254510",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T02:10:01.020",
"Id": "254510",
"Score": "1",
"Tags": [
"java",
"mvc",
"spring",
"controller"
],
"Title": "An efficient way to order content in controller [Spring Boot]"
}
|
254510
|
<p>This defines <code>count-pairs</code> which</p>
<ul>
<li>takes a collection of integers</li>
<li>returns the number of pairs of integers that are equal to each other.</li>
</ul>
<p>If the input collection has these integers ...</p>
<pre><code>1 2 0 2 1 3 2
</code></pre>
<p>... then <code>count-pairs</code> returns 2 because</p>
<ol>
<li>one pair can be made with the 1's</li>
<li>a second pair can be made with the 2's</li>
<li>The leftover unpaired integers do not affect the answer.</li>
</ol>
<pre><code>(defun make-pair (table i)
(setf
;; increment pair count:
(gethash 'pairs table) (1+ (gethash 'pairs table 0))
;; make first half of the new pair unavailable:
(gethash i table) nil)
table)
(defun keep-first-half-of-pair (table i)
(setf (gethash i table) t)
table)
(defun first-half-available-p (table i)
(gethash i table))
(defun consider-one (table i)
(if (first-half-available-p table i)
(make-pair table i)
(keep-first-half-of-pair table i)))
(defun count-pairs (integers)
(let ((table (reduce #'consider-one
integers
:initial-value
(make-hash-table))))
(gethash 'pairs table 0)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; boilerplate for running as a hacker rank submission
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(read-line) ;; we don't need n
(defvar integers
(read-from-string
(concatenate 'string
"(" (read-line) ")")))
(format t "~a~%" (count-pairs integers))
</code></pre>
<p>Some questions I have:</p>
<ol>
<li>What changes would make this more idiomatic?</li>
<li>Is there an alternative for <code>setf</code> that returns the modified container instead of the multiple values returned by the storing form for the last altered place? (See how I really want the container as the result of <code>make-pair</code> and <code>keep-first-half-available-p</code> ...)</li>
<li>Should I stick with the <code>-p</code> naming convention for predicates? It seems ending with a <code>?</code> is possible and looks more readable to me.</li>
<li>I guess Emacs knows <code>if</code> is a macro and is indenting it that way?</li>
<li>If there is an entirely different and better way to solve in Common Lisp, please do let me know.</li>
</ol>
<p>Thanks in advance!</p>
|
[] |
[
{
"body": "<p>Stylistic consideration: a global variable is usually written with double "*" (earmuffs), so the global variable <code>integers</code> should be written as <code>*integers*</code>.</p>\n<p>Now, for your questions.</p>\n<ol>\n<li>I think your code is not particularly unidiomatic, just a little bit complex to read. What I find more unusual is your use of <code>reduce</code> to iterate over a list. In fact reduce is normally called with a binary function that takes pairs of elements of the <em>same</em> type, while you use it as a kind of iterator. In your case I would use a more classical iterator, like <code>mapc</code>, or, even better for me, <code>loop</code>. Another thing that I don't like is the use of the table to store also the global counter that will be used as result.</li>\n</ol>\n<p>Summing all these considerations, I will rewrite your solution using\nlocal helper functions, to reduce the complexity and simplify the\nuse of the parameters, and substitute the iterator while reducing by\none the number of auxiliary functions.</p>\n<pre><code> (defun count-pairs (integers)\n (let ((pairs 0)\n (table (make-hash-table)))\n (flet ((make-pair (i)\n (incf pairs)\n (setf (gethash i table) nil))\n (keep-first-half-of-pair (i)\n (setf (gethash i table) t))\n (first-half-available-p (i)\n (gethash i table)))\n (loop for i in integers\n if (first-half-available-p i)\n do (make-pair i)\n else\n do (keep-first-half-of-pair i)))\n pairs))\n</code></pre>\n<ol start=\"2\">\n<li><p>If you need to return the table there is no other possibility. In the above solution this is not necessary, since <code>table</code> is not returned by the functions.</p>\n</li>\n<li><p>It's just a convention that you can follow or not. If you want to stick to Common Lisp common style, it is better to use the <code>-p</code> convention.</p>\n</li>\n<li><p>Yes.</p>\n</li>\n</ol>\n<p>Finally, for the fifth point, I would prefer a more concise solution, that counts all the elements, and only at the end counts all the pairs, in this way:</p>\n<pre><code>(defun count-pairs (integers)\n "returns the numbers the pairs of the list integers"\n (let ((table (make-hash-table)))\n (loop for i in integers\n do (incf (gethash i table 0)))\n (loop for v being the hash-value of table\n sum (truncate v 2))))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T18:31:07.833",
"Id": "501964",
"Score": "0",
"body": "Thanks! I learned a lot from your suggestions. I think I should also get a better understanding of when to use `loop` and when to reach for something else. Is there a community rule of thumb? `loop` definitely was the way to go here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T09:35:55.967",
"Id": "501999",
"Score": "2",
"body": "The `loop` construct is loved by some people and hated by others (mostly for its syntax), but in general it is widely used and accepted. See for instance [this chapter](http://www.gigamonkeys.com/book/loop-for-black-belts.html) in [Practical Common Lisp](http://www.gigamonkeys.com/book/)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T08:51:23.820",
"Id": "254518",
"ParentId": "254513",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254518",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T03:16:32.667",
"Id": "254513",
"Score": "4",
"Tags": [
"common-lisp"
],
"Title": "count pairs of matching integers in a collection in Common Lisp"
}
|
254513
|
<p>I had like to get some feedback about my Thread Safe Python Client-Server example.
Is it really thead-safe?
Do you see any dead-locks or other thread-safe problems?
<a href="https://github.com/icarpis/PyThreadSafeClientServer" rel="nofollow noreferrer">https://github.com/icarpis/PyThreadSafeClientServer</a></p>
<pre><code># Server
import socket
import sys
import threading
import select
class ServerConnection():
def __clientThread(self, callback, connection, client_address):
try:
inputs = [ connection ]
outputs = [ ]
timeout = 1
while self.startClient:
readable, writable, exceptional = select.select(inputs, outputs, inputs, timeout)
if not ((readable or writable or exceptional)):
if (not self.startClient):
break
continue
if (not self.startClient):
break
for sock in readable:
data = sock.recv(16)
if (data):
callback(client_address, data)
except Exception as e:
print ('Server: ', e)
finally:
print("Exiting Client Thread")
def __listenerThread(self, callback, numOfAllowedConnections):
try:
self.sock.settimeout(0)
self.sock.setblocking(0)
self.sock.listen(numOfAllowedConnections)
print ('Server: Waiting for a connection...')
read_list = [self.sock]
timeout = 1
while self.startListener:
readable, writable, exceptional = select.select(read_list, [], [], timeout)
if not ((readable or writable or exceptional)):
if (not self.startListener):
break
continue
connection = None
connection, client_address = self.sock.accept()
connection.setblocking(0)
self.mutex.acquire()
if (self.startListener and connection):
self.connections.append(connection)
print ('\nServer: client connected:', client_address)
t = threading.Thread( target=self.__clientThread, args=(callback, connection, client_address) )
self._connectionThreads.append(t)
t.start()
self.mutex.release()
except Exception as e:
print (e)
self.Close()
finally:
print("Exiting Listener Thread")
def __init__(self):
self._listenerThread = None
self.connections = []
self._connectionThreads = []
self.mutex = threading.Lock()
self.sock = None
self.callback = None
self.numOfAllowedConnections = None
def Open(self, ip, port, callback, numOfAllowedConnections):
try:
self.mutex.acquire()
if (self.sock):
return False
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.callback = callback
self.numOfAllowedConnections = numOfAllowedConnections
server_address = (ip, port)
self.sock.bind(server_address)
print ('Creating socket on %s port %s' % self.sock.getsockname())
self.startListener = True
self.startClient = True
self._listenerThread = threading.Thread( target=self.__listenerThread, args=(self.callback, self.numOfAllowedConnections, ) )
self._listenerThread.start()
return True
finally:
self.mutex.release()
def Close(self):
self.mutex.acquire()
try:
if (self.startListener == False):
return False
self.startListener = False
if (self._listenerThread):
try:
self._listenerThread.join(3)
except Exception as e:
pass
self.startClient = False
try:
for connection in self.connections:
connection.close()
except Exception as e:
pass
self.connections = []
for t in self._connectionThreads:
try:
t.join(3)
except Exception as e:
pass
self._connectionThreads = []
finally:
self.mutex.release()
return True
def SendDataAll(self, data):
try:
self.mutex.acquire()
print ('Server: sending "%s"' % data)
for connection in self.connections:
connection.sendall(data)
return True
except Exception as e:
print(e)
return False
finally:
self.mutex.release()
def SendData(self, con, data):
try:
self.mutex.acquire()
if con in self.connections:
print (con.getpeername(), 'Server: sending "%s"' % data)
con.sendall(data)
return True
except Exception as e:
print(e)
return False
finally:
self.mutex.release()
def GetNumOfConnections(self):
try:
self.mutex.acquire()
numOfCon = len(self.connections)
return numOfCon
finally:
self.mutex.release()
def GetConnection(self, index):
try:
conn = None
self.mutex.acquire()
conn = self.connections[index]
return conn
except IndexError:
return None
finally:
self.mutex.release()
def cb(client_address, data):
print (client_address, 'server received "%s"' % data)
pass
def main():
import sys
serverConnection = ServerConnection()
serverConnection.Open('localhost', 5000, cb, 3)
print("\nPress Enter to continue...\n")
sys.stdin.flush()
sys.stdin.read(1)
serverConnection.SendDataAll(bytes("Itay3", encoding='utf8'))
numOfCon = serverConnection.GetNumOfConnections()
print ("\nConnections: ", numOfCon)
con = None
if (numOfCon > 0):
con = serverConnection.GetConnection(0)
if (con):
serverConnection.SendData(con, bytes("Itay4", encoding='utf8'))
print("\nPress Enter to Exit...\n")
sys.stdin.flush()
sys.stdin.read(1)
serverConnection.Close()
pass
if __name__ == "__main__":
main()
# Client
import socket
import sys
import threading
import select
class ClientConnection():
def __init__(self, ip, port, callback):
self.mutex = threading.Lock()
self.sock = None
self.ip = ip
self.port = port
self.callback = callback
self.clientThread = None
self.connect = False
def __clientThread(self):
try:
inputs = [ self.sock ]
outputs = [ ]
timeout = 1
while self.connect:
readable, writable, exceptional = select.select(inputs, outputs, inputs, timeout)
if not ((readable or writable or exceptional)):
if (not self.connect):
break
continue
if (not self.connect):
break
for sock in readable:
data = sock.recv(16)
if (data):
self.callback(self.sock.getsockname(), data)
except Exception as e:
print (self.sock.getsockname()[1], e)
finally:
print(self.sock.getsockname()[1], "Exiting Client Thread")
def Connect(self):
try:
self.mutex.acquire()
if (self.connect):
return False
self.connect = True
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (self.ip, self.port)
print ('Client: connecting to %s port %s' % server_address)
self.sock.connect(server_address)
#self.sock.setblocking(0)
t = threading.Thread( target=self.__clientThread)
self.clientThread = t
self.clientThread.start()
return True
except Exception as e:
print (e)
return False
finally:
self.mutex.release()
def Disconnect(self):
try:
self.mutex.acquire()
if (not self.connect):
return False
self.connect = False
if (self.clientThread):
try:
self.clientThread.join(3)
except Exception as e:
pass
if (self.sock):
self.sock.close()
return True
finally:
self.mutex.release()
def SendData(self, data):
try:
self.mutex.acquire()
if (not self.connect):
return False
if (self.sock):
print (self.sock.getsockname(), 'Client: sending "%s"' % data)
self.sock.sendall(data)
return True
except Exception as e:
print(e)
return False
finally:
self.mutex.release()
def cb1(address, data):
print (address, 'Client1: received "%s"' % data)
pass
def cb2(address, data):
print (address, 'Client2: received "%s"' % data)
pass
def main():
client1 = ClientConnection('localhost', 5000, cb1)
if (client1.Connect()):
client1.SendData(bytes("Itay1", encoding='utf8'))
if (client1.Connect()):
client1.SendData(bytes("Itay1", encoding='utf8'))
client2 = ClientConnection('localhost', 5000, cb2)
if (client2.Connect()):
client2.SendData(bytes("Itay2", encoding='utf8'))
print ("\nPress Enter key to exit...\n")
sys.stdin.flush()
sys.stdin.read(1)
client1.Disconnect()
client2.Disconnect()
pass
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T08:41:54.107",
"Id": "254517",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"thread-safety",
"server",
"client"
],
"Title": "Thread Safe Python Client Server Service"
}
|
254517
|
<p>I am looking for feedback on my code's overall structure and design. I made a few concessions in reusability for the sake of not overcomplicating things (static/const public variables in the Game1 class) but think it's pretty usable otherwise. I would like to make this room generator easy to use and adjust for future projects, and would love any feedback on how I can better do so. <a href="https://github.com/Kakapio/room-generator" rel="nofollow noreferrer">Here is my code on GitHub.</a></p>
<p>Game1.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace RoomGenerator
{
public class Game1 : Game
{
public enum TileType
{
Floor,
Wall
}
//Variables that are accessed by the eater class.
public static TileType[,] TileMap { get; set; }
public const int MapSize = 100; //The square dimensions of the tile map in terms of tiles.
public const int MaxFloors = 1200;
public static int CurrentFloors { get; set; } = MaxFloors;
private GraphicsDeviceManager graphics;
private SpriteBatch spriteBatch;
private List<Eater> eaters;
private List<Eater> eatersAccumulator; //Used to ensure an enumeration operation error does not occur.
private Texture2D floor;
private Texture2D wall;
private const int TileSize = 8; //The square dimensions of each tile sprite.
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
TileMap = new TileType[MapSize, MapSize];
eaters = new List<Eater>();
eatersAccumulator = new List<Eater>();
}
protected override void Initialize()
{
base.Initialize();
//Resolution of window.
graphics.PreferredBackBufferWidth = 1000;
graphics.PreferredBackBufferHeight = 1000;
graphics.ApplyChanges();
Reset();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
floor = Content.Load<Texture2D>("Ground");
wall = Content.Load<Texture2D>("Wall");
}
protected override void Update(GameTime gameTime)
{
base.Update(gameTime);
//Handle input
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (Keyboard.GetState().IsKeyDown(Keys.R))
Reset();
foreach (var eater in eaters)
{
eater.Move();
}
foreach (var eater in eatersAccumulator)
{
eaters.Add(eater);
}
eatersAccumulator.Clear();
Console.WriteLine($"Number floors created: {MaxFloors - CurrentFloors}, " +
$"Number Eaters: {eaters.Count}");
int trueCount = 0;
for (int i = 0; i < TileMap.GetLength(0); i++)
{
for (int j = 0; j < TileMap.GetLength(1); j++)
{
if (TileMap[i, j] == TileType.Floor)
trueCount++;
}
}
Console.WriteLine($"True Count: {trueCount}");
}
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
GraphicsDevice.Clear(Color.SkyBlue);
//Rendering to a RenderTarget and then later passing it to the back buffer.
RenderTarget2D target = new RenderTarget2D(GraphicsDevice, MapSize * TileSize, MapSize * TileSize);
GraphicsDevice.SetRenderTarget(target);
spriteBatch.Begin();
//Draw each tile in the proper position.
for (int i = 0; i < TileMap.GetLength(0); i++)
{
for (int j = 0; j < TileMap.GetLength(1); j++)
{
switch (TileMap[i, j])
{
case TileType.Floor:
spriteBatch.Draw(floor,
new Rectangle(i * TileSize, j * TileSize, TileSize, TileSize),
Color.White);
break;
case TileType.Wall:
spriteBatch.Draw(wall,
new Rectangle(i * TileSize, j * TileSize, TileSize, TileSize),
Color.White);
break;
default:
throw new InvalidEnumArgumentException("Given tile type is not supported.");
}
}
}
spriteBatch.End();
//Render target to back buffer.
GraphicsDevice.SetRenderTarget(null);
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp);
spriteBatch.Draw(target, new Rectangle(0, 0, graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight), Color.White);
spriteBatch.End();
}
private void Reset()
{
//Set all tiles back to wall.
for (int i = 0; i < TileMap.GetLength(0); i++)
{
for (int j = 0; j < TileMap.GetLength(1); j++)
{
TileMap[i, j] = TileType.Wall;
}
}
CurrentFloors = MaxFloors;
eaters.Clear();
eaters.Add(new Eater(new Vector2(0, 0),
new Vector2(MapSize / 2, MapSize / 2)));
eaters[0].GenerateDirection();
eaters[0].AddEater += AddEater;
}
/// <summary>
/// Triggered by Eaters to add more eaters to the generator. Allows for generation of separate corridors.
/// </summary>
private void AddEater(Vector2 startPosition)
{
Eater eater = new Eater(new Vector2(0, 0), startPosition);
eater.GenerateDirection();
eater.AddEater += AddEater; //Subscribe new eater to this method.
eatersAccumulator.Add(eater);
}
}
}
</code></pre>
<p>Eater.cs</p>
<pre><code>using System;
using Microsoft.Xna.Framework;
namespace RoomGenerator
{
public class Eater
{
public Vector2 Direction { get; private set; }
public Vector2 Position { get; private set; }
public event Action<Vector2> AddEater;
private Random random;
public Eater(Vector2 direction, Vector2 position)
{
Direction = direction;
Position = position;
random = new Random();
}
/// <summary>
/// Move the Eater in its Direction by one step, remove whatever wall is in the way.
/// </summary>
public void Move()
{
var newPos = Position + Direction;
if (Game1.CurrentFloors <= 0)
return;
//Invalid direction, change direction and return.
if (newPos.X < 0 || newPos.Y < 0 || newPos.X > Game1.MapSize - 1 || newPos.Y > Game1.MapSize - 1)
{
GenerateDirection();
return;
}
Position = newPos;
if (Game1.TileMap[(int) Position.X, (int) Position.Y] != Game1.TileType.Floor)
{
Game1.TileMap[(int) Position.X, (int) Position.Y] = Game1.TileType.Floor;
Game1.CurrentFloors--;
}
else
{
GenerateDirection();
}
int genNewEater = random.Next(400);
if (genNewEater == 0) //10% chance of adding new eater
{
AddEater?.Invoke(Position);
}
GenerateDirection();
}
/// <summary>
/// Generate a new direction for the eater.
/// </summary>
/// <exception cref="ArgumentException"></exception>
public void GenerateDirection()
{
Random rand = new Random();
int dir = rand.Next(4);
switch (dir)
{
//Left
case 0:
Direction = new Vector2(-1, 0);
break;
//Up
case 1:
Direction = new Vector2(0, 1);
break;
//Right
case 2:
Direction = new Vector2(1, 0);
break;
//Down
case 3:
Direction = new Vector2(0, -1);
break;
default:
throw new ArgumentException("Invalid value generated for new direction.");
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T11:22:00.467",
"Id": "501951",
"Score": "3",
"body": "Please tell us more about the purpose of the code. Does it function well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T22:07:38.903",
"Id": "501975",
"Score": "0",
"body": "@Mast Yes, it does its job well. It is made to generate random rooms for usage in games. It does so by generating an Eater to remove tiles by moving in random directions, which can occasionally spawn new Eaters."
}
] |
[
{
"body": "<p>Top smells of your code are</p>\n<ul>\n<li>Comments. Names of classes, functions, variables should tell why it exists and what it does. If you want to write a comment, then your code is not self-descriptive and should be refactored.</li>\n<li>Too big functions. 10 lines of code is a pretty big function. 5-6 is ok. You have functions 30-40 lines long. That also creates inconsistent level of abstraction in your functions.</li>\n<li>Violation of <em>Tell don't ask</em> principle - you ask data from objects to perform some logic instead of asking objects to do what you want. Check how you use <code>Game</code> object in the <code>Eater</code> class.</li>\n<li>Lot of magic values which have meaning and should be named properly. Check direction vectors, initial position, window size, etc.</li>\n</ul>\n<p>I'm not going to refactor everything. But I'll show you idea. Let's take a look at your <code>Game1</code> class. Of course it should not be named <code>Game1</code>. Name it <code>CaveEatersGame</code> or whatever. Here is self-descriptive game loop:</p>\n<pre><code>protected override void Update(GameTime gameTime)\n{\n base.Update(gameTime);\n\n if (ExitRequested)\n Exit();\n\n if (RestartRequested)\n RestartGame();\n\n MoveEaters();\n SpawnNewEaters();\n}\n</code></pre>\n<p>That's easy to achieve with small propertis and methods:</p>\n<pre><code>private void MoveEaters()\n{\n foreach (var eater in eaters)\n {\n if (AllWallsGone) // Check condition in game loop, not in each eater\n EndGame(); // Whatever it means\n\n eater.TryMove(); // Eater does not always move\n }\n}\n\nprivate void SpawnNewEaters()\n{\n // No events or additional accumulators required\n var newEaters = eaters.Where(Eater.IsLuckyToHaveChild).Select(Eater.CreateChild);\n eaters.AddRange(newEaters);\n}\n</code></pre>\n<p>You can even pass direction to eater and simplify movement to</p>\n<pre><code>public void TryMove(Vector2 direction)\n{\n var newPosition = Position + direction;\n if (!game.IsAvailableToMove(newPosition)) // move this logic to game\n return;\n\n MoveTo(newPosition);\n}\n</code></pre>\n<p>Maybe you don't need eater class at all. Eventually that is just a vector. Especially if you'll move direction generation to separate class, making it focused on one thing and reusable:</p>\n<pre><code>public class RandomDirectionGenerator : IDirectionGenerator\n{\n private readonly Vector2 up = new Vector2(0, 1);\n private readonly Vector2 left = new Vector2(-1, 0);\n private readonly Vector2 down = new Vector2(0, -1);\n private readonly Vector2 right = new Vector2(1, 0);\n private readonly Random random = new Random(); // inject for unit-testing\n\n public Vector2 GetNext() =>\n random.Next(4) switch\n {\n 0 => left,\n 1 => up,\n 2 => right,\n _ => down\n };\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T06:43:20.853",
"Id": "502179",
"Score": "0",
"body": "Wow Sergey, that's amazing! Thanks so much for the extensive feedback. It's all really helpful and I'll be sure to integrate it. I made a lot of decisions based on the assumption that I wouldn't be touching the code again, so I wrote it a bit messily to make it easier to work. Thank you again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T10:24:28.933",
"Id": "502504",
"Score": "0",
"body": "Sergey, I made many of the modifications you suggested. I had some trouble with the Linq implementation for SpawnNewEaters but I integrated most of your feedback. I'd appreciate it if you could take a quick look! https://github.com/Kakapio/room-generator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T13:00:18.753",
"Id": "502517",
"Score": "0",
"body": "@Ovicior for cave generation it will be totally fine to generate eaters in the game class. Just define a function that accepts eater and returns boolean if new eater should be generated (something like `eater => 0 == random.Next(chance)`) and function which creates new eater from detail of existing (something like `eater => new Eater(eater.Position)`)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T02:49:14.780",
"Id": "254578",
"ParentId": "254520",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T10:45:13.130",
"Id": "254520",
"Score": "0",
"Tags": [
"c#",
"game",
"random"
],
"Title": "Random Cave Generator Design Feedback"
}
|
254520
|
<p>This currently runs with 1400+ sockets and manages data correctly and in the manner the application requires. I do have an issue with the <code>HandleData</code> method where the receive channel stacks an excess of messages. They eventually all get processed the channel rarely exceeds 250 items.</p>
<p>Besides the obvious of using an off the shelf socket class, I have a few questions about my implementation.</p>
<ul>
<li>How can I speed up the processing of the received channel?</li>
<li>Are there any glaring issues with the code (code smells) or potential improvements?</li>
<li>Is the <code>async/await task</code> implemented correctly?</li>
<li>Would it be better to use a <code>BlockingCollection</code> instead of <code>Channel</code> for the <code>_receive</code> messages?</li>
</ul>
<p>Logger:</p>
<pre><code>using Serilog;
public static class Logger
{
public static ILogger Create(string name)
{
return Log.Logger.ForContext("SourceContext", name);
}
}
</code></pre>
<p>SocketOptions:</p>
<pre><code>using System;
public class SocketOptions
{
public int ReceiveBufferSize { get; set; } = 1024;
public int SendBufferSize { get; set; } = 1024;
public bool AutoReconnect { get; set; } = false;
public TimeSpan AutoReconnectDelay { get; set; } = TimeSpan.FromMilliseconds(500);
public int AutoReconnectAttempts { get; set; } = 10;
}
</code></pre>
<p>ISocket:</p>
<pre><code>using System;
using System.Threading.Tasks;
public interface ISocket : IDisposable
{
void Add(ISocketListener listener);
Task CloseAsync();
Task<bool> ConnectAsync();
void Remove(ISocketListener listener);
void Send(string data);
}
</code></pre>
<p>ISocketListener:</p>
<pre><code>using System;
public interface ISocketListener
{
void OnConnected(Socket socket);
void OnData(dynamic data);
void OnDisconnected(Socket socket);
void OnError(Socket socket, Exception e);
}
</code></pre>
<p>Socket: (Updated with aepot suggestions)</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Core.Utils;
using Newtonsoft.Json;
using Serilog;
public class Socket : ISocket
{
private readonly string _endpoint;
private readonly IList<ISocketListener> _listeners =
new List<ISocketListener>();
private readonly ILogger _logger =
Logger.Create(nameof(Socket));
private readonly SocketOptions _options;
private readonly Channel<string> _receive =
Channel.CreateUnbounded<string>(
new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = true
});
private readonly Channel<string> _send =
Channel.CreateUnbounded<string>(
new UnboundedChannelOptions
{
SingleReader = true,
SingleWriter = false
});
private CancellationTokenSource _stopping;
private int _count;
private ClientWebSocket _socket;
private bool _disposed;
public Socket(string endpoint, SocketOptions options)
{
_endpoint = endpoint;
_options = options;
}
public bool IsConnected => _socket?.State == WebSocketState.Open;
private readonly AutoResetEvent _wait = new (true);
public async Task<bool> ConnectAsync()
{
_wait.WaitOne();
try
{
if (IsConnected)
{
return IsConnected;
}
if (_socket?.State != WebSocketState.None)
{
_socket = new ClientWebSocket
{
Options =
{
KeepAliveInterval = Timeout.InfiniteTimeSpan
}
};
}
_stopping ??= new CancellationTokenSource();
var token = _stopping.Token;
await _socket.ConnectAsync(new Uri(_endpoint), token);
if (IsConnected)
{
_ = RunTasks(token);
HandleConnected();
}
}
catch (OperationCanceledException)
{
/* Ignore */
}
catch (Exception e)
{
_logger.Error(e, $"Error connecting: {_endpoint}");
HandleError(e);
}
finally
{
_wait.Set();
}
return IsConnected;
}
public async Task CloseAsync()
{
_logger.Information($"Closed: {_endpoint}");
try
{
if (IsConnected)
{
await _socket
.CloseAsync(
WebSocketCloseStatus.NormalClosure,
string.Empty,
CancellationToken.None)
.ConfigureAwait(false);
}
_stopping?.Cancel();
}
finally
{
_socket.Dispose();
_stopping?.Dispose();
_stopping = null;
}
HandleDisconnected();
}
public void Send(string data)
{
_send.Writer.TryWrite(data);
}
public void Add(ISocketListener listener)
{
lock (_listeners)
{
if (!_listeners.Contains(listener))
{
_listeners.Add(listener);
}
}
}
public void Remove(ISocketListener listener)
{
lock (_listeners)
{
if (_listeners.Contains(listener))
{
_listeners.Remove(listener);
}
}
}
public void Dispose()
{
Dispose(_disposed = true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
try
{
_stopping?.Cancel();
}
catch
{
/* Ignore */
}
_stopping?.Dispose();
_socket?.Dispose();
_wait.Dispose();
}
}
private void HandleConnected()
{
ISocketListener[] listeners;
lock (_listeners)
{
listeners = _listeners.ToArray();
}
foreach (var listener in listeners)
{
listener.OnConnected(this);
}
}
private async Task HandleDataAsync(string item)
{
await Task
.Run(() =>
{
var data = JsonConvert
.DeserializeObject<dynamic>(item);
ISocketListener[] listeners;
lock (_listeners)
{
listeners = _listeners.ToArray();
}
foreach (var listener in listeners)
{
try
{
listener.OnData(data);
}
catch (Exception e)
{
_logger.Error(e, "Error invoking listener");
}
}
})
.ConfigureAwait(false);
}
private void HandleDisconnected()
{
ISocketListener[] listeners;
lock (_listeners)
{
listeners = _listeners.ToArray();
}
foreach (var listener in listeners)
{
listener.OnDisconnected(this);
}
}
private void HandleError(Exception e)
{
ISocketListener[] listeners;
lock (_listeners)
{
listeners = _listeners.ToArray();
}
foreach (var listener in listeners)
{
listener.OnError(this, e);
}
}
private async Task ProcessDataAsync(CancellationToken token)
{
try
{
var reader = _receive.Reader;
while (await reader.WaitToReadAsync(token).ConfigureAwait(false))
{
if (reader.TryRead(out var item))
{
try
{
await HandleDataAsync(item);
}
catch (Exception e)
{
_logger.Error(e, "Error handling data");
HandleError(e);
}
finally
{
Interlocked.Decrement(ref _count);
}
}
}
}
catch (OperationCanceledException)
{
/* Ignore */
}
}
private async Task ReceiveAsync(CancellationToken token)
{
try
{
await using var stream = new MemoryStream();
var buffer = new Memory<byte>(new byte[_options.ReceiveBufferSize]);
var read = 0;
while (!token.IsCancellationRequested)
{
if (!IsConnected)
{
break;
}
stream.Seek(0, SeekOrigin.Begin);
ValueWebSocketReceiveResult result;
do
{
result = await _socket
.ReceiveAsync(buffer, token)
.ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
break;
}
if (buffer.Length > 0)
{
await stream
.WriteAsync(buffer.Slice(0, result.Count), token)
.ConfigureAwait(false);
read += result.Count;
}
} while (!result.EndOfMessage);
var data = Encoding.UTF8.GetString(stream.GetBuffer(), 0, read);
read = 0;
Interlocked.Increment(ref _count);
if (_count > 250)
{
_logger.Warning($"Channel: {_count} items");
}
_receive.Writer.TryWrite(data);
}
}
catch (OperationCanceledException)
{
/* Ignore */
}
catch (Exception e)
{
_logger.Error(e, "Error receiving data");
HandleError(e);
}
finally
{
await CloseAsync().ConfigureAwait(false);
if (_options.AutoReconnect)
{
await ReconnectAsync(token).ConfigureAwait(false);
}
}
}
private async Task ProcessSendAsync(CancellationToken token)
{
try
{
var reader = _send.Reader;
while (await reader.WaitToReadAsync(token).ConfigureAwait(false))
{
if (_socket.State != WebSocketState.Open)
{
break;
}
if (reader.TryRead(out var item))
{
var data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(item));
await _socket
.SendAsync(data, WebSocketMessageType.Text, true, token)
.ConfigureAwait(false);
}
}
}
catch (OperationCanceledException)
{
/* Ignore */
}
catch (Exception e)
{
_logger.Error(e, "Error sending data");
HandleError(e);
}
}
private async Task ReconnectAsync(CancellationToken token)
{
try
{
var count = 0;
while (!_disposed)
{
if (_options.AutoReconnectAttempts <= 0 ||
_options.AutoReconnectAttempts <= count)
{
_logger.Warning("Reconnect attempts exceeded");
break;
}
_logger.Information($"Attempting reconnect: {_endpoint}");
if (await ConnectAsync().ConfigureAwait(false))
{
break;
}
count++;
await Task
.Delay(_options.AutoReconnectDelay, token)
.ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
/* Ignore */
}
}
private async Task RunTasks(CancellationToken token)
{
await Task
.WhenAll(
ReceiveAsync(token),
ProcessSendAsync(token),
ProcessDataAsync(token)
)
.ConfigureAwait(false);
}
}
</code></pre>
<p>SocketListener Implementation:</p>
<pre><code>public class CoinbaseCandleListener : ISocketListener
{
private readonly ILogger _logger =
Logger.Create(nameof(Coinbase));
private readonly List<CandleConsolidator> _consolidators =
new ();
public CoinbaseCandleListener(Symbol symbol)
{
Symbol = symbol;
}
public Symbol Symbol { get; }
public void OnConnected(Socket socket)
{
_logger.Information($"Connected: {Symbol.Name}");
Subscribe(socket);
}
public void OnData(dynamic data)
{
if (data.type != "match" ||
data.type != "last_match")
{
return;
}
var time = (DateTime) data.time;
var price = (double) data.price;
var size = (double) data.size;
foreach (var consolidator in _consolidators)
{
consolidator.Process(time, price, size);
}
}
public void OnDisconnected(Socket socket)
{
_logger.Information($"Disconnected: {Symbol.Name}");
}
public void OnError(Socket socket, Exception e)
{
_logger.Error(e, $"Error: {Symbol.Name}");
}
public void Add(CandleConsolidator consolidator)
{
_consolidators.Add(consolidator);
}
private void Subscribe(Socket socket)
{
var name = $"{Symbol.Base}-{Symbol.Quote}";
var data = new
{
type = "subscribe",
product_ids = new[]
{
name
},
channels = new[]
{
"matches"
}
};
socket.Send(
JsonConvert.SerializeObject(data));
}
private void Unsubscribe(Socket socket)
{
var name = $"{Symbol.Base}-{Symbol.Quote}";
var data = new
{
type = "unsubscribe",
product_ids = new[]
{
name
},
channels = new[]
{
"matches"
}
};
socket.Send(
JsonConvert.SerializeObject(data));
}
}
</code></pre>
<p>CandleConsolidator:</p>
<pre><code>public class CandleConsolidator : IDisposable
{
private readonly ILogger _logger =
Logger.Create(nameof(CandleConsolidator));
private readonly Action<Candle> _action;
private readonly IntervalType _interval;
private readonly SemaphoreQueue _sync = new(1, 1);
public CandleConsolidator(IntervalType interval, Action<Candle> action)
{
_interval = interval;
_action = action;
}
public Candle Current { get; set; }
public void Dispose()
{
_sync?.Dispose();
}
public async void Process(DateTime time, double price, double size)
{
var open = time
.RoundTo(_interval)
.Subtract(_interval.ToTimeSpan());
Candle updated;
try
{
await _sync.WaitAsync();
if (Current?.OpenTime != open)
{
if (Current != null)
{
var closed = Current;
closed.IsClosed = true;
// TODO: Move this outside of _sync
_action.Invoke(closed);
}
Current = new Candle
{
OpenTime = open,
Open = price,
High = price,
Low = price,
Close = price,
Volume = size
};
}
else
{
Current.High = Math.Max(Current.High, price);
Current.Low = Math.Min(Current.Low, price);
Current.Close = price;
Current.Volume += size;
}
updated = Current;
}
finally
{
_sync.Release();
}
_action.Invoke(updated);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T09:58:39.317",
"Id": "502002",
"Score": "1",
"body": "I've looked at the continuations mixed with `async` and I do agree and have changed that. The socket does implement `IDisposable` which is on the `ISocket` interface. I've made the `HandleData` `async` and awaitable now as if one exception was thrown on the `ISocketListener` all other listeners would not receive data - fixed with try catch. This is using the producer consumer pattern, the `Socket` is the producer and the `ISocketListener` is the consumer, I'm just not using RX. `Span<T>` and `Memory<T>` are new to me, looking into them now. Thanks for the feedback, it's much appreciated!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T21:49:44.270",
"Id": "502044",
"Score": "0",
"body": "`async Task SomeMethod() { await SomeInnerMethod(); }` can be optimized as `Task SomeMethod() { return SomeInnerMethod(); }`. It eliminates redundant State Machine which is somewhat good for performance. The optimization is applicable 1) only with single `await` per method, 2) only if it's the last statement, 3) `await` is not inside `try-catch` or `using` block. _Please don't edit the code anymore because someone probably is writing review at the moment. Review for not actual code is not helpful._ I removed my previous comment as it's not actual."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T09:29:50.417",
"Id": "502320",
"Score": "0",
"body": "@AdamH Please amend your question and include everything which is not built-in, like `ISocket`, `ISocketListener`, `SocketOptions`, etc. Please also amend your existing code to be able compile it. For example, this is not a valid C# code `private readonly AutoResetEvent _wait = new(true);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T13:33:22.627",
"Id": "502332",
"Score": "0",
"body": "Please add the using statements at the top of the file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:03:43.143",
"Id": "502350",
"Score": "1",
"body": "@PeterCsala I'm using .NET 5.0, in C# 9.0 this is valid syntax `private readonly AutoResetEvent _wait = new(true);` I have updated to include everything referenced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T09:09:42.580",
"Id": "502407",
"Score": "1",
"body": "Why would I assume a problem in the [code presented in revision 4](https://codereview.stackexchange.com/revisions/254521/4) and not in, say, the implementations of `ISocketListener` in general and `ISocketListener.OnData()` in particular?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T09:51:04.023",
"Id": "502411",
"Score": "0",
"body": "@greybeard To be fair, you're right. An implementation of the `ISocketListener` does have a bottleneck using `SemaphoreSlim` which limits the processing of that queue. I'll look at refactoring that code. Happy to attach it if you're interested?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T10:01:26.917",
"Id": "502412",
"Score": "0",
"body": "In essence, the `CandleConsolidator` performs a database insert or update and notifies the application of the data change. I'll focus my efforts on optimizing that, most importantly the `sync` logic and the `TODO` comment which I forgot about."
}
] |
[
{
"body": "<h3><code>SocketOptions</code></h3>\n<ul>\n<li><code>ReceiveBufferSize</code>/ <code>SendBufferSize</code>: They are quite error-prone. For instance the consumer of your utility specifies a negative number. Then it will crash with an <code>OverflowException</code>.</li>\n<li><code>AutoReconnectAttempts</code>: you can safely restrict the valid range. Don't need to allow users to specify negative attempt count.</li>\n</ul>\n<h3><code>ISocket</code></h3>\n<ul>\n<li>This interface is a mixture. One group of the methods are related to the Socket. The other half is related to the <a href=\"https://en.wikipedia.org/wiki/Observer_pattern\" rel=\"nofollow noreferrer\">Observer pattern</a>'s <code>Subject</code> (register >> <code>Add</code>, unregister >> <code>Remove</code>). <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Interface segregation</a> could help here.</li>\n</ul>\n<h3><code>ISocketListener</code></h3>\n<ul>\n<li><code>OnXYZ</code>: They do seem like they are events but they are not for whatever reason.</li>\n<li>Always be careful when you call user provided code in your context. Image that someone provides an <code>ISocketListener</code> with the following implementation:<br />\n<code>OnConnected(Socket socket) => Thread.Sleep(100*1000);</code></li>\n<li><code>OnData</code>: It is really weird for me to use <code>dynamic</code> in an interface method. Maybe it is just me.</li>\n</ul>\n<h3><code>Socket</code></h3>\n<ul>\n<li><code>Socket</code> is not really a good name for your class. There is a class with the same name <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.socket?\" rel=\"nofollow noreferrer\">inside the BCL</a>, which resides inside the <code>System.Net.Sockets</code> namespace.</li>\n<li><code>_listeners</code>: You should consider to use one of the built-in <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.concurrent\" rel=\"nofollow noreferrer\">Concurrent Collections</a> to avoid locking (<code>lock(_listeners)</code>) and copying (<code>ToArray</code>) manually.</li>\n<li><code>_receive</code> / <code>_send</code>: Even though <code>Unbounded</code> channels can <a href=\"https://ndportmann.com/system-threading-channels/\" rel=\"nofollow noreferrer\">perform better</a> than bounded ones, but they can run out of memory.</li>\n<li><code>IsConnected</code>: I don't get it why is this property <code>public</code>, or if it is <code>public</code> then why is not part of the <code>ISocket</code> interface?</li>\n<li><code>_endpoint</code>: It is used without any preliminary checks. <code>new Uri(_endpoint)</code> could fail with <code>UriFormatException</code> if the provided endpoint is not a valid Url.</li>\n<li><code>_wait</code>: <code>AutoResetEvent</code> does have async counterpart (<a href=\"https://devblogs.microsoft.com/pfxteam/building-async-coordination-primitives-part-2-asyncautoresetevent/\" rel=\"nofollow noreferrer\">1</a>, <a href=\"https://github.com/StephenCleary/AsyncEx/wiki/AsyncAutoResetEvent\" rel=\"nofollow noreferrer\">2</a>) it might make sense to make use one of them.</li>\n<li><code>OperationCanceledException</code>: Silently swallowing exceptions (without even logging the fact) is really strange for me. It might make sense to extract the ignorance logic into a separate method to streamline the core logic. <a href=\"https://weblog.west-wind.com/posts/2018/Jun/16/Explicitly-Ignoring-Exceptions-in-C\" rel=\"nofollow noreferrer\">Here is a really good article</a> about this topic.</li>\n<li><code>Send</code>: I don't get it why it is synchronous. <code>TryWrite</code> has its async counter part <code>WriteAsync</code>. Why don't you use that one? (Or <code>WaitToWriteAsync</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channelwriter-1.waittowriteasync\" rel=\"nofollow noreferrer\">1</a>) if you consider to use bounded channels)</li>\n<li><code>Dispose</code>: <code> GC.SuppressFinalize(this);</code> is missing.</li>\n<li><code>Dispose(bool disposing)</code>: Your implementation does not use <code>disposing</code> parameter. Please check these guidances how to implement Dispose pattern properly (<a href=\"https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1063\" rel=\"nofollow noreferrer\">1</a>, <a href=\"https://www.codeproject.com/Articles/15360/Implementing-IDisposable-and-the-Dispose-Pattern-P\" rel=\"nofollow noreferrer\">2</a>, <a href=\"https://dzone.com/articles/when-and-how-to-use-dispose-and-finalize-in-c\" rel=\"nofollow noreferrer\">3</a> (more recent article))</li>\n<li><code>HandleDataAsync</code>: Why do you wrap all the functionality into a <code>Task.Run</code> and then <code>await</code> it? Does it really require to run the whole method on a separate thread?</li>\n<li><code>ProcessDataAsync</code>: Here you are mixing sync and async channel access. Try to use <code>ReadAsync</code> instead of <code>TryRead</code>. (Or <code>WaitToReadAsync</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.channels.channelreader-1.readasync\" rel=\"nofollow noreferrer\">1</a>) if you consider to use bounded channels)</li>\n<li><code>_count</code>: You are increasing and decreasing it manually and then your implementation checks its value against a hard coded limit. Why don't you use bounded channel in the first place?</li>\n<li><code>ReceiveAsync</code>: It might make sense to use <code>ArrayPool</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.buffers.arraypool-1\" rel=\"nofollow noreferrer\">1</a>, <a href=\"https://adamsitnik.com/Array-Pool/\" rel=\"nofollow noreferrer\">2</a>) if you could receive quite large data.</li>\n<li><code>ReconnectAsync</code>: It might make sense to use <a href=\"https://github.com/App-vNext/Polly/wiki/Retry\" rel=\"nofollow noreferrer\">Polly's retry policy</a> to accomplish the retry logic.</li>\n</ul>\n<hr />\n<p>Unfortunately I could not spend more time to review the consumer side as well. :(</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:44:53.607",
"Id": "502445",
"Score": "1",
"body": "Very thorough and very much appreciate the links to resources! I'll look to getting through this. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T14:16:47.217",
"Id": "254747",
"ParentId": "254521",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254747",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T13:34:59.290",
"Id": "254521",
"Score": "1",
"Tags": [
"c#",
"async-await",
"socket"
],
"Title": "How can I speed up the processing of the received channel socket"
}
|
254521
|
<p>I have written an API for a dating service. This part is related to user authentification, authorization, login and etc.</p>
<p>It uses FastAPI, which in turn is based on starlette web server.</p>
<p>You may wonder what is <code>fastapi.Depends...</code>. It's internally calling a passed function when the endpoint is requested to satisfy its dependencies. I don't know what is a problem to satisfy a dependencies manually, but just using it.</p>
<p>Here is my code, please give me any feedback.</p>
<pre><code>import fastapi
import uvicorn
from sqlalchemy.orm import Session
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
import config
import schemas
import database
import services
import crud
from datetime import datetime, timedelta
app = fastapi.FastAPI(title='api', description='A very verbose API.', version='0.1')
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="login", auto_error=False) # Add GUI from to login
fastapi_http_errors = {
'no_token_401': fastapi.HTTPException(
status_code=fastapi.status.HTTP_401_UNAUTHORIZED,
detail="Invalid token",
headers={"WWW-Authenticate": "Bearer"}),
'wrong_token_403': fastapi.HTTPException(
status_code=fastapi.status.HTTP_403_FORBIDDEN,
detail="Wrong email or password", # TODO wrong token ?
headers={"WWW-Authenticate": "Bearer"}, ),
'not_found_404': fastapi.HTTPException(
status_code=fastapi.status.HTTP_404_NOT_FOUND,
detail="Interest not found"),
'email_already_exists_409': fastapi.HTTPException(
status_code=fastapi.status.HTTP_409_CONFLICT,
detail="Email already exists"),
'double_voting_409': fastapi.HTTPException(
status_code=fastapi.status.HTTP_409_CONFLICT,
detail="Same vote for the same interest"),
'expired_410': fastapi.HTTPException(
status_code=fastapi.status.HTTP_410_GONE,
detail="Confirmation link is expired"),
'fatal_error_503': fastapi.HTTPException(
status_code=fastapi.status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Unknown error"),
}
@app.post("/register", status_code=201, )
def register(
user_log_in: schemas.UserLogIn,
db: Session = fastapi.Depends(database.get_db)):
try:
if not crud.read_user_by(db, column='email', value=user_log_in.email): # If email is new
token = services.create_access_token(email=user_log_in.email,
expires_min=config.ACCESS_TOKEN_EXPIRE_MINUTES)
services.send_email_confirm_link(token=token, endpoint='http://127.0.0.1:8000/confirm-email')
return crud.create_user(db=db, user=user_log_in, token=token)
else:
return fastapi_http_errors['email_already_exists_409']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
@app.get("/confirm-email", status_code=303, )
def confirm_email(
token: str = fastapi.Query(...,
min_length=64, max_length=256,
description="jwt_token placed in url",
example='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkc2IzMjFtcEBnbWFpbC5jb20iLCJleHAiOjE2MTAzNjY1MDV9.ZT0G5bHSNBdrh-onuAp4Q6m8mqWxfjBWbIg6GLJEAgk'),
db: Session = fastapi.Depends(database.get_db)):
try:
if user := services.get_user_by_token(db=db, token=token):
if user.created_datetime + timedelta(minutes=30) > datetime.now(): # TODO change minutes to days
crud.update_user(db=db, user=user, column='is_active', value=True)
return fastapi.responses.RedirectResponse(url=f"http://127.0.0.1:8000/users/me?token={token}")
else:
return fastapi_http_errors['expired_410']
else:
return fastapi_http_errors['wrong_token_403']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
@app.post("/login", response_model=schemas.Token)
def grant_token(
form_data: OAuth2PasswordRequestForm = fastapi.Depends(),
db: Session = fastapi.Depends(database.get_db)):
try:
if token := services.grant_token(db=db, email=form_data.username, password=form_data.password):
return token
else:
return fastapi_http_errors['wrong_token_403']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
@app.post("/refresh-token",
response_model=schemas.Token)
def refresh_token(
token: str = fastapi.Depends(oauth2_scheme),
db: Session = fastapi.Depends(database.get_db)):
try:
if token:
if user := services.get_user_by_token(db=db, token=token):
access_token = services.create_access_token(
email=user.email, expires_min=config.ACCESS_TOKEN_EXPIRE_MINUTES)
crud.update_user(db=db, user=user, column='current_token', value=access_token)
return 'Token successfully refreshed'
else:
return fastapi_http_errors['wrong_token_403']
else:
return fastapi_http_errors['no_token_401']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
@app.post("/logout")
def logout(token: str, db: Session = fastapi.Depends(database.get_db)):
try:
if token:
if user := services.get_user_by_token(db=db, token=token):
crud.update_user(db=db, user=user, column='current_token', value=None) # Set token to None
return f'Successfully logout user_id {user.id}'
else:
return fastapi_http_errors['wrong_token_403']
else:
return fastapi_http_errors['no_token_401']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
@app.get("/users/me", status_code=200) # response model
def read_users_me(
token: str = fastapi.Query(None),
jwt_token: str = fastapi.Depends(oauth2_scheme),
db: Session = fastapi.Depends(database.get_db)):
"""
token: url_token indeed! REST requiring '-' instead of '_' in url,
but python variable can't contain '-', unfortunately FastAPI doesn't converting it.
"""
try:
if token := (jwt_token or token):
if user := services.get_user_by_token(db=db, token=token):
return user
else:
return fastapi_http_errors['wrong_token_403']
else:
return fastapi_http_errors['no_token_401']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
@app.patch("/users/me", status_code=200) # See PATCH vs PUT in module annotation.
def patch_users_me(
column: str = fastapi.Query(..., description="Column to patch", example='email'), # TODO restrict some columns
value: str = fastapi.Query(..., description="New value", example='foo@gmail.com'),
token: str = fastapi.Depends(oauth2_scheme),
db: Session = fastapi.Depends(database.get_db)):
try:
if token:
if user := services.get_user_by_token(db=db, token=token):
crud.update_user(db=db, user=user, column=column, value=value) # TODO test it
return 'User successfully updated'
else:
return fastapi_http_errors['wrong_token_403']
else:
return fastapi_http_errors['no_token_401']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
@app.put("/users/me", status_code=200) # See PATCH vs PUT in file annotation.
def put_users_me():
pass
@app.delete("/users/me", status_code=200) # response model
def delete_users_me(
token: str = fastapi.Depends(oauth2_scheme),
db: Session = fastapi.Depends(database.get_db)):
try:
if token := token:
if user := services.get_user_by_token(db=db, token=token):
crud.delete_user(db=db, user=user)
return 'User successfully deleted'
else:
return fastapi_http_errors['wrong_token_403']
else:
return fastapi_http_errors['no_token_401']
except Exception as e:
raise fastapi_http_errors['fatal_error_503']
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T15:10:29.697",
"Id": "501959",
"Score": "0",
"body": "@GrajdeanuAlex edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T17:40:10.087",
"Id": "502031",
"Score": "1",
"body": "@Graipher Thanks for editing"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T14:34:39.067",
"Id": "254522",
"Score": "1",
"Tags": [
"python",
"rest"
],
"Title": "Python Rest API user registration based on FastAPI framework"
}
|
254522
|
<p>Still a bit new to Kotlin and coroutines, so I want to learn best practices. The following code seems to work as expected in it's original context, though the naming has been tweaked here. The list of widgets is retrieved from the database, and the UI is updated correctly.
My main question is, in <code>updateList</code> is it approprate to use <code>withContext (Dispatchers.Main)</code> to access the UI from a job on the IO context? Feels a bit kludgy at first blush, but it does seem to work as expected.</p>
<pre><code>class WidgetListActivity : AppCompatActivity() {
private lateinit var db: AppDatabase
private lateinit var getListJob: Job
private lateinit var widgetList: List<WidgetRecord>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_widget_list)
runBlocking {
db = Room.databaseBuilder(applicationContext, AppDatabase::class.java, "Widget.db")
.createFromAsset("database/prepop_db.sqlite").build()
}
val recyclerView = findViewById<RecyclerView>(R.id.widget_recycler_view)
val linearLayoutManager = LinearLayoutManager(this.applicationContext)
recyclerView.layoutManager = linearLayoutManager
updateList()
}
private fun updateList() {
getListJob = GlobalScope.launch (Dispatchers.IO) {
widgetList = db.widgetDao().getAllWidgets()
// HERE'S THE SECTION IN QUESTION
withContext(Dispatchers.Main) {
val recyclerView = findViewById<RecyclerView>(R.id.deck_recycler_view)
var widgetListAdapter = WidgetListAdapter(widgetList)
recyclerView.adapter = widgetListAdapter
widgetListAdapter.notifyDataSetChanged()
}
}
}
override fun onDestroy() {
runBlocking {
getListJob.join()
}
// PLEASE NOTE: I know you wouldn't normally destroy the database
// like this. The whole point of this Activity is simply to test
// loading and displaying the contents of a prepopulated database.
this.applicationContext.deleteDatabase("Widgets.db")
super.onDestroy()
}
}
</code></pre>
|
[] |
[
{
"body": "<p>One thing that makes it kludgy is using GlobalScope, <a href=\"https://elizarov.medium.com/the-reason-to-avoid-globalscope-835337445abc\" rel=\"nofollow noreferrer\">which is discouraged by the coroutines design lead</a>. In this case, if this were a very long-running job, you would be leaking your UI elements because they are captured by the coroutine.</p>\n<p>Also, since you are using Room, you can make your DAO's <code>getAllWidgets()</code> a suspend function, in which case, there's no reason to use a specific dispatcher to call it. A properly composed suspend function doesn't block the dispatcher it is called from, so you never should have to specify a dispatcher to call a suspend function. The proper way to do this would be:</p>\n<pre><code>private fun updateList() {\n getListJob = lifecycleScope.launch {\n widgetList = db.widgetDao().getAllWidgets()\n val recyclerView = findViewById<RecyclerView>(R.id.deck_recycler_view)\n var widgetListAdapter = WidgetListAdapter(widgetList)\n recyclerView.adapter = widgetListAdapter\n widgetListAdapter.notifyDataSetChanged()\n }\n}\n</code></pre>\n<p>No Dispatcher specifying needed at all, because the coroutine doesn't call any blocking code and <code>lifecycleScope</code> defaults to <code>Dispatchers.Main</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:43:52.330",
"Id": "502230",
"Score": "0",
"body": "Thanks so much for the info. There are a couple of things in particular in your answer that I simply wasn't aware of.\nI didn't realize there was a `lifeCycleScope` available as a member. That's very handy.\nI also didn't realize that a dispatcher isn't needed to call a `suspend` function. I think the relationships between dispatchers, coroutine scopes, and suspending functions have been the hardest part to wrap my head around, but this information helps a lot.\n\nCheers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:06:01.087",
"Id": "502233",
"Score": "1",
"body": "Also, just to note for anyone who reads this later, you have to add `lifecycle-runtime` as a dependency in build.gradle to use the `lifecycleScope` member. [https://developer.android.com/jetpack/androidx/releases/lifecycle](https://developer.android.com/jetpack/androidx/releases/lifecycle)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:25:25.173",
"Id": "502242",
"Score": "0",
"body": "Yes, it took a while for it all to click for me because there are so many components to a coroutine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:37:48.317",
"Id": "502259",
"Score": "0",
"body": "Since the documentation for lifecycleScope says that \"This scope will be cancelled when the Lifecycle is destroyed\", I guess it's unnecessary to call `getListJob.join()` in `onDestroy`, correct? Or would it be considered best practice to wait for jobs to finish when possible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:05:06.037",
"Id": "502263",
"Score": "1",
"body": "If you start a job in lifecycleScope, its because you are fetching something for that Activity or Fragment, so presumably you don't care about the result and want it to be cancelled when the Activity or Fragment is destroyed. The cancellation is done automatically because lifecycleScope is automatically cancelled in the onDestroy phase. Joining it waits for the result, but there's no point if you are just going to throw the result away. If you join, you are holding the Activity/Fragment and everything it references in memory until the job is done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:07:25.743",
"Id": "502264",
"Score": "1",
"body": "Also, `runBlocking` has no place *anywhere* in an Android application. Its only two intended purposes are for use in unit tests and directly in the `main` function of a JVM app. Blocking a main thread locks the UI and can cause an ANR error."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T21:26:03.020",
"Id": "254571",
"ParentId": "254526",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254571",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T16:32:29.700",
"Id": "254526",
"Score": "3",
"Tags": [
"database",
"kotlin",
"user-interface"
],
"Title": "Read database from IO context and update UI from Main context in Kotlin"
}
|
254526
|
<p><a href="https://github.com/speedrun-program/load-extender" rel="nofollow noreferrer">https://github.com/speedrun-program/load-extender</a></p>
<p>I posted a version of these programs for review about a week ago and ended up getting good advice on how to improve them. this was the post which shows the old code: <a href="https://codereview.stackexchange.com/questions/254324/c-and-c-programs-which-let-you-lengthen-the-time-it-takes-to-access-files">C and C++ programs which let you lengthen the time it takes to access files</a></p>
<p>Now that I've improved the code, I'm posting the new version here for review since <a href="https://codereview.stackexchange.com/help/someone-answers">this page</a> says I'm allowed to.</p>
<p>I did everything suggested by the accepted answer in the original post except for using std::filesystem::path objects in the hash map because I couldn't figure out how to do that.</p>
<p>*sorry that I've been making so many small adjustments to the code occasionally. But I think at this point it should be complete.</p>
<p>struct_and_functions.h:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <stdint.h>
#include <iostream>
#include <fstream>
#include <string>
#include <atomic>
#include <vector>
#include <exception>
static bool TOO_BIG_DELAY_SEEN = false;
struct delay_sequence
{
std::atomic<std::size_t> index;
std::vector<std::chrono::milliseconds> delays;
bool repeat;
bool reset_all;
delay_sequence() { index = 0; repeat = false; reset_all = false; }
delay_sequence(const delay_sequence& copy_sequence)
{
index = copy_sequence.index.load();
delays = copy_sequence.delays;
repeat = copy_sequence.repeat;
reset_all = copy_sequence.reset_all;
}
delay_sequence& operator=(delay_sequence copy_sequence)
{
index = copy_sequence.index.load();
delays = copy_sequence.delays;
repeat = copy_sequence.repeat;
reset_all = copy_sequence.reset_all;
return *this;
}
};
static std::size_t setup_delay_sequence(delay_sequence& current_sequence, std::wstring& line, std::size_t start_position)
{
std::size_t delay_sequence_length = 1;
for (std::size_t line_position = start_position; line_position < line.length(); line_position++)
{
if (line[line_position] == L'/')
{
++delay_sequence_length;
}
else if (line[line_position] == L'-')
{
--delay_sequence_length;
if (delay_sequence_length == 0)
{
current_sequence.reset_all = true;
break;
}
current_sequence.repeat = true;
break;
}
}
return delay_sequence_length;
}
static void remove_non_digits(std::wstring& delay_substr)
{
std::size_t position_to_write = 0;
for (std::size_t i = 0; i < delay_substr.length(); i++)
{
if (isdigit(delay_substr[i]))
{
delay_substr[position_to_write] = delay_substr[i];
++position_to_write;
}
}
delay_substr.erase(position_to_write);
}
static void set_delays(std::vector<std::chrono::milliseconds>& delays, std::wstring& line, std::size_t delay_sequence_length, std::size_t slash_position)
{
delays.reserve(delay_sequence_length);
unsigned long long max_delay = std::chrono::milliseconds::max().count();
while (slash_position != std::wstring::npos && delays.size() != delay_sequence_length)
{
std::size_t next_slash_position = line.find(L'/', slash_position + 1);
std::wstring delay_substr = line.substr(slash_position + 1, next_slash_position - slash_position - 1);
remove_non_digits(delay_substr);
if (delay_substr.length() == 0)
{
delays.push_back(std::chrono::milliseconds(0));
slash_position = next_slash_position;
continue;
}
try
{
unsigned long long delay_time = std::stoull(delay_substr);
if (delay_time > max_delay)
{
throw std::out_of_range(NULL);
}
delays.push_back(std::chrono::milliseconds(delay_time));
}
catch (const std::out_of_range& oor)
{
if (!TOO_BIG_DELAY_SEEN)
{
printf("delay time can only be %llu milliseconds\n", max_delay);
TOO_BIG_DELAY_SEEN = true; // TOO_BIG_DELAY_SEEN only changed here
}
delays.push_back(std::chrono::milliseconds(max_delay));
}
slash_position = next_slash_position;
}
}
static void set_key_and_value(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& line)
{
std::size_t slash_position = line.find(L'/');
if (slash_position == std::wstring::npos)
{
return;
}
std::size_t position_before_whitespace = line.find_last_not_of(L" \t\f\v\r/", slash_position);
if (position_before_whitespace == std::wstring::npos)
{
return;
}
std::wstring file_name = line.substr(0, position_before_whitespace + 1);
delay_sequence current_sequence;
std::size_t delay_sequence_length = setup_delay_sequence(current_sequence, line, slash_position + 1);
set_delays(current_sequence.delays, line, delay_sequence_length, slash_position);
my_rh_map[file_name] = current_sequence;
}
static unsigned char rh_map_setup(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)
{
std::size_t line_count = 1;
std::wstring line;
std::wifstream my_file;
my_file.open("files_and_delays.txt");
if (my_file.fail())
{
printf("couldn't open files_and_delays.txt\n");
return 1;
}
while (std::getline(my_file, line) && line_count < SIZE_MAX)
{
++line_count;
}
if (line_count == SIZE_MAX)
{
printf("can't store %zu delays\n", SIZE_MAX);
return 1;
}
my_rh_map.reserve(line_count);
my_file.clear();
if (!my_file.seekg(0, std::ios::beg))
{
printf("seekg on files_and_delays.txt failed\n");
return 1;
}
line.clear();
while (std::getline(my_file, line))
{
set_key_and_value(my_rh_map, line);
line.clear();
}
my_file.close();
return 0;
}
static void delay_file(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& file_name)
{
rh::unordered_flat_map<std::wstring, delay_sequence>::iterator rh_map_iter = my_rh_map.find(file_name);
if (rh_map_iter != my_rh_map.end()) // key found
{
printf("%ls successfully found in hash map\n", file_name.c_str());
delay_sequence& found_sequence = rh_map_iter->second;
if (found_sequence.reset_all) // reset all delay sequences
{
for (auto& it : my_rh_map)
{
it.second.index = 0;
}
printf("all delay sequences reset\n");
}
else
{
if (found_sequence.repeat) // reset delay sequence
{
found_sequence.index = found_sequence.index.load() % found_sequence.delays.size();
printf("%ls delay sequence reset\n", file_name.c_str());
}
if (found_sequence.index < found_sequence.delays.size())
{
// this is defined in the main file so it won't sleep if being used with load_extender_test.exe
call_sleep_thread(found_sequence.delays[found_sequence.index]);
found_sequence.index += 1;
}
else // delay sequence already finished
{
printf("%ls delay sequence already finished\n", file_name.c_str());
}
}
}
else // key not found
{
printf("%ls not found in hash map\n", file_name.c_str());
}
}
</code></pre>
<p>load_extender_test.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include <chrono>
#include <thread>
#include "robin_hood.h"
// thank you for making this hash map, martinus.
// here's his github: https://github.com/martinus/robin-hood-hashing
// this is defined here so delay_file function will use the right version
static void call_sleep_thread(std::chrono::milliseconds duration)
{
unsigned long long total_milliseconds = duration.count();
unsigned long long total_seconds = total_milliseconds / 1000;
short remaining_milliseconds = total_milliseconds % 1000;
printf("sleep for %llu second(s) and %d millisecond(s)\n", total_seconds, remaining_milliseconds);
}
namespace rh = robin_hood;
#include "struct_and_functions.h" // included here so alias can be used
// these are global so the hooked function can see them
static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;
// SETUP_SUCCEEDED only changed here
static unsigned char SETUP_SUCCEEDED = rh_map_setup(my_rh_map);
static void print_rh_map()
{
printf("\n---------- hash map current state ----------\n");
for (auto& it : my_rh_map)
{
printf("%ls / ", it.first.c_str());
delay_sequence& sequence_to_print = it.second;
for (std::size_t i = 0; i < sequence_to_print.delays.size(); i++)
{
// casted to unsigned long long to get rid of warning message
// visual studio on windows wants %lu, but gcc on linux wants %llu
printf("%llu ", (unsigned long long)sequence_to_print.delays[i].count());
}
if (sequence_to_print.reset_all)
{
printf("RESET_ALL ");
}
else if (sequence_to_print.repeat)
{
printf("REPEAT ");
}
printf(": INDEX %zu", sequence_to_print.index.load());
printf("\n");
}
printf("---------------------------------------------\n\n");
}
static void test_all_inputs()
{
std::wstring test_path;
std::wifstream input_test_file;
input_test_file.open("test_input.txt");
if (input_test_file.fail())
{
printf("couldn't open test_input.txt\n");
return;
}
if (SETUP_SUCCEEDED == 0)
{
print_rh_map();
while (std::getline(input_test_file, test_path))
{
printf("testing input: %ls\n", test_path.c_str());
delay_file(my_rh_map, test_path);
print_rh_map();
test_path.clear();
}
}
else
{
printf("setup failed\n");
}
input_test_file.close();
}
int main(int argc, char* argv[])
{
printf("\ntest start\n");
test_all_inputs();
printf("test finished, press Enter to exit\n");
std::wstring input;
std::getline(std::wcin, input);
return 0;
}
</code></pre>
<p>load_extender.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include <chrono>
#include <thread>
#include <stdio.h>
#include <dlfcn.h>
#include "robin_hood.h"
// thank you for making this hash map, martinus.
// here's his github: https://github.com/martinus/robin-hood-hashing
#define DISABLE_PRINTF
#ifdef DISABLE_PRINTF
#define printf(fmt, ...) (0)
#endif
// this is defined here so delay_file function will use the right version
static void call_sleep_thread(std::chrono::milliseconds duration)
{
std::this_thread::sleep_for(duration);
}
namespace rh = robin_hood;
#include "struct_and_functions.h" // included here so alias can be used
// these are global so the hooked function can see them
static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;
// SETUP_SUCCEEDED only changed here
static unsigned char SETUP_SUCCEEDED = rh_map_setup(my_rh_map);
static auto original_fopen = reinterpret_cast<FILE *(*)(const char *path, const char *mode)>(dlsym(RTLD_NEXT, "fopen"));
FILE *fopen(const char *path, const char *mode)
{
if (SETUP_SUCCEEDED == 0)
{
// finding part of path which shows file name
std::size_t file_name_index = SIZE_MAX; // overflows to 0 and checks entire path if no slash is found
std::size_t end_index = 0;
for (; path[end_index] != '\0'; end_index++)
{
if (path[end_index] == '/')
{
file_name_index = end_index;
}
}
std::wstring file_name(&path[file_name_index + 1], &path[end_index]);
delay_file(my_rh_map, file_name);
}
return original_fopen(path, mode);
}
</code></pre>
<p>load_extender_dll.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>// allows std::chrono::milliseconds::max().count();
#define NOMINMAX
#include <chrono>
#include <thread>
#include <Windows.h>
#include <easyhook.h>
#include "robin_hood.h"
// thank you for making this hash map, martinus.
// here's his github: https://github.com/martinus/robin-hood-hashing
#define DISABLE_PRINTF
#ifdef DISABLE_PRINTF
#define printf(fmt, ...) (0)
#endif
// this is defined here so delay_file function will use the right version
static void call_sleep_thread(std::chrono::milliseconds duration)
{
std::this_thread::sleep_for(duration);
}
namespace rh = robin_hood;
// included here so alias can be used
#include "struct_and_functions.h"
// these are global so the hooked function can see them
static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;
static unsigned char SETUP_SUCCEEDED = rh_map_setup(my_rh_map);
static NTSTATUS WINAPI NtOpenFileHook(
PHANDLE FileHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,
PIO_STATUS_BLOCK IoStatusBlock,
ULONG ShareAccess,
ULONG OpenOptions)
{
if (SETUP_SUCCEEDED == 0)
{
std::wstring file_path = ObjectAttributes->ObjectName->Buffer;
// +1 so '\' isn't included. If '\' isn't found, the whole wstring is checked because npos is -1
std::wstring file_name = file_path.substr(file_path.rfind(L"\\") + 1);
delay_file(my_rh_map, file_name);
}
return NtOpenFile(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions);
}
extern "C" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo);
void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) {
HOOK_TRACE_INFO hHook1 = { NULL };
LhInstallHook(
GetProcAddress(GetModuleHandle(TEXT("ntdll")), "NtOpenFile"),
NtOpenFileHook,
NULL,
&hHook1);
ULONG ACLEntries[1] = { 0 };
LhSetExclusiveACL(ACLEntries, 1, &hHook1);
return;
}
</code></pre>
<p>load_extender_exe.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include <tchar.h>
#include <iostream>
#include <string>
#include <Windows.h>
#include <easyhook.h>
void get_exit_input()
{
std::wcout << "Press Enter to exit";
std::wstring input;
std::getline(std::wcin, input);
std::getline(std::wcin, input);
}
int _tmain(int argc, _TCHAR* argv[])
{
WCHAR* dllToInject32 = NULL;
WCHAR* dllToInject64 = NULL;
LPCWSTR lpApplicationName = argv[0];
DWORD lpBinaryType;
if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))
{
std::wcout << "ERROR: This exe wasn't identified as 32-bit or as 64-bit";
get_exit_input();
return 1;
}
else if (lpBinaryType == 0)
{
dllToInject32 = (WCHAR*)L"load_extender_32.dll";
}
else
{
dllToInject64 = (WCHAR*)L"load_extender_64.dll";
}
DWORD processId;
std::wcout << "Enter the target process Id: ";
std::cin >> processId;
wprintf(L"Attempting to inject dll\n\n");
// Inject dllToInject into the target process Id, passing
// freqOffset as the pass through data.
NTSTATUS nt = RhInjectLibrary(
processId, // The process to inject into
0, // ThreadId to wake up upon injection
EASYHOOK_INJECT_DEFAULT,
dllToInject32, // 32-bit
dllToInject64, // 64-bit
NULL, // data to send to injected DLL entry point
0 // size of data to send
);
if (nt != 0)
{
printf("RhInjectLibrary failed with error code = %d\n", nt);
PWCHAR err = RtlGetLastErrorString();
std::wcout << err << "\n";
get_exit_input();
return 1;
}
else
{
std::wcout << L"Library injected successfully.\n";
}
get_exit_input();
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T17:00:46.040",
"Id": "503603",
"Score": "0",
"body": "I posted a follow up question: https://codereview.stackexchange.com/questions/255255/c-program-which-let-you-lengthen-the-time-it-takes-to-access-files-revision-2"
}
] |
[
{
"body": "<h2>General Observations</h2>\n<p>Interesting project. The code looks a little too much like C and not enough like C++. You might want to convert the <code>struct</code>s to classes to take advatage of data encapsulation.</p>\n<p>I suggest that you follow more of the advice given in the answer on your first question:</p>\n<blockquote>\n<p>Make your code as platform-independent as possible</p>\n<p>You should not need two completely different implementations. A lot of code can be shared. The only things that are different between Linux and Windows are the function calls that need to be intercepted, and how you intercept them.</p>\n</blockquote>\n<p>Rather than have 2 separate code bases, one for Linux and one for Windows, the code that is platform specific should be <a href=\"https://stackoverflow.com/questions/142508/how-do-i-check-os-with-a-preprocessor-directive\">within ifdefs</a>.</p>\n<p>The major problem with having 2 separate sets of files for a program is that it doubles the cost of the maintenance. If there is a bug in the code it needs to be fixed in 2 places rather than one.</p>\n<h2>Follow Conventions</h2>\n<p>A convention that started in the C program is that macros or symbolic constants should be in all caps and regular variables should follow the naming convention used throughout the rest of the program whether that is snake_case or camelCase. The following statement is a violation of that convention:</p>\n<pre><code>static bool TOO_BIG_DELAY_SEEN = false;\n</code></pre>\n<p>since <code>TOO_BIG_DELAY_SEEN</code> is not a <code>const</code> declaration.</p>\n<p>It is generally a bad idea to declare a variable in a header file since that can lead to linking problems. In this case the <code>static</code> declaration localizes the variable but it does exist in every file that includes the header.</p>\n<h2>Function Bodies Should be in .cpp Files</h2>\n<p>The code defines a structure with a number of functions in the file <code>struct_and_functions.h</code>. For a number of reasons it is better to define these as pointers to functions in the struct and define the body of the function in a .cpp file. This means that the code will only be compiled once rather than multiple times and can prevent linking problems. It also decreases build times since the functions are supplied by a .o file (Linux) or .obj file (Windows). This will decrease the size of the binary is that header file is included in multiple .cpp files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T21:51:43.533",
"Id": "502146",
"Score": "0",
"body": "Thank you for helping with this, I’ll try to change it using your advice. For TOO_BIG_DELAY_SEEN would it be better if I made it in rh_map_setup and passed it to set_key_and_value and set_delays?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:03:43.233",
"Id": "502148",
"Score": "1",
"body": "I can't find the declaration/body of rh_map_setup() in your code, only the usage, so I can't say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:11:33.047",
"Id": "502151",
"Score": "0",
"body": "They’re in struct_and_functions.h, the 2nd and 3rd lowest functions. I ended up making it global because I thought it seemed clumsy to pass it up multiple functions just to use it in a single area to prevent a message from repeating. But I maybe that’s the wrong way to deal with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:30:13.950",
"Id": "502152",
"Score": "0",
"body": "I tried looking up mutable default arguments for c++ but I didn’t see anything for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:46:39.707",
"Id": "502153",
"Score": "0",
"body": "Nevermind, I think I finally found something. I can make it in set_delays as a static local variable."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T21:39:57.490",
"Id": "254623",
"ParentId": "254528",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254623",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T17:59:03.373",
"Id": "254528",
"Score": "1",
"Tags": [
"c++",
"beginner"
],
"Title": "C++ programs for Windows and Linux which let you lengthen the time it takes to access files REVISED VERSION"
}
|
254528
|
<p><strong>Background</strong></p>
<p>I have a script that either takes a text file that contains a list of <code>player_ids</code> or not. If the user provides a <code>player_id</code> list i ensure that all the ids are part of the tranche date they provided and then run the process job for all the player ids in the list.</p>
<p>If the user has not provided a list of players to run the jobs on we run the process job on all the players that are part of the tranche date.</p>
<p><strong>Code</strong></p>
<pre><code>import argparse
from nba import release_checks, s3, shell
from typing import List
from nba.process_jobs_off_sqs import batch
from nba.process_jobs_off_sqs.exceptions import BatchTimeoutException
def _get_all_player_id(tranche_date: str) -> List[str]:
return s3.download_str_key(
s3.S3Path(
"player-datasets",
f"ENVIRONMENTS/staging/{tranche_date}/all_player_ids_in_delivery.txt",
)
).splitlines()
def _is_player_id_list_valid(
provided_player_id_list: List[str], all_player_id_list: List[str]
) -> bool:
for player_id in provided_player_id_list:
if player_id not in all_player_id_list:
raise Exception(
f"The following player id: {player_id} in the text file is not part of the tranche you provided."
)
return True
def _launch_process_job(list_of_player_ids: List[str]) -> None:
jobs = [
{"player_id": player_id, "job_id": player_id}
for player_id in list_of_player_ids
]
try:
batch.launch_and_await_batch("automated_player_selection", jobs)
except BatchTimeoutException:
print(f"Jobs are known to fail due data missingness.")
def _run_mentality_check(nba_folder_name: List[str]) -> None:
try:
release_checks.mentality_check(
nba_folder_name
)
except Exception as e:
print(e)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--nba-folder-name", required=True)
parser.add_argument("--tranche-date", required=True)
parser.add_argument("--list-of-player-id-file-path")
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
all_player_id_list = _get_all_player_id(args.tranche_date)
if args.list_of_player_id_file_path:
provided_player_id_list = shell.lines_from_file(
args.list_of_player_id_file_path
)
if _is_player_id_list_valid(provided_player_id_list, all_player_id_list):
_launch_process_job(provided_player_id_list)
else:
_launch_process_job(provided_player_id_list)
_run_mentality_check(args.nba_folder_name)
</code></pre>
<p>I am mostly looking for a code review for better python usage as i am new to python. I gave a vague background as i am less concerned on getting code review on the actual algorithm but more so about my code and how to make it more pythonic and clean.</p>
|
[] |
[
{
"body": "<h2>Validation</h2>\n<p>This function <code>_is_player_id_list_valid</code> is stuck between two useful concepts - validating and returning <code>bool</code>, and throwing-or-not. Don't attempt to do a half-measure of both. Given its current name, it would be less surprising to do</p>\n<pre><code>for player_id in provided_player_id_list:\n if player_id not in all_player_id_list:\n return False\nreturn True\n</code></pre>\n<p>If you want to keep the exception, then</p>\n<ul>\n<li>Delete the return</li>\n<li>Change the return type to <code>None</code></li>\n<li>Use a more specific type than <code>Exception</code></li>\n<li>Rename the method to something like <code>check_player_id_list</code>.</li>\n</ul>\n<p>For this method you should also get rid of the loop, cast the lists to <code>set</code>s, use set intersection, and then base your error message off of <em>all</em> of the missing elements instead of just the first.</p>\n<h2>Late serialization</h2>\n<p>Validation should be done on <code>tranche_date</code>. The sanest way to do this is expect a date of a specific format (which you probably already do, though you haven't shown it); parse it into a real <code>datetime</code> (or perhaps <code>date</code>), and then re-serialize it in <code>_get_all_player_id</code>. Its representation should only be <code>str</code> at the extreme edges of your program - in your argument parsing, and in your S3 call. In the middle it should be a real date type.</p>\n<h2>Error messages</h2>\n<pre><code>except BatchTimeoutException:\n print(f"Jobs are known to fail due data missingness.")\n</code></pre>\n<p>is... a little strange. You could print this and it would still be valid even if there were no timeout. Instead perhaps consider</p>\n<pre><code> print('Batch timed out. Data may be missing.')\n</code></pre>\n<p>Note that this does not need to be an f-string. Also, what data?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T18:56:47.463",
"Id": "254530",
"ParentId": "254529",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T18:17:08.447",
"Id": "254529",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Processing Batch Job"
}
|
254529
|
<p>The code below is an implementation of purely recursive solution to find a powerset of any given set. The input set is a string, and the output - array of strings. Both of them are wrapped into a structure for convenience. The underlying algorithm is pretty common one. The recursive function executes exactly 2^n - 1 times.</p>
<p>I've intentionally removed all memory allocation error checking to make the snippet shorter.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct set {
char* data;
int size;
} Set;
typedef struct pset {
char **data;
int size;
} PSet;
Set *initSet(char *str) {
Set *set;
set = malloc(sizeof(Set));
set->data = calloc(strlen(str) + 1, 1);
strcpy(set->data, str);
set->size = strlen(str);
return set;
}
PSet *initPSet(const Set* sset) {
// wrapper for recursive function getPSet
void getPSet(PSet *pset, const Set *inputStr, int buffer, int index);
PSet *pset = malloc(sizeof(PSet));
pset->data = malloc (sizeof(char *) * (1 << sset->size));
// empty set is a subset of any set
pset->data[pset->size] = calloc(2, 1);
strcpy(pset->data[pset->size], "");
pset->size = 1;
// in case the input set is empty return a set with just one element
if (sset->size != 0)
getPSet(pset, sset, 0, 0);
return pset;
}
void getPSet(PSet *pset, const Set *set, int buffer, int index) {
//allocating place for a new subset
pset->data[pset->size] = calloc(strlen(pset->data[buffer]) + 2, sizeof(char));
strcpy(pset->data[pset->size], pset->data[buffer]);
pset->data[pset->size][strlen(pset->data[buffer])] = set->data[index];
pset->size++;
// local variable pos keeps track of a position of a prefix stored in pset for future recurrent calls
int pos = pset->size - 1;
index++;
if (index >= set->size) return;
getPSet(pset, set, buffer, index);
getPSet(pset, set, pos, index);
}
int main () {
Set *sset = initSet("abcd");
PSet *pset;
pset = initPSet(sset);
for (int i = 0; i < pset->size; ++i) {
printf("{%s}\n", pset->data[i]);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T00:31:57.620",
"Id": "501982",
"Score": "2",
"body": "`pset->size` is used in `initPSet` without having been initialized."
}
] |
[
{
"body": "<p>Just a review of a small portion of code:</p>\n<pre><code>PSet *pset = malloc(sizeof(PSet));\npset->data = malloc (sizeof(char *) * (1 << sset->size));\npset->data[pset->size] = calloc(2, 1);\n</code></pre>\n<p><code>pset->size</code> is not yet assigned a value. <code>pset->data[pset->size]</code> is a <strong>Bug</strong>. <a href=\"https://codereview.stackexchange.com/questions/254532/find-a-powerset-of-a-set-in-c/254543#comment501982_254532\">@1201ProgramAlarm</a></p>\n<p><code>sizeof(char *)</code> --> Is that the correct size? I need to look for the declarations of <code>pset</code> up some lines and then the definition of <code>PSet</code> some 20 lines upstream.</p>\n<p>Consider below instead - no need to check if the correct type. The size is correct by inspection of this line alone.</p>\n<pre><code>pset->data = malloc(sizeof pset->data[0] * (1 << sset->size));\n</code></pre>\n<p>Later code uses <code>int</code> for indexing and buffer size, yet could have used <code>unsigned</code> and incur no additional cost in performance. To support <code>unsigned</code>, add <code>u</code>:</p>\n<pre><code>pset->data = malloc(sizeof pset->data[0] * (1u << sset->size));\n</code></pre>\n<hr />\n<p><strong>Redundant string length calculation</strong></p>\n<p>Compiler may not optimize the 2 <code>strlen()</code> calls into 1. Recommend to do so by direct code.</p>\n<pre><code>//pset->data[pset->size] = calloc(strlen(pset->data[buffer]) + 2, sizeof(char));\n//strcpy(pset->data[pset->size], pset->data[buffer]);\n//pset->data[pset->size][strlen(pset->data[buffer])] = set->data[index];\n\nsize_t len = strlen(pset->data[buffer];\npset->data[pset->size] = calloc(len + 2, sizeof(char));\nstrcpy(pset->data[pset->size], pset->data[buffer]); // or memcpy()\npset->data[pset->size][len] = set->data[index]; // re-use `len`\n</code></pre>\n<hr />\n<p><strong>Use <code>const</code> for unchanged refenced data</strong></p>\n<p>It better conveys code's intent, allows for some optimizations and greater functionally usage.</p>\n<pre><code>// Set *initSet(char *str) {\nSet *initSet(const char *str) {\n</code></pre>\n<hr />\n<p><strong>Missing freeing of memory</strong></p>\n<p>For general usage of these routines, de-allocation routines are needed like <code>uninitSet()</code> and <code>uninitPSet()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T08:57:14.623",
"Id": "502319",
"Score": "0",
"body": "Appreciate your feedback. I especially like the idiom of dereferencing a pointer variable for the calculation of memory being allocated. The only thing that isn't that clear to me is using `unsigned` instead of `int`. Do you use it for better demonstration of your intentions or it yields some advantages in efficiency/allows for certain optimizations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:01:53.547",
"Id": "502341",
"Score": "0",
"body": "@anfauglit Increased range with `u`. `1u << sset->size` good for `sset->size` in the range [0...N). `1 << sset->size` good for `sset->size` in the range [0...N-1). Same efficiency. Other code would need to move from `int` indexing to support this wider range."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T05:58:47.750",
"Id": "254543",
"ParentId": "254532",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254543",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T20:57:18.320",
"Id": "254532",
"Score": "0",
"Tags": [
"c",
"recursion",
"set"
],
"Title": "Find a powerset of a set in C"
}
|
254532
|
<pre><code>us = 'US Dollar [$]'
sr = 'Saudi Riyal [S.R]'
# Questions for the user :)
print('Which Currency You Want?\n')
print("1 - Saudi Riyal To US Dollar\n")
print("2 - US Dollar To Saudi Riyal\n")
def convert():
amount = input('Please enter the amount: ')
def option1():
calculation = val_am * 3.75
print('calculating...')
time.sleep(3)
print('The amount is', calculation, 'S.R')
def option2():
calculation = val_am / 3.75
print('calculating...')
time.sleep(3)
print('The amount is', str(calculation) + '$')
if amount > '10000':
print("Larg Amount, Try Again")
while True:
amount2 = input('Please enter the amount: ')
try:
val_am = int(amount2)
if val_am > 10000:
print('Larg Amount, Try Again')
else:
if val == 1:
return option1()
if val == 2:
return option2()
break;
except ValueError:
print('This Not A Number')
while True:
option = input("Which one?: ")
try:
val = int(option)
if val > 2:
print('Sorry, There\'s Only Two Options')
else:
convert()
break;
except ValueError:
print('Sorry, This not a number!')
input('Press Enter To Continue...')
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T21:12:50.343",
"Id": "501969",
"Score": "1",
"body": "Are you after user experience, correctness, or readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T11:21:47.423",
"Id": "502007",
"Score": "0",
"body": "@ted, we consider all of those to be fair game for review here. Any and all aspects of the code can be critiqued."
}
] |
[
{
"body": "<p>Your <code>option1</code> and <code>option2</code> functions are a bit confusing in that they use <code>val_am</code>, but up until that point, <code>val_am</code> hasn't been assigned yet. This forces me to read ahead a bit\nthen scroll back a bit if I'm trying to follow the data, and also opens up the possibility of accidentally calling one of those two function before <code>val_am</code> has been set if you refactor your code later. To avoid relying on variables being defined in the enclosing scope, I'd pass the required data in as an argument:</p>\n<pre><code>def option1(val_am): # Then do the same to option2\n calculation = val_am * 3.75\n print('calculating...')\n time.sleep(3)\n print('The amount is', calculation, 'S.R')\n</code></pre>\n<p>Then</p>\n<pre><code>if val == 1:\n return option1(val_am) # Explictly provide the required data as an argument\nif val == 2:\n return option2(val_am)\n</code></pre>\n<p>If you want to get a little advanced, those functions can actually be combined. There are two differences between the functions:</p>\n<ul>\n<li><code>option1</code> uses multiplication, while <code>option2</code> uses division.</li>\n<li><code>option1</code> prints out <code>'S.R'</code> for the currency, while <code>option2</code> prints a <code>'$'</code> at the end.</li>\n</ul>\n<p>These differences can be accounted for by making them additional parameters of the function:</p>\n<pre><code>def option(val_am, converter_op, currency):\n calculation = converter_op(val_am, 3.75)\n print('calculating...')\n time.sleep(3)\n print('The amount is', calculation, currency)\n</code></pre>\n<p>Then, it would be used as either:</p>\n<pre><code>if val == 1:\n return option(val_am, lambda x, y: x * y, "S.R")\nif val == 2:\n return option(val_am, lambda x, y: x / y, "$")\n</code></pre>\n<p>or,</p>\n<pre><code>import operator as op\n\nif val == 1:\n return option(val_am, op.mul, "S.R")\nif val == 2:\n return option(val_am, op.truediv, "$")\n</code></pre>\n<p>The difference between the two ways is how the multiply/divide is communicated to the <code>option</code> function. In the first case, I'm passing a <code>lambda</code> function, in the second, I'm making use of the <code>operator</code> module which are basically normal functions wrapping the operators like <code>*</code> and <code>/</code>. Prefer <code>operator</code>. I showed the <code>lambda</code> version in case you already knew about <code>lambda</code>s.</p>\n<p>This also isn't a major improvement here, but as functions become more complicated, and you begin writing different functions that look very similar, it's helpful to know how to generalize them and make single functions more generally useful.</p>\n<p>I would also take the <code>option</code> function(s) out of <code>convert</code>. Once you've made <code>val_am</code> a parameter of the function, there's no longer any reason it should be inside of <code>convert</code>. Having it in there is just making the function longer than it needs to be and thus harder to read.</p>\n<hr />\n<p>Similarly as above, I would also make <code>val</code> a parameter of <code>convert</code>:</p>\n<pre><code>def convert(val):\n . . .\n\nif val > 2:\n print('Sorry, There\\'s Only Two Options') \nelse:\n convert(val) # Pass it in\n</code></pre>\n<p>A good general rule of thumb to follow: If a function requires some data, supply it as an argument to the function. It makes it clearer where data is coming from, and prevents you from attempting to use data before it's been set. Both of those become increasingly important as your code becomes more complicated.</p>\n<hr />\n<p><code>if val > 2:</code> isn't checking for negative numbers being entered. If you're going to print a warning for numbers higher than <code>2</code>, you might as well also warn against other illegal input. I'd write that as:</p>\n<pre><code>if 1 <= val <= 2:\n convert(val) \nelse:\n print('Please enter either 1 or 2')\n</code></pre>\n<p>Also note, you had the string <code>'Sorry, There\\'s Only Two Options'</code> previously, and are escaping the quote using <code>\\'</code>. That's not necessary though. You can have single quotes unescaped if you use double outer quotes:</p>\n<pre><code>print("Sorry, There's Only Two Options") # Runs fine\n</code></pre>\n<hr />\n<pre><code>return option2()\nbreak;\n</code></pre>\n<ul>\n<li>Once you've <code>return</code>ed from a function, you leave it at that point. That means that that <code>break</code> will never be reached. A good IDE (like Pycharm) will warn you of oddities like this using warnings.</li>\n<li>The <code>;</code> isn't necessary here. You should avoid <code>;</code> altogether though. It's really never needed, and just adds to noise on the line.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T03:41:16.783",
"Id": "501987",
"Score": "0",
"body": "Thanks i appreciate your support, also if you could explain specifically where should the function(s) be and the conditions like the if statement etc., You have my thanks again\n@Carcigenicate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:20:45.227",
"Id": "502011",
"Score": "0",
"body": "@MohammedAhmed First day of classes today, so I'll see if I have time later. The functions should be all \"top level\" though; not inside of anything else. And everything else is the same as where you already have it. I showed the `if` part because I changed it, not because it should be moved."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T22:55:50.897",
"Id": "254537",
"ParentId": "254533",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254537",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T21:05:57.417",
"Id": "254533",
"Score": "-1",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Dollar/Riyal currency converter in Python"
}
|
254533
|
<p>I want to fix number of digits after '.' in digit represented by string.</p>
<p>Is there better solution than mine?</p>
<h3>My code</h3>
<pre><code>def convert(s):
""" Convert 1234.12345678 to 1234.123"""
vec = s.split('.')
if len(vec) == 2 and len(vec[1]) > 3:
return vec[0] + '.' + vec[1][:3]
return s
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T22:43:20.917",
"Id": "501977",
"Score": "0",
"body": "`def convert(s): return f'{float(s):.3f}'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T23:42:14.300",
"Id": "501978",
"Score": "11",
"body": "@TedBrownlow The answer box is the place for posting answers. Comments are for requesting clarifications."
}
] |
[
{
"body": "<p>You can just use the format() function to get the result.</p>\n<pre><code>def convert(s):\n """ Convert 1234.12345678 to 1234.123"""\n s = print("{:.3f}".format(float(s)))\ns = "1234.12345678"\nconvert(s)\n</code></pre>\n<p>Refer to this link to know more about <a href=\"https://www.geeksforgeeks.org/string-formatting-in-python/\" rel=\"nofollow noreferrer\">String Formatting</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T17:41:14.910",
"Id": "502032",
"Score": "4",
"body": "Why do you assign the return value of `print()` to `s`? And why do you print in `convert()` at all instead of just returning the formatted str?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T10:53:37.077",
"Id": "254548",
"ParentId": "254535",
"Score": "0"
}
},
{
"body": "<p>In fact this would be sufficient:</p>\n<pre><code>return '{0:1.3f}'.format(s)\n</code></pre>\n<p>(provided that the argument passed is a float).\nThere is no need for a function.</p>\n<p>The above will return a <strong>string</strong>, if you want to return a float then use the float function:</p>\n<pre><code>return float('{0:1.3f}'.format(s))\n</code></pre>\n<p>Or even shorter, taking advantage of F-strings. I prefer this option personally:</p>\n<pre><code>return f'{s:.3f}'\n</code></pre>\n<p>Again, this returns a string but you can cast it to a float if necessary.</p>\n<p>As a reference: <a href=\"http://zetcode.com/python/fstring/\" rel=\"nofollow noreferrer\">Python f-string tutorial</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:15:53.260",
"Id": "502113",
"Score": "0",
"body": "The f-string is impressively faster than the string format method. If you are in 3.6+ I would go for that option."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T20:55:09.757",
"Id": "254569",
"ParentId": "254535",
"Score": "3"
}
},
{
"body": "<p>Let's raise the bar a bit here.</p>\n<h1>Function Declaration</h1>\n<p><code>def convert(s):</code></p>\n<p>This function converts ... something. Inches to feet? Celsius to Fahrenheit? The function name doesn't give us any clue. The function argument <code>s</code> is similarly non-descriptive.</p>\n<p>What does the function do? It truncates a string 3 characters after the first period character, if one is present. We could name the function that:</p>\n<p><code>def truncate_3_characters_after_period(s):</code></p>\n<p>A wee bit too verbose, and it doesn't quite match what appears to be the intended usage. From the doc-string, the function seems to be intended to apply to strings representing floating-point quantities, so maybe:</p>\n<p><code>def truncate_to_3_decimal_places(s):</code></p>\n<p>That is better, but no longer implies the function is expecting a string, or returns a string. Type-hints go a long way here.</p>\n<p><code>def truncate_to_3_decimal_places(s: str) -> str:</code></p>\n<p>The type-hints don't actually do anything; they are ignored by the Python interpreter. They are read by programs like <code>mypy</code>, which can use this static type information to spot possible errors in your program. They are also read and used by some documentation generating programs, which is very useful.</p>\n<h1>Doc-string</h1>\n<p><code> """ Convert 1234.12345678 to 1234.123"""</code></p>\n<p>I love doc-strings. But this one is a little lacking in detail. It looks like it says it converts a floating point value to another floating point value with fewer significant digits. But the function doesn't do that at all; the function expects and returns strings.</p>\n<p><code> """Convert '1234.12345678' to '1234.123'"""</code></p>\n<p>That is slightly clearer. The astute reader will see the single quotation marks, and realize it is not a numerical transformation, but a textual one.</p>\n<p>But, many questions are left unanswered. Does <code>'123.4567'</code> get rounded to <code>'123.457'</code>, or truncated to <code>'123.456'</code>?</p>\n<pre class=\"lang-py prettyprint-override\"><code> """\n Truncate the string representation of a float after 3 decimal places.\n\n >>> convert('1234.12345678')\n '1234.123'\n\n >>> convert('123.45678')\n '123.456'\n\n >>> convert('123')\n '123'\n """\n</code></pre>\n<p>That is better doc-string. It describes, in words, what the function is doing, and then goes on to provide three examples, the second showing the truncation, the third showing what happens when the string doesn't have a decimal point.</p>\n<p>As a bonus, the format of the examples in the doc-string allow the doc-string to do double duty. You can run <code>doctest.testmod()</code> on the module, and the examples become test-cases, and the output is compared with the documented output, and deviations are flagged.</p>\n<h1>Exceptional cases</h1>\n<p>The function does a few bizarre things.</p>\n<h2><code>len(vec) == 2</code></h2>\n<p>If and only if the string has 2 parts, will the length of the second part be tested.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> convert('192.168.0.1')\n'192.168.0.1'\n</code></pre>\n<p>Should the function have returned that value? Would <code>192.168</code> be a more expected result? Perhaps raising a <code>ValueError</code> would be even better?</p>\n<h2>Exponential Notation</h2>\n<pre class=\"lang-py prettyprint-override\"><code>>>> convert(str(1234567890123456.0))\n'1.234'\n\n>>> convert(str(0.000000001234))\n'1.234'\n</code></pre>\n<p>Whoa! Those results are unexpected! Clearly, it does not handle the floating point values in exponential representation.</p>\n<p>Is this a bug? Or is this a limitation, which should be spelt out in the docstring?</p>\n<h2>Alternate representation</h2>\n<pre class=\"lang-py prettyprint-override\"><code>>>> convert("123.4")\n'123.4'\n\n>>> convert("123.400321")\n'123.400'\n</code></pre>\n<p>The returned values would both represent the same floating point values, but their representations are different. Should the function add zeros to pad to 3 decimal places? Should this difference be mentioned in the doc-string?</p>\n<h1>Quality-of-Life</h1>\n<p>How is this function used? Do you already have the string representation of the floating point value, or are you converting the float-point value into a string for passing to the function?</p>\n<p>A function which takes a float, and converts it to a string, truncated to the desired precision might make handling special cases easier.</p>\n<h1>Internationalization</h1>\n<p>Some regions do not use the period (<code>.</code>) as the decimal indicator. A comma (<code>,</code>) may be used to separate the integral part from the fractional. For instance, an approximation to pi might appear as <code>3,14159</code>. Since you've hard-coded your function to split the string at the period character, the application would break in France.</p>\n<p>Using built-in formatting would take care of internationalization concerns. For instance, <code>f"{value:.3f}"</code> would convert <code>value</code> to a fixed-point string with 3 digits after the decimal point, even if the decimal point appears as the comma (<code>,</code>) character. However, it would <strong>round</strong> based on the digit that comes next, instead of <strong>truncating</strong> the value, which does not appear to match what you've written.</p>\n<p>You could explicitly truncate the value to the required resolution</p>\n<pre><code>value = math.trunc(value * 1000) / 1000\n</code></pre>\n<p>and then convert the result to a string using <code>f"{value:.3f}"</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T19:27:52.753",
"Id": "254616",
"ParentId": "254535",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254569",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-10T22:22:04.493",
"Id": "254535",
"Score": "2",
"Tags": [
"python",
"beginner",
"strings",
"formatting"
],
"Title": "Convert string format python"
}
|
254535
|
<p>I'm learning ML/DL and found the process of getting the data and labels quite tedious. There is not much details on how to get JPG files into H5, which is (afaik) the only way to work smoothly later on.</p>
<p>I wrote my own simple script, and would like to hear about modifications, to improve my Python syntax. And maybe there are shortcuts I'm not aware of.</p>
<pre><code>import h5py
import numpy as np
from glob import glob # import "submodule"
from PIL import Image
import matplotlib.pyplot as plt
# img source directory
src = "images/raw/cats/*"
# self explanatory
outfile = "images/clean/cat.hdf5"
listOfImages = glob(src)
# img loaded as JpegImageFile Object
oneImage = Image.open(listOfImages[0])
# open file
f = h5py.File(outfile, "w")
data = np.array(oneImage) #this is an array 200x200x3
# save dataset (ndarray but with more features)
dset = f.create_dataset("images", data=data) # array 200x200x3
# Check if files can be read from the h5py file
with h5py.File(outfile, "r") as f:
image = f['images']
print(image.shape, image.dtype)
plt.imshow(image)
plt.show()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T08:03:58.957",
"Id": "254544",
"Score": "0",
"Tags": [
"python-3.x",
"machine-learning"
],
"Title": "Convert JPG to H5 and plot the images"
}
|
254544
|
<p>I wrote the following C++ code a while ago to generate random graphs for a project I was working on:</p>
<pre><code>#include "stdafx.h"
#include <iostream>
#include <algorithm> // std::min_element, std::max_element
#include <sstream>
#include <fstream>
#include <string>
#include <iterator>
#include <random>
#include <vector>
#define NoOfNodes 30
struct GPU_data
{
int number_Copies;
int workItems;
int workGroups;
bool memory;
double power_consumption;
double execTime;
};
struct DAG_data
{
int processid; //Node's ID
int PEid; //Processor's ID to which node is assigned
std::vector<GPU_data> Node_config;
int precede;
int follow; //nodes following this node
int noOfCopies;
double transData;
double ExecTime;
double powerDraw;
};
void CreateandAssignEdges(DAG_data Sample, int NoOfEdges)
{
unsigned int i = 0;
if (Sample.processid == 0)
{
//parent process- so there will be no edges
Sample.precede = 0;
Sample.follow = rand()% NoOfEdges + 1;
}
else if (Sample.processid == NoOfNodes - 1)
{
//sink process- so there will be no following edges
Sample.follow = 0;
}
else
{
//which nodes will the edges connect to (Anywhere from among the following nodes, including the sink node)
Sample.follow = (Sample.processid + 1) + (std::rand() % (29 - (Sample.processid) + 1));
if (Sample.follow == 30)
{
Sample.follow -= 1;
}
}
}
DAG_data EdgeAssignment(DAG_data Sample, int NoOfEdges)
{
unsigned int i = 0;
if (Sample.processid == 0)
{
//parent process- so there will be no edges
Sample.precede = 0;
Sample.follow = rand() % NoOfEdges + 1;
return Sample;
}
else if (Sample.processid == NoOfNodes - 1)
{
//sink process- so there will be no following edges
Sample.follow = 0;
return Sample;
}
else
{
//which nodes will the edges connect to (Anywhere from among the following nodes, including the sink node)
Sample.follow = (Sample.processid + 1) + (std::rand() % (29 - (Sample.processid) + 1));
return Sample;
}
}
//Sample->precede = rand() % NoOfEdges;
//Sample->follow = rand() % NoOfEdges;
////Preceding and following edges of a node should not be the same.
//while (Sample->precede > Sample->follow || Sample->precede == Sample->follow)
//{
// //assign both edges again
// Sample->follow = rand() % NoOfEdges;
// Sample->precede = rand() % NoOfEdges;
//}
void whenPEisGPU(DAG_data Sample, int processorID)
{
GPU_data emptySet;
int i = 0;
int NoOfConfigs = rand() % 5;
GPU_data* sub_tasks = &emptySet;
while (i != NoOfConfigs)
{
sub_tasks->memory = rand() % 1;
sub_tasks->number_Copies = rand() % 3;
sub_tasks->workGroups = rand() % 10 +1;
sub_tasks->workItems = rand() % (sub_tasks->workGroups * 2) + 1;
sub_tasks->power_consumption = rand() % 250;
sub_tasks->execTime = rand() % (int)(Sample.ExecTime / 2);
Sample.Node_config.push_back(*sub_tasks);
i++;
}
}
void PESpecificParameters(DAG_data Sample, int processorID)
{
if (processorID == 0)
{
Sample.ExecTime = rand() % 100;
Sample.powerDraw = 0.0;
Sample.noOfCopies = 0;
}
else if (processorID == 1)
{
Sample.PEid = processorID;
//whenPEisGPU(Sample, processorID);
int i = 0;
int NoOfConfigs = rand() % 5;
GPU_data sub_tasks;
while (i != NoOfConfigs)
{
sub_tasks.memory = rand() % 1;
sub_tasks.number_Copies = rand() % 3+1;
sub_tasks.workGroups = rand() % 10 + 1;
sub_tasks.workItems = rand() % (sub_tasks.workGroups * 2) + 1;
sub_tasks.power_consumption = rand() % 250;
sub_tasks.execTime = rand() % (int)(Sample.ExecTime / 2);
Sample.Node_config.push_back(sub_tasks);
i++;
}
}
}
DAG_data PEParameters(DAG_data Sample, int processorID)
{
if (processorID == 0)
{
Sample.ExecTime = rand() % 100;
Sample.powerDraw = 0.0;
Sample.noOfCopies = 0;
return Sample;
}
else if (processorID == 1)
{
Sample.PEid = processorID;
//whenPEisGPU(Sample, processorID);
int i = 0;
int NoOfConfigs = rand() % 5;
GPU_data sub_tasks;
while (i != NoOfConfigs)
{
sub_tasks.memory = rand() % 1;
sub_tasks.number_Copies = rand() % 3 + 1;
sub_tasks.workGroups = rand() % 10 + 1;
sub_tasks.workItems = rand() % (sub_tasks.workGroups * 2) + 1;
sub_tasks.power_consumption = rand() % 250;
sub_tasks.execTime = rand() % (int)(Sample.ExecTime / 2) + 1;
Sample.Node_config.push_back(sub_tasks);
i++;
}
return Sample;
}
}
void generateEdges(std::vector<DAG_data> &myTaskGraph)
{
unsigned int i = 0;
while (i != myTaskGraph.size())
{
for (unsigned int j = (myTaskGraph[i].processid)+1; j < myTaskGraph.size(); j++)
{
if (myTaskGraph[i].follow == 30)
{
myTaskGraph[i].follow -= 1;
}
//create an edge between the current node and any of its following nodes according to the following random number
if (rand() % 100 < 30)
{
myTaskGraph[i].follow = j;
break;
}
}
i++;
}
}
int main()
{
DAG_data emptyDAG;
unsigned int i = 0;
std::ofstream myFile;
std::vector<DAG_data> All_DAGs;
while (i != NoOfNodes)
{
DAG_data DAG1;
DAG1.processid = i;
DAG1.transData = i + 1;
DAG1.PEid = 0;
DAG1= PEParameters(DAG1, DAG1.PEid);
DAG1= EdgeAssignment(DAG1, 10);
All_DAGs.push_back(DAG1);
//DAG1.Node_config.clear();
i++;
}
generateEdges(All_DAGs);
for (int h = 0; h < All_DAGs.size(); h++)
{
if (h % 2 != 0)
{
DAG_data forNewPE =PEParameters(All_DAGs[h], 1);
All_DAGs.push_back(forNewPE);
All_DAGs[h].Node_config.clear();
if (All_DAGs[h].processid ==29)
{
break;
}
}
}
myFile.open("TG_Data_30NewEdges.txt");
for (int i = 0; i < All_DAGs.size(); i++)
{
myFile << "Node id: " << All_DAGs[i].processid << std::endl;
myFile << "Following Edge: " << All_DAGs[i].follow << std::endl;
myFile << "Transfer Data: " << All_DAGs[i].transData << std::endl;
myFile << "Node PE: " << All_DAGs[i].PEid << std::endl;
if (All_DAGs[i].PEid == 0)
{
myFile << "Execution time: " << All_DAGs[i].ExecTime << std::endl;
}
else
{
myFile << "-------------------------------" << std::endl;
for (int j = 0; j < All_DAGs[i].Node_config.size(); j++)
{
myFile << "Execution time: " << All_DAGs[i].Node_config[j].execTime << std::endl;
myFile << "Copies: " << All_DAGs[i].Node_config[j].number_Copies << std::endl;
myFile << "Memory: " << All_DAGs[i].Node_config[j].memory << std::endl;
myFile << "Work-Items: " << All_DAGs[i].Node_config[j].workItems << std::endl;
myFile << "Work-Groups: " << All_DAGs[i].Node_config[j].workGroups << std::endl;
myFile << "Power: " << All_DAGs[i].Node_config[j].power_consumption << std::endl;
myFile << "++++++++++++++++++" << std::endl;
}
}
myFile << "=================" << std::endl;
}
myFile.close();
std::cout << "DONE NOW." << std::endl;
std::cin.get();
}
</code></pre>
<p>The code fulfilled its objective for me but there is a lot of room for improvement for this code. Please advise how this code can be rewritten to better adhere to the desired C++ practices.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T22:34:15.727",
"Id": "502476",
"Score": "0",
"body": "What is a DAG? I read the question and all answers, but it is still unclear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T23:17:34.660",
"Id": "502479",
"Score": "1",
"body": "@Aganju DAG stands for [Directed Acyclic Graph](https://en.wikipedia.org/wiki/Directed_acyclic_graph)."
}
] |
[
{
"body": "<blockquote>\n<pre><code>#define NoOfNodes 30\n</code></pre>\n</blockquote>\n<p>I think it would be better to use a <code>static constexpr</code> here rather than a preprocessor macro.</p>\n<blockquote>\n<pre><code> //which nodes will the edges connect to (Anywhere from among the following nodes, including the sink node)\n Sample.follow = (Sample.processid + 1) + (std::rand() % (29 - (Sample.processid) + 1));\n\n if (Sample.follow == 30)\n {\n Sample.follow -= 1;\n }\n</code></pre>\n</blockquote>\n<p>Where do the constants <code>29</code> and <code>30</code> come from? Should they be derived from <code>NoOfNodes</code> instead?</p>\n<p>It may be better to use the C++ <code><random></code> library than <code>std::rand()</code>.</p>\n<p><code>CreateandAssignEdges()</code> and <code>EdgeAssignment()</code> are very similar - I think the duplication can be greatly reduced.</p>\n<blockquote>\n<pre><code> //Sample->precede = rand() % NoOfEdges;\n //Sample->follow = rand() % NoOfEdges;\n\n ////Preceding and following edges of a node should not be the same.\n //while (Sample->precede > Sample->follow || Sample->precede == Sample->follow)\n //{\n // //assign both edges again\n // Sample->follow = rand() % NoOfEdges;\n // Sample->precede = rand() % NoOfEdges;\n //}\n</code></pre>\n</blockquote>\n<p>Chunks of commented-out code like this often become a problem, becoming out of date and inconsistent as the surrounding code changes. Either remove it, or find a way to ensure it gets compiled and unit-tested with the rest of the code.</p>\n<blockquote>\n<pre><code> myFile << "Node id: " << All_DAGs[i].processid << std::endl;\n myFile << "Following Edge: " << All_DAGs[i].follow << std::endl;\n myFile << "Transfer Data: " << All_DAGs[i].transData << std::endl;\n myFile << "Node PE: " << All_DAGs[i].PEid << std::endl;\n</code></pre>\n</blockquote>\n<p>There's no real need to flush <code>myFile</code> each statement - prefer <code>'\\n'</code> to <code>std::endl</code> for all of these (and most/all of the remaining uses).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T19:44:51.850",
"Id": "502039",
"Score": "0",
"body": "Thank you for this answer. Do you think it would be better to split my code into classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T19:45:50.323",
"Id": "502040",
"Score": "0",
"body": "_Where do the constants `29` and `30` come from? Should they be derived from `NoOfNodes` instead?_ Yes. Those values should be coming from `NoOfNodes`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T11:32:58.270",
"Id": "254550",
"ParentId": "254545",
"Score": "1"
}
},
{
"body": "<p>Important errors:</p>\n<ul>\n<li><p>your random isn't random (seed it)</p>\n</li>\n<li><p>your random isn't uniform (use uniform distributions rather than just taking\nthe modulus, which will skew the distribution)</p>\n</li>\n<li><p><code>precede</code> is often uninitialized; <code>NoOfConfigs</code> is often uninitialized, and never used?</p>\n</li>\n<li><p>The last loop before writing the output file <strong>modifies the collection while iterating</strong>:</p>\n<pre><code> for (size_t h = 0; h < nodes.size(); h++) {\n // ...\n nodes.push_back(forNewPE);\n</code></pre>\n<p>This is an anti-pattern. You only just get away with it because of</p>\n<pre><code> if (nodes[h].processid == 29) { break; }\n</code></pre>\n<p>which of course suffers from magic numbers, and could easily have been put\nin the loop condition instead:</p>\n<pre><code> for (size_t h = 0; h < NoOfNodes; ++h) {\n</code></pre>\n</li>\n<li><p><code>void PESpecificParameters(DAG_data Sample, int processorID)</code> is not used.</p>\n<p>When used, it will never have any effect (because it has netiher return\nvalues nor holds references to anything outside)</p>\n</li>\n<li><p>Same with <code>whenPEisGPU</code></p>\n</li>\n<li><p>After removing duplicate code, it looks like <code>PEParameters</code> was identical to <code>PESpecificParameters</code> (see below)</p>\n</li>\n<li><p>Likewise <code>CreateandAssignEdges</code> was unused and seems to be duplicating <code>EdgeAssignment</code>?</p>\n</li>\n</ul>\n<p>Major notes:</p>\n<ul>\n<li><p>Naming! <code>DAG_Data</code> means next to nothing. Your graph model represents\n<em>something</em> in real life. The fact that it is a DAG is like calling\nvariables "textstring" instead of "FirstName" and "ZipCode"</p>\n</li>\n<li><p>Extract some functions. Use them to</p>\n<ul>\n<li>separate responsibilities,</li>\n<li>levels of abstraction</li>\n<li>reduce duplication</li>\n</ul>\n</li>\n<li><p>Optionally group related functions with their data into classes (see "BONUS" section below)</p>\n</li>\n</ul>\n<hr />\n<p>Here comes a blow by blow of things I addressed:</p>\n<ol>\n<li><p>Use warnings (-Wall -Wextra -pedantic at minimum) and swat them:</p>\n<pre><code>test.cpp:43:18: warning: unused variable ‘i’ [-Wunused-variable]\n 43 | unsigned int i = 0;\ntest.cpp:74:18: warning: unused variable ‘i’ [-Wunused-variable]\n 74 | unsigned int i = 0;\ntest.cpp:119:39: warning: unused parameter ‘processorID’ [-Wunused-parameter]\n 119 | void whenPEisGPU(DAG_data Sample, int processorID)\ntest.cpp:259:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<DAG_data>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]\n 259 | for (int h = 0; h < All_DAGs.size(); h++)\ntest.cpp:277:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<DAG_data>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]\n 277 | for (int i = 0; i < All_DAGs.size(); i++)\ntest.cpp:290:31: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<GPU_data>::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]\n 290 | for (int j = 0; j < All_DAGs[i].Node_config.size(); j++)\ntest.cpp:204:1: warning: control reaches end of non-void function [-Wreturn-type]\n 204 | }\n</code></pre>\n<p>Changes:</p>\n<pre><code>CreateandAssignEdges:\n- unsigned int i = 0;\n\nEdgeAssignment:\n- unsigned int i = 0;\n\n-void whenPEisGPU(DAG_data Sample, int processorID)\n+void whenPEisGPU(DAG_data Sample, int /*processorID*/)\n\nPEParameters:\n+ throw std::range_error("processorID");\n\n- for (int h = 0; h < All_DAGs.size(); h++)\n+ for (size_t h = 0; h < All_DAGs.size(); h++)\n\n- for (int i = 0; i < All_DAGs.size(); i++)\n+ for (size_t i = 0; i < All_DAGs.size(); i++)\n\n- for (int j = 0; j < All_DAGs[i].Node_config.size(); j++)\n+ for (size_t j = 0; j < All_DAGs[i].Node_config.size(); j++)\n</code></pre>\n</li>\n<li><p>Running modernize/readability check shows a lot of magic number warning and some easy improvements:</p>\n<pre><code>clang-apply-replacements version 9.0.0\nclang-tidy-9 -header-filter=.* -checks=-*,readability-*,modernize-*,-modernize-use-trailing-return-type -export-fixes /tmp/tmp6CfbSr/tmpYGk6CX.yaml -p=/home/sehe/Projects/stackoverflow /home/sehe/Projects/stackoverflow/test.cpp\n/home/sehe/Projects/stackoverflow/test.cpp:59:66: warning: 29 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n Sample.follow = (Sample.processid + 1) + (std::rand() % (29 - (Sample.processid) + 1));\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:61:30: warning: 30 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n if (Sample.follow == 30)\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:81:5: warning: do not use 'else' after 'return' [readability-else-after-return]\n else if (Sample.processid == NoOfNodes - 1)\n ^~~~~\n/home/sehe/Projects/stackoverflow/test.cpp:92:66: warning: 29 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n Sample.follow = (Sample.processid + 1) + (std::rand() % (29 - (Sample.processid) + 1));\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:119:32: warning: 5 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n int NoOfConfigs = rand() % 5;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:123:29: warning: implicit conversion 'int' -> bool [readability-implicit-bool-conversion]\n sub_tasks->memory = rand() % 1;\n ^\n (( ) != 0)\n/home/sehe/Projects/stackoverflow/test.cpp:125:42: warning: 10 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n sub_tasks->workGroups = rand() % 10 +1;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:127:49: warning: 250 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n sub_tasks->power_consumption = rand() % 250;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:138:36: warning: 100 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n Sample.ExecTime = rand() % 100;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:148:36: warning: 5 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n int NoOfConfigs = rand() % 5;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:152:32: warning: implicit conversion 'int' -> bool [readability-implicit-bool-conversion]\n sub_tasks.memory = rand() % 1;\n ^\n (( ) != 0)\n/home/sehe/Projects/stackoverflow/test.cpp:154:45: warning: 10 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n sub_tasks.workGroups = rand() % 10 + 1;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:156:52: warning: 250 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n sub_tasks.power_consumption = rand() % 250;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:170:36: warning: 100 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n Sample.ExecTime = rand() % 100;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:177:5: warning: do not use 'else' after 'return' [readability-else-after-return]\n else if (processorID == 1)\n ^~~~~\n/home/sehe/Projects/stackoverflow/test.cpp:182:36: warning: 5 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n int NoOfConfigs = rand() % 5;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:186:32: warning: implicit conversion 'int' -> bool [readability-implicit-bool-conversion]\n sub_tasks.memory = rand() % 1;\n ^\n (( ) != 0)\n/home/sehe/Projects/stackoverflow/test.cpp:188:45: warning: 10 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n sub_tasks.workGroups = rand() % 10 + 1;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:190:52: warning: 250 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n sub_tasks.power_consumption = rand() % 250;\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:211:42: warning: 30 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n if (myTaskGraph[i].follow == 30)\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:216:26: warning: 100 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n if (rand() % 100 < 30)\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:216:32: warning: 30 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n if (rand() % 100 < 30)\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:246:36: warning: 10 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n DAG1= EdgeAssignment(DAG1, 10);\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:264:41: warning: 29 is a magic number; consider replacing it with a named constant [readability-magic-numbers]\n if (All_DAGs[h].processid ==29)\n ^\n/home/sehe/Projects/stackoverflow/test.cpp:274:5: warning: use range-based for loop instead [modernize-loop-convert]\n for (size_t i = 0; i < All_DAGs.size(); i++)\n ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n (auto & All_DAG : All_DAGs)\n7510 warnings generated.\nSuppressed 7485 warnings (7485 in non-user code).\nUse -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.\nApplying fixes ...\n</code></pre>\n<p>At least take the ranged-for loop immediately:</p>\n<pre><code>for (auto& DAG : All_DAGs)\n{\n myFile << "Node id: " << DAG.processid << std::endl;\n myFile << "Following Edge: " << DAG.follow << std::endl;\n myFile << "Transfer Data: " << DAG.transData << std::endl;\n myFile << "Node PE: " << DAG.PEid << std::endl;\n if (DAG.PEid == 0)\n {\n myFile << "Execution time: " << DAG.ExecTime << std::endl;\n }\n else\n {\n myFile << "-------------------------------" << std::endl;\n for (auto& cfg : DAG.Node_config)\n {\n myFile << "Execution time: " << cfg.execTime << std::endl;\n myFile << "Copies: " << cfg.number_Copies << std::endl;\n myFile << "Memory: " << cfg.memory << std::endl;\n myFile << "Work-Items: " << cfg.workItems << std::endl;\n myFile << "Work-Groups: " << cfg.workGroups << std::endl;\n myFile << "Power: " << cfg.power_consumption << std::endl;\n myFile << "++++++++++++++++++" << std::endl;\n }\n }\n myFile << "=================" << std::endl;\n}\n</code></pre>\n</li>\n<li><p>Don't unnecessarily separate initialization from declaration.</p>\n<pre><code>std::ofstream myFile;\n// 40 lines...\nmyFile.open("TG_Data_30NewEdges.txt");\n</code></pre>\n<p>Don't unnecessarily manually resource manage:</p>\n<pre><code>myFile.close();\n</code></pre>\n<p>C++'s RAII pattern means the file will always be closed.</p>\n<pre><code>{\n std::ofstream output("TG_Data_30NewEdges.txt");\n\n for (auto& DAG : All_DAGs)\n {\n // ...\n }\n}\n</code></pre>\n<p>Note I also renamed <code>myFile</code> to something more descriptive.</p>\n</li>\n<li><p>Time to extract some functions for the above:</p>\n<pre><code>std::ofstream output("TG_Data_30NewEdges.txt");\nwriteReport(output, All_DAGs);\n</code></pre>\n<p>And then somewhere else:</p>\n<pre><code>using DAGs = std::vector<DAG_data>;\n\nvoid writeReport(std::ostream& output, DAGs const& graphs) {\n for (auto& g : graphs) {\n // ...\n }\n}\n</code></pre>\n</li>\n<li><p>De-mystify loops</p>\n<pre><code>unsigned int i = 0;\nwhile (i != myTaskGraph.size()) {\n // ...\n i++;\n}\n</code></pre>\n<p>Is conventionally written as</p>\n<pre><code>for (size_t i = 0; i < myTaskGraph.size(); ++i) {\n // ...\n}\n</code></pre>\n<p>Or, ever since c++0x:</p>\n<pre><code>for (Node& node : myTaskGraph) {\n // ...\n}\n</code></pre>\n</li>\n<li><p>Likewise the loops that build containers should probably read more like:</p>\n<pre><code>Nodes nodes(NoOfNodes);\n\nsize_t i = 0;\nfor (auto& current : nodes) {\n current.processid = i;\n current.transData = i + 1;\n current.PEid = 0;\n\n i++;\n\n current = PEParameters(current, current.PEid);\n current = EdgeAssignment(current, 10);\n}\n</code></pre>\n<p>And</p>\n<pre><code>void whenPEisGPU(Node& node, int /*processorID*/)\n{\n int NoOfConfigs = rand() % 5;\n node.Node_config.assign(NoOfConfigs, {});\n\n for (auto& sub_task : node.Node_config) {\n sub_task.memory = ((rand() % 1) != 0);\n sub_task.number_Copies = rand() % 3;\n sub_task.workGroups = rand() % 10 +1;\n sub_task.workItems = rand() % (sub_task.workGroups * 2) + 1;\n sub_task.power_consumption = rand() % 250;\n sub_task.execTime = rand() % (int)(node.ExecTime / 2);\n }\n}\n</code></pre>\n<p>etc.</p>\n<blockquote>\n<p>I'd probably write them as <code>std::generate_n</code> calls in real life, but\nmaybe we'll naturally arrive there, later below</p>\n</blockquote>\n</li>\n<li><p>Naming. Somewhere halfway the code, suddenly we get a glimpse of what we're really dealing with:</p>\n<pre><code>void generateEdges(std::vector<DAG_data> &myTaskGraph)\n</code></pre>\n<p>So, I guess we could name <code>DAG_data</code> <code>Node</code> or <code>Task</code> (or even <code>TaskNode</code>?).</p>\n<p>Likewise, we get subtle hints here:</p>\n<pre><code>if (Sample.processid == 0) {\n //parent process- so there will be no edges\n</code></pre>\n<p>and</p>\n<pre><code>else if (node.processid == NoOfNodes - 1) {\n // sink process- so there will be no following edges\n</code></pre>\n<blockquote>\n<p>Side Note: you use <code>parent</code> as if it means "no edges". Which is\ndemonstratively inaccurate, because you immediately <strong>do</strong> set a follower\nedge. What you seem to mean is the "parent without a parent", which in a\nDAG is usually known as a "root". Note also, that if you have a DAG with\nonly 1 root, why not call it a Tree?</p>\n<p>// file under: naming is important</p>\n</blockquote>\n<p>So, we should make that more readable:</p>\n<pre><code>using ProcessID = int;\nstatic constexpr size_t NoOfNodes = 30;\nstatic constexpr ProcessID RootNodeId = 0;\nstatic constexpr ProcessID SinkNodeId = NoOfNodes - 1;\n\n// ...\nstatic bool constexpr IsSink(ProcessID id) { return SinkNodeId == id; }\nstatic bool constexpr IsSink(Node const& node) { return IsSink(node.processid); }\n// etc?\n</code></pre>\n</li>\n<li><p>In fact, maybe it's better to combine the whole thing:</p>\n<pre><code>enum ProcessID : int {\n RootNodeId = 0,\n NoOfNodes = 30,\n SinkNodeId = NoOfNodes -1,\n};\n</code></pre>\n<p>This leads to a great reduction of all magic numbers (<code> = 0</code> becomes <code>= RootNodeId</code> etc).</p>\n<p>However, it forces us to address the problem with the other "magic" assignements:</p>\n<pre><code>node.follow = rand() % NoOfEdges + 1;\nnode.follow =\n (node.processid + 1) + (std::rand() % (29 - (node.processid) + 1));\n</code></pre>\n<p>I mean, we were going to address those anways (because, ugh and skewed random).</p>\n</li>\n<li><p>So, let's address random! You started out correctly:</p>\n<pre><code>#include <random>\n</code></pre>\n<p>but never used a thing from that <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"noreferrer\">treasure trove</a>!</p>\n<pre><code>std::mt19937 prng { std::random_device{} () };\n</code></pre>\n<p>Now we have our UniformRandomBitGenerator <strong>and</strong> we securely seeded it!</p>\n<p>Let's create some helper functions that will help us generate uniformly distributed numbers:</p>\n<p>Generate numbers up to and including max:</p>\n<pre><code>auto gen_number(int max, bool includeZero = true) {\n using Dist = std::uniform_int_distribution<>;\n using Param = Dist::param_type;\n static Dist dist;\n\n auto min = includeZero? 0:1;\n assert(max >= min);\n return dist(prng, Param(min, max));\n}\n</code></pre>\n<p>Adding a short hand for [1, max] random sample:</p>\n<pre><code>auto gen_positive(int max) {\n return gen_number(max, false);\n}\n</code></pre>\n<p>Now, to generate ProcessID we need some conversions and we can assume some\ndefaults for the range limits:</p>\n<pre><code>ProcessID gen_follower(int from = FirstFollow, int to = NoOfNodes) {\n using T = std::underlying_type_t<ProcessID>;\n using Dist = std::uniform_int_distribution<T>;\n using Param = Dist::param_type;\n\n static Param full{static_cast<T>(FirstFollow), static_cast<T>(NoOfNodes)};\n static Dist dist(full);\n\n return static_cast<ProcessID>(dist(prng, Param(from, to)));\n}\n</code></pre>\n<p>Now we can rephrase the expressions:</p>\n<pre><code>// node.follow = rand() % NoOfEdges + 1;\nnode.follow = gen_follower(FirstFollow, NoOfEdges);\n</code></pre>\n<p>And</p>\n<pre><code>// node.follow =\n// (node.processid + 1) + (std::rand() % (29 - (node.processid) + 1));\nnode.follow = gen_follower(node.processid+1);\n</code></pre>\n<blockquote>\n<p>Much simpler, type-safe and uniform!</p>\n</blockquote>\n<p>Now, there's some weird things about this.</p>\n<ul>\n<li><p>Everywhere <code>follow</code> is implied to be from the <code>ProcessId</code> domain.\nHowever, the expression <code>gen_follower(FirstFollow, NoOfEdges)</code> uses\n<code>NoOfEdges</code> instead of <code>NoOfNodes</code>?! <code>NoOfEdges</code> is also just hardcoded\nat <code>10</code> for the one call to <code>EdgeAssignment</code>.</p>\n<p>Are you sure you meant to "arbitrarily" limit follower nodes for the\nRoot Node to <code>[1..10]</code> regardless of <code>NoOfNodes</code>?</p>\n<blockquote>\n<p>Since subsequent followers are always taken "down-stream" I can\n<strong>guess</strong> that you wanted to pick from a "first 10" partition only to\nincrease the likelihood of subtasks to beget "grand children". If so,\nthe name <code>NoOfEdges</code> is completely misleading, and could be something\nlike <code>FirstGenerationNodes</code>?)</p>\n</blockquote>\n</li>\n<li><p>There are <em><strong>two</strong></em> locations where the result of these expressions is being corrected:</p>\n<pre><code> if (myTaskGraph[i].follow == 30) {\n myTaskGraph[i].follow -= 1;\n }\n\n if (Sample.follow == 30) {\n Sample.follow -= 1;\n }\n</code></pre>\n<p>If that's the desired range, simply fix your expressions!</p>\n<p>As written it makes the code hard to understand, spreads responsibility\nacross functions (which invites bugs) and also further skews the\ndistribution: <code>29</code> is now a much more likely edge target.</p>\n<p>I chose to fix the expression to match the implied intent from this other comment:</p>\n<pre><code>// which nodes will the edges connect to (Anywhere from among the\n// following nodes, including the sink node)\nnode.follow = gen_follower(node.processid+1, SinkNodeId);\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p>Code duplication. The generation of subtasks (<code>node.Node_config</code>) is\nduplicated, with some spurious differences that might be bugs, but could be\nintentional?</p>\n<p>E.g.:</p>\n<pre><code>sub_task.number_Copies = rand() % 3 + 1;\n</code></pre>\n<p>One of three copies omit <code>+1</code> which is likely a bug.</p>\n<p>In similar fashion we see one copy of</p>\n<pre><code>sub_task.execTime = rand() % static_cast<int>(node.ExecTime / 2);\n</code></pre>\n<p>that adds an <code>+1</code>. Likely this avoids zero <code>execTime</code>, and is a code smell that this too should have been a strong-typed, uniform real random distribution.</p>\n<blockquote>\n<p>It's hard to guess what you actually want <code>execTime</code> to mean. If you mean\nit to be such that parent node's execTime always totals the sum of their\nsubtasks, that is much easier to express with some business logic, rather\nthan having the data redundant in your datastructure and add undocumented\ninvariants (which, again, invite bugs).</p>\n<p>For fun, I added how I'd write the distribution on a whim:</p>\n<pre><code> void distributeExecTime(Node& node) {\n std::vector<double> weights;\n std::uniform_real_distribution<> dist;\n std::generate_n(\n back_inserter(weights),\n node.Node_config.size(),\n [&dist] { return dist(prng); });\n\n auto total_w = std::accumulate(begin(weights), end(weights), 0.);\n\n for (size_t i = 0; i < weights.size(); ++i) {\n node.Node_config[i].execTime = (weights[i]/total_w) * node.ExecTime;\n }\n }\n</code></pre>\n</blockquote>\n</li>\n<li><p>For total power draw there seems to be similar things going on. Perhaps you can replace powerDraw with a function:</p>\n<pre><code>double powerDraw() const {\n return std::accumulate(begin(Node_config), end(Node_config), 0.);\n};\n</code></pre>\n</li>\n</ol>\n<h2>BONUS</h2>\n<p>Going over the edge, we can envision a world where the generating is "automatic", as is the reporting:</p>\n<ul>\n<li><p>Consider moving generation into constructors:</p>\n<pre><code> struct GPU_data {\n int number_Copies = gen_positive(3);\n int workGroups = gen_positive(10); // order is important!\n int workItems = gen_positive(workGroups * 2);\n bool memory = odds(50);\n double power_consumption = gen_real(249);\n double execTime = 0; // see distributeExecTime\n };\n</code></pre>\n<blockquote>\n<p>Note</p>\n<ul>\n<li>we're using C++11 NSMI to generate the default constructor for us</li>\n</ul>\n</blockquote>\n<pre><code> struct Node {\n enum Type { CPUNode, GPUNode };\n\n Type PEid; // Processor's ID to which node is assigned\n ProcessID processid; // Node's ID\n Configs sub_tasks;\n ProcessID follow = RootNodeId; // nodes following this node\n double transData = 0;\n double ExecTime = 0;\n\n explicit Node(int id, int NoOfEdges = 10)\n : PEid(CPUNode),\n processid(ProcessID(id)),\n transData(id + 1)\n {\n PEParameters();\n EdgeAssignment(NoOfEdges);\n }\n\n explicit Node(Node const& node)\n : PEid(GPUNode),\n processid(node.processid),\n sub_tasks(),\n follow(node.follow),\n transData(node.transData),\n ExecTime(node.ExecTime)\n {\n PEParameters();\n }\n\n double powerDraw() const;\n bool isGPU() const { return PEid == GPUNode; }\n\n private:\n void PEParameters();\n void EdgeAssignment(int NoOfEdges);\n void distributeExecTime();\n };\n</code></pre>\n<p>Now, <code>Node</code> can group with it's manipulating functions:</p>\n<blockquote>\n<ul>\n<li><p>This sort of assumes the types are not already in use elsewhere. In case\nthat's not the case, we can sub-class the types and benefit from object\nslicing to convert back to its base class.</p>\n</li>\n<li><p>Note as well that several places in the code (PEParameters, output and\nEdgeAssignment) switch behaviour on PEid which apparently has only two\nvalid values. I've changed that to be an enum reflecting that fact:</p>\n<pre><code>enum Type { CPUNode, GPUNode };\nType PEid; // Processor's ID to which node is assigned\n</code></pre>\n<p>As an exercise for the reader, it might make sense to change <code>Node</code> to some kind of polymorphic type instead of switching all the time:</p>\n<pre><code>using Node = std::variant<CPUNode, GPUNode>;\n</code></pre>\n<p>Or using virtual types (inheritance).</p>\n</li>\n</ul>\n</blockquote>\n</li>\n</ul>\n<h2>Demo Listing(s)</h2>\n<p>All revisison are here in a Gist: <a href=\"https://gist.github.com/sehe/32c07118031a049042bd9fb469355caf/revisions\" rel=\"noreferrer\">https://gist.github.com/sehe/32c07118031a049042bd9fb469355caf/revisions</a></p>\n<p><strong><a href=\"http://coliru.stacked-crooked.com/a/a4e46b62b35e6a0d\" rel=\"noreferrer\">Live On Coliru</a></strong></p>\n<pre><code>#include <iostream>\n#include <algorithm> // std::min_element, std::max_element\n#include <fstream>\n#include <string>\n#include <random>\n#include <vector>\n#include <cassert>\n\nnamespace {\n static std::mt19937 prng { std::random_device{} () };\n\n enum ProcessID : int {\n RootNodeId /*= 0 */,\n NoOfNodes = 30,\n\n FirstFollow = RootNodeId +1,\n SinkNodeId = NoOfNodes -1,\n };\n\n auto gen_number(int max, bool includeZero = true) {\n using Dist = std::uniform_int_distribution<>;\n using Param = Dist::param_type;\n static Dist dist;\n\n auto min = includeZero? 0:1;\n assert(max >= min);\n return dist(prng, Param(min, max));\n }\n\n auto gen_positive(int max) {\n return gen_number(max, false);\n }\n\n ProcessID gen_follower(int from = FirstFollow, int to = NoOfNodes) {\n using T = std::underlying_type_t<ProcessID>;\n using Dist = std::uniform_int_distribution<T>;\n using Param = Dist::param_type;\n\n static Param full{static_cast<T>(FirstFollow), static_cast<T>(NoOfNodes)};\n static Dist dist(full);\n\n return static_cast<ProcessID>(dist(prng, Param(from, to)));\n }\n\n bool odds(int percentage) {\n if (percentage == 100)\n return true;\n assert(percentage > 0 && percentage < 100);\n return std::discrete_distribution<bool>(percentage, 100-percentage)(prng);\n }\n\n double gen_real(double mean = 100.0, double stddev = 0) {\n if (stddev == 0)\n stddev = mean/4;\n assert(stddev>0);\n return std::normal_distribution(mean, stddev)(prng);\n }\n}\n\nstruct GPU_data {\n int number_Copies = gen_positive(3);\n int workGroups = gen_positive(10); // order is important!\n int workItems = gen_positive(workGroups * 2);\n bool memory = odds(50);\n double power_consumption = gen_real(249);\n double execTime = 0; // see distributeExecTime\n};\n\nusing Configs = std::vector<GPU_data>;\n\nstruct Node {\n enum Type { CPUNode, GPUNode };\n\n Type PEid; // Processor's ID to which node is assigned\n ProcessID processid; // Node's ID\n Configs sub_tasks;\n ProcessID follow = RootNodeId; // nodes following this node\n double transData = 0;\n double ExecTime = 0;\n\n explicit Node(int id, int NoOfEdges = 10)\n : PEid(CPUNode),\n processid(ProcessID(id)),\n transData(id + 1)\n {\n PEParameters();\n EdgeAssignment(NoOfEdges);\n }\n\n explicit Node(Node const& node)\n : PEid(GPUNode),\n processid(node.processid),\n sub_tasks(),\n follow(node.follow),\n transData(node.transData),\n ExecTime(node.ExecTime)\n {\n PEParameters();\n }\n\n double powerDraw() const {\n double total = 0;\n for (auto& sub: sub_tasks) {\n total += sub.power_consumption;\n }\n return total;\n };\n\n bool isGPU() const { return PEid == GPUNode; }\n\n private:\n void PEParameters() {\n switch(PEid) {\n case CPUNode:\n ExecTime = gen_real(100.0);\n break;\n case GPUNode:\n sub_tasks.resize(gen_number(5));\n distributeExecTime();\n break;\n default:\n throw std::range_error("PEid");\n }\n }\n\n void EdgeAssignment(int NoOfEdges) {\n if (processid == RootNodeId) {\n // parent process- so there will be no edges\n follow = gen_follower(FirstFollow, NoOfEdges);\n }\n else if (processid == SinkNodeId) {\n // sink process- so there will be no following edges\n follow = RootNodeId;\n }\n else {\n // which nodes will the edges connect to (Anywhere from among the\n // following nodes, including the sink node)\n follow = gen_follower(processid+1, SinkNodeId);\n }\n }\n\n void distributeExecTime() {\n std::vector<double> weights;\n std::uniform_real_distribution<> dist;\n std::generate_n(\n back_inserter(weights),\n sub_tasks.size(),\n [&dist] { return dist(prng); });\n\n auto total_w = std::accumulate(begin(weights), end(weights), 0.);\n\n for (size_t i = 0; i < weights.size(); ++i) {\n sub_tasks[i].execTime = (weights[i]/total_w) * ExecTime;\n }\n }\n};\n\nusing Nodes = std::vector<Node>;\n\nvoid generateEdges(Nodes& nodes) {\n for (Node& node : nodes) {\n // Create an edges to following nodes given 30% odds\n for (size_t j = node.processid+1; j < nodes.size(); j++) {\n if (odds(30)) {\n node.follow = static_cast<ProcessID>(j); \n break;\n } \n }\n }\n}\n\nstatic std::ostream& operator<<(std::ostream& os, Node const& n);\n\nint main() {\n Nodes nodes;\n for (auto id = 0; id < NoOfNodes; ++id) {\n nodes.emplace_back(id);\n }\n\n generateEdges(nodes);\n\n for (size_t h = 0; h < NoOfNodes; h++) {\n if (h % 2 == 0)\n continue;\n\n nodes.emplace_back(nodes[h]);\n nodes[h].sub_tasks.clear();\n }\n\n std::ofstream output("TG_Data_30NewEdges.txt");\n for (auto& n : nodes) {\n output << n << "=================\\n";\n }\n\n std::cout << "DONE" << std::endl;\n}\n\nstatic std::ostream& operator<<(std::ostream& os, GPU_data const& cfg) {\n return os \n << "Execution time: " << cfg.execTime << "\\n"\n << "Copies: " << cfg.number_Copies << "\\n"\n << "Memory: " << cfg.memory << "\\n"\n << "Work-Items: " << cfg.workItems << "\\n"\n << "Work-Groups: " << cfg.workGroups << "\\n"\n << "Power: " << cfg.power_consumption << "\\n";\n}\n\nstatic std::ostream& operator<<(std::ostream& os, Node const& n) {\n os << "Node id: " << n.processid << "\\n"\n << "Following Edge: " << n.follow << "\\n"\n << "Transfer Data: " << n.transData << "\\n"\n << "Node powerDraw: " << n.powerDraw() << "\\n"\n << "Node PE: " << n.PEid << "\\n";\n\n if (n.isGPU()) {\n os << "-------------------------------\\n";\n for (auto& cfg : n.sub_tasks) {\n os << cfg << "++++++++++++++++++\\n";\n }\n } else {\n os << "Execution time: " << n.ExecTime << "\\n";\n }\n return os;\n}\n</code></pre>\n<p>Prints, e.g.</p>\n<pre><code>DONE\n</code></pre>\n<p>And generates TG_Data_30NewEdges.txt:</p>\n<pre><code>Node id: 0\nFollowing Edge: 1\nTransfer Data: 1\nNode powerDraw: 1020.61\nNode PE: 1\n-------------------------------\nExecution time: 12.2428\nCopies: 1\nMemory: 1\nWork-Items: 10\nWork-Groups: 9\nPower: 229.989\n++++++++++++++++++\nExecution time: 39.2756\nCopies: 1\n\n// ...\n// 825 lines snipped\n// ...\n\nCopies: 3\nMemory: 1\nWork-Items: 3\nWork-Groups: 9\nPower: 235.512\n++++++++++++++++++\n=================\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T19:58:07.510",
"Id": "502143",
"Score": "1",
"body": "Added all revisison are here in a Gist: https://gist.github.com/sehe/32c07118031a049042bd9fb469355caf/revisions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:51:26.250",
"Id": "502261",
"Score": "1",
"body": "Thank you very much for responding to my request to review my code and thank you again for posting such a comprehensive review. The \"new\" code has many C++ concepts I did not know about earlier. I can enhance my C++ knowledge considerably just by reading this review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T15:44:29.017",
"Id": "504380",
"Score": "0",
"body": "What's happening?! A month later I suddenly get a stream of upvotes on this answer :) Not complaining, just confused"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-05T07:21:01.627",
"Id": "504440",
"Score": "0",
"body": "It's on the c++ subreddit "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-05T07:22:43.353",
"Id": "504441",
"Score": "0",
"body": "I just have to say how impressed I am at the level of detail and positive advice you've given here, it's really impressive. I can only imagine how much time it took you. Really wholesome and generous. Kudos"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-06T21:39:38.917",
"Id": "504627",
"Score": "0",
"body": "@sehe The code in the question more or less represents the height of my C++ knowledge. I am going to read [A Tour of C++](https://www.amazon.ca/Tour-C-2nd-Bjarne-Stroustrup/dp/0134997832) to enhance my knowledge and understanding of C++. Do you have any further suggestions for me?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T19:34:12.007",
"Id": "254617",
"ParentId": "254545",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "254617",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T08:18:50.680",
"Id": "254545",
"Score": "3",
"Tags": [
"c++"
],
"Title": "C++ code to generate random DAGs"
}
|
254545
|
<p>I have implemented a C code in order to answer an interview question. I would be appreciated if someone would improve the code. Task is an easy, however I want to achieve best efficiency in terms of readability and simplicity. Pardon my English again.</p>
<ul>
<li>Sorry that I have just printed out the result.</li>
</ul>
<blockquote>
<p>The edit distance between two strings refers to the minimum number of
character insertions, deletions, and substitutions required to change
one string to the other. For example, the edit distance between
“kitten” and “sitting” is three: substitute the “k” for “s”,
substitute the “e” for “i”, and append a “g”.</p>
<p>Given two strings, compute the edit distance between them.</p>
</blockquote>
<p><strong>CODE:</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int count_edit_dist(const char list1[],
const char list2[])
{
unsigned int count=0;
size_t len_str1 = strlen(list1);
size_t len_str2 = strlen(list2);
for(int i=0; list1[i]!='\0'; i++)
{
if(list2[i]=='\0') //means len(list2) < len(list1)
{
count += (unsigned int)(len_str1 - len_str2);
return count;
}
if(list1[i] != list2[i])
count++;
}
//reacing here means len(list1) <= len(list2)
count += (unsigned int)(len_str2 - len_str1);
return count;
}
int main(void)
{
unsigned int count;
char list1[] = "category";
char list2[] = "caterirrrr";
count = count_edit_dist(list1, list2);
printf("edit distance between strings: %u\n", count);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-25T07:59:48.223",
"Id": "531378",
"Score": "0",
"body": "the program gives edit distance as 7 b/w 'sunday' and 'saturday'"
}
] |
[
{
"body": "<p><strong>Minimum edit distance</strong></p>\n<p><code>count_edit_dist()</code> does return a value, yet it is certainly not the <em>minimum</em> possible edit distance as defined. To compute the minimum, a fair amount more code is needed.</p>\n<hr />\n<p>Small stuff</p>\n<p><strong><code>unsigned</code> vs. <code>size_t</code> vs. <code>int</code></strong></p>\n<p>For practical uses, makes no difference, yet code would avoid casting by using <code>size_t</code> and making the <code>printf()</code> format strings agree. <code>size_t</code> also correctly handles extreme cases.</p>\n<pre><code>// unsigned int count=0;\nsize_t count=0;\n</code></pre>\n<p><code>size_t</code> is the best full range type for array indexing:</p>\n<pre><code>// for(int i=0; list1[i]!='\\0'; i++)\nfor(size_t i=0; list1[i]!='\\0'; i++)\n</code></pre>\n<p><strong>Declare when needed</strong></p>\n<p>Instead of defining variables far from their first use ...</p>\n<blockquote>\n<pre><code>unsigned int count;\n...\ncount = count_edit_dist(list1, list2);\n</code></pre>\n</blockquote>\n<p>... consider defining when needed:</p>\n<pre><code>...\nunsigned int count = count_edit_dist(list1, list2);\n</code></pre>\n<p><strong>Spell check</strong></p>\n<p>Run spell checker.</p>\n<pre><code>// vv \n//reacing here means len(list1) <= len(list2)\n//reaching\n</code></pre>\n<p><strong>Consider a more informative output</strong></p>\n<pre><code>printf("Edit distance between strings \\"%s\\" and \\"%s\\": %u\\n", list1, list2, count);\n</code></pre>\n<p><strong>Testing with some form of <code>!</code></strong></p>\n<p>I find alternatives that avoid a form of negation easier to follow. Yet this is a style issue - best to code to your group's style guide.</p>\n<pre><code>// for(int i=0; list1[i]!='\\0'; i++)\nfor (int i=0; list1[i]; i++)\n</code></pre>\n<hr />\n<ul>\n<li><p>Good formatting</p>\n</li>\n<li><p>Good use of <code>const</code> in <code>unsigned int count_edit_dist(const char list1[], const char list2[])</code></p>\n</li>\n<li><p>Style: I'd use <code>unsigned</code> rather than <code>unsigned int</code>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T19:03:29.580",
"Id": "254564",
"ParentId": "254546",
"Score": "4"
}
},
{
"body": "<p>Running <code>strlen()</code> at the beginning is unecessary and can be replaced with a simpler <code>while</code> loop.</p>\n<pre><code>// A,B are strings\nunsigned int count_edit_dist(const char *A, const char *B)\n{\n unsigned count=0;\n // a,b are pointers to current letters of A,B\n const char *a = A;\n const char *b = B;\n // while we have characters from either\n while (*a||*b) {\n // add to count i different\n if (*a!=*b) ++count;\n // increment letter if not at end of string\n if (*a) ++a;\n if (*b) ++b;\n }\n return count;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T19:20:02.063",
"Id": "254567",
"ParentId": "254546",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254564",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T08:49:31.697",
"Id": "254546",
"Score": "3",
"Tags": [
"c",
"interview-questions"
],
"Title": "Count edit distance"
}
|
254546
|
<p>I have attempted to implement a similar version of the STL Vector; several functions are missing but I'd like a few words of advice on whether I am indeed on the right track or whether I should change my approach. My goal here is to understand how the vector works behind the scenes, rather than using it for my applications.</p>
<pre><code>#include <initializer_list>
#include <algorithm>
#include <memory>
struct out_of_range {};
template<typename T, typename A>
struct vector_base
{
A alloc; //allocator
T* elem; //start of allocation
int sz; //number of elements
int space; //amount of allocated space
vector_base(int n)
:elem{alloc.allocate(n)}, sz{n}, space{n} {}
void construct(T def) {for (int i = 0; i < sz; i++) alloc.construct(&elem[i], def); }
~vector_base()
{
//for(int i = 0; i < sz; i++) alloc.destroy(&elem[i]);
alloc.deallocate(elem, space);
std::cout << "Vector destroyed.\n";
}
};
template<typename T, typename A = std::allocator<T>> //requires Element<T>()
class vector : private vector_base<T,A>
{
void reserve(int newspace);
public:
vector (int size, T def = T())
: vector_base<T,A>(size)
{
this->construct(def); // initialize each element to 0
std::cout << "Vector constructed\n";
}
//~vector() {delete [] this->elem;}
//{} initialization
vector (std::initializer_list<int> lst)
:vector_base<T,A>(lst.size())
{
std::copy (lst.begin(), lst.end(), this->elem);
std::cout << "Vector constructed\n";
}
//destruction of elements is managed in vector_base
vector (const vector& arg); //copy constructor
vector& operator= (const vector& arg); //copy assignment
vector ( vector&& arg); //move constructor
vector& operator= (vector&& arg); //move assignment
//subscript operators
T& operator[] (int n) { return this->elem[n]; }
const T& operator[] (int n) const { return this->elem[n]; }
T& at(int n);
const T& at(int n) const;
int size() const { return this->sz; }
int capacity() const { return this->space; }
void resize(int newspace, T def = T()); //growth
void push_back(const T& d);
void erase();
};
//copy constructor
template<typename T,typename A>
vector<T,A>::vector (const vector<T,A>& arg)
:vector_base<T,A>{arg.size()}
{
std::copy (arg.elem, arg.elem + arg.sz, this->elem);
std::cout << "Vector constructed\n";
}
//copy assignment
template<typename T,typename A>
vector<T,A>& vector<T,A>::operator= (const vector<T,A>& arg)
{
if (this == &arg) return *this; //self-assignment, do nothing
if (arg.sz <= this->space) // enough space, no need for extra allocation
{
for (int i = 0; i < arg.sz; i++) this->elem[i] = arg.elem[i]; //copy elements
this->sz = arg.sz;
return *this;
}
T* n = this->alloc.allocate(arg.sz);
for (int i = 0; i < arg.sz; i++) n[i] = arg.elem[i]; //copy all the elements from a to the newly allocated array
//for (int i = 0; i < arg.sz; i++) this->alloc.destroy(&this->elem[i]);
this->alloc.deallocate(this->elem, this->space);
this->space = arg.space;
this->sz = arg.sz;
this->elem = n; //set the elem (of the current vector) to the argumen's elem
return *this; //return a self-reference
}
template<typename T, typename A>
T& vector<T,A>::at(int n)
{
if (n < 0 || n >= this->sz) throw out_of_range();
return this->elem[n];
}
template<typename T, typename A>
const T& vector<T,A>::at(int n) const
{
if (n < 0 || n >= this->sz) throw out_of_range();
return this->elem[n];
}
//move constructor
template<typename T,typename A>
vector<T,A>::vector (vector<T,A> && arg)
:vector_base<T,A>{arg.size()}
{
this->elem = arg.elem;
arg.elem = nullptr;
arg.space = 0;
arg.sz = 0;
std::cout << "Vector constructed\n";
}
//move assignment
template<typename T,typename A>
vector<T,A>& vector<T,A>::operator= (vector<T,A> && arg)
{
this->elem = arg.elem;
this->sz = arg.sz;
for (int i = 0; i < arg.sz; i++) this->alloc.destroy(&this->elem[i]);
arg.elem = nullptr;
arg.sz = 0;
return *this;
}
template<typename T,typename A>
void vector<T,A>::reserve(int newspace)
{
if(newspace <= this->space) return; //never allocate less memory
T* p = this->alloc.allocate(newspace);
for(int i = 0; i < this->sz; i++) this->alloc.construct(&p[i], this->elem[i]); //copy the elements from the old array to the new one
//for(int i = 0; i < this->sz; i++) this->alloc.destroy(&this->elem[i]);
this->alloc.deallocate(this->elem, this->space);
this->elem = p; //point elem to the newly allocated array p
this->space = newspace;
}
template<typename T,typename A>
void vector<T,A>::resize(int newspace, T def)
//make the vector have newspace elements
//initialize each new element with a default value
// -default T value
// -or a value d if specified
{
reserve(newspace);
for (int i = this->sz; i < newspace; i++) this->alloc.construct(&this->elem[i],def);
for (int i = newspace; i < this->sz; i++) this->alloc.destroy(&this->elem[i]);
this->sz = newspace;
}
template<typename T,typename A>
void vector<T,A>::push_back(const T& d)
{
if(this->space == 0) //if there's no space (default constructor)
reserve(8); //reserve space for 8 elements
else if (this->sz == this->space) //if the space is equal to the size
reserve(this->space * 2); //double the space
this->alloc.construct(&this->elem[this->sz], d); // add d at the end
++this->sz; // increase size by 1
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:41:42.377",
"Id": "502091",
"Score": "0",
"body": "@BCdotWEB The purpose of the project was to understand how it worked, not that he doesn't understand it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:55:27.353",
"Id": "502092",
"Score": "0",
"body": "exactly. I am a beginner, and I really want to understand how vector (and later, other containers, data structures and algorithms ) work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T18:13:22.633",
"Id": "502136",
"Score": "0",
"body": "have a read of the vector series: https://lokiastari.com/series/"
}
] |
[
{
"body": "<h2>Summary</h2>\n<p>Broken.</p>\n<ul>\n<li>It leaks memory.</li>\n<li>It does not construct/destruct the object correctly.</li>\n</ul>\n<p>Please have a read of the articles I wrote on building your own vector.</p>\n<p>Have a read of the vector series: lokiastari.com/series</p>\n<h2>Code Review</h2>\n<p>There is one of these in the <a href=\"https://en.cppreference.com/w/cpp/error/out_of_range\" rel=\"nofollow noreferrer\">standard</a>!</p>\n<pre><code>struct out_of_range {};\n</code></pre>\n<p>If you are going to define your own exceptions then please at least inherit from <code>std::exception</code> but preferably <code>std::runtime_error</code>. These base classes allow you to store an error message that you can use for logging.</p>\n<hr />\n<p>Sure it is fine to use a standard allocator. But remember that allocators simply allocate the space they do not call the constructor or the destructor of the object that they store.</p>\n<pre><code>template<typename T, typename A> struct vector_base {\n A alloc; //allocator\n</code></pre>\n<hr />\n<p>All relatively standard.</p>\n<pre><code> T* elem; //start of allocation\n int sz; //number of elements\n int space; //amount of allocated space\n</code></pre>\n<hr />\n<p>You only have one constructor here?</p>\n<pre><code> vector_base(int n)\n :elem{alloc.allocate(n)}, sz{n}, space{n} {}\n</code></pre>\n<p>What happens when the <code>vector</code> is move constructed? Having this as a base class will force you to allocate space when the move constructor is not supposed to. You are supposed to move the pre-allocated storage from the source to the new vector.</p>\n<hr />\n<p>Another question above this constructor.</p>\n<pre><code> vector_base(int n)\n :elem{alloc.allocate(n)}, sz{n}, space{n} {}\n</code></pre>\n<p>Why is size <code>sz</code> set to <code>n</code>? You always allocate all the objects in the array on construction. That sort of defeats the purpose of pre-allocating with extra space. There is a difference between the space you have and the number of elements you have. There should be a constructor that allows the child to establish this.</p>\n<hr />\n<p>Side note here:<br />\nThe std::vector behaves like a normal C array. It destroys the objects contained in the reverse order. This mimics the normal behavior of RAII objects. The most recently created is the first to be destroyed.</p>\n<p>I would use this behavior as well.</p>\n<pre><code> ~vector_base() \n {\n //for(int i = 0; i < sz; i++) alloc.destroy(&elem[i]);\n alloc.deallocate(elem, space);\n std::cout << "Vector destroyed.\\n";\n } };\n</code></pre>\n<hr />\n<p>I don't see a default constructor ?</p>\n<pre><code> vector (int size, T def = T())\n : vector_base<T,A>(size)\n {\n this->construct(def); // initialize each element to 0\n std::cout << "Vector constructed\\n";\n }\n</code></pre>\n<p>What happens if I want to create an empty vector? I need to explicitly set the size to zero? Sure it's a valid design (but not what I would expect).</p>\n<hr />\n<p>Delete commented out code.</p>\n<pre><code> //~vector() {delete [] this->elem;}\n\n //{} initialization\n</code></pre>\n<hr />\n<p>Normally the move operators are marked <code>noexcept</code>.</p>\n<pre><code> vector ( vector&& arg); //move constructor\n vector& operator= (vector&& arg); //move assignment\n</code></pre>\n<p>This is because if they are added to standard containers objects with <code>noecept</code> move operations can have certain optimizations done to them without violating the string exception gurantee.</p>\n<hr />\n<p>When I grow the internal array it because I want to put more stuff in it.</p>\n<pre><code> void resize(int newspace, T def = T()); //growth\n</code></pre>\n<p>The stuff I put in it may not necessarily be a default initialized T object, nor will I usually want to put the same object into all locations. Forcing me to initialize all the objects now is going to be very inefficient if I am just going to overwrite them.</p>\n<p>You should allocate the space (increase <code>space</code>) but not increase size <code>sz</code> and not initalize the objects. When you add more items to the containre then you can initialize the objects either via copy or move.</p>\n<hr />\n<p>You only support copy insertion into the contaienr.</p>\n<pre><code> void push_back(const T& d);\n</code></pre>\n<p>I would add move and build in place.</p>\n<pre><code> void push_back(T&& d);\n template<typename... Args>\n void emplace_back(Args&&...);\n</code></pre>\n<hr />\n<p>Copy only works if the elements are already constructed.</p>\n<pre><code>//copy constructor\ntemplate<typename T,typename A> vector<T,A>::vector (const vector<T,A>& arg)\n :vector_base<T,A>{arg.size()} {\n std::copy (arg.elem, arg.elem + arg.sz, this->elem);\n std::cout << "Vector constructed\\n";\n}\n</code></pre>\n<p>Your base class allocated the space but does not initialize the objects in that space. So you have uninitialized memory there. You then try and copy into that un-initialized memory. This will invoke the copy assignment operator on the objects (this makes the assumption that the object has been constructed (which it has not).</p>\n<p>You need to construct each if the elements. The easy way to do this is to call push_back.</p>\n<pre><code>//copy constructor\ntemplate<typename T,typename A>\nvector<T,A>::vector(vector<T,A> const& arg)\n : vector_base<T,A>{arg.size()}\n{\n // First set size to zero as your base class sets it to n.\n sz = 0;\n for (auto const& element: arg) {\n push_back(element);\n }\n}\n</code></pre>\n<p>Note: push back needs to call the constructor (I will check that when I get there).</p>\n<hr />\n<p>You make things hard for your self by doing this manually. Look up the copy and swap idiom.</p>\n<pre><code>template<typename T,typename A> \nvector<T,A>& vector<T,A>::operator= (const vector<T,A>& arg) {\n\n // Sure.\n // But this pattern is self deeating as normally you\n // don't do self assignment so you on average this makes the\n // copy slower because now every time you have to do this check.\n //\n // The copy and swap idium goes the other way.\n // Normally operations (which is 99.9999999999999% of them) don't pay\n // the cost for this test.\n // unfortunately on self assignment you do lots of extra work and\n // make an unnecessary copy. But on average it is still cheaper as\n // self assignment happens rareally in normal code (if it happens a lot\n // in your code then make an exception and do the test but prove that\n // you are doing a lot of self assignment first to make it worth the\n // hassle.\n if (this == &arg) return *this; //self-assignment, do nothing\n\n\n\n if (arg.sz <= this->space) // enough space, no need for extra allocation\n {\n // You can use copy for the first `this->sz` elements.\n // But from this->sz to arg.sz you need to initialize the elements first.\n // and if arg.sz is smaller than this->sz you will need to call\n // the destructor on the elements.\n for (int i = 0; i < arg.sz; i++) this->elem[i] = arg.elem[i]; //copy elements\n this->sz = arg.sz;\n return *this;\n }\n\n\n // Get some space.\n // Remember the allocator has not initialized the object in this\n // storage so you can not simply copy. You must initialize\n // each member (call the constructor).\n // note: calling the constructor can throw. If this happens you\n // should make sure to release the allocated array correctly.\n T* n = this->alloc.allocate(arg.sz);\n for (int i = 0; i < arg.sz; i++) n[i] = arg.elem[i]; \n\n // Before you call deallocate you must call the destructor on all the\n // elements that have been stored in this space. The allocator does not\n // do this for you.\n // Note: Calling the destructor can potentially throw. You must make sure\n // to call deallocate even if you throw otherwise you will leak.\n this->alloc.deallocate(this->elem, this->space);\n\n // Make sure this still happens if there is an exception thrown.\n // otherwise your object will be in some funcky state.\n this->space = arg.space;\n this->sz = arg.sz;\n this->elem = n; //set the elem (of the current vector) to the argumen's elem\n return *this; //return a self-reference }\n</code></pre>\n<hr />\n<p>This move does extra allocation (why).<br />\nBut then leaks it.</p>\n<pre><code>template<typename T,typename A>\nvector<T,A>::vector (vector<T,A> && arg)\n // The base class allocates space you are not going to use.\n :vector_base<T,A>{arg.size()} {\n // You just leaked the memory allocated in the base class constructor.\n this->elem = arg.elem;\n\n // Sure.\n arg.elem = nullptr;\n arg.space = 0;\n arg.sz = 0;\n std::cout << "Vector constructed\\n"; }\n</code></pre>\n<hr />\n<p>Again you are leaking memory.</p>\n<pre><code>template<typename T,typename A>\nvector<T,A>& vector<T,A>::operator= (vector<T,A> && arg) {\n \n // You just leaked this->elem\n this->elem = arg.elem;\n this->sz = arg.sz;\n\n // Now you are calling the destructor\n // on the elements thus making them invalid.\n // There seems be an ordering issue here.\n // destory and release this object first.\n // then copy over the elements.\n for (int i = 0; i < arg.sz; i++) this->alloc.destroy(&this->elem[i]);\n arg.elem = nullptr;\n arg.sz = 0;\n return *this; }\n</code></pre>\n<hr />\n<p>Reserve should not initialize the memory.</p>\n<pre><code>template<typename T,typename A> void vector<T,A>::reserve(int newspace) {\n if(newspace <= this->space) return; //never allocate less memory\n T* p = this->alloc.allocate(newspace);\n\n // What happens if the constructor throws an exception.?\n for(int i = 0; i < this->sz; i++) this->alloc.construct(&p[i], this->elem[i]); \n \n\n // You have not called the destructor on the current elements.\n this->alloc.deallocate(this->elem, this->space);\n this->elem = p; //point elem to the newly allocated array p\n this->space = newspace; }\n</code></pre>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T05:58:03.800",
"Id": "502176",
"Score": "0",
"body": "Thank you a lot for this answer. I think I will rebuild and go through the process of building the vector again. I followed the Programming Principles and Practice Using C++, where the constructor would use `new` to allocate memory for the array. The problem is that classes with no default constructor couldn't be used as a template argument, as new searches for a default constructor for the type initialized. Therefore, I tried using allocators for basically everything; it seems like I kinda broke it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T06:53:43.543",
"Id": "502181",
"Score": "0",
"body": "Oh and also, calling alloc.destroy() for each object means that I am properly destroying that object. Am I right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:06:44.387",
"Id": "502191",
"Score": "0",
"body": "When you use it yes But you don't use it in all the places needed (see copy assignment and move assignment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:07:50.973",
"Id": "502192",
"Score": "0",
"body": "The problem is you should not be initializing the objects until they are placed in the container. Initializing the memory retrieved from the allocator is wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:08:15.900",
"Id": "502193",
"Score": "0",
"body": "Please read the articles I wrote. It goes through all the issues you have here and many more in some detail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:11:08.540",
"Id": "502194",
"Score": "0",
"body": "You need to learn a couple of basic idioms. Copy And Swap. Placement new. Rule of zero (you have done the rule of 3/5 even if they are broken)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T10:25:06.203",
"Id": "502202",
"Score": "0",
"body": "`buffer(static_cast<T*>(::operator new(sizeof(T) * capacity)))` i just don't get this line. Why are you casting ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:19:43.530",
"Id": "502238",
"Score": "0",
"body": "Because `buffer` is a `T*`, while `operator new` returns a `void*`. Putting the cast in there documents (and thus makes code reviewers take a closer look) that I have made an explicit change in type (allowing a hidden type change that is not properly reviewed is dangerous). Consider this `buffer(::operator new(3))`. This will work and the pointer will be assigned without any worries. But there is no guarantee that the pointer is correctly aligned (this type of cast should be reviewed by humans)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T19:04:56.287",
"Id": "254614",
"ParentId": "254547",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254614",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T09:37:25.007",
"Id": "254547",
"Score": "0",
"Tags": [
"c++",
"memory-management",
"template",
"vectors",
"raii"
],
"Title": "Vector Implementation C++ using RAII"
}
|
254547
|
<p>I'm currently trying to develop an easy to use TCP networking library based on <code>boost::asio</code>.
This is my first attempt to work with <code>boost::asio</code> and therefore I've got some questions:</p>
<ol>
<li>Firstly, is my code okay and easy to understand?</li>
<li>Are there any misleading conventions?</li>
<li>Are there any memory leaks?</li>
<li>Is there any improvement for my written code?</li>
<li>What about the style-guide?</li>
</ol>
<p>Additional information about the three different classes:</p>
<ul>
<li><code>TCPSession</code> handles the read/write operations of the socket.</li>
<li><code>TCPClient</code> contains an object of the <code>TCPSession</code> and handles the connection to a server.</li>
<li><code>TCPServer</code> holds an acceptor and <code>std::unordererd_map<std::uint64_t, TCPSessionPtr></code> with all the active connections.</li>
</ul>
<p>Base.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include <cassert>
#include <string>
#include <boost/asio.hpp>
#include <boost/asio/strand.hpp>
#include <boost/bind.hpp>
#include <boost/asio/signal_set.hpp>
#define SPDLOG_ACTIVE_LEVEL 1
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/async.h>
#include "Utils.hpp"
namespace nelw
{
typedef std::uint64_t id_type;
typedef boost::asio::ip::tcp::socket socket_t;
typedef boost::asio::io_context& io_context_ref;
typedef boost::asio::ip::tcp::acceptor tcp_acceptor;
class TCPSession;
typedef std::shared_ptr<TCPSession> TConnectionPtr;
typedef std::function<void(const TConnectionPtr&)> TConnectionCallback;
typedef std::function<void(const TConnectionPtr&, const boost::system::error_code&)> TErrorCallback;
class Buffer;
typedef std::unique_ptr<Buffer> TBufferPtr;
typedef std::function<void(const TConnectionPtr&, const TBufferPtr&)> TRecvCallback;
}
</code></pre>
<p>Utils.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
namespace nelw
{
template<class F, class...Args>
void for_each_arg(F f, Args&&...args) {
(f(std::forward<Args>(args)), ...);
}
}
</code></pre>
<p>TCPSession.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "Buffer.hpp"
namespace nelw
{
class TCPSession : public std::enable_shared_from_this<TCPSession>
{
public:
TCPSession(io_context_ref context, std::uint64_t buffer_size = 4096);
virtual ~TCPSession();
friend class TCPServer;
friend class TCPClient;
public:
auto socket() -> socket_t& { return socket_; }
auto write_buffer() ->TBufferPtr& { return write_buffer_; }
auto id() -> id_type { return id_; }
auto set_id(id_type id) { id_ = id; }
auto read_buffer() ->TBufferPtr& { return read_buffer_; }
bool is_connected() { return is_connected_; }
template <class T> void set_dc_cb(T&& cb) { dc_cb_ = cb; }
template <class T> void set_connection_cb(T&& cb) { connection_cb_ = cb; }
template <class T> void set_recv_cb(T&& cb) { recv_cb_ = cb; }
template <class T> void set_error_cb(T&& cb) { error_cb_ = cb; }
public:
void Disconnect();
void Send(void* pData, size_t length);
void Read();
template <typename... Args> void Send(Args&&... args)
{
//constexpr std::size_t n = sizeof...(Args);
std::uint32_t size = 0;
for_each_arg([&size](auto& arg) { size += sizeof(arg); }, args...);
if (size <= 0)
return;
size_t offset = 0;
std::vector<std::byte> buffer{ size };
for_each_arg([&buffer, &offset](auto& arg)
{
std::memcpy(&buffer[offset], &arg, sizeof(arg));
offset += sizeof(arg);
}
, args...);
Send((void*)buffer.data(), buffer.size());
}
void WriteProcess();
void RemoteDisconnect();
protected:
virtual void OnError(const boost::system::error_code& ec);
virtual void OnConnection();
virtual void OnRecv();
protected:
io_context_ref context_;
socket_t socket_;
id_type id_;
std::function<void()> dc_cb_;
TBufferPtr write_buffer_; // write buffer
TBufferPtr read_buffer_;
bool is_connected_;
bool is_writing_;
TConnectionCallback connection_cb_;
TRecvCallback recv_cb_;
TErrorCallback error_cb_;
};
}
</code></pre>
<p>TCPSession.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "nelw/Base.hpp"
#include "nelw/TcpSession.hpp"
#include <iostream>
namespace nelw
{
TCPSession::TCPSession(io_context_ref context, std::uint64_t buffer_size) : context_(context), socket_(context),
id_ { 0 }, dc_cb_{ nullptr },
is_connected_ { true }, connection_cb_ { nullptr },
recv_cb_ { nullptr }, error_cb_ { nullptr },
is_writing_{ false }
{
if (buffer_size)
{
read_buffer_ = std::make_unique<nelw::Buffer>(buffer_size);
write_buffer_ = std::make_unique<nelw::Buffer>(buffer_size);
}
}
TCPSession::~TCPSession()
{
if (read_buffer_)
read_buffer_.reset();
if (write_buffer_)
write_buffer_.reset();
if (dc_cb_)
{
dc_cb_();
dc_cb_ = nullptr;
}
spdlog::info("Remove from session! {}", id_);
}
void TCPSession::Disconnect()
{
if (!is_connected_)
return;
auto self{ shared_from_this() };
context_.post([self]() {
if (!self->socket().is_open())
return;
self->is_connected_ = false;
self->socket_.cancel();
self->socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
self->socket_.close();
self->OnConnection();
if (self->dc_cb_)
{
self->dc_cb_();
self->dc_cb_ = nullptr;
}
});
}
void TCPSession::Read()
{
if (!is_connected_)
return;
assert(read_buffer_);
if (!socket_.is_open())
return;
//spdlog::debug("Start reading from {}", e.address().to_string(), e.port());
auto self{ shared_from_this() };
auto write_able = read_buffer_->WritableBytes();
if (write_able <= 0)
{
//spdlog::debug("Waiting for bytes...");
try
{
socket_.async_wait(boost::asio::ip::tcp::socket::wait_read, [self = shared_from_this()](const boost::system::error_code& ec) {
if (!ec)
{
auto s = self->socket_.available();
if (s > 0)
self->read_buffer_->EnsureWritableBytes(s);
spdlog::debug("Ensure bytes size: {}", s);
self->Read();
}
else
{
self->OnError(ec);
if (boost::asio::error::eof == ec || boost::asio::error::connection_reset == ec)
{
spdlog::debug("Disconnect from async_wait!");
self->RemoteDisconnect();
}
}
});
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;//spdlog::error("socket_.async_wait -> {}", e.what());
}
}
else if (write_able > 0)
{
socket_.async_read_some(boost::asio::buffer(read_buffer_->WriteBegin(), read_buffer_->WritableBytes()),
[self = shared_from_this()](const boost::system::error_code& ec, std::size_t length)
{
if (!ec)
{
if (length)
{
self->read_buffer_->WriteBytes(length);
self->OnRecv();
}
self->Read();
}
else
{
self->OnError(ec);
if (boost::asio::error::eof == ec || boost::asio::error::connection_reset == ec)
{
spdlog::debug("Disconnect from read!");
self->RemoteDisconnect();
}
}
});
}
}
void TCPSession::Send(void* pData, size_t length)
{
if (!is_connected_)
return;
write_buffer_->Append(pData, length);
if (!is_writing_)
WriteProcess();
}
void TCPSession::WriteProcess()
{
if (!is_connected_)
return;
auto length = write_buffer_->length();
if (length <= 0)
return;
auto self{ shared_from_this() };
boost::asio::async_write(
socket_,
boost::asio::buffer(write_buffer_->data(), write_buffer_->length()),
[self](const boost::system::error_code& ec, size_t bytes_transfered)
{
if (ec)
{
self->OnError(ec);
if (boost::asio::error::eof == ec || boost::asio::error::connection_reset == ec)
self->RemoteDisconnect();
return;
}
else
{
if (bytes_transfered)
{
self->write_buffer_->Skip(bytes_transfered);
if (self->write_buffer_->length() > 0)
self->WriteProcess();
else
self->is_writing_ = false;
}
}
}
);
is_writing_ = true;
}
void TCPSession::RemoteDisconnect()
{
if (is_connected_)
{
is_connected_ = false;
OnConnection();
if (dc_cb_)
{
dc_cb_();
dc_cb_ = nullptr;
}
}
}
void TCPSession::OnError(const boost::system::error_code& ec)
{
if (error_cb_)
error_cb_(shared_from_this(), ec);
}
void TCPSession::OnConnection()
{
if (connection_cb_)
connection_cb_(shared_from_this());
}
void TCPSession::OnRecv()
{
if (recv_cb_)
recv_cb_(shared_from_this(), read_buffer_);
}
}
</code></pre>
<p>TCPClient.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
#include "TcpSession.hpp"
namespace nelw
{
class TCPClient
{
public:
enum flags : std::uint8_t
{
kTimerRunning = (1 << 1), // for the connection_timer_
kReconnecting = (1 << 2)
};
TCPClient(io_context_ref context);
~TCPClient();
virtual TConnectionPtr CreateSession();
void Connect(const std::string& host, std::uint16_t port);
void Disconnect();
// getters and setters
public:
void set_connection_timeout(boost::asio::deadline_timer::duration_type connection_timeout);
auto connection_timeout() -> boost::asio::deadline_timer::duration_type;
TConnectionPtr& connection();
// end of getters and setters
void Send(void* pData, size_t length);
template <typename... Args> void Send(Args&&... args)
{
if (connection_ && connection_->is_connected())
connection_->Send(args...);
}
template <class T> void set_connection_cb(T&& cb) { connection_cb_ = cb; }
template <class T> void set_recv_cb(T&& cb) { recv_cb_ = cb; }
template <class T> void set_error_cb(T&& cb) { error_cb_ = cb; }
void set_buffer_size(std::uint64_t buffer_size);
void set_reconnect(bool b);
bool is_connected();
protected:
io_context_ref context_;
TConnectionPtr connection_;
std::uint8_t flags_;
boost::asio::deadline_timer connection_timer_;
boost::asio::deadline_timer::duration_type connection_timeout_;
TConnectionCallback connection_cb_;
TErrorCallback error_cb_;
TRecvCallback recv_cb_;
std::uint64_t buffer_size_;
};
}
</code></pre>
<p>TCPClient.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "nelw/Base.hpp"
#include "nelw/TcpClient.hpp"
#include "nelw/TcpSession.hpp"
namespace nelw
{
TCPClient::TCPClient(io_context_ref context) : context_{ context }, flags_{ 0 }, connection_timer_{ context }, connection_timeout_(boost::posix_time::seconds(5)),
connection_cb_{ nullptr }, error_cb_{ nullptr }, recv_cb_{ nullptr }, buffer_size_{ 4096 }
{
}
TCPClient::~TCPClient()
{
Disconnect(); // be sure
if (flags_ & flags::kTimerRunning)
{
connection_timer_.cancel();
flags_ &= ~(flags::kTimerRunning);
}
}
TConnectionPtr TCPClient::CreateSession()
{
return std::make_shared<TCPSession>(context_, buffer_size_);
}
void TCPClient::Connect(const std::string& host, std::uint16_t port)
{
if (connection_)
connection_.reset();
spdlog::debug("Starting connection to {}, {}", host, port);
connection_ = CreateSession();
boost::asio::ip::tcp::resolver resolver(context_);
auto endpoints = resolver.resolve(boost::asio::ip::tcp::resolver::query(host, std::to_string(port)));
boost::asio::async_connect(connection_->socket(), endpoints,
[this, h = host, p = port](boost::system::error_code ec, boost::asio::ip::tcp::endpoint)
{
if (!ec)
{
flags_ &= ~(flags::kTimerRunning);
connection_->set_dc_cb([this]() {
connection_ = nullptr;
});
if (error_cb_)
connection_->set_error_cb(error_cb_);
if (recv_cb_)
connection_->set_recv_cb(recv_cb_);
if (connection_cb_)
connection_->set_connection_cb(connection_cb_);
connection_->OnConnection();
connection_->Read();
}
else
{
if (connection_)
connection_->OnError(ec);
if (flags_ & flags::kReconnecting)
{
flags_ |= flags::kTimerRunning;
connection_timer_.expires_from_now(connection_timeout_);
connection_timer_.async_wait([this, h = h, p = p](const boost::system::error_code& ec) {
if (!ec)
{
Connect(h, p);
}
else
{
flags_ &= ~(flags::kTimerRunning);
}
});
}
}
});
}
void TCPClient::Disconnect()
{
if (!connection_)
return;
if (connection_->is_connected())
connection_->Disconnect();
connection_ = nullptr;
}
bool TCPClient::is_connected()
{
return connection_ ? connection_->is_connected() : false;
}
void TCPClient::set_connection_timeout(boost::asio::deadline_timer::duration_type connection_timeout)
{
connection_timeout_ = connection_timeout;
}
auto TCPClient::connection_timeout() -> boost::asio::deadline_timer::duration_type
{
return connection_timeout_;
}
TConnectionPtr& TCPClient::connection()
{
return connection_;
}
void TCPClient::Send(void* pData, size_t length)
{
if (connection_)
connection_->Send(pData, length);
}
void TCPClient::set_buffer_size(std::uint64_t buffer_size)
{
buffer_size_ = buffer_size_;
}
void TCPClient::set_reconnect(bool b)
{
if (b)
flags_ |= flags::kReconnecting;
else
flags_ &= ~(flags::kReconnecting);
}
}
</code></pre>
<p>TCPServer.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
namespace nelw
{
class option_wrapper
{
private:
boost::asio::ip::tcp::acceptor& acceptor_;
public:
option_wrapper(boost::asio::ip::tcp::acceptor& acceptor) : acceptor_(acceptor)
{
}
~option_wrapper() = default;
template <typename SettableSocketOption>
option_wrapper& set_option(const SettableSocketOption& option)
{
acceptor_.set_option(option);
return *this;
}
};
class TCPServer
{
public:
using TConnectionMap = std::unordered_map<id_type, TConnectionPtr>;
public:
TCPServer(io_context_ref io_service);
virtual ~TCPServer();
public:
void Run(boost::asio::ip::tcp::endpoint&& e);
void Run(std::uint16_t port, std::string_view ip = "127.0.0.1");
void Stop();
public:
/**********************/
/* getters & setters*/
auto context()->io_context_ref { return context_; }
auto acceptor()->tcp_acceptor& { return acceptor_; }
template <typename SettableSocketOption>
option_wrapper& set_option(const SettableSocketOption& option)
{
return option_wrapper_.set_option(option);
}
/**********************/
protected:
void Disconnect(std::shared_ptr<id_type> id);
virtual void Accept();
virtual TConnectionPtr CreateSession() // Override it
{
return std::make_shared<TCPSession>(context_, buffer_size_);
}
public:
template <class T> void set_connection_cb(T&& cb) { connection_cb_ = cb; }
template <class T> void set_recv_cb(T&& cb) { recv_cb_ = cb; }
template <class T> void set_error_cb(T&& cb) { error_cb_ = cb; }
void set_buffer_size(std::uint64_t buffer_size);
void BroadCastPacket(void* pData, size_t length);
protected:
io_context_ref context_;
tcp_acceptor acceptor_;
id_type next_id_;
TConnectionMap connection_map_;
bool is_running_;
TConnectionCallback connection_cb_;
TErrorCallback error_cb_;
TRecvCallback recv_cb_;
std::uint64_t buffer_size_;
option_wrapper option_wrapper_;
};
}
</code></pre>
<p>TCPServer.cpp</p>
<pre class="lang-cpp prettyprint-override"><code>#include "nelw/Base.hpp"
#include "nelw/TcpServer.hpp"
#include "nelw/TcpSession.hpp"
#include <algorithm>
namespace nelw
{
TCPServer::TCPServer(io_context_ref io_service) : context_(io_service), acceptor_(context_), next_id_{ 0 }, is_running_(false),
connection_cb_{ nullptr }, error_cb_{ nullptr }, recv_cb_{ nullptr }, buffer_size_{ 4096 }, option_wrapper_(acceptor_)
{
}
TCPServer::~TCPServer()
{
Stop();
}
void TCPServer::Run(boost::asio::ip::tcp::endpoint&& e)
{
acceptor_.open(e.protocol());
acceptor_.bind(e);
acceptor_.listen();
Accept();
is_running_ = true;
}
void TCPServer::Run(std::uint16_t port, std::string_view ip)
{
Run(boost::asio::ip::tcp::endpoint(boost::asio::ip::make_address(ip), port));
}
void TCPServer::Disconnect(std::shared_ptr<id_type> id)
{
if (auto it = connection_map_.find(*id); it != connection_map_.end())
{
connection_map_.erase(it);
spdlog::debug("Remove last id {0} left_size {1}", *id, connection_map_.size());
}
}
void TCPServer::Stop()
{
if (!is_running_)
return;
if (!acceptor_.is_open())
return;
for (auto& [_, con] : connection_map_)
con->Disconnect();
acceptor_.cancel();
acceptor_.close();
is_running_ = false;
}
void TCPServer::Accept()
{
if (!acceptor_.is_open())
return;
auto session = CreateSession();
acceptor_.async_accept(session->socket(), [this, session = session](boost::system::error_code const& ec) {
if (!ec)
{
auto id = ++next_id_;
session->set_id(id);
connection_map_[id] = session;
context_.post([this, idPtr = std::make_shared<id_type>(id), session = session, ec = ec]() {
if (error_cb_)
session->set_error_cb(error_cb_);
if (recv_cb_)
session->set_recv_cb(recv_cb_);
if (connection_cb_)
session->set_connection_cb(connection_cb_);
session->set_dc_cb(boost::bind(&TCPServer::Disconnect, this, idPtr));
session->Read();
Accept();
session->OnConnection();
});
}
else
{
if (session)
{
session->OnConnection();
}
}
});
}
void TCPServer::BroadCastPacket(void* pData, size_t length)
{
for (auto& [_, con] : connection_map_)
if (con) con->Send(pData, length);
}
void TCPServer::set_buffer_size(std::uint64_t buffer_size)
{
buffer_size_ = buffer_size_;
}
}
</code></pre>
<p>Buffer.hpp</p>
<pre class="lang-cpp prettyprint-override"><code>#pragma once
// Modified from evpp project https://github.com/Qihoo360/evpp
// @see https://github.com/Qihoo360/evpp/blob/master/evpp/buffer.h and https://github.com/Qihoo360/evpp/blob/master/evpp/buffer.cc
namespace nelw
{
class Buffer
{
public:
inline static constexpr size_t kCheapPrependSize = 8;
inline static constexpr size_t kInitialSize = 1024;
explicit Buffer(size_t initial_size = kInitialSize, size_t reserved_prepend_size = kCheapPrependSize)
: capacity_(reserved_prepend_size + initial_size)
, read_index_(reserved_prepend_size)
, write_index_(reserved_prepend_size)
, reserved_prepend_size_(reserved_prepend_size) {
buffer_ = new char[capacity_];
assert(length() == 0);
assert(WritableBytes() == initial_size);
assert(PrependableBytes() == reserved_prepend_size);
}
~Buffer() {
delete[] buffer_;
buffer_ = nullptr;
capacity_ = 0;
}
void Swap(Buffer& rhs) {
std::swap(buffer_, rhs.buffer_);
std::swap(capacity_, rhs.capacity_);
std::swap(read_index_, rhs.read_index_);
std::swap(write_index_, rhs.write_index_);
std::swap(reserved_prepend_size_, rhs.reserved_prepend_size_);
}
// Skip advances the reading index of the buffer
void Skip(size_t len) {
if (len < length()) {
read_index_ += len;
}
else {
Reset();
}
}
// Retrieve advances the reading index of the buffer
// Retrieve it the same as Skip.
void Retrieve(size_t len) {
Skip(len);
}
// Truncate discards all but the first n unread bytes from the buffer
// but continues to use the same allocated storage.
// It does nothing if n is greater than the length of the buffer.
void Truncate(size_t n) {
if (n == 0) {
read_index_ = reserved_prepend_size_;
write_index_ = reserved_prepend_size_;
}
else if (write_index_ > read_index_ + n) {
write_index_ = read_index_ + n;
}
}
// Reset resets the buffer to be empty,
// but it retains the underlying storage for use by future writes.
// Reset is the same as Truncate(0).
void Reset() {
Truncate(0);
}
// Increase the capacity of the container to a value that's greater
// or equal to len. If len is greater than the current capacity(),
// new storage is allocated, otherwise the method does nothing.
void Reserve(size_t len) {
if (capacity_ >= len + reserved_prepend_size_) {
return;
}
// TODO add the implementation logic here
grow(len + reserved_prepend_size_);
}
// Make sure there is enough memory space to append more data with length len
void EnsureWritableBytes(size_t len) {
if (WritableBytes() < len) {
grow(len);
}
assert(WritableBytes() >= len);
}
// ToText appends char '\0' to buffer to convert the underlying data to a c-style string text.
// It will not change the length of buffer.
void ToText() {
AppendInt8('\0');
UnwriteBytes(1);
}
// TODO XXX Little-Endian/Big-Endian problem.
#define evppbswap_64(x) \
((((x) & 0xff00000000000000ull) >> 56) \
| (((x) & 0x00ff000000000000ull) >> 40) \
| (((x) & 0x0000ff0000000000ull) >> 24) \
| (((x) & 0x000000ff00000000ull) >> 8) \
| (((x) & 0x00000000ff000000ull) << 8) \
| (((x) & 0x0000000000ff0000ull) << 24) \
| (((x) & 0x000000000000ff00ull) << 40) \
| (((x) & 0x00000000000000ffull) << 56))
// Write
public:
void Write(const void* /*restrict*/ d, size_t len) {
EnsureWritableBytes(len);
memcpy(WriteBegin(), d, len);
assert(write_index_ + len <= capacity_);
write_index_ += len;
}
void Append(const char* /*restrict*/ d, size_t len) {
Write(d, len);
}
void Append(const void* /*restrict*/ d, size_t len) {
Write(d, len);
}
// Append int64_t/int32_t/int16_t with network endian
void AppendInt64(int64_t x) {
int64_t be = evppbswap_64(x);
Write(&be, sizeof be);
}
void AppendInt32(int32_t x) {
int32_t be32 = htonl(x);
Write(&be32, sizeof be32);
}
void AppendInt16(int16_t x) {
int16_t be16 = htons(x);
Write(&be16, sizeof be16);
}
void AppendInt8(int8_t x) {
Write(&x, sizeof x);
}
// Prepend int64_t/int32_t/int16_t with network endian
void PrependInt64(int64_t x) {
int64_t be = evppbswap_64(x);
Prepend(&be, sizeof be);
}
void PrependInt32(int32_t x) {
int32_t be32 = htonl(x);
Prepend(&be32, sizeof be32);
}
void PrependInt16(int16_t x) {
int16_t be16 = htons(x);
Prepend(&be16, sizeof be16);
}
void PrependInt8(int8_t x) {
Prepend(&x, sizeof x);
}
// Insert content, specified by the parameter, into the front of reading index
void Prepend(const void* /*restrict*/ d, size_t len) {
assert(len <= PrependableBytes());
read_index_ -= len;
const char* p = static_cast<const char*>(d);
memcpy(begin() + read_index_, p, len);
}
void UnwriteBytes(size_t n) {
assert(n <= length());
write_index_ -= n;
}
void WriteBytes(size_t n) {
assert(n <= WritableBytes());
write_index_ += n;
}
//Read
public:
// Peek int64_t/int32_t/int16_t/int8_t with network endian
int64_t ReadInt64() {
int64_t result = PeekInt64();
Skip(sizeof result);
return result;
}
int32_t ReadInt32() {
int32_t result = PeekInt32();
Skip(sizeof result);
return result;
}
int16_t ReadInt16() {
int16_t result = PeekInt16();
Skip(sizeof result);
return result;
}
int8_t ReadInt8() {
int8_t result = PeekInt8();
Skip(sizeof result);
return result;
}
std::string ToString() const {
return std::string(data(), length());
}
void Shrink(size_t reserve) {
// Buffer other(length() + reserve);
// other.Append(ToSlice());
// Swap(other);
}
// ReadByte reads and returns the next byte from the buffer.
// If no byte is available, it returns '\0'.
char ReadByte() {
assert(length() >= 1);
if (length() == 0) {
return '\0';
}
return buffer_[read_index_++];
}
// UnreadBytes unreads the last n bytes returned
// by the most recent read operation.
void UnreadBytes(size_t n) {
assert(n < read_index_);
read_index_ -= n;
}
// Peek
public:
// Peek int64_t/int32_t/int16_t/int8_t with network endian
int64_t PeekInt64() const {
assert(length() >= sizeof(int64_t));
int64_t be64 = 0;
::memcpy(&be64, data(), sizeof be64);
return evppbswap_64(be64);
}
int32_t PeekInt32() const {
assert(length() >= sizeof(int32_t));
int32_t be32 = 0;
::memcpy(&be32, data(), sizeof be32);
return ntohl(be32);
}
int16_t PeekInt16() const {
assert(length() >= sizeof(int16_t));
int16_t be16 = 0;
::memcpy(&be16, data(), sizeof be16);
return ntohs(be16);
}
int8_t PeekInt8() const {
assert(length() >= sizeof(int8_t));
int8_t x = *data();
return x;
}
public:
// data returns a pointer of length Buffer.length() holding the unread portion of the buffer.
// The data is valid for use only until the next buffer modification (that is,
// only until the next call to a method like Read, Write, Reset, or Truncate).
// The data aliases the buffer content at least until the next buffer modification,
// so immediate changes to the slice will affect the result of future reads.
const char* data() const {
return buffer_ + read_index_;
}
char* WriteBegin() {
return begin() + write_index_;
}
const char* WriteBegin() const {
return begin() + write_index_;
}
// length returns the number of bytes of the unread portion of the buffer
size_t length() const {
assert(write_index_ >= read_index_);
return write_index_ - read_index_;
}
// size returns the number of bytes of the unread portion of the buffer.
// It is the same as length().
size_t size() const {
return length();
}
// capacity returns the capacity of the buffer's underlying byte slice, that is, the
// total space allocated for the buffer's data.
size_t capacity() const {
return capacity_;
}
size_t WritableBytes() const {
assert(capacity_ >= write_index_);
return capacity_ - write_index_;
}
size_t PrependableBytes() const {
return read_index_;
}
// Helpers
public:
const char* FindCRLF() const {
const char* crlf = std::search(data(), WriteBegin(), kCRLF, kCRLF + 2);
return crlf == WriteBegin() ? nullptr : crlf;
}
const char* FindCRLF(const char* start) const {
assert(data() <= start);
assert(start <= WriteBegin());
const char* crlf = std::search(start, WriteBegin(), kCRLF, kCRLF + 2);
return crlf == WriteBegin() ? nullptr : crlf;
}
const char* FindEOL() const {
const void* eol = memchr(data(), '\n', length());
return static_cast<const char*>(eol);
}
const char* FindEOL(const char* start) const {
assert(data() <= start);
assert(start <= WriteBegin());
const void* eol = memchr(start, '\n', WriteBegin() - start);
return static_cast<const char*>(eol);
}
private:
char* begin() {
return buffer_;
}
const char* begin() const {
return buffer_;
}
void grow(size_t len) {
if (WritableBytes() + PrependableBytes() < len + reserved_prepend_size_) {
//grow the capacity
size_t n = (capacity_ << 1) + len;
size_t m = length();
char* d = new char[n];
memcpy(d + reserved_prepend_size_, begin() + read_index_, m);
write_index_ = m + reserved_prepend_size_;
read_index_ = reserved_prepend_size_;
capacity_ = n;
delete[] buffer_;
buffer_ = d;
}
else {
// move readable data to the front, make space inside buffer
assert(reserved_prepend_size_ < read_index_);
size_t readable = length();
memmove(begin() + reserved_prepend_size_, begin() + read_index_, length());
read_index_ = reserved_prepend_size_;
write_index_ = read_index_ + readable;
assert(readable == length());
assert(WritableBytes() >= len);
}
}
private:
char* buffer_;
size_t capacity_;
size_t read_index_;
size_t write_index_;
size_t reserved_prepend_size_;
inline static constexpr const char kCRLF[3] = { "\r\n" };
};
}
</code></pre>
<p>Echo Server example:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <nelw/nelw.hpp>
auto main() -> int
{
spdlog::set_pattern("[%l][%t] %v");
boost::asio::io_context context;
std::uint16_t port = 9005;
auto srv = std::make_unique<nelw::TCPServer>(context);
srv->Run(port);
srv->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)).
set_option(boost::asio::ip::tcp::no_delay(true));
srv->set_recv_cb([](const nelw::TConnectionPtr& con, const nelw::TBufferPtr& buf) {
if (auto size = buf->length(); size)
{
auto str = buf->ToString();
con->Send((void*)str.data(), str.size());
buf->Skip(size);
}
});
context.run();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><code>Base.hpp</code> drags in a lot of stuff that isn't needed for what it defines:</p>\n<blockquote>\n<pre><code>#define SPDLOG_ACTIVE_LEVEL 1\n#include <spdlog/spdlog.h>\n#include <spdlog/sinks/basic_file_sink.h>\n#include <spdlog/async.h>\n#include "Utils.hpp"\n</code></pre>\n</blockquote>\n<p>As far as I can see, all of these can be removed, and only included by the implementation files that need them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T09:58:07.273",
"Id": "254593",
"ParentId": "254551",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T12:33:19.523",
"Id": "254551",
"Score": "2",
"Tags": [
"c++",
"io",
"boost",
"tcp"
],
"Title": "Network library based on boost::asio"
}
|
254551
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.