body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've put together a simple CRUD application to keep track of my library of books in an effort to learn the model-view-controller pattern, as well as better myself at PHP. Everything I have works so far, but I'm definitely looking to streamline/condense/refactor the more verbose parts of it, as well as address any possible security concerns that I may be overlooking.</p>
<p>In the snippets below I'm utilizing two libraries: <code>twig/twig</code> and <code>bramus/router</code>. Everything else is written by me.</p>
<p><strong>index.php</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
/**
* TODO: Create a proper mechanism for flash methods. Perhaps a Flash class?
*/
session_start();
require_once __DIR__ . "/vendor/autoload.php";
require_once __DIR__ . "/models.php";
require_once __DIR__ . "/controllers.php";
$loader = new \Twig\Loader\FilesystemLoader(__DIR__ . "/views");
$twig = new \Twig\Environment($loader);
$router = new \Bramus\Router\Router();
$router->get("/", function () use ($twig) {
echo $twig->render("index.twig", ["title" => "Home"]);
});
$router->get("/books", function () use ($twig) {
$controller = new BookController($twig);
$controller->index();
});
$router->post("/books", function () use ($twig) {
$controller = new BookController($twig);
$controller->index();
});
$router->get("/books/update/(\d+)", function ($id) use ($twig) {
$controller = new BookController($twig);
$controller->update($id);
});
$router->post("/books/update/(\d+)", function ($id) use ($twig) {
$controller = new BookController($twig);
$controller->update($id);
});
$router->get("/books/delete/(\d+)", function ($id) use ($twig) {
$controller = new BookController($twig);
$controller->delete($id);
});
$router->post("/books/delete/(\d+)", function ($id) use ($twig) {
$controller = new BookController($twig);
$controller->delete($id);
});
$router->set404(function () use ($twig) {
header("HTTP/1.1 404 Not Found");
echo $twig->render("404.twig", ["title" => "404 Not Found"]);
});
$router->run();
function set_flash($message, $type) {
$_SESSION["flash"] = ["message" => $message, "type" => $type];
}
function get_flash() {
return $_SESSION["flash"] ?? null;
}
function destroy_flash() {
unset($_SESSION["flash"]);
}
</code></pre>
<p><strong>controllers.php</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
class BookController {
private $model;
private $view;
function __construct($view) {
$this->model = new BookModel();
$this->view = $view;
}
public function index() {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$title = $_POST["title"];
$status = $_POST["status"];
if (empty($title)) {
set_flash("Please enter a title.", "error");
} elseif (empty($status)) {
set_flash("Please select a status.", "error");
} else {
$this->model->insert($title, $status);
set_flash("Book information added!", "success");
}
header("Location: /books");
exit();
}
$flash = get_flash();
destroy_flash();
$books = $this->model->selectAll();
echo $this->view->render("books.twig", ["title" => "Books", "books" => $books, "flash" => $flash]);
}
public function update($id) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$title = $_POST["title"];
$status = $_POST["status"];
if (empty($title)) {
set_flash("Please enter a title.", "error");
header("Location: /books/update/" . $id);
exit();
} elseif (empty($status)) {
set_flash("Please select a status.", "error");
header("Location: /books/update/" . $id);
exit();
} else {
$this->model->update($title, $status, $id);
set_flash("Book information updated!", "success");
}
header("Location: /books");
exit();
}
$flash = get_flash();
destroy_flash();
$book = $this->model->selectById($id);
if (empty($book)) {
set_flash("No book found with the corresponding ID to update.", "error");
header("Location: /books");
exit();
}
echo $this->view->render("books.update.twig", ["title" => "Books - " . $book["title"], "book" => $book, "flash" => $flash]);
}
public function delete($id) {
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$this->model->delete($id);
set_flash("Book successfully deleted.", "success");
header("Location: /books");
exit();
}
$flash = get_flash();
destroy_flash();
$book = $this->model->selectById($id);
if (empty($book)) {
set_flash("No book found with the corresponding ID to remove.", "error");
header("Location: /books");
exit();
}
echo $this->view->render("books.delete.twig", ["title" => "Books - " . $book["title"], "book" => $book, "flash" => $flash]);
}
}
</code></pre>
<p><strong>models.php</strong></p>
<pre class="lang-php prettyprint-override"><code><?php
class Model {
private $options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
];
protected $db;
function __construct() {
try {
$this->db = new PDO("pgsql:host=localhost;dbname=testdb", "postgres", "doritos1~", $this->options);
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), (int) $e->getCode());
}
}
}
class BookModel extends Model {
public function selectAll() {
$stmt = $this->db->prepare("SELECT id, title, status FROM books ORDER BY title ASC");
$stmt->execute();
return $stmt->fetchAll();
}
public function selectById($id) {
$stmt = $this->db->prepare("SELECT id, title, status FROM books WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
public function insert($title, $status) {
$stmt = $this->db->prepare("INSERT INTO books (title, status) VALUES (?, ?)");
$stmt->execute([$title, $status]);
}
public function update($title, $status, $id) {
$stmt = $this->db->prepare("UPDATE books SET title = ?, status = ? WHERE id = ?");
$stmt->execute([$title, $status, $id]);
}
public function delete($id) {
$stmt = $this->db->prepare("DELETE FROM books WHERE id = ?");
$stmt->execute([$id]);
}
}
</code></pre>
<p><strong>books.twig</strong></p>
<pre><code>{% extends "base.twig" %}
{% block content %}
<h1>Books</h1>
{% if flash %}
<p class="alert alert-{{ flash.type }}">{{ flash.message }}</p>
{% endif %}
<form action="/books" method="post">
<div>
<label for="input-title">Title</label>
</div>
<div>
<input type="text" name="title" id="input-title" size="32">
</div>
<div>
<label>Status</label>
</div>
<div>
<input type="radio" name="status" value="Unread" id="input-status-unread" checked>
<label for="input-status-unread">Unread</label>
</div>
<div>
<input type="radio" name="status" value="Reading" id="input-status-reading">
<label for="input-status-reading">Reading</label>
</div>
<div>
<input type="radio" name="status" value="Read" id="input-status-read">
<label for="input-status-read">Read</label>
</div>
<div>
<button type="submit">Add Book</button>
</div>
</form>
{% if books|length > 0 %}
<table>
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th>Options</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<td class="book-title">{{ book.title|e }}</td>
<td>{{ book.status }}</td>
<td><a href="/books/update/{{ book.id }}">Update</a> | <a href="/books/delete/{{ book.id }}">Delete</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No books found.</p>
{% endif %}
{% endblock %}
</code></pre>
<p><strong>books.update.twig</strong></p>
<pre><code>{% extends "base.twig" %}
{% block content %}
<h1>Books</h1>
{% if flash %}
<p class="alert alert-{{ flash.type }}">{{ flash.message }}</p>
{% endif %}
<form action="/books/update/{{ book.id }}" method="post">
<div>
<label for="input-title">Title</label>
</div>
<div>
<input type="text" name="title" id="input-title" size="32" value="{{ book.title|e }}">
</div>
<div>
<label>Status</label>
</div>
<div>
<input type="radio" name="status" value="Unread" id="input-status-unread" {{ book.status is same as("Unread") ? "checked" : ""}}>
<label for="input-status-unread">Unread</label>
</div>
<div>
<input type="radio" name="status" value="Reading" id="input-status-reading" {{ book.status is same as("Reading") ? "checked" : ""}}>
<label for="input-status-reading">Reading</label>
</div>
<div>
<input type="radio" name="status" value="Read" id="input-status-read" {{ book.status is same as("Read") ? "checked" : ""}}>
<label for="input-status-read">Read</label>
</div>
<div>
<button type="submit">Update Book</button>
</div>
</form>
{% endblock %}
</code></pre>
<p><strong>books.remove.twig</strong></p>
<pre><code>{% extends "base.twig" %}
{% block content %}
<h1>Books</h1>
{% if flash %}
<p class="alert alert-{{ flash.type }}">{{ flash.message }}</p>
{% endif %}
<p>Do you really want to remove the book <span class="book-title">{{ book.title|e }}</span>? Click <a href="/books">here</a> to go back.</p>
<form action="/books/delete/{{ book.id }}" method="post">
<div>
<button type="submit" class="remove-book">Remove Book</button>
</div>
</form>
{% endblock %}
</code></pre>
|
[] |
[
{
"body": "<p>That's pretty solid an implementation, I can find only a few spots.</p>\n\n<h3>Database connection</h3>\n\n<p>First and foremost, never a Model should create a database connection. All right now you have only a single model. What if you'd decide to extend it for CDs? Magazines? Add users? How many simultaneous connections will be made from a single script instance? A model should never connect on its own, it should just accept the existing connection as a constructor parameter. </p>\n\n<p>It constitutes quite a problem as there is no database connection to pass into a model in the controller. To solve it, you have to adapt a Dependency Injection Container. </p>\n\n<p>I am yet to learn this approach myself so I cannot provide a ready made code. But examples are plenty. </p>\n\n<p>On a bright side, you could use the same container in order to supply other services for your models, such as logger service, email service, and such. And even twig, so your router won't have to create an instance of a template engine, which is quite embarrassing, if you think of it. </p>\n\n<h3>Duplicated code</h3>\n\n<p>I see a condition to test the request method is duplicated in both the router and the controller. Why? You already determined the method in the router and there is no common code in the GET and POST processing. Why not to create separate functions for them?</p>\n\n<pre><code>public function updateSave($id) {\n $title = $_POST[\"title\"];\n $status = $_POST[\"status\"];\n\n if (empty($title)) {\n set_flash(\"Please enter a title.\", \"error\");\n header(\"Location: /books/update/\" . $id);\n exit();\n } elseif (empty($status)) {\n set_flash(\"Please select a status.\", \"error\");\n header(\"Location: /books/update/\" . $id);\n exit();\n } else {\n $this->model->update($title, $status, $id);\n set_flash(\"Book information updated!\", \"success\");\n }\n header(\"Location: /books\");\n exit();\n}\npublic function update($id) {\n $flash = get_flash();\n destroy_flash();\n $book = $this->model->selectById($id);\n\n if (empty($book)) {\n set_flash(\"No book found with the corresponding ID to update.\", \"error\");\n header(\"Location: /books\");\n exit();\n }\n echo $this->view->render(\"books.update.twig\", [\"title\" => \"Books - \" . $book[\"title\"], \"book\" => $book, \"flash\" => $flash]);\n}\n</code></pre>\n\n<h3>Better user experience.</h3>\n\n<p>It is considered a bad practice to feed a user with one error message at a time. Get all errors and show them at once</p>\n\n<pre><code> $error = '';\n $error .= ($title) ? '' : \"Please enter a title.\\n\";\n $error .= ($status) ? '' : \"Please enter a status.\\n\";\n\n if ($error) {\n set_flash($error, \"error\");\n $location = \"/books/update/$id\";\n } else {\n $this->model->update($title, $status, $id);\n set_flash(\"Book information updated!\", \"success\");\n $location = \"/books\";\n }\n header(\"Location: $location\");\n exit();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T15:04:26.257",
"Id": "469554",
"Score": "0",
"body": "Thank you for the advice! I've refactored my code to split things such as `update()` into `updateGet()` and `updatePost()` for each respective request method, as well as implementing the suggested error messaging model. I also separated the database connection from the model, supplying it instead in the `use` part of the router (for now). I definitely need to implement some kind of dependency injection, instead of passing around half a dozen arguments."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T14:03:23.897",
"Id": "239405",
"ParentId": "239402",
"Score": "2"
}
},
{
"body": "<p>Going through your code, it looks like a really good implementation, although when using bramus you could handle the method directly from the route, example:</p>\n<pre><code>$router->get('/listBooks','BookController@showall');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-16T11:00:42.817",
"Id": "270112",
"ParentId": "239402",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "239405",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T13:21:47.517",
"Id": "239402",
"Score": "1",
"Tags": [
"performance",
"php",
"mvc",
"twig"
],
"Title": "Improving upon basic MVC in PHP"
}
|
239402
|
<p>I am currently self-studying on Python generator object and use it to generate training data and do augmentation on-the-fly, then feed it into Convolutional Neural Networks.</p>
<p>Could anyone please help me to review my code? It runs properly, but I need review to make it more efficient and more properly structured. Besides, how can I check that using the generator will consume less memory (compared to just passing regular numpy array to the model)?</p>
<p>Thank you very much!</p>
<pre><code>from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten
import pandas as pd
import os
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
import tensorflow as tf
from augment import ImageAugment
class Generator():
def __init__(self, feat, labels, width, height):
self.feat = feat
self.labels = labels
self.width = width
self.height = height
def gen(self):
'''
Yields generator object for training or evaluation without batching
Yields:
im: np.array of (1,width,height,1) of images
label: np.array of one-hot vector of label (1,num_labels)
'''
feat = self.feat
labels = self.labels
width = self.width
height = self.height
i=0
while (True):
im = cv2.imread(feat[i],0)
im = im.reshape(width,height,1)
im = np.expand_dims(im,axis=0)
label = np.expand_dims(labels[i],axis=0)
yield im,label
i+=1
if i>=len(feat):
i=0
def gen_test(self):
'''
Yields generator object to do prediction
Yields:
im: np.array of (1,width,height,1) of images
'''
feat = self.feat
width = self.width
height = self.height
i=0
while (True):
im = cv2.imread(feat[i],0)
im = im.reshape(width,height,1)
im = np.expand_dims(im,axis=0)
yield im
i+=1
def gen_batching(self, batch_size):
'''
Yields generator object with batching of batch_size
Args:
batch_size (int): batch_size
Yields:
feat_batch: np.array of (batch_size,width,height,1) of images
label_batch: np.array of (batch_size,num_labels)
'''
feat = self.feat
labels = self.labels
width = self.width
height = self.height
num_examples = len(feat)
num_batch = num_examples/batch_size
X = []
for n in range(num_examples):
im = cv2.imread(feat[n],0)
try:
im = im.reshape(width,height,1)
except:
print('Error on this image: ', feat[n])
X.append(im)
X = np.array(X)
feat_batch = np.zeros((batch_size,width,height,1))
label_batch = np.zeros((batch_size,labels.shape[1]))
while(True):
for i in range(batch_size):
index = np.random.randint(X.shape[0],size=1)[0] #shuffle the data
feat_batch[i] = X[index]
label_batch[i] = labels[index]
yield feat_batch,label_batch
# def on_next(self):
# '''
# Advance to the next generator object
# '''
# gen_obj = self.gen_test()
# return next(gen_obj)
#
# def gen_show(self, pred):
# '''
# Show the image generator object
# '''
# i=0
# while(True):
# image = self.on_next()
# image = np.squeeze(image,axis=0)
# cv2.imshow('image', image)
# cv2.waitKey(0)
# i+=1
def gen_augment(self,batch_size,augment):
'''
Yields generator object with batching of batch_size and augmentation.
The number of examples for 1 batch will be multiplied based on the number of augmentation
augment represents [speckle, gaussian, poisson]. It means, the augmentation will be done on the augment list element that is 1
for example, augment = [1,1,0] corresponds to adding speckle noise and gaussian noise
if batch_size = 100, the number of examples in each batch will become 300
Args:
batch_size (int): batch_size
augment (list): list that defines what kind of augmentation we want to do
Yields:
feat_batch: np.array of (batch_size*n_augment,width,height,1) of images
label_batch: np.array of (batch_size*n_augment,num_labels)
'''
feat = self.feat
labels = self.labels
width = self.width
height = self.height
num_examples = len(feat)
num_batch = num_examples/batch_size
X = []
for n in range(num_examples):
im = cv2.imread(feat[n],0)
try:
im = im.reshape(width,height,1)
except:
print('Error on this image: ', feat[n])
X.append(im)
X = np.array(X)
n_augment = augment.count(1)
print('Number of augmentations: ', n_augment)
feat_batch = np.zeros(((n_augment+1)*batch_size,width,height,1))
label_batch = np.zeros(((n_augment+1)*batch_size,labels.shape[1]))
while(True):
i=0
while (i<=batch_size):
index = np.random.randint(X.shape[0],size=1)[0] #shuffle the data
aug = ImageAugment(X[index])
feat_batch[i] = X[index]
label_batch[i] = labels[index]
j=0
if augment[0] == 1:
feat_batch[(j*n_augment)+i+batch_size] = aug.add_speckle_noise()
label_batch[(j*n_augment)+i+batch_size] = labels[index]
j+=1
if augment[1] == 1:
feat_batch[(j*n_augment)+i+batch_size] = aug.add_gaussian_noise()
label_batch[(j*n_augment)+i+batch_size] = labels[index]
j+=1
if augment[2] == 1:
feat_batch[(j*n_augment)+i+batch_size] = aug.add_poisson_noise()
label_batch[(j*n_augment)+i+batch_size] = labels[index]
j+=1
i+=1
yield feat_batch,label_batch
def CNN_model(width,height):
# #create model
model = Sequential()
model.add(Conv2D(64, kernel_size=3, activation="relu", input_shape=(width,height,1)))
model.add(Conv2D(32, kernel_size=3, activation="relu"))
model.add(Flatten())
model.add(Dense(labels.shape[1], activation="softmax"))
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
if __name__ == "__main__":
input_dir = './mnist'
output_file = 'dataset.csv'
filename = []
label = []
for root,dirs,files in os.walk(input_dir):
for file in files:
full_path = os.path.join(root,file)
filename.append(full_path)
label.append(os.path.basename(os.path.dirname(full_path)))
data = pd.DataFrame(data={'filename': filename, 'label':label})
data.to_csv(output_file,index=False)
labels = pd.get_dummies(data.iloc[:,1]).values
X, X_val, y, y_val = train_test_split(
filename, labels,
test_size=0.2,
random_state=1234,
shuffle=True,
stratify=labels
)
X_train, X_test, y_train, y_test = train_test_split(
X, y,
test_size=0.025,
random_state=1234,
shuffle=True,
stratify=y
)
width = 28
height = 28
test_data = pd.DataFrame(data={'filename': X_test})
image_gen_train = Generator(X_train,y_train,width,height)
image_gen_val = Generator(X_val,y_val,width,height)
image_gen_test = Generator(X_test,None,width,height)
batch_size = 900
print('len data: ', len(X_train))
print('len test data: ', len(X_test))
#augment represents [speckle, gaussian, poisson]. It means, the augmentation will be done on the augment list element that is 1
#for example, augment = [1,1,0] corresponds to adding speckle noise and gaussian noise
augment = [1,1,1]
model = CNN_model(width,height)
model.fit_generator(
generator=image_gen_train.gen_augment(batch_size=batch_size,augment=augment),
steps_per_epoch=np.ceil(len(X_train)/batch_size),
epochs=20,
verbose=1,
validation_data=image_gen_val.gen(),
validation_steps=len(X_val)
)
model.save('model_aug_3.h5')
model = tf.keras.models.load_model('model_aug_3.h5')
#Try evaluate_generator
image_gen_test = Generator(X_test,y_test,width,height)
print(model.evaluate_generator(
generator=image_gen_test.gen(),
steps=len(X_test)
))
#Try predict_generator
image_gen_test = Generator(X_test,None,width,height)
pred = model.predict_generator(
generator=image_gen_test.gen_test(),
steps=len(X_test)
)
pred = np.argmax(pred,axis=1)
# image_gen_test = Generator(X_test,pred,width*3,height*3)
# image_gen_test.gen_show(pred)
wrong_pred = []
for i,ex in enumerate(zip(pred,y_test)):
if ex[0] != np.argmax(ex[1]):
wrong_pred.append(i)
print(wrong_pred)
# for i in range(len(X_test)):
# im = cv2.imread(X_test[i],0)
# im = cv2.putText(im, str(pred[i]), (10,15), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
# print(i)
# cv2.imshow('image',im)
# cv2.waitKey(0)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Class syntax</h2>\n\n<p>The parens are not necessary here:</p>\n\n<pre><code>class Generator():\n</code></pre>\n\n<h2>Type hints</h2>\n\n<p>Type hints will add more built-in documentation to your code, and will help the better IDEs give you static analysis hints:</p>\n\n<pre><code>def __init__(self, feat, labels, width, height):\n</code></pre>\n\n<p>can become, at a guess,</p>\n\n<pre><code>def __init__(self, feat: Sequence[float], labels: Sequence[str], width: int, height: int):\n</code></pre>\n\n<h2>Iteration</h2>\n\n<p>First of all, this in <code>gen</code>:</p>\n\n<pre><code> while (True):\n</code></pre>\n\n<p>does not require parens. Also, rather than manually maintaining <code>i</code>, you should use <code>for i in itertools.cycle(range(len(feat)))</code>.</p>\n\n<p>Similarly, this:</p>\n\n<pre><code> i=0\n while (i<=batch_size):\n # ...\n i+=1\n</code></pre>\n\n<p>should just be <code>for i in range(batch_size):</code>.</p>\n\n<h2>Bare <code>except</code></h2>\n\n<p>This:</p>\n\n<pre><code> try:\n im = im.reshape(width,height,1)\n except:\n print('Error on this image: ', feat[n])\n</code></pre>\n\n<p>should not have an exception catch clause that is so general. The broadest that you should catch, if you do not know what the typical exceptions are, is <code>Exception</code>. Catching everything also prevents <code>KeyboardInterrupt</code> (Ctrl+C break) from working.</p>\n\n<h2>Variable names</h2>\n\n<p>This:</p>\n\n<pre><code> X = []\n</code></pre>\n\n<p>should be lowercase, according to the PEP8 style guide.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:06:02.787",
"Id": "239480",
"ParentId": "239403",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T13:30:55.843",
"Id": "239403",
"Score": "3",
"Tags": [
"python",
"machine-learning",
"generator",
"neural-network",
"tensorflow"
],
"Title": "Creating generator object with image augmentation to train Convolutional Neural Networks with Keras"
}
|
239403
|
<p>I am making a super simple and dumb terminal text game to try out unittest in python. I have ran into a problem. When I run the test, the game loop is ran, and I have to manually insert input to continue to the tests. </p>
<p>Is there a way to not run the game loop when I run my tests, so I can test the class methods only?</p>
<p>Any other advice on the code in general would be helpful appreciated as well.</p>
<p>Game concept: Player is prompted to build, gather, recruit, or attack every turn and when someone's castle health is <= 0, game is over. </p>
<pre class="lang-py prettyprint-override"><code>import os, random
class Player():
def __init__(self):
self.castle = 1
self.villagers = 1
self.warriors = 0
self.food = 0
self.stone = 0
def takeTurn(self):
action = 0
action = int(input("1) Build\n2) Gather\n3) Recruit\n4) Attack\n"))
if action == 1:
self.build()
elif action == 2:
self.gather()
elif action == 3:
self.recruit()
elif action == 4:
self.attack()
else:
self.takeTurn()
def build(self):
if self.stone >= 1:
self.castle += 1
self.stone -= 1
else:
os.system('clear')
if self.__class__.__name__ == "Player":
print("You don't have enough stone!\n")
printMenu()
self.takeTurn()
def gather(self):
self.food += self.villagers
self.stone += self.villagers
def recruit(self):
if self.food >= 1:
self.warriors += 1
self.food -= 1
else:
os.system('clear')
if self.__class__.__name__ == "Player":
print("You don't have enough food!\n")
printMenu()
self.takeTurn()
def attack(self):
if self.warriors >= 1:
if self.__class__.__name__ == "Player":
ai.castle -= self.warriors
elif self.__class__.__name__ == "AI":
player.castle -= self.warriors
class AI(Player):
def __init__(self):
super().__init__()
def makeMove(self):
action = 0
# Win if player castle weak
if player.castle == self.warriors:
player.castle -= self.warriors
# Build if castle weak
elif self.castle == player.warriors:
if self.stone >= 1:
self.castle += 1
else:
action = random.randint(2, 4)
else:
action = random.randint(1, 4)
if action == 1:
super().build()
if action == 2:
super().gather()
if action == 3:
super().recruit()
if action == 4:
super().attack()
player = Player()
ai = AI()
def printMenu():
print("You:\nCastle: " + str(player.castle) + " Food: " + str(player.food) + " Stone: " + str(player.stone) + " Villagers: " + str(player.villagers) + " Warriors: " + str(player.warriors) + "\n")
print("Computer:\nCastle: " + str(ai.castle) + " Food: " + str(ai.food) + " Stone: " + str(ai.stone) + " Villagers: " + str(ai.villagers) + " Warriors: " + str(ai.warriors) + "\n")
def gameLoop():
# MAIN LOOP
playing = False
if playing:
printMenu()
player.takeTurn()
ai.makeMove()
if ai.castle <= 0:
playing = False
print("You Win!\n")
elif player.castle <= 0:
playing = False
print("You Lose!")
else:
os.system('clear')
gameLoop()
</code></pre>
<pre class="lang-py prettyprint-override"><code>import unittest
from game.main import Player
class TestPlayer(unittest.TestCase):
def setUp(self):
self.player = Player()
def test_build(self):
# Should fail
self.player.castle = 2
self.player.stone = 1
self.player.build()
self.assertEqual(self.player.castle, 1)
if __name__ == '__main__':
unittest.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T14:46:26.210",
"Id": "469553",
"Score": "7",
"body": "Put your `gameloop()` call inside a `if __name__ == '__main__':` block so it doesn't run when you import the module."
}
] |
[
{
"body": "<p>You already have the answer to your \"bug\" given in the comments, but I will try to give you a more in-depth review. Nevertheless, I will repeat the aforementioned solution: to avoid the program auto-running on import, but your main call inside of a <code>if __name__ == \"__main__\"</code> (read more <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">here</a> if interested).</p>\n\n<p>For your <code>__init__</code> method, having your method initializers as (default) arguments tend to give more flexibility down the road as the project grows:</p>\n\n<pre><code> def __init__(self, castle=1, villagers=1, warriors=0, food=0, stone=0):\n self.castle = castle\n self.villagers = villagers\n self.warriors = warriors\n self.food = food\n self.stone = stone\n</code></pre>\n\n<p>For your first real method, I would recommend staying with the Python standard of <code>snake_case</code> over <code>camelCase</code>. Furthermore, initialising the variable <code>action</code> to 0 doesn't really do you anything since you overwrite it in the following line. And since you rely on that input I think you should figure out what to do when you <em>don't</em> get an <code>int</code>, or if you get something like 11 (because 11 here would likely be a typo, given the options).</p>\n\n<p>This, quite naturally, leads on to the purpose of testing (yay!). A nice thing about tests is that they allow you to think about what exactly you want to happen when you create an object or call on a function. For your <code>takeTurns</code> function, that would maybe be that you're only allowed to enter digits, and if you don't enter a single digit in the range 0–5 it throws an exception or it asks for another input. You would then basically implement your function (after the tests) to meet all the requirements you set forth in the beginning. You may then also find that maybe you were thinking about it the wrong way; in this case it could be that maybe <code>take_turns</code> (I renamed it for you...) shouldn't be asking for <code>input()</code> but rather be accepting an argument <code>take_turns(user_choice)</code>.</p>\n\n<p>To finalise, I'll add some smaller pieces of advice.</p>\n\n<ul>\n<li><p>Instead of <code>self.__class__.__name__ == \"Player\":</code> you could (and should) use <code>isinstance(self, Player)</code>.</p></li>\n<li><p>Instead of <code>action = random.randint(1, 4)</code> coupled with 4 <code>if</code>-statements, there's a handy little function in <code>random</code> called <code>choice</code> (have a look <a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\">here</a>). You could also make your <code>AI</code> class much smaller by rethinking how the AI differs (or doesn't differ) from a <code>Player</code>.</p></li>\n<li><p><a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">f-strings are super nice</a>. Instead of <code>print(\"You:\\nCastle: \" + str(player.castle) + \" Food: \" + str(player.food) + \" Stone: \" + str(player.stone) + \" Villagers: \" + str(player.villagers) + \" Warriors: \" + str(player.warriors) + \"\\n\")</code>, you could have (and notice that I removed <code>str()</code> since you don't need it):</p>\n\n<pre><code>print(f\"\"\"You:\nCastle: {player.castle}\nFood: {player.food}\nStone: {player.stone}\nVillagers: {player.villagers}\nWarriors: {player.warriors}\"\"\")\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T20:49:02.807",
"Id": "469663",
"Score": "3",
"body": "There's a typo here but it's not enough characters to submit an edit: `instanceof` should be `isinstance`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:52:37.393",
"Id": "469721",
"Score": "1",
"body": "Corrected, thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:09:30.987",
"Id": "469827",
"Score": "0",
"body": "Thank you very much! Lots of good advice."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:28:06.023",
"Id": "239459",
"ParentId": "239408",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239459",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T14:37:07.370",
"Id": "239408",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"unit-testing"
],
"Title": "Testing Terminal Text Game with Classes and Game Loop"
}
|
239408
|
<p>Here is a good <a href="https://foonathan.net/2018/07/optional-reference/" rel="nofollow noreferrer">article</a> on an optional reference type in C++. They discuss <code>std::optional<T&></code>, but as that doesn't compile I have made my own.</p>
<p>One purpose of this type is to remove raw pointers from function signatures (where references alone cannot be used), as a raw pointer does not convey any indication of what it will be used for (become owned, deleted, iterated, dereferenced, etc).</p>
<pre><code>#include <functional>
#include <optional>
template<typename T>
/** @brief An optional refference **/
class opt_ref {
using std_opt_ref = std::optional<std::reference_wrapper<T>>;
std_opt_ref data = std::nullopt;
public:
using type = typename std::reference_wrapper<T>::type;
/** public member functions **/
T& get() { return data.value().get(); }
const T& get() const { return data.value().get(); }
bool has_value() const { return data.has_value(); }
T& value_or(T&& other) const { return data.value_or(other); }
/** constructors **/
opt_ref() {}
opt_ref(T& source) : data(source) {}
opt_ref& operator = (T&& other) { data.value().get() = other; return *this; }
/** comparisons **/
bool operator == (const T& t) { return data.value() == t; }
bool operator == (const std::nullopt_t&) {return !data.has_value(); }
/** implicit conversion **/
operator T&() { return data.value().get(); }
operator const T&() const { return data.value().get(); }
operator std::reference_wrapper<T>() { return data.value(); }
operator const std::reference_wrapper<T>() const { return data.value(); }
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T15:40:17.060",
"Id": "469558",
"Score": "1",
"body": "A strange article indeed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T19:15:56.070",
"Id": "469570",
"Score": "0",
"body": "Here's another article for you: https://thephd.github.io/to-bind-and-loose-a-reference-optional It seems like you've implemented assign-through? Is that what you meant to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T11:17:53.030",
"Id": "528855",
"Score": "0",
"body": "Another nice article: [Why Optional References Didn’t Make It In C++17](https://www.fluentcpp.com/2018/10/05/pros-cons-optional-references/)"
}
] |
[
{
"body": "<h1>Design</h1>\n\n<p>References are different from pointers in two ways:</p>\n\n<ul>\n<li><p>they are designed to be aliases to the objects they refer to, so syntactically they are treated with special care;</p></li>\n<li><p>they cannot be rebound.</p></li>\n</ul>\n\n<p>You cannot always emulate the first bullet with an <code>optional</code> — for example, there's no general way to make <code>opt.f()</code> call <code>opt.value().f()</code>. You still have to resort to some other syntax like <code>opt->value()</code>. Therefore, my advice is to simply treat <code>opt_ref<T></code> like an immutable nullable pointer that does not own the referred-to object — don't follow <code>std::reference_wrapper</code>.</p>\n\n<h1>Code Review</h1>\n\n<blockquote>\n<pre><code>using type = typename std::reference_wrapper<T>::type;\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper#Member_types\" rel=\"nofollow noreferrer\"><code>typename std::reference_wrapper<T>::type</code></a> is just <code>T</code>. Also, the standard terminology is <code>value_type</code>.</p>\n\n<blockquote>\n<pre><code>T& get() { return data.value().get(); }\nconst T& get() const { return data.value().get(); }\nbool has_value() const { return data.has_value(); }\nT& value_or(T&& other) const { return data.value_or(other); }\n</code></pre>\n</blockquote>\n\n<p><code>has_value</code> is <code>noexcept</code>. Why does <code>value_or</code> take an rvalue reference? To introduce dangling references as in <code>opt.value_or(1)</code>? Take an lvalue reference instead.</p>\n\n<blockquote>\n<pre><code>bool operator == (const T& t) { return data.value() == t; }\nbool operator == (const std::nullopt_t&) {return !data.has_value(); }\n</code></pre>\n</blockquote>\n\n<p>I'm not sure this is the right approach. The first <code>==</code> compares values (and throws an exception if there is no value), whereas the second <code>==</code> compares the references themselves. You can imitate the behavior of <code>std::optional</code>:</p>\n\n<pre><code>bool operator==(const opt_ref<T>& a, const opt_ref<T>& b)\n{\n if (a.has_value() != b.has_value()) {\n return false;\n } else if (!a.has_value()) { // and !b.has_value()\n return true;\n } else {\n return a.get() == b.get();\n }\n}\n</code></pre>\n\n<blockquote>\n<pre><code>operator T&() { return data.value().get(); }\noperator const T&() const { return data.value().get(); }\noperator std::reference_wrapper<T>() { return data.value(); }\noperator const std::reference_wrapper<T>() const { return data.value(); }\n</code></pre>\n</blockquote>\n\n<p>As I said before: are you sure you want this (especially the implicit conversions to <code>reference_wrapper</code>)?</p>\n\n<h1>Other functionalities</h1>\n\n<p>Consider:</p>\n\n<ul>\n<li><p><code>operator*</code> and <code>operator-></code>;</p></li>\n<li><p><code>explicit operator bool</code>;</p></li>\n<li><p><code>has_value</code>;</p></li>\n<li><p>...</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T02:15:11.563",
"Id": "239426",
"ParentId": "239409",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239426",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T14:53:12.267",
"Id": "239409",
"Score": "4",
"Tags": [
"c++",
"c++17",
"optional",
"reference"
],
"Title": "C++ Optional Reference"
}
|
239409
|
<p>I am trying to get my head around exceptions, and implement exception handling that ultimately gets logged, since my code runs as a remote job and reviewing a txt log is the best means of reviewing results. Currently I have an issue where "unexpected" exceptions only show up in the console, so my focus right now is dealing with that.</p>
<p>So... here I have a first pass at trying to catch an unexpected exception and provide output that shows me script name and line, the exception message, and the exception type so I can potentially go back and add "expected" exception handling by specific type, and log those slightly differently.</p>
<pre><code>class PxUnexpectedException : Exception {
#PxUnexpectedException() {}
PxUnexpectedException([string] $message) : base($message) {}
#PxUnexpectedException([string] $message, [Exception] $inner) : base($message, $inner) {}
static [array] ReviseTrace ([string]$path, [array]$trace) {
$scriptPath = ", $(Split-Path $path -parent)\"
$revisedTrace = $trace -replace [Regex]::Escape($scriptPath), ' in '
return $revisedTrace
}
}
function Test ($path) {
try {
Test-Path $path -errorAction:stop > $null
} catch {
# Standard Px error trap
$trace = [PxUnexpectedException]::ReviseTrace($_.InvocationInfo.ScriptName, $_.ScriptStackTrace)
throw [PxUnexpectedException] "[$($_.Exception.GetType().fullname)] $($_.Exception.Message)`n$trace"
}
}
function ConvertException ([Exception]$exception) {
foreach ($line in ($exception.Message -split "`n")) {
Write-Host "$line" -ForegroundColor:red
}
}
CLS
$path = '\\Server\InvalidFolder|'
try {
Test $path
} catch [PxUnexpectedException] {
ConvertException $_.Exception
}
</code></pre>
<p>My issue at this point is all the work needed to get a good message for <code>throw [PxUnexpectedException]</code>. I will have this same two lines (the <code>$trace =</code> and the <code>throw</code>) perhaps hundreds of times, and it feels like I SHOULD be able to instantiate my own exception but pass the entire error item to my constructor. Something like <code>throw [PxUnexpectedException] $_</code> and handle creating the message within the constructor.</p>
<p>Am I really getting this all wrong? Or is duplication of code just the way this will have to be done?
Also, in the .NET examples I have adapted my class from, all three constructors are there. But it seems to me that, assuming this IS the only way to build the message, the only constructor I will ever need is the one that takes the single <code>$message</code> argument, so simplification is best hear. Am I missing something and not having all three constructors is really going to come back to bite me?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T10:51:31.483",
"Id": "469727",
"Score": "0",
"body": "Unable to find type `[PxExpectedException]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:15:54.980",
"Id": "469762",
"Score": "0",
"body": "@JosefZ Typo. The type should be `[PxUnexpectedException]` in all cases. Revised the OP."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T20:57:09.740",
"Id": "239416",
"Score": "2",
"Tags": [
"powershell",
"exception"
],
"Title": "Powershell custom exception class"
}
|
239416
|
<p>This is a script I've written to deploy the Elastic Stack.</p>
<p>Can you help me improve it? Especially the parts called out with <code>***</code> markings.</p>
<p><code>deploy.sh</code>:</p>
<pre class="lang-bsh prettyprint-override"><code>#!/usr/bin/env bash
sudo sysctl -w vm.max_map_count=262144
#use the elastic utility to gen certs
docker-compose -f create-certs.yml run --rm create_certs
# Start the stack initially per Elastic documentation
docker-compose up -d
#run a password gen script to make some passwords
docker exec elasticsearch /bin/bash -c "bin/elasticsearch-setup-passwords \
auto --batch \
--url https://elasticsearch:9200" | tee es_passes.txt
#sub generated kibana and es passes into .env -> *** This could be better ***
cat es_passes.txt | grep 'PASSWORD kibana' | awk '{print $4}' | xargs -I {} sed -r -i 's/(KIBANA_PASS=)\w/\1{}/gip' .env
cat es_passes.txt | grep 'PASSWORD elastic' | awk '{print $4}' | xargs -I {} sed -r -i 's/(ES_PASS=)\w/\1{}/gip' .env
#eliminate duplicate lines -> *** How can I do this better ***
awk '!seen[$0]++' .env > .env_dedup
mv .env_dedup .env
#show the contents of .env
cat .env
#restart the stack after setting the passwords
docker-compose stop
docker-compose up -d
</code></pre>
<p><code>.env</code>:</p>
<pre><code>KIBANA_PASS=some_supersecure_kibana_pass
ES_PASS=some_supersecure_elasticsearch_pass
</code></pre>
<p>other files:</p>
<ul>
<li><code>docker-compose.yml</code></li>
<li><code>create-certs.yml</code></li>
</ul>
<hr>
<p>update:
I have fixed the substitution lines. They now read:</p>
<pre class="lang-bsh prettyprint-override"><code>cat es_passes.txt | grep 'PASSWORD kibana' | awk '{print $4}' | xargs -I {} sed -r -i 's/^KIBANA_PASS=.*$/KIBANA_PASS={}/' .env
cat es_passes.txt | grep 'PASSWORD elastic' | awk '{print $4}' | xargs -I {} sed -r -i 's/^ES_PASS=.*$/ES_PASS={}/' .env
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T22:02:09.113",
"Id": "469572",
"Score": "2",
"body": "(Down-voters please comment.) You are right: \"the `cat|grep|awk|sed` pipes\" leave ample room for improvement. Let me add security concerns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T13:15:05.730",
"Id": "469621",
"Score": "0",
"body": "Not only is this deploy script piping everything here and there and saving passwords to plaintext files in the dir where it is deployed(!), it is also not functional :( The `.env` currently does not substitute the old password with the new completely.\nI end up with:\n```\nKIBANA_PASS=newly_genned_passsome_supersecure_kibana_pass\nES_PASS=newly_genned_passsome_supersecure_elasticseach_pass\n```\nFixing that now..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T14:25:35.487",
"Id": "469625",
"Score": "0",
"body": "Please don't update the code in your question after answers come in. Feel free to ask a new question instead."
}
] |
[
{
"body": "<p>Shots from the hip, three decades since I seriously <em>programmed</em> shell notwithstanding:</p>\n\n<ul>\n<li>document your code - in the code.<br>\nThe comments presented are a good start - in the middle, irritatingly.<br>\nWhat is the whole script useful for, how shall it be used?<br>\nYou can even have <em>executable comments</em>:<br>\nif called incorrectly or with <code>-h</code>, <code>--help</code> (or even <code>-?</code>), print a<br>\n<code>Usage:</code> to \"standard error output\"/file descriptor 2<br>\nThen there are things left open:<br>\nWhy <code>tee</code> to <code>es_passes.txt</code> instead of redirect, have <code>sed</code> <code>p</code>rint the pattern space? (I read <em>Spanish</em>_passes at first - the reason why in the following comment <code>es</code> may be as appropriate as <code>elastic</code> needed horizontal scrolling)</li>\n<li>with security related artefacts, assess security implications</li>\n<li>choose the right tool<br>\nthis does not just depend on task at hand and tools available, but on \"craftsperson\", too<br>\n(Here, I might have chosen perl in the 90ies and Python in the current <strike>millenium</strike> century)</li>\n<li>the options and commands to <code>sed</code> speak of GNU sed<br>\n• mention such in your question<br>\n• consider using <code>--posix</code></li>\n<li>don't use <code>cat | command</code> where <code>command</code> allows specifying input file(s)</li>\n<li>prefer using <code>awk</code>s <em>patterns</em> over separate filtering (e.g.,<code>grep</code>)<br>\n(unless input is <em>massive</em>):<br>\n<code>awk '/PASSWORD kibana|elastic/{print $4}' es_passes.txt …</code><br>\n(<em>not</em> convinced piping to <code>xargs -I</code> is the way to proceed.)</li>\n<li>the conventional \"unix\" way to <code>eliminate duplicate lines</code> is <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/utilities/uniq.html\" rel=\"noreferrer\">uniq</a>, preceded with a <code>sort</code> where global uniqueness is necessary and altering line sequence admissible.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T09:06:16.977",
"Id": "239435",
"ParentId": "239417",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "239435",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T21:11:38.143",
"Id": "239417",
"Score": "2",
"Tags": [
"bash"
],
"Title": "Writing a better deploy script"
}
|
239417
|
<p>An exercise asks that we extend the below random number generator app to print to the console how many times the user guessed before guessing the correct random number. </p>
<p>I first declared what I call a counter variable <code>numberOfGuesses</code> inside the <code>keepPlaying</code> while loop and then inside the <code>continueGuessing</code> while loop I increment this number by 1 before I check the user's guess against the random number generated. This works, but then I tried declaring numberOfGuesses at the top of the program and commented out the former placement, as you can see below, and this also worked. </p>
<p>My question is, which is the better way of these two to solve this, and is there another even better way to solve this problem by using another loop perhaps or would that be silly/overkill/not workable? </p>
<pre><code>var randomNumber = 1
var numberOfGuesses = 0
var continueGuessing = true
var keepPlaying = true
var input = ""
while keepPlaying {
//get a random number between 0 - 100
randomNumber = Int(arc4random_uniform(101))
print("The random number to guess is: \(randomNumber)")
//var numberOfGuesses = 0 //can go here, or in global variables up top!
while continueGuessing { //
print("Pick a number between 0 and 100.")
//get keyboard input, and trim the new line
input = String(bytes: FileHandle.standardInput.availableData, encoding: .utf8)!
input = input.trimmingCharacters(in: .whitespacesAndNewlines)
if let userGuess = Int(input) {
numberOfGuesses += 1
if userGuess == randomNumber {
continueGuessing = false //terminator for this while loop
print("Correct number!")
print("You have made this number of attempts to get it right: \(numberOfGuesses)")
} else if userGuess > randomNumber {
//user guessed too high
print("Your guess is too high!")
} else {
//no reason to check if userGuess < randomNumber. It has to be.
print("Your guess is too low!")
}
} else {
print("Invalid guess, please try again.")
}
}
print("Play again? Y or N")
input = String(bytes: FileHandle.standardInput.availableData,encoding: .utf8)!
input = input.trimmingCharacters(in: .whitespacesAndNewlines)
if input == "N" || input == "n" {
keepPlaying = false //a way to exit while loop
print("You have played the game this number of times: \(numberOfGuesses)")
}
continueGuessing = true
}
</code></pre>
|
[] |
[
{
"body": "<p>As a general rule, you want to use the narrowest possible scope for all variables. We do this so that:</p>\n\n<ol>\n<li><p>The declaration is close to where we use it, making it easier to reason about why the variable exists.</p></li>\n<li><p>It minimizes the chance of unintended consequences where the variable is accidentally updated somewhere else.</p></li>\n</ol>\n\n<p>In this case, it’s so trivial that it doesn’t matter that much, but as your code increases in complexity, this becomes increasingly important. This practice of restricting variables to the narrowest possible scope becomes a central precept in writing safe code: It’s much harder to have unintended consequences or accidentally state changes if variables have narrow scopes.</p>\n\n<p>So, if <code>numberOfGuesses</code> represents how many guesses it took you to guess a particular random number, then it should be inside the <code>keepPlaying</code> loop. But if you also wanted to keep track of the total number of guesses for all the times you played, then that (probably best kept track in another variable, perhaps, <code>totalNumberOfGuesses</code>) would be outside this outer loop.</p>\n\n<p>By the way, while you’re at it, the <code>continueGuessing</code> and <code>randomNumber</code>, belong inside this <code>keepPlaying</code> loop, too.</p>\n\n<p>By the way,</p>\n\n<ol start=\"3\">\n<li>If you define variables only used within the scope of a loop, it saves you from having to reset that variable for the next iteration. For example, right now you are resetting <code>continueGuessing</code> back to <code>true</code> as the last step in the <code>keepPlaying</code> loop; if you define <code>continueGuessing</code> within the loop, then you wouldn’t have to reset it again at the end of the loop, resulting in simpler code.</li>\n</ol>\n\n<p>In your code, you make reference to “globals”. As a general rule, we try to minimize the use of globals because as as apps scale, globals can make it hard to test, harder to reason about state changes, etc. See <a href=\"https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil#148109\">Why is Global State so Evil</a> or google “globals are evil”.</p>\n\n<hr>\n\n<p>Some unrelated observations:</p>\n\n<ol>\n<li><p>Rather than </p>\n\n<pre><code>let randomNumber = Int(arc4random_uniform(101))\n</code></pre>\n\n<p>I’d instead recommend:</p>\n\n<pre><code>let randomNumber = Int.random(in: 0...100)\n</code></pre>\n\n<p>It is equivalent, but arguably is more intuitive. (This would be especially true if you wanted to go from 1 to 100 instead, the <code>arc4random_uniform</code> code would become even less intuitive, whereas <code>random(in: 1...100)</code> is perfectly natural and trivial to reason about.</p></li>\n<li><p>When you have a loop that you are always going to do at least once, rather than a <code>while</code> loop, we’d often consider <code>repeat</code>-<code>while</code>. E.g. rather than</p>\n\n<pre><code>var shouldPlayAgain = true\nwhile shouldPlayAgain {\n ...\n\n shouldPlayAgain = ...\n}\n</code></pre>\n\n<p>You might do:</p>\n\n<pre><code>var shouldPlayAgain: Bool\nrepeat {\n ...\n\n shouldPlayAgain = ...\n} while shouldPlayAgain\n</code></pre>\n\n<p>Technically the latter is a tad more efficient, but the main benefit is that it makes your intent (to check at the end) absolutely clear.</p></li>\n<li><p>At the end, you appear to want to be printing number of times the game was played, but you’re printing the number of guesses.</p>\n\n<p>E.g. if you played twice, the first time requiring 3 guesses and the second time requiring 4 guesses, do you want to say “you played 2 times” or do you want to say “you guessed a total of 7 times”?</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:15:58.637",
"Id": "239491",
"ParentId": "239418",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239491",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T21:38:43.640",
"Id": "239418",
"Score": "0",
"Tags": [
"swift"
],
"Title": "Where best to declare a counter variable to track number of guesses?"
}
|
239418
|
<p>I would like to ask for a code review as I feel like it's not the most efficient way of doing it. For context I have a add-ins with all the code in module and then the <code>SheetChange</code>event is in <code>ThisWorkbook</code>. Also in the add-ins I have 2 sheets that will have data on it so that the <code>ActiveWorkbook</code> will be able to read this info when running code form module the events will fire and do a <code>vlookup</code> against the sheet in the add-ins.</p>
<pre><code>Private Sub ExcelApp_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Dim KeyCells As Range
Dim wsMyList As Worksheet
Set wsMyList = ThisWorkbook.Sheets(2)
Set KeyCells = [B3,B5] 'I only need this 2 cells to fire events
If Sh.Name <> "Response" Then
If Not Intersect(Target, Sh.Range("B3:B5")) Is Nothing Then 'not too sure how to do it here so I put 3 cells instead of 2
If Target.Row = 3 Then
If Range("B3").Value = vbNullString Then Exit Sub
Application.EnableEvents = False
If Sh.Range("B3").Value <> vbNullString Then
Sh.Range("B4").Value = Application.WorksheetFunction.VLookup(Sh.Range("B3").Value, wsMyList.Range("A:B"), 2, False)
Sh.Range("B6").Value = "Type or Select a transaction"
Else
Sh.Range("B4").Value = "Type or Select a program"
End If
Columns.ClearColumns
Transactions.FetchTransactions
Application.EnableEvents = True
ElseIf Target.Row = 5 Then
If Range("B5").Value = vbNullString Then Exit Sub
Application.EnableEvents = False
If Range("B5").Value <> vbNullString Then
Sh.Range("B6").Value = Application.WorksheetFunction.VLookup(Sh.Range("B5").Value, wsMyList.Range("D:E"), 2, False)
Columns.ClearColumns
Columns.PopulateFields
End If
Application.EnableEvents = True
End If
End If
End If
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T20:35:43.650",
"Id": "470863",
"Score": "0",
"body": "Please could you flesh out the description, currently it conveys nothing to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-07T07:32:34.970",
"Id": "470902",
"Score": "0",
"body": "@Peilonrayz sorry what do you mean? I don’t understand your ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-13T17:08:09.487",
"Id": "471665",
"Score": "0",
"body": "Please attempt to provide a more general description of the code's purpose. What are you doing with Excel and why? What are your specific efficiency concerns?"
}
] |
[
{
"body": "<p>When writing any kind of event method, I always try to minimize the code that executes because you don't want the user to be aware of processing that is happening between the keystrokes. In your case, your code is firing each time ANY cell on ANY sheet is changed. So in the spirit of keeping things streamlined, don't create, initialize, or perform any logic that you don't really need (until you need it). Using this philosophy, the beginning of my example method would look like this:</p>\n\n<pre><code>If Sh.Name = \"Response\" Then Exit Sub\n\nDim checkCells As Range\nSet checkCells = Union(Sh.Range(\"B3\"), Sh.Range(\"B5\"))\nIf Intersect(Target, checkCells) Is Nothing Then Exit Sub\nIf Target.Address = vbNullString Then Exit Sub\n</code></pre>\n\n<p>Notice that if the changed sheet is \"Response\", then initializing any other variable is meaningless. Once we get past that, a <code>checkCells</code> range is established using the <code>Union</code> function. It may be a bit overkill sometimes, but clearly illustrates the idea that you're looking at multiple, non-contiguous cells/ranges. </p>\n\n<p>Also, from your OP code, if either cell is empty, you are immediately exiting. So you can check the target address after the other checks right away.</p>\n\n<p>But then I get into an issue where you check if the cell value is null, but right away you're checking that it has a value:</p>\n\n<pre><code>If Range(\"B3\").Value = vbNullString Then Exit Sub\nApplication.EnableEvents = False\nIf Sh.Range(\"B3\").Value <> vbNullString Then ...\n</code></pre>\n\n<p>This is redundant. And -- by the way -- you'll never get to your <code>Else</code> statement because you've already exited if B3 is a null string.</p>\n\n<p>The statement in both parts of your <code>If</code> statement is confusing:</p>\n\n<pre><code>Columns.ClearColumns\n</code></pre>\n\n<p><code>Columns</code> is a property of a <code>Range</code> or <code>Worksheet</code>, and <code>ClearColumns</code> is not a method of <code>Range</code> at all that I know of. So I'm assuming it's a part of the add-in. But if <code>Columns</code> is the name of one of your code modules, then change it. Using <code>Columns</code> is not a good name to use because it is the same as an existing property and is confusing. If you are clearing columns on a worksheet, then specify which worksheet <strong>always</strong>. I'm also assuming the <code>Transactions</code> is a code module in your VBA project as well.</p>\n\n<p>Here is all of the code:</p>\n\n<pre><code>Option Explicit\n\nPrivate Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)\n If Sh.Name = \"Response\" Then Exit Sub\n\n Dim checkCells As Range\n Set checkCells = Union(Sh.Range(\"B3\"), Sh.Range(\"B5\"))\n If Intersect(Target, checkCells) Is Nothing Then Exit Sub\n If Target.Address = vbNullString Then Exit Sub\n\n Dim wsMyList As Worksheet\n Set wsMyList = ThisWorkbook.Sheets(2)\n\n Application.EnableEvents = False\n With Sh\n Dim lookupArea As Range\n If Target.Row = 3 Then\n Set lookupArea = wsMyList.Range(\"A:B\")\n .Range(\"B4\").Value = Application.WorksheetFunction.VLookup(Target.Value, _\n lookupArea, _\n 2, False)\n .Range(\"B6\").Value = \"Type or Select a transaction\"\n Columns.ClearColumns\n Transactions.FetchTransactions\n ElseIf Target.Row = 5 Then\n Set lookupArea = wsMyList.Range(\"D:E\")\n .Range(\"B6\").Value = Application.WorksheetFunction.VLookup(Target.Value, _\n lookupArea, _\n 2, False)\n Columns.ClearColumns\n Columns.PopulateFields\n End If\n End With\n Application.EnableEvents = True\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T16:12:59.980",
"Id": "469793",
"Score": "0",
"body": "thanks for the feedback and all your assumptions are correct. I will modify everything accordingly. Also if you have time are you able to provide any feedback on the vlookup because I ended up putting on error resume next and on error goto 0 before and after that line as it was failing in some conditions. Thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T18:57:54.767",
"Id": "469808",
"Score": "0",
"body": "I would suggest you change your `VLookup` to use `Application.VLookup` instead. See [this guide](https://excelmacromastery.com/vba-vlookup/#Using_Application) for more information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:08:29.390",
"Id": "239512",
"ParentId": "239419",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "239512",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T21:56:05.160",
"Id": "239419",
"Score": "2",
"Tags": [
"vba"
],
"Title": "SheetChange event VBA"
}
|
239419
|
<p>In an interview I was giving the following problem:</p>
<blockquote>
<p>Count the number of click on on the entire page.</p>
</blockquote>
<p>Can you think of a better way to do this?</p>
<pre><code>let counter = 0;
document.addEventListener('click', clickCounter);
function clickCounter() {
counter++;
console.log(counter);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T00:47:01.397",
"Id": "469578",
"Score": "0",
"body": "I don't think the task is actually possible as stated, suppose the page has an iframe, so far as I know there's no way to detect clicks inside the iframe. Certainly what you've written won't work in that instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T06:02:54.330",
"Id": "469599",
"Score": "0",
"body": "you are right! the question was very open and lacking of details tho"
}
] |
[
{
"body": "<p>From my experience, this is a <em>good first cut</em> solution for a less experienced candidate as opposed to some experienced candidate. Also, a lot of other info is missing in question such as was there any further discussion on how to improve the solution or about adapting some good practices or how to make this code bug free etc.</p>\n\n<p>I will try to list down possible issues which can to addressed:</p>\n\n<ol>\n<li>The <code>counter</code> variable is a <code>global variable</code> here which is <em>not recommended</em></li>\n<li>The function is <code>not reusable</code>. Suppose, I want to track clicks in 2 different sections in same document now, the approach will fail</li>\n<li>Any <code>user can easily modify counter</code> value. Anytime in window, user can do <code>counter = 0</code> and the value will reset to 0 losing data</li>\n<li>What if user refreshes the pages? In that case, do we need to store the data or losing it would be fine</li>\n<li>If some additional functionality needs to be added (send total counter to backend server etc), so how easily it can be added without modifying the existing code</li>\n</ol>\n\n<p>A lot of things depends on how the discussion goes after you present the solution. You can use closures, class based approach etc. I will try to list them below.</p>\n\n<h3>1. Use closure</h3>\n\n<p>(Not the best approach but better than OP's) </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const clickCounter = clicker()\ndocument.addEventListener('click', clickCounter);\n\nfunction clicker() {\n let counter = 0\n return function() {\n ++counter\n console.log(counter)\n return counter\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>2. Use class like approach</h3>\n\n<ul>\n<li>This is the one people generally expect and works best; covering most of the cases </li>\n<li>You can also do the same by using ES6 classes </li>\n<li>Adding new functionality is lot more easier here</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Counter() {\n let clicks = 0\n this.registerClick = function() {\n ++clicks\n console.log(clicks)\n return clicks\n }\n}\n\nconst clicker = new Counter()\n\ndocument.addEventListener(\"click\", function() {\n clicker.registerClick()\n})</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Hope it helps. Revert for any doubts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:02:32.693",
"Id": "469664",
"Score": "0",
"body": "Honesty i didn't even think on this due to time constrain, they technical questions where coming from left to right up and down in a very short period of time, very cool thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:08:36.967",
"Id": "239456",
"ParentId": "239420",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T22:47:24.550",
"Id": "239420",
"Score": "1",
"Tags": [
"javascript",
"interview-questions",
"dom"
],
"Title": "Counting the number of click on the entire page"
}
|
239420
|
<p>I have a dataset <code>X_train</code>, which is an array where each entry is an email (a string of characters). There are 11,314 emails, each of which is about 500 characters long. (<code>X_train</code> is a processed version of the training data in the newsgroups dataset.)</p>
<p>Ultimately, my goal is to build from scratch a tf-idf function (knowledge of which is probably not necessary for answering my question). To get there, I have constructed a lexicon which contains each unique word in <code>X_train</code> once and only once. My lexicon has 211441 elements. I also need an array where each entry <code>frequency_train[i]</code> is the number of emails in which a given term <code>lexicon_train[i]</code> appears.</p>
<p>I construct the frequency array as follows:</p>
<pre><code>frequency_train = np.zeros(211441)
for i in range(211441):
count = 0
for email in X_train:
if lexicon_train[i] in email:
count = count + 1
frequency_train[i] = count
</code></pre>
<p>In the same cell, I am also doing something similar with the testing data <code>X_test</code>. I've been running this in Jupyter notebook, and this process takes <strong>a while</strong>. A previous and very similar task took about 90 minutes. I suspect that I'm doing this task the slowest possible way. Is there a faster way of doing this? I would also welcome answers that explain why this process should take a long time.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T01:39:39.983",
"Id": "469583",
"Score": "1",
"body": "This is missing information to be able to provide an answer that contains helpful content. What are `X_train` and `lexicon_train`? Do you only need the total `count`, what are the bounds? It's almost like you're trying to impede us from helping you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T01:47:09.130",
"Id": "469584",
"Score": "0",
"body": "@Peilonrayz I think my question explains what X_train is: it's an array where each entry is an email. X_train is a processed version of the training data from the very well-known newsgroups dataset. Specifically, X_train is what results after 1) converting all characters in the newsgroups dataset to lower case letters, 2) removing \"stopwords\" which are the 200 or so most common words of the English language and 3) converting all remaining words to their stems (via the ps.stem() function in the nltk library). \n\nI have also explained what lexicon_train is: a lexicon, obtained from X_train"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T01:48:36.277",
"Id": "469585",
"Score": "0",
"body": "And yes, I only need the count. However, I'm not sure what you mean by \"the bounds\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T03:42:48.253",
"Id": "469592",
"Score": "1",
"body": "What constitutes a unique word? If `”mark”` is in `lexicon_train`, then the `in email` will count `\"Denmark\"` and `\"marker\"`, but not `\"Mark\"`. Should only complete words be matched? What glyphs can exist in the words? Hyphens or apostrophes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T04:34:52.793",
"Id": "469594",
"Score": "0",
"body": "@AJNeufeld \"mark\", \"Denmark\", and \"marker\" are all unique words in my lexicon. And, to be clear, there is no \"Denmark\" nor \"Mark\" in X_train, as all characters in X_train are lower case. There are also no instances of \"mark,\" , \"mark.\", \"mark:\", etc in my lexicon. For better or worse, with the exception of apostrophes, all punctuation marks have been purged."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T05:03:46.610",
"Id": "469595",
"Score": "1",
"body": "Why did you separate constructing the dictionary from establishing the counts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T05:40:29.887",
"Id": "469597",
"Score": "5",
"body": "I will be clearer: Your existing `frequency_train` will contain **incorrect** counts. If an email contains `\"i’m going to denmark\"`, and `lexicon_train` contains `\"mark\"` and `\"denmark\"`, the email will be counted as containing both those words, because `”mark\" in \"i’m going to denmark\"` is `True`. It would also be counted as including words `den`, `go`, `in`, and `ark` if those words also appear in `lexicon_train` because `str in str` checks if the needle appears anywhere in the haystack, without regard for word boundaries."
}
] |
[
{
"body": "<p>Your <code>for</code> loop can be reduced to one line, utilizing <a href=\"https://docs.python.org/3/library/functions.html#sum\" rel=\"nofollow noreferrer\"><code>sum</code></a>:</p>\n\n<pre><code>frequency_train = [\n sum(1 if lexicon_train[i] in email else 0 for email in X_train) for i in range(211441)\n]\n</code></pre>\n\n<p>It removes the need to create the initial list of zeros. For performance, I'm guessing the size of the lexicon and the number of iterations are slowing it down.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T00:34:16.283",
"Id": "469577",
"Score": "0",
"body": "Thank you! This does indeed simplify my code. However, about 15 minutes later, the cell is still running. There may very well be no way around this: just running through the for loops requires about 2.2 billion steps, not to mention the other computations that the entire cell requires. I'm pretty new here, so I'll defer to the community as to whether or not I should accept this as an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T00:47:43.060",
"Id": "469579",
"Score": "1",
"body": "@co-contravariant This answer is really just about reducing the lines in your program and utilizing a built in function. If an answer comes along that reduces your performance, definitely go with that one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T01:34:41.453",
"Id": "469582",
"Score": "0",
"body": "For anyone in the audience who's curious: the process has finally terminated. It took about an hour. Now onto the testing data..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T06:10:54.537",
"Id": "469600",
"Score": "0",
"body": "Cf. [Histogram word counter in Python](https://codereview.stackexchange.com/a/200294)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T00:16:20.450",
"Id": "239424",
"ParentId": "239423",
"Score": "1"
}
},
{
"body": "<p>For each word in the lexicon you are searching through each email: (11,314 emails) * (60 words/email) * (211441 word lexicon) = lots of comparisons.</p>\n\n<p>Flip it around. Use <code>collections.Counter</code>. Get the unique words in each email (use a set()) and then and update the counter.</p>\n\n<pre><code>from collections import Counter\n\ncounts = Counter()\n\nfor email in x_train:\n words = set(email.split()) # <= or whatever you use to parse the words\n counts.update(words)\n</code></pre>\n\n<p>This will give you a dict mapping words in the emails to the number of emails they are in. (11,314 emails) * (60 words/email) = a lot fewer loops.\nThis probably also recreated the lexicon (e.g. \n<code>counter.keys()</code> should be the lexicon.</p>\n\n<p>On my computer, it takes 7 seconds to generate 115000 random 60-word emails and collect the counts.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T06:19:53.700",
"Id": "469601",
"Score": "0",
"body": "Yes, I would go with this answer. Improves performance and reduces code required. Nice job."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T03:30:02.787",
"Id": "239429",
"ParentId": "239423",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "239429",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T00:07:40.153",
"Id": "239423",
"Score": "2",
"Tags": [
"python",
"performance",
"beginner"
],
"Title": "Constructing a lexicon and frequency array from a long string"
}
|
239423
|
<p>I implemented a Simpletron simulator in C for learning C.<br>
Simpletron is a virtual machine invented by Deitel for his books. Simpletron runs programs written in the Simpletron Machine Language, an simple Machine Language.</p>
<p>An instruction (and data) in the Simpletron Machine Language is a signed four-digit integer, like <code>+1009</code>. The first two digits are the opcode, and the last two digits are the operand.</p>
<p>I wrote a manual for the Simpletron Simulator in troff, it contains the instructions of the Simpletron Machine Language and some example programs.</p>
<p>Here's the manual, read it using the command man(1):</p>
<pre class="lang-none prettyprint-override"><code>simpletron(6) Games Manual simpletron(6)
NAME
simpletron - simulates a simpletron computer
SYNOPSIS
simpletron [-c] [-m memsize] file
DESCRIPTION
simpletron simulates a simpletron machine running a program con‐
tained in file and written in SML, the Simpletron Machine Language.
The options are as follows:
-c Do a computer dump at the end of the simulation. A core dump
prints the name and contents of each register as well as the
complete contents of memory.
-m memsize
Set the size of the memory of the Simpletron simulator. The
memory must be big enough to hold the instructions and the
data.
The input have the same format as instruction (see the section THE
SIMPLETRON MACHINE LANGUAGE for information on the instruction syn‐
tax).
THE SIMPLETRON SIMULATOR
For information on how to implementate a Simpletron simulator, read
the README file provided with the code.
The memory
All information in the Simpletron is handled in terms of words. A
word is a signed four-digit decimal number such as +3364, -1293,
+0007, -0001, and so on.
The Simpletron is equipped with a 100-word memory by default (but it
can be expanded with the -m option). Each word in the memory is
referenced by their two-digit location numbers 00, 01, ..., 99. The
location 00 is the location of the first word, 01 is the location of
the second word, and so on.
Before running an SML program, the Simpletron Simulator loads the
programinto memory. The first instruction of every program is al‐
ways placed in location 00. Each location in the Simpletron's mem‐
ory may contain either an instruction, a data value used by a pro‐
gram, or an unused (and hence undefined) area of memory.
The registers
The Simpletron has a single “general purpose” register known as the
accumulator. Information must be put on the accumulator before the
Simpletron uses that information in calculations or examines it in
various ways.
The Simpletron also has “special purpose” registers used to manage
the instruction execution cycle. These registers cannot be changed
directly.
counter
The instruction counter keep track of the locationin memory
that contains the instruction being performed.
instruction register
The instruction register is a word containing the instruction
currently being performed.
opcode The opcode indicates the operation currently being performed.
It is the leftmost two digits of the instruction currently
being performed.
operand
The operand indicates the memory location or the immediate
value on which the current instruction operates. It is the
rightmost two digits of the instruction currently being per‐
formed.
The instruction execution cycle
After the SML program has been loaded into the memory, the Sim‐
pletron simulator executes it. It begins with the instruction in
location 00 and continues sequentially, unless directed to some
other part of the program by a transfer of control.
The instruction execution cycle do as the following.
The instruction counter tell the location of the next in‐
struction to be performed.
The contents of that location is fetched from memory into the
instruction register.
The operation code and the operand are extracted from the in‐
struction register.
The simpletron determines the operation to be executed.
At this point, the simulation of a instruction is completed.
All that remains is to prepare the Simpletron to execute the
next instruction. So the Simpletron ajust the instruction
counter accordingly.
THE SIMPLETRON MACHINE LANGUAGE
Each instruction written in the Simpletron Machine Language (SML)
occupies one word of the Simpletron's memory, so instructions are
signed four-digit decimal numbers. We assume that the sign of an
SML instruction is always plus, but the sign of a data word may be
either plus or minus. An instruction is a plus-signed 4-digit word
composed of two parts: the 2-digit operation code (aka “opcode”) and
the 2-digit operand.
The first two digits of each SML instruction are the operation code,
which specifies the operation to be performed. SML operation codes
are summarized in the following sections between parentheses.
The last two digits of an SML instruction are the operand, which is
either the address of the memory location containing the word to
which the operation indirectly applies, or a value to which the op‐
eration directly applies.
In a SML file, each line is a instruction, a instruction begins with
a plus or minus sign followed by four decimal digits. The remaining
of the line is ignored.
Input/output operations
READ (10)
Read a word from the terminal into a specific location in
memory.
WRITE (11)
Write a word from a specific location in memory to the termi‐
nal.
Memory loading/storing
LOAD (20)
Loada word from a specific location in memory into the accu‐
mulator.
STORE (21)
Store a word from the accumulator into a specific location in
memory.
Memory arithmetic operations
Note that all the results are left in accumulator.
ADD (30)
Add a word from a specific location in memory to the word in
the accumulator.
SUBTRACT (31)
Subtract a word from a specific location in memory from the
word in the accumulator.
DIVIDE (32)
Divide a word from a specific location in memory into the
word in the accumulator.
MULTIPLY (33)
Multiply a word from a specific location in memory by the
word in the accumulator.
Immediate arithmetic operations
Note that all the results are left in accumulator.
ADD_I (40)
Add a the value in operand to the word in the accumulator.
SUBTRACT_I (41)
Subtract the value in operand from the word in the accumula‐
tor.
DIVIDE_I (42)
Divide the value in operand into the word in the accumulator.
MULTIPLY_I (43)
Multiply the value in operand by the word in the accumulator.
Transfer-of-control operations
BRANCH (50)
Branch to a specific location in memory.
BRANCHNEG (51)
Branch to a specific location in memory if the accumulator is
negative.
BRANCHZERO (52)
Branch to a specific location in memory if the accumulator is
zero.
HALT (53)
Halt (i'e', the program has completed its task).
EXAMPLES
The following are example of programs in the Simpletron Machine Lan‐
guage (SML).
adder.sml
The following SML program reads two numbers from the keyboard and
computes and prints their sum.
+1007 READ A
+1008 READ B
+2007 LOAD A
+3008 ADD B
+2109 STORE C
+1109 WRITE C
+5300 HALT
+0000 A
+0000 B
+0000 C
(1) The instruction +1007 reads the first number from the keyboard
and places it into location 07 (which has been initialized to zero).
(2) Then +1008 reads the next number into location 08.
(3) The load instruction (+2007) puts the first number into the ac‐
cumulator.
(4) The add instruction (+3008) adds the second number to the number
in theaccumulator. All SML aritmetic instructions leave their re‐
sults in the accumulator.
(5) The store instruction (+2109) placesthe result back into memory
location 09.
(6) From the location 09, the write instruction (+1109) takes the
number and prints it (as a signed four-digit decimal number).
(7) The halt instruction (+4300) terminates the execution.
larger.sml
The following SML program reads two numbers from the keyboard, and
determines and prints the larger value. Note the use of the in‐
struction +5107 as a conditional transfer of control, much the same
as C's if statement.
+1009 READ A
+1010 READ B
+2009 LOAD A
+3110 SUBTRACT B
+5107 BRANCHNEG 07
+1109 WRITE A
+5300 HALT
+1110 WRITE B
+5300 HALT
sum.sml
The following program uses a sentinel-controlled loop to read posi‐
tive integers and compute and printe their sum.
+1008 READ A
+2008 LOAD A
+5206 BRANCHZERO 06
+3009 SUM B
+2109 STORE B
+5000 BRANCH 00
+1109 WRITE B
+5300 HALT
+0000 A
+0000 B
average7.sml
The following program uses a counter-controlled loop to read seven
numbers, some positive and some negative, and compute and print
their average.
+2015 LOAD N
+5210 BRANCHZERO 10
+1016 READ A
+2016 LOAD A
+3017 ADD B
+2117 STORE B
+2015 LOAD N
+4101 SUB_I 01
+2115 STORE N
+5000 BRANCH 00
+2017 LOAD B
+4207 DIV_I 07
+2117 STORE B
+1117 WRITE B
+5300 HALT
+0007 N
+0000 A
+0000 B
EXIT STATUS
0 Success.
>0 Error occurred.
HISTORY
This version of simpletron, the Simpletron Simulator, is based on
the exercises 7.27~7.29 from the [Deitel & Deitel] book.
The immediate operations are unique to this implementation, since
the exercise does not mention them.
SEE ALSO
[Deitel & Deitel]
C: How to Program (8th edition), Paul Deitel and Harvey Dei‐
tel
simpletron(6)
</code></pre>
<p>And here is the Simpletron Simulator:</p>
<pre><code>#include <err.h>
#include <errno.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
#include <unistd.h>
#define DEFMEMSIZE 100
#define MEM_MAX 9999
#define MEM_MIN -9999
#define INSTRUCTIONSIZE 4
#define OPSIZE 2
enum operation {
READ = 10,
WRITE = 11,
LOAD = 20,
STORE = 21,
ADD = 30,
SUBTRACT = 31,
DIVIDE = 32,
MULTIPLY = 33,
REMINDER = 34,
ADD_I = 40,
SUBTRACT_I = 41,
DIVIDE_I = 42,
MULTIPLY_I = 43,
REMINDER_I = 44,
BRANCH = 50,
BRANCHNEG = 51,
BRANCHZERO = 52,
HALT = 53
};
/* Simpletron's memory is simulated with a one-dimensional array */
static int *memory;
static int memsize = DEFMEMSIZE;
/* Simpletron's registers are simulated with the following variables */
static int acc; /* accumulator register (value being processed) */
static int ireg; /* instruction register (current instruction) */
static int simpletron(void);
static void load(FILE *);
static void dump(void);
static int getinstruction(FILE *, int *);
static int getmemsize(const char *s);
static void usage(void);
/* load a program in the Simpletron Machine Language into memory and execute it*/
int
main(int argc, char *argv[])
{
int c, exitval, coredump;
FILE *fp;
coredump = 0;
while ((c = getopt(argc, argv, "cm:")) != -1) {
switch (c) {
case 'm':
if ((memsize = getmemsize(optarg)) < 1)
errx(EXIT_FAILURE, "%s: improper memory size", optarg);
break;
case 'c':
coredump = 1;
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc != 1)
usage();
if ((memory = calloc(memsize, sizeof *memory)) == NULL)
err(EXIT_FAILURE, NULL);
if ((fp = fopen(*argv, "r")) == NULL)
err(EXIT_FAILURE, "%s", *argv);
load(fp); /* load program into memory */
exitval = simpletron(); /* execute instructions in memory */
if (coredump)
dump(); /* do coredump, if needed */
free(memory);
return exitval;
}
/* run instructions from memory; return 1 if error occurs, return 0 otherwise */
static int
simpletron(void)
{
static int count;
static int opcode;
static int operand;
/* memory location of next instruction */
/* simulation begins with the instruction in the location 00 and continues sequentially */
count = 0;
/* this loop implements the "instruction execution cycle" */
while (count < memsize) {
ireg = memory[count];
opcode = ireg / 100; /* opcode is the leftmost two digits of instruction register*/
operand = ireg % 100; /* operand is the rightmost two digits of instruction register*/
/* this switch statement determine the operation to be performed */
/* each case set the counter for next instruction accordingly */
switch (opcode) {
case READ:
if (getinstruction(stdin, &memory[operand]) == 0) {
warnx("improper input");
return 1;
}
count++;
break;
case WRITE:
printf("%+05d\n", memory[operand]);
count++;
break;
case LOAD:
acc = memory[operand];
count++;
break;
case STORE:
memory[operand] = acc;
count++;
break;
case ADD:
if ((memory[operand] > 0 && acc > MEM_MAX - memory[operand]) ||
(memory[operand] < 0 && acc < MEM_MIN - memory[operand])) {
warnx("integer overflow");
return 1;
}
else
acc += memory[operand];
count++;
break;
case SUBTRACT:
if ((memory[operand] > 0 && acc < MEM_MIN + memory[operand]) ||
(memory[operand] < 0 && acc > MEM_MAX + memory[operand])) {
warnx("integer overflow");
return 1;
}
else
acc -= memory[operand];
count++;
break;
case DIVIDE:
if (memory[operand] == 0) {
warnx("division by zero");
return 1;
} else if ((acc == MEM_MIN) && (memory[operand] == -1)) {
warnx("signed integer overflow");
return 1;
} else {
acc /= memory[operand];
}
count++;
break;
case MULTIPLY:
acc *= memory[operand];
if (acc < MEM_MIN || acc > MEM_MAX) {
warnx("integer overflow");
return 1;
}
count++;
break;
case REMINDER:
if (memory[operand] == 0) {
warnx("remainder by zero");
return 1;
} else if ((acc == MEM_MIN) && (memory[operand] == -1)) {
warnx("signed integer overflow");
return 1;
} else {
acc %= memory[operand];
}
count++;
break;
case ADD_I:
if ((operand > 0 && acc > MEM_MAX - operand) ||
(operand < 0 && acc < MEM_MIN - operand)) {
warnx("integer overflow");
return 1;
} else {
acc += operand;
}
count++;
break;
case SUBTRACT_I:
if ((operand > 0 && acc < MEM_MIN + operand) ||
(operand < 0 && acc > MEM_MAX + operand)) {
warnx("integer overflow");
return 1;
} else {
acc -= operand;
}
count++;
break;
case DIVIDE_I:
if (operand == 0) {
warnx("division by zero");
return 1;
} else if ((acc == MEM_MIN) && (operand == -1)) {
warnx("signed integer overflow");
return 1;
} else {
acc /= operand;
}
count++;
break;
case MULTIPLY_I:
acc *= operand;
if (acc < MEM_MIN || acc > MEM_MAX) {
warnx("integer overflow");
return 1;
}
count++;
break;
case REMINDER_I:
if (operand == 0) {
warnx("remainder by zero");
return 1;
} else if ((acc == MEM_MIN) && (operand == -1)){
warnx("signed integer overflow");
return 1;
} else {
acc %= operand;
}
count++;
break;
case BRANCH:
count = operand;
break;
case BRANCHNEG:
if (acc < 0)
count = operand;
else
count++;
break;
case BRANCHZERO:
if (acc == 0)
count = operand;
else
count++;
break;
case HALT:
return 0;
default:
warnx("%+05d: invalid instruction", ireg);
return 1;
}
}
warnx("execution reached end of memory without halting");
return 1;
}
/* load memory from file */
static void
load(FILE *fp)
{
size_t i;
int instruction;
i = 0;
while(getinstruction(fp, &instruction) && i < memsize)
memory[i++] = instruction;
}
/* write a core dump of memory and registers into stdout */
static void
dump(void)
{
size_t i, j;
fprintf(stderr, "\nREGISTERS:\n"
"accumulator %+05d\n"
"instruction register %+05d\n",
acc, ireg);
fprintf(stderr, "\nMEMORY:\n"
" 0 1 2 3 4 5 6 7 8 9\n");
for (i = 0; i < memsize / 10; i++) {
fprintf(stderr, "%2lu ", i * 10);
for (j = 0; j < memsize / 10; j++)
fprintf(stderr, "%+05d%s", memory[(i*10)+j],
(j == memsize / 10 - 1) ? "\n" : " ");
}
}
/* get instruction from fp; return 0 if instruction is improper */
static int
getinstruction(FILE *fp, int *instruction)
{
size_t i;
int c, num, sign;
num = 0;
/* get initial blank */
while (isblank(c = getc(fp)))
;
/* get instruction/data sign */
sign = (c == '-') ? -1 : 1;
if (c != '+' && c != '-')
return 0;
else
c = getc(fp);
/* get instruction/data number */
for (i = 0; i < INSTRUCTIONSIZE; i++) {
if (!isdigit(c))
return 0;
num = num * 10 + c - '0';
c = getc(fp);
}
/* get remaining of command line */
while (c != '\n' && c != EOF)
c = getc(fp);
*instruction = sign * num;
return 1;
}
/* get an integer from s to be used as the memory size */
static int
getmemsize(const char *s)
{
long n;
char *endp;
n = strtol(s, &endp, 10);
if (errno == ERANGE || n > INT_MAX || n < INT_MIN || endp == s || *endp != '\0')
return -1;
return (int) n;
}
static void
usage(void)
{
(void) fprintf(stderr, "usage: simpletron [-c] [-m memsize] file\n");
exit(EXIT_FAILURE);
}
</code></pre>
<p>Here is a sample program in the Simpletron Machine Language, average7.sml, it receives 7 values from input and calculates the average between them.</p>
<pre><code>+1008
+2008
+5206
+3009
+2109
+5000
+1109
+5300
+0000
+0000
</code></pre>
<p>The input of a Simpletron program must be a signed four-digit integer, like <code>+0007</code> or <code>-0001</code>.</p>
<p>Is there any way I can make the code more elegant and portable?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T05:11:50.067",
"Id": "469596",
"Score": "0",
"body": "(I had a look at the troff \"source\" without syntax colouring - did not find it much improved.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T08:20:35.993",
"Id": "469606",
"Score": "1",
"body": "It might be more helpful if you displayed that help text in your console using `man` and pasted the formatted output here. It seems like an unnecessary hoop to jump through for reviewers otherwise. Unless the code of the man page is explicitly included in what you want reviewed, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:47:46.090",
"Id": "469634",
"Score": "0",
"body": "In the review below the section `Assignment-in-condition` is addressing code readability and maintainability, and it section is correct, your code is not as readable as it could be and someone could definitely miss the assignment statements."
}
] |
[
{
"body": "<h2>Re-entrance</h2>\n\n<p>These:</p>\n\n<pre><code>static int *memory;\nstatic int acc; /* accumulator register (value being processed) */\nstatic int ireg; /* instruction register (current instruction) */\n// ...\n\n static int count;\n static int opcode;\n static int operand;\n</code></pre>\n\n<p>force a user to start a new program if they want a new instance of the calculator. If you want to offer an API that allows the co-existence of multiple calculators, pass around a struct instead.</p>\n\n<h2>C99</h2>\n\n<p>These:</p>\n\n<pre><code>int c, exitval, coredump;\nFILE *fp;\n</code></pre>\n\n<p>haven't needed declaration at the beginning of the function for 20-ish years. It's more legible for them to be declared and initialized closer to where they're actually being used in the function.</p>\n\n<h2>Assignment-in-condition</h2>\n\n<p>About these various statements -</p>\n\n<pre><code>while ((c = getopt(argc, argv, \"cm:\")) != -1) {\nif ((memory = calloc(memsize, sizeof *memory)) == NULL)\nif ((fp = fopen(*argv, \"r\")) == NULL)\nwhile (isblank(c = getc(fp)))\n</code></pre>\n\n<p>Don't, please. Expand this out so that the variable is assigned in its own statement. The above is confusing and error-prone, and has no performance gains. The only thing it's good for is code golf, which you aren't currently playing.</p>\n\n<h2>Addition efficiency</h2>\n\n<pre><code> if ((memory[operand] > 0 && acc > MEM_MAX - memory[operand]) ||\n (memory[operand] < 0 && acc < MEM_MIN - memory[operand])) {\n warnx(\"integer overflow\");\n return 1;\n }\n else\n acc += memory[operand];\n</code></pre>\n\n<p>can become something like</p>\n\n<pre><code>int sum = memory[operand] + acc;\nif (sum > MEM_MAX || sum < MEM_MIN) {\n warnx(\"integer overflow\");\n return 1;\n}\nacc = sum;\n</code></pre>\n\n<p>In other words: don't do the addition three times; do it once. The same applies to <code>SUBTRACT</code>.</p>\n\n<h2>Order of operations</h2>\n\n<pre><code>((acc == MEM_MIN) && (memory[operand] == -1))\n</code></pre>\n\n<p>doesn't require inner parens, due to operator precedence.</p>\n\n<h2>Typo</h2>\n\n<p><code>REMINDER</code> should be <code>REMAINDER</code>.</p>\n\n<h2>Loop sanity</h2>\n\n<pre><code> size_t i;\n\n i = 0;\n while(getinstruction(fp, &instruction) && i < memsize)\n memory[i++] = instruction;\n</code></pre>\n\n<p>is better represented by</p>\n\n<pre><code>for (size_t i = 0; i < memsize; i++) {\n if (!getinstruction(fp, &instruction))\n break;\n memory[i] = instruction;\n}\n</code></pre>\n\n<h2>Memory efficiency</h2>\n\n<p>Currently you're storing integers in 32 bits that, since they have values of less than 10,000, could fit in 16. Depending on your constraints - whether you're optimizing for execution speed or memory efficiency - you might want to change this. 16 bits might actually be slower on your architecture, but to be sure you'd want to profile. Also, if you ever plan on serializing the state of the machine into a file, you should use 16 bits (<code>int16_t</code> from <code>stdint.h</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T09:12:27.033",
"Id": "469610",
"Score": "0",
"body": "For the addition, I was using SEI's [CERT INT32-C](https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow) to ensure integer overflow. The assignment-in-condition is a hint that survived from when I read K&R book, they use assignment-in-condition all the time. Declaration at the beginning of function was also from K&R.\nI am reading Deitel's C:How to Program after have read K&R, is this a good path choice? I think Deitel's codes are much less elegant than K&R's..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T09:16:18.263",
"Id": "469611",
"Score": "0",
"body": "Also, the assignments-in-condition (particularly the one for getopt(3)) are idioms I've learnt from OpenBSD's manpages. I think assignment-in-conditions are not out of fashion in operating system development cycles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T14:38:56.343",
"Id": "469627",
"Score": "0",
"body": "Re. K&R - the most recent (2nd) edition is from 1988. C99 should be used by everyone at this point. The classics are classic, but they need to be taken with a grain of salt and some understanding of the modern world."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T14:41:31.987",
"Id": "469628",
"Score": "0",
"body": "_is this a good path choice?_ - It's difficult to say. Deitel apparently has an 8th edition from 2015 but I cannot speak to its contents. Generally speaking, I think that it's great for you to be working from textbooks, and it should be easy for you to pick up modern industry trends after."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T14:48:49.217",
"Id": "469629",
"Score": "1",
"body": "_I was using SEI's CERT INT32-C to ensure integer overflow_ - it's excellent for you to be thinking about those details, but I fear that the situation is more complicated. Modern optimizing compilers are able to move terms across the sides of an inequality, for instance. That aside, since you're currently using a 32-bit representation, the data range is significantly narrower than the register range, so you do not have to worry about these details. Even if you switched to 16-bit, you would still be safe, because 2*10^4 < 2^15."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T14:53:24.473",
"Id": "469630",
"Score": "1",
"body": "Also, it does not surprise me that man pages and operating system code both show signs of predating C99, since the BSD kernel certainly happened first, and it's entirely likely that it hasn't switched styles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:05:44.383",
"Id": "469631",
"Score": "0",
"body": "This program is from an exercise from Deitel's last book (8th edition). I am doing now its second part: a Simple Compiler (a compiler that translates a BASIC-like language into Simpletron Machine Language), it is VERY hard. After Deitel, I am thinking in going to «The Practice of Programming», by Kernighan and Rob Pike, and to «Modern C», and then to Sedgewick's «Algoritms in C» and «Advanced Programming in the UNIX Environment». I appreciate any opinions on this path I chose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:15:38.647",
"Id": "469632",
"Score": "0",
"body": "The extent of my textbook education in C is Yaroshenko's 1994 _Beginner's Guide to C++_; so in terms of book path I cannot offer any intelligent opinions. I think that, given the mix of textbook learning and verification on Stack Exchange, you will do just fine :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T20:34:09.597",
"Id": "469662",
"Score": "0",
"body": "Sounds like a job for `int16_fast_t`!"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T02:57:13.030",
"Id": "239428",
"ParentId": "239425",
"Score": "7"
}
},
{
"body": "<p>In addition to the review you already have, I have a few more suggestions.</p>\n\n<h2>Fix the bug</h2>\n\n<p>As was already pointed out, the <em>assignment-in-condition</em> practice is problematic. In this particular case, the problem is in <code>main</code>. The current code has this:</p>\n\n<pre><code>if ((memory = calloc(memsize, sizeof *memory)) == NULL)\n err(EXIT_FAILURE, NULL);\nif ((fp = fopen(*argv, \"r\")) == NULL)\n err(EXIT_FAILURE, \"%s\", *argv);\n</code></pre>\n\n<p>The problem is that if the file doesn't exist, the memory just allocated will not be freed. For that reason and for the fact that it's generally better to define variables when they are declared, I'd write that sequence like this instead:</p>\n\n<pre><code>FILE *fp = fopen(*argv, \"r\");\nif (fp == NULL) {\n free(memory);\n err(EXIT_FAILURE, \"%s\", *argv);\n}\n</code></pre>\n\n<h2>Think carefully about signed vs. unsigned numbers</h2>\n\n<p>What would it mean for the <code>memsize</code> to be a negative number? I can't think of a rational interpretation for such a thing, so I'd recommend making that <code>size_t</code> which is unsigned.</p>\n\n<h2>Eliminate global variables</h2>\n\n<p>In this case there lot of global variables such as <code>memory</code> and <code>memsize</code> which are probably better gathered up into a structure and made part of <code>main</code> instead of global. Then for each of the relevant functions such as <code>load</code> or <code>dump</code>, pass a pointer to the structure as one of the arguments.</p>\n\n<pre><code>struct Simpletron {\n /* Simpletron's memory is simulated with a one-dimensional array */\n int *memory;\n size_t memsize;\n\n /* Simpletron's registers are simulated with the following variables */\n int acc; /* accumulator register (value being processed) */\n size_t pc; /* program counter points to current instruction */\n int opcode; /* current opcode */\n int operand; /* current operand */\n};\n</code></pre>\n\n<p>Note that I've also changed from <code>ireg</code> to <code>pc</code>. More on that later.</p>\n\n<h2>Make the program data driven</h2>\n\n<p>Instead of the <code>operation</code> <code>enum</code>, a large <code>switch</code> statement, etc. I think it would be much neater to have a <code>struct</code> for instructions. Here's how I'd define it:</p>\n\n<pre><code>struct Instruction {\n int opcode;\n const char *mnemonic;\n const char *printstr;\n int (*exec)(struct Simpletron* s);\n};\n</code></pre>\n\n<p>Now we can create an array of instructions. Here's an example of one:</p>\n\n<pre><code>{ 52,\"BRANCHZERO\",\" %2u\", simple_instr_branchzero },\n</code></pre>\n\n<p>Now all that remains is to write the code that performs the instruction:</p>\n\n<pre><code>static int simple_instr_branchzero(struct Simpletron *s) {\n if (s->acc == 0) {\n s->pc = s->operand;\n } else {\n ++s->pc;\n }\n return WARN_NONE;\n}\n</code></pre>\n\n<h2>Make error messages and numbers neater</h2>\n\n<p>You may have noticed that the function above returns <code>WARN_NONE</code>. This is somewhat easier for a programmer to read and understand than something like <code>return 0</code> and also has the advantage that we now have both a code and a message (which might be translated to other languages, for instance). So instead of this inside the large <code>switch</code>:</p>\n\n<pre><code>case ADD_I:\n if ((operand > 0 && acc > MEM_MAX - operand) ||\n (operand < 0 && acc < MEM_MIN - operand)) {\n warnx(\"integer overflow\");\n return 1;\n } else {\n acc += operand;\n }\n count++;\n break;\n</code></pre>\n\n<p>We can write this:</p>\n\n<pre><code>static int simple_instr_add_i(struct Simpletron *s) {\n int result = s->acc + s->operand;\n if (isOutOfRange(result)) {\n return WARN_OVERFLOW;\n }\n s->acc = result;\n ++s->pc;\n return WARN_NONE;\n}\n</code></pre>\n\n<p>This is enabled using this code:</p>\n\n<pre><code>enum warning { WARN_NONE, WARN_HALT, WARN_INPUT, WARN_OVERFLOW, WARN_DIVZERO, WARN_SIGNEDOVERFLOW, WARN_REMAINZERO, WARN_COUNT };\nstatic const struct Error {\n enum warning value;\n const char *text;\n} simpletron_errors[WARN_COUNT] = {\n { WARN_NONE, \"ok\" },\n { WARN_HALT, \"halt\" },\n { WARN_INPUT, \"improper input\" },\n { WARN_OVERFLOW, \"integer overflow\" },\n { WARN_DIVZERO, \"division by zero\" },\n { WARN_SIGNEDOVERFLOW, \"signed integer overflow\"},\n { WARN_REMAINZERO, \"remainder by zero\"},\n};\n</code></pre>\n\n<p>Note that <code>WARN_COUNT</code> is not a real warning, but rather a marker to define the size of the array and also for us with error checking on access to that array.</p>\n\n<h2>Use helper functions to clarify code</h2>\n\n<p>The code above uses <code>isOutOfRange</code> which simplifies the code and makes it clear to the reader. The content is this:</p>\n\n<pre><code>static bool isOutOfRange(int n) {\n return n < MEM_MIN || n > MEM_MAX;\n}\n</code></pre>\n\n<h2>Use action words for functions</h2>\n\n<p>The functions <code>load</code> and <code>dump</code> are named in a way that suggests their function, but I think <code>simpletron</code> is not as good. Since they are all dealing with the same underlying machine, I'd suggest naming them as <code>simpletron_load</code>, <code>simpletron_dump</code> and <code>simpletron_run</code>.</p>\n\n<h2>Separate interface from implementation</h2>\n\n<p>I'd suggest splitting the program into three pieces: <code>main.c</code> which would contain <code>main</code> and functions only needed by it, a <code>simpletron.h</code> file that defines the interface to the virtual machine and <code>simpletron.c</code> which would contain the implementation. Here's how I would define <code>simpletron.h</code>:</p>\n\n<pre><code>#ifndef SIMPLETRON_H\n#define SIMPLETRON_H\n#include <stdio.h>\n#include <stdbool.h>\n\nstruct Simpletron {\n /* Simpletron's memory is simulated with a one-dimensional array */\n int *memory;\n size_t memsize;\n\n /* Simpletron's registers are simulated with the following variables */\n int acc; /* accumulator register (value being processed) */\n size_t pc; /* program counter points to current instruction */\n int opcode; /* current opcode */\n int operand; /* current operand */\n};\n\nint simpletron_run(struct Simpletron *s, bool trace, bool verbose);\nint simpletron_load(struct Simpletron *s, FILE *fp);\nvoid simpletron_dump(struct Simpletron *s);\n#endif // SIMPLETRON_H\n</code></pre>\n\n<p>Only the minimal information to use the interface is here. All of the other details are encapsulated in <code>simpletron.c</code>. </p>\n\n<h2>Prefer <code>const</code> to <code>#define</code></h2>\n\n<p>Since C99, it's generally better to use <code>const</code> rather than <code>#define</code> for numerical constants. For instance, I'd put these inside <code>simpletron.c</code>:</p>\n\n<pre><code>static const int MEM_MAX = 9999;\nstatic const int MEM_MIN = -9999;\nstatic const int INSTRUCTIONSIZE = 4;\n</code></pre>\n\n<p>This way, we get the benefit of type checking and also limiting scope.</p>\n\n<h2>Consider adding features</h2>\n\n<p>I thought it would be nice to be able to trace the program and also, optionally, to dump the contents of the machine after each instruction. This heavily modified version of your original <code>simpletron</code> function does just that.</p>\n\n<pre><code>/* run instructions from memory; return 1 if error occurs, return 0 otherwise */\nint simpletron_run(struct Simpletron *s, bool trace, bool verbose) {\n /* memory location of next instruction */\n /* simulation begins with the instruction in the location 00 and continues sequentially */\n s->pc = 0;\n\n /* this loop implements the \"instruction execution cycle\" */\n while (s->pc < s->memsize) {\n /* opcode is the leftmost two digits of instruction register*/\n s->opcode = s->memory[s->pc] / 100;\n /* operand is the rightmost two digits of instruction register*/\n s->operand = s->memory[s->pc] % 100;\n /* simple linear scan for opcode */\n const struct Instruction *op = findop(s->opcode);\n if (op == NULL) {\n warnx(\"%+05d: invalid instruction\", s->memory[s->pc]);\n return 1;\n }\n if (trace) {\n fprintf(stderr, \"%05lu: %+05d\\t\", s->pc, s->memory[s->pc]);\n fprintf(stderr, op->mnemonic);\n fprintf(stderr, op->printstr, s->operand);\n fprintf(stderr, \"\\n\");\n }\n int result = op->exec(s);\n if (verbose) {\n simpletron_dump(s);\n }\n if (result == WARN_HALT) {\n return 0;\n }\n if (result != WARN_NONE && result < WARN_COUNT) {\n warnx(simpletron_errors[result].text);\n return 1;\n }\n }\n warnx(\"execution reached end of memory without halting\");\n return 1;\n}\n</code></pre>\n\n<p>Using these features was a simple matter of adding the appropriate arguments for <code>main</code> and passing two boolean values. Much of this functionality is enabled by the use of the data-driven design, but there's still more.</p>\n\n<h2>Fully use data structures to simplify features</h2>\n\n<p>The posted example code purports to take an average of seven numbers, but it does no such thing. In fact, it computes a sum of a list of numbers terminated by a sentinel value of zero. A program that computes an average might look like this in source code form:</p>\n\n<pre><code>READ [13] ; read a number from the uset\nLOAD [13] ; acc = number\nADD [15] ; add to running sum\nSTORE [15] ; store sum\nLOAD [14] ; fetch counter\nADD_I 1 ; increment by one\nSTORE [14] ; save updated count\nBRANCHNEG 0 ; if <0, we're not done yet\nLOAD [15] ; fetch the running sum\nDIVIDE_I 7 ; divide by seven\nSTORE [13] ; store the updated value\nWRITE [13] ; write it to stdout\nHALT\n+0000 ; this is location 13 used as a scratchpad for input\n-0007 ; this is the value -n (number of numbers to avg)\n+0000 ; this is location 15 that holds the running sum\n</code></pre>\n\n<p>It was certainly not obvious from a raw list of numbers what the original code actually did until I added the trace function mentioned above. It's a relatively simple task to allow the code to accept either this nice source code version or the original raw number version. Here's an enhanced <code>simpletron_load</code> function that does just that:</p>\n\n<pre><code>int simpletron_load(struct Simpletron *s, FILE *fp) {\n unsigned linenum = 1;\n char inst[13];\n inst[12] = '\\0'; // assure it's terminated\n size_t i = 0;\n const char* error = NULL;\n while (!error && (fscanf(fp, \"%12s\", inst) == 1)) {\n // is it a number\n if (inst[0] == '+' || inst[0] == '-') {\n int arg;\n if (sscanf(inst, \"%5d\", &arg) == 1) {\n s->memory[i++] = arg;\n } else {\n error = \"reading number\";\n }\n } else {\n const struct Instruction *in = findmnemonic(inst);\n if (in) {\n if (strlen(in->printstr)) {\n int arg = parsearg(in->printstr, fp);\n if (arg >= 0) {\n s->memory[i++] = in->opcode*100 + arg;\n } else {\n error = \"reading instruction\";\n }\n } else {\n s->memory[i++] = in->opcode*100;\n }\n } else {\n error = \"reading instruction\";\n }\n }\n // ignore the rest of the line\n for (int c = getc(fp); c != '\\n' && c != EOF; c = getc(fp)) {\n }\n ++linenum;\n if (i >= s->memsize) {\n error = \"memory full\";\n }\n }\n if (error) {\n printf(\"ERROR:%s:%d\\n\", error, linenum);\n return 1;\n }\n return 0;\n}\n</code></pre>\n\n<h2>Make the machine do the counting</h2>\n\n<p>Rather than fiddling with tedious parsing of formatted output, I generally prefer to let the machine do the counting for me. To that end, the rewritten <code>simpletron_dump</code> function now looks like this:</p>\n\n<pre><code>/* write a core dump of memory and registers into stdout */\nvoid simpletron_dump(struct Simpletron *s) {\n const unsigned linelen = 10;\n fprintf(stderr, \"\\nREGISTERS:\\n\"\n \"accumulator %+05d\\n\"\n \"instruction pointer +%04lu\\n\"\n \"\\nMEMORY:\\n \",\n s->acc, s->pc);\n for (unsigned i = 0; i < linelen; ++i) {\n fprintf(stderr, \"%7u\", i);\n }\n unsigned dumpcount = 0;\n for (size_t i = 0; i < s->memsize; ++i, --dumpcount) {\n if (dumpcount == 0) {\n fprintf(stderr, \"\\n%2lu \", i );\n dumpcount = linelen;\n }\n fprintf(stderr, \"%+05d \", s->memory[i]);\n }\n fprintf(stderr, \"\\n\");\n}\n</code></pre>\n\n<p>The code uses the <code>const unsigned linelen</code> to keep track of how many values to print out per line for both the header and for the memory dump. That also fixes another bug in the original which did not print memory correctly.</p>\n\n<h2>Understand real CPUs</h2>\n\n<p>I know this is all a learning exercise, but one thing that may be useful is to understand a bit more about real CPU architecture. For example, rather than throwing an error in the event of overflow, real CPUs typically have a <em>carry flag</em> which indicates this and an <em>overflow flag</em> to indicate signed overflow. Also, it is more typical to have an <em>instruction pointer</em> (sometimes called a <em>program counter</em>) rather than an instruction register that actually holds the current instruction. Of course internal to the machine, something eventually does fetch and parse the value of the instruction, but it's quite rare for that to be directly accessible from the outside. This was one reason I changed from <code>ireg</code> to <code>pc</code> as mentioned above. It keeps things neater and more clearly mimics how real machines work.</p>\n\n<h2>Results</h2>\n\n<p>Here's the revised version of <code>simpletron.c</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include \"simpletron.h\"\n#include <err.h>\n#include <errno.h>\n#include <ctype.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <string.h>\n#include <limits.h>\n#include <unistd.h>\n\nstatic const int MEM_MAX = 9999;\nstatic const int MEM_MIN = -9999;\nstatic const int INSTRUCTIONSIZE = 4;\n\nenum warning { WARN_NONE, WARN_HALT, WARN_INPUT, WARN_OVERFLOW, WARN_DIVZERO, WARN_SIGNEDOVERFLOW, WARN_REMAINZERO, WARN_COUNT };\nstatic const struct Error {\n enum warning value;\n const char *text;\n} simpletron_errors[WARN_COUNT] = {\n { WARN_NONE, \"ok\" },\n { WARN_HALT, \"halt\" },\n { WARN_INPUT, \"improper input\" },\n { WARN_OVERFLOW, \"integer overflow\" },\n { WARN_DIVZERO, \"division by zero\" },\n { WARN_SIGNEDOVERFLOW, \"signed integer overflow\"},\n { WARN_REMAINZERO, \"remainder by zero\"},\n};\n\nstatic bool isOutOfRange(int n) {\n return n < MEM_MIN || n > MEM_MAX;\n}\n\n/* get instruction from fp; return 0 if instruction is improper */\nstatic int fetch_number(FILE *fp, int *instruction) {\n int num = 0;\n int c;\n int sign = 1;\n\n /* get initial blank */\n while (isblank(c = getc(fp)))\n ;\n\n /* get instruction/data sign */\n switch (c) {\n case '-':\n sign = -1;\n // fall through\n case '+':\n c = getc(fp);\n break;\n default: // error condition\n return 0;\n }\n\n /* get instruction/data number */\n for (int i = INSTRUCTIONSIZE; i; --i) {\n if (!isdigit(c)) { // error\n return 0;\n }\n num = num * 10 + c - '0';\n c = getc(fp);\n }\n\n /* get remaining of command line */\n while (c != '\\n' && c != EOF) {\n c = getc(fp);\n }\n\n *instruction = sign * num;\n return 1;\n}\n\nstatic int simple_instr_read(struct Simpletron *s) {\n if (fetch_number(stdin, &s->memory[s->operand]) == 0) {\n return WARN_INPUT;\n }\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_write(struct Simpletron *s) {\n printf(\"%+05d\\n\", s->memory[s->operand]);\n ++s->pc;\n return WARN_NONE;\n}\nstatic int simple_instr_load(struct Simpletron *s) {\n s->acc = s->memory[s->operand];\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_store(struct Simpletron *s) {\n s->memory[s->operand] = s->acc;\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_add(struct Simpletron *s) {\n int result = s->acc + s->memory[s->operand];\n if (isOutOfRange(result)) {\n return WARN_OVERFLOW;\n }\n s->acc = result;\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_subtract(struct Simpletron *s) {\n int result = s->acc - s->memory[s->operand];\n if (isOutOfRange(result)) {\n return WARN_OVERFLOW;\n }\n s->acc = result;\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_divide(struct Simpletron *s) {\n if (s->memory[s->operand] == 0) {\n return WARN_DIVZERO;\n } else if ((s->acc == MEM_MIN) && (s->memory[s->operand] == -1)) {\n return WARN_SIGNEDOVERFLOW;\n } else {\n s->acc /= s->memory[s->operand];\n }\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_multiply(struct Simpletron *s) {\n s->acc *= s->memory[s->operand];\n if (isOutOfRange(s->acc)) {\n return WARN_OVERFLOW;\n }\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_remainder(struct Simpletron *s) {\n if (s->memory[s->operand] == 0) {\n return WARN_REMAINZERO;\n } else if ((s->acc == MEM_MIN) && (s->memory[s->operand] == -1)) {\n return WARN_SIGNEDOVERFLOW;\n } else {\n s->acc %= s->memory[s->operand];\n }\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_add_i(struct Simpletron *s) {\n int result = s->acc + s->operand;\n if (isOutOfRange(result)) {\n return WARN_OVERFLOW;\n }\n s->acc = result;\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_subtract_i(struct Simpletron *s) {\n int result = s->acc - s->operand;\n if (isOutOfRange(result)) {\n return WARN_OVERFLOW;\n }\n s->acc = result;\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_divide_i(struct Simpletron *s) {\n if (s->operand == 0) {\n return WARN_DIVZERO;\n } else if ((s->acc == MEM_MIN) && (s->operand == -1)) {\n return WARN_SIGNEDOVERFLOW;\n } else {\n s->acc /= s->operand;\n }\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_multiply_i(struct Simpletron *s) {\n s->acc *= s->operand;\n if (isOutOfRange(s->acc)) {\n return WARN_OVERFLOW;\n }\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_remainder_i(struct Simpletron *s) {\n if (s->operand == 0) {\n return WARN_REMAINZERO;\n } else if ((s->acc == MEM_MIN) && (s->operand == -1)){\n return WARN_SIGNEDOVERFLOW;\n } else {\n s->acc %= s->operand;\n }\n ++s->pc;\n return WARN_NONE;\n}\n\nstatic int simple_instr_branch(struct Simpletron *s) {\n s->pc = s->operand;\n return WARN_NONE;\n}\n\nstatic int simple_instr_branchneg(struct Simpletron *s) {\n if (s->acc < 0) {\n s->pc = s->operand;\n } else {\n ++s->pc;\n }\n return WARN_NONE;\n}\n\nstatic int simple_instr_branchzero(struct Simpletron *s) {\n if (s->acc == 0) {\n s->pc = s->operand;\n } else {\n ++s->pc;\n }\n return WARN_NONE;\n}\n\nstatic int simple_instr_halt(struct Simpletron *s) {\n s=s;\n return WARN_HALT;\n}\n\nstatic const struct Instruction {\n int opcode;\n const char *mnemonic;\n const char *printstr;\n int (*exec)(struct Simpletron* s);\n} instructions[] = {\n { 10,\"READ\",\" [%2u]\", simple_instr_read },\n { 11,\"WRITE\",\" [%2u]\", simple_instr_write },\n { 20,\"LOAD\",\" [%2u]\", simple_instr_load },\n { 21,\"STORE\",\" [%2u]\", simple_instr_store },\n { 30,\"ADD\",\" [%2u]\", simple_instr_add },\n { 31,\"SUBTRACT\",\" [%2u]\", simple_instr_subtract },\n { 32,\"DIVIDE\",\" [%2u]\", simple_instr_divide },\n { 33,\"MULTIPLY\",\" [%2u]\", simple_instr_multiply },\n { 34,\"REMAINDER\",\" [%2u]\", simple_instr_remainder },\n { 40,\"ADD_I\",\" %2u\", simple_instr_add_i },\n { 41,\"SUBTRACT_I\",\" %2u\", simple_instr_subtract_i },\n { 42,\"DIVIDE_I\",\" %2u\", simple_instr_divide_i },\n { 43,\"MULTIPLY_I\",\" %2u\", simple_instr_multiply_i },\n { 44,\"REMAINDER_I\",\" %2u\", simple_instr_remainder_i },\n { 50,\"BRANCH\",\" %2u\", simple_instr_branch },\n { 51,\"BRANCHNEG\",\" %2u\", simple_instr_branchneg },\n { 52,\"BRANCHZERO\",\" %2u\", simple_instr_branchzero },\n { 53,\"HALT\",\"\" , simple_instr_halt },\n\n};\n\nstatic const struct Instruction *findop(int opcode) {\n for (size_t i=0; i < sizeof(instructions)/sizeof(instructions[0]); ++i) {\n if (opcode == instructions[i].opcode) {\n return &instructions[i];\n }\n }\n return NULL;\n}\n\nstatic const struct Instruction *findmnemonic(const char *mnemonic) {\n for (size_t i=0; i < sizeof(instructions)/sizeof(instructions[0]); ++i) {\n if (strcmp(mnemonic, instructions[i].mnemonic) == 0) {\n return &instructions[i];\n }\n }\n return NULL;\n}\n\n/* run instructions from memory; return 1 if error occurs, return 0 otherwise */\nint\nsimpletron_run(struct Simpletron *s, bool trace, bool verbose)\n{\n /* memory location of next instruction */\n /* simulation begins with the instruction in the location 00 and continues sequentially */\n s->pc = 0;\n\n /* this loop implements the \"instruction execution cycle\" */\n while (s->pc < s->memsize) {\n /* opcode is the leftmost two digits of instruction register*/\n s->opcode = s->memory[s->pc] / 100;\n /* operand is the rightmost two digits of instruction register*/\n s->operand = s->memory[s->pc] % 100;\n /* simple linear scan for opcode */\n\n const struct Instruction *op = findop(s->opcode);\n if (op == NULL) {\n warnx(\"%+05d: invalid instruction\", s->memory[s->pc]);\n return 1;\n }\n if (trace) {\n fprintf(stderr, \"%05lu: %+05d\\t\", s->pc, s->memory[s->pc]);\n fprintf(stderr, op->mnemonic);\n fprintf(stderr, op->printstr, s->operand);\n fprintf(stderr, \"\\n\");\n }\n int result = op->exec(s);\n if (verbose) {\n simpletron_dump(s);\n }\n if (result == WARN_HALT) {\n return 0;\n }\n if (result != WARN_NONE && result < WARN_COUNT) {\n warnx(simpletron_errors[result].text);\n return 1;\n }\n }\n warnx(\"execution reached end of memory without halting\");\n return 1;\n}\n\nstatic int parsearg(const char *fmt, FILE *fp) {\n unsigned arg = 0;\n int result = fscanf(fp, fmt, &arg);\n return (result == 1) ? (int)arg : -1;\n}\n\nint simpletron_load(struct Simpletron *s, FILE *fp) {\n unsigned linenum = 1;\n char inst[13];\n inst[12] = '\\0'; // assure it's terminated\n size_t i = 0;\n const char* error = NULL;\n while (!error && (fscanf(fp, \"%12s\", inst) == 1)) {\n // is it a number\n if (inst[0] == '+' || inst[0] == '-') {\n int arg;\n if (sscanf(inst, \"%5d\", &arg) == 1) {\n s->memory[i++] = arg;\n } else {\n error = \"reading number\";\n }\n } else {\n const struct Instruction *in = findmnemonic(inst);\n if (in) {\n if (strlen(in->printstr)) {\n int arg = parsearg(in->printstr, fp);\n if (arg >= 0) {\n s->memory[i++] = in->opcode*100 + arg;\n } else {\n error = \"reading instruction\";\n }\n } else {\n s->memory[i++] = in->opcode*100;\n }\n } else {\n error = \"reading instruction\";\n }\n }\n // ignore the rest of the line\n for (int c = getc(fp); c != '\\n' && c != EOF; c = getc(fp)) {\n }\n ++linenum;\n if (i >= s->memsize) {\n error = \"memory full\";\n }\n }\n if (error) {\n printf(\"ERROR:%s:%d\\n\", error, linenum);\n return 1;\n }\n return 0;\n}\n\n/* write a core dump of memory and registers into stdout */\nvoid simpletron_dump(struct Simpletron *s) {\n fprintf(stderr, \"\\nREGISTERS:\\n\"\n \"accumulator %+05d\\n\"\n \"instruction pointer +%04lu\\n\",\n s->acc, s->pc);\n fprintf(stderr, \"\\nMEMORY:\\n \");\n const unsigned linelen = 10;\n for (unsigned i = 0; i < linelen; ++i) {\n fprintf(stderr, \"%7u\", i);\n }\n unsigned dumpcount = 0;\n for (size_t i = 0; i < s->memsize; ++i, --dumpcount) {\n if (dumpcount == 0) {\n fprintf(stderr, \"\\n%2lu \", i );\n dumpcount = linelen;\n }\n fprintf(stderr, \"%+05d \", s->memory[i]);\n }\n fprintf(stderr, \"\\n\");\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T22:25:39.643",
"Id": "469670",
"Score": "0",
"body": "I am in fact too much adapted with old idioms I learned from K&R and manpages. Do you recommend any book I can read to make me adapt to the modern programming practices and idioms?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:50:04.720",
"Id": "469742",
"Score": "0",
"body": "I would recommend \"Modern C\" by Jens Gustedt. It is a very recent book published by Manning and looks like an excellent resource for learning the modern version of the language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:12:03.383",
"Id": "469771",
"Score": "0",
"body": "_define variables when they are defined_ - you mean initialize when defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:14:13.910",
"Id": "469772",
"Score": "0",
"body": "Yes, I meant *define variables when they are **declared***. Corrected now, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T20:49:02.680",
"Id": "469812",
"Score": "0",
"body": "For that conversion, I opened the file in two windows and cut and pasted the body of each `case` statement into each separate function. Then just do minimal modifications for converting to use the `struct Simpletron` and you're done. Tedious, perhaps, but not hard. Let me know if I can answer any questions or help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T20:53:05.560",
"Id": "469813",
"Score": "0",
"body": "I have already done the `struct simpletron` thing, it's in the edition I linked to in my last comment. It was easy, the conversion of the case statements is what is exhausting me."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:23:54.610",
"Id": "239468",
"ParentId": "239425",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "239468",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T01:52:54.293",
"Id": "239425",
"Score": "8",
"Tags": [
"c",
"virtual-machine"
],
"Title": "Simpletron simulator in C"
}
|
239425
|
<p>As I was advised, I broke my code into 2 classes. Could you take a look at the repository class and report what problems this code has</p>
<pre><code>public class JsonSharedPreferences {
private static Gson gson = new Gson();
private Context context;
public JsonSharedPreferences(Context context) {
this.context = context.getApplicationContext();
}
public <T> T loadObject(Class<T> classType, String key) {
SharedPreferences settings = context.getSharedPreferences(key, Context.MODE_PRIVATE);
String json = settings.getString(key, null);
return gson.fromJson(json, classType);
}
public <T> void saveObject(T objective, String key) {
SharedPreferences settings = context.getSharedPreferences(key, Context.MODE_PRIVATE);
String json = gson.toJson(objective);
settings.edit().putString(key, json).apply();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T11:52:56.850",
"Id": "469615",
"Score": "1",
"body": "`Objective` class does not hold a single responsibility. It acts as a *POJO* and *Service layer* class. I would create 2 different classes and segregate the functionalities. Using static will tempt to cause runtime rabbit holes. Therefore, verify your static methods would work properly on concurrent scenarios."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T10:22:57.947",
"Id": "469725",
"Score": "0",
"body": "Sorry, needed to rollback, as changing code to incorporate answers (or in this case: helpful comments) is not done on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T16:06:48.723",
"Id": "469792",
"Score": "0",
"body": "@mtj we don't have the same rules about comments that we do for answers, please do not rollback for a comment's sake."
}
] |
[
{
"body": "<ul>\n<li>Why saving reference to <code>Context</code> and then create <code>SharedPreferences</code> each time? There's duplicate code for creating <code>SharedPreferences</code> You could just use context in constructor to create member <code>SharedPreferences</code> to use in your methods. If you want to keep it as it is, at least extract duplicate code into separate method.</li>\n<li>I am missing null checks. I expect to get very obscure behaviour when passing null for keys or classes. Test for null and throw <code>NullPointerException</code> early, be fail-fast. For example <a href=\"https://guava.dev/releases/19.0/api/docs/com/google/common/base/Preconditions.html#checkNotNull(T)\" rel=\"nofollow noreferrer\">checkNotNull</a> or some <a href=\"https://www.jetbrains.com/help/idea/nullable-and-notnull-annotations.html\" rel=\"nofollow noreferrer\">NotNull</a> annotation to help better fighting against null. Another way to fight is to use <code>kotlin</code>, which doesn't allow null on compiler level unless you make variable optional.</li>\n<li><p>I don't like that <code>gson</code> is private and static.</p>\n\n<ul>\n<li>That means there is no way to configure <code>gson</code>. Would be better if this was member property and I would be able to pass different configuration of gson. Can add consructor overloads for that. Maybe this is overdoing it for your case, but I usually configure <code>Gson</code> quite a lot, have my own <code>TypeAdapters</code> and I wouldn't be able to use my <code>Gson</code> configuration with your class.</li>\n<li>At first I was concerned about thread-safety <code>Gson</code> is <a href=\"https://stackoverflow.com/questions/10380835/is-it-ok-to-use-gson-instance-as-a-static-field-in-a-model-bean-reuse\">thread-safe</a>, so there's no argument against static in this sense. Always check for that when you make something static like this.</li>\n</ul></li>\n<li><p>Pretty sure that when saving preferences in android, you first put <code>key</code> and then <code>value</code>. Your <code>saveObject</code> has it the other way around, that is imho confusing. I'd switch parameters in <code>loadObject</code> too so that key is always first in those cases, but guess that's a bit subjective.</p></li>\n<li>Immutability makes code simpler to use and read. If something is final, you don't need to keep be alert if it changed anytime. <code>context</code> member variable can be final and all method parameters can be final too. After refactoring possible <code>SharedPreferences</code> and <code>Gson</code> instances can also be final - set in constructor.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T09:32:41.750",
"Id": "239551",
"ParentId": "239430",
"Score": "1"
}
},
{
"body": "<p>Hellow <a href=\"https://codereview.stackexchange.com/users/214636/k-h\">K.H.</a> thanks for the answer.\nI rewrote the code using Dagger 2 for dependency injection and following your advice. Could you take a look at this code and answer a couple of questions:</p>\n\n<ul>\n<li>How to correctly pass name to JsonSharedPreferences (Make a\nsetter, make a module that will provide name).</li>\n<li>Is it correct to select this code as a separate component or more\ncorrectly add these modules to the application component(I use application component to provide context and application)</li>\n</ul>\n\n<p>JsonSharedPreferences:</p>\n\n<pre><code>public class JsonSharedPreferences {\n private Gson gson;\n private SharedPreferences settings;\n\n public JsonSharedPreferences(@NonNull Context context, @NonNull String name, @NonNull Gson gson) {\n SharedPreferences settings = context.getSharedPreferences(name, Context.MODE_PRIVATE);\n this.settings = settings;\n this.gson = gson;\n }\n\n public <T> T loadObject(@NonNull String key, @NonNull Class<T> classType) {\n String json = settings.getString(key, null);\n return gson.fromJson(json, classType);\n }\n\n public <T> void saveObject(@NonNull String key, @NonNull T objective) {\n String json = gson.toJson(objective);\n settings.edit().putString(key, json).apply();\n }\n}\n</code></pre>\n\n<p>JsonSharedPreferencesModule:</p>\n\n<pre><code>@Module\npublic class JsonSharedPreferencesModule {\n\n @Provides\n JsonSharedPreferences provideJsonSharedPreferences(Context context, String name, Gson gson) {\n return new JsonSharedPreferences(context, name,gson);\n }\n\n}\n</code></pre>\n\n<p>GsonModule:</p>\n\n<pre><code>@Module\npublic class GsonModule {\n\n @Provides\n Gson provideGson() {\n return new Gson();\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T10:22:55.223",
"Id": "469863",
"Score": "0",
"body": "Not sure if this is how site should be used. This is probably for another separate question. I will try to answer anyway. I think passing name in constructor is fine as you have it now. Sorry cannot give good answer about the other question, my knowledge is limited there. You can also make all parameters and member variables final. Immutability is always good :-) Actually I will add that to my original answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T10:06:36.990",
"Id": "239552",
"ParentId": "239430",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239551",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T06:06:00.437",
"Id": "239430",
"Score": "3",
"Tags": [
"java",
"beginner",
"android",
"json",
"gson"
],
"Title": "Code for saving / loading a class object"
}
|
239430
|
<p>I am learning C and, for learning purposes, I implemented a dice roller.</p>
<p>It uses <a href="https://man.openbsd.org/arc4random.3" rel="nofollow noreferrer">arc4random(3)</a> for random number generation, as I couldn't find something better.</p>
<p>It works both interactively, if no argument is given, reading dice string from stdin, one per line (I used <a href="https://man.openbsd.org/getline.3" rel="nofollow noreferrer">getline(3)</a> for this); and reading dice string from arguments.<br>
A dice string is a dice specification similar to those used in most role playing games, for example, <code>rolldice 3d6</code> rolls 3 6-sized dice and sum them up, and <code>rolldice 4d8+2s1</code> rolls 4 8-sized dice, discards one roll, sum the rolls, and add 2 to the result. More information on this on the manual.</p>
<p>I wrote a manual page for it, the manual page is based on the manual of <a href="https://github.com/sstrickl/rolldice" rel="nofollow noreferrer">Stevie Strickland's rolldice</a>, but the code I wrote from scratch.</p>
<p>Here's the manual:</p>
<pre class="lang-none prettyprint-override"><code>rolldice(6) Games Manual rolldice(6)
NAME
rolldice - rolls virtual dice
SYNOPSIS
rolldice [-s] [dice string...]
DESCRIPTION
rolldice rolls virtual dice. The dice strings passed on the command
line contain information on the dice to roll in a format comparable
to the format used in most role playing games.
If no dice strings are provided as command line arguments, rolldice
uses stdin as input and runs interactivelly.
The options are as follows:
-s Print out the result of each individual die separately, as
well as the operations and totals.
DICE STRING FORMAT
The dice string uses the exact format outlined below. Optional
parts are between square brackets. A # must be replaced by a num‐
ber.
[#x][#]d[#|%][*#][+#|-#][s#]
[#x] How many times to roll. If ommited, defaults to 1 roll.
[#]d[#|%]
Main part of the dice string. The first number is the number
of dice to roll in each roll, if ommited, roll just one die.
The second number is the number of sides the dice have, if
ommited, roll 6-sided die. The second number can be replaced
by a percent sign, implying a 100-sided die. The numbers
rolled on each die are then added up and given as the result.
[*#] How many times to multiply the result of each roll.
[+#|-#]
Number to be added or subtracted, depending on the sign, from
each roll. This step is handled after the multiplication.
[s#] How many lowest dice rolls to drop. This step is handled be‐
fore the multiplication.
EXIT STATUS
0 Success.
>0 Error occurred.
EXAMPLES
Roll three six-sided dice and sum the results:
rolldice 3d
Roll four eight-sided dice and sum the results, them multiply the
result by 2 and add 2 to it:
rolldice 4d8*2+2
Roll four six-sided dice, drop the lowest result and add the remain‐
ing results. Do this three times:
rolldice 3x4d6s1
HISTORY
This version of rolldice was written as an exercise for practicing
C.
The idea for getnumber() was from an anon from /g/'s dpt. I
could've used strtol(3) but, as I said, I did it for practicing.
rolldice(6)
</code></pre>
<p>Here's the code:</p>
<pre><code>#include <err.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <bsd/stdlib.h>
#define DEFROLLS 1
#define DEFDICE 1
#define DEFFACES 6
#define DEFMULTIPLIER 1
#define DEFMODIFIER 0
#define DEFDROP 0
static int separate;
/* structure of a dice string */
struct dice {
int rolls;
int dice;
int faces;
int multiplier;
int modifier;
int drop;
};
static void rolldice(struct dice);
static struct dice getdice(char *);
static int getnumber(char **);
static void usage(void);
/* roll a virtual dice */
int
main(int argc, char *argv[])
{
struct dice *d;
int c, i, exitval;
char *line = NULL;
size_t linesize = 0;
ssize_t linelen;
separate = 0;
while ((c = getopt(argc, argv, "s")) != -1) {
switch (c) {
case 's':
separate = 1;
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
exitval = EXIT_SUCCESS;
if (argc == 0) { /* no arguments, run interactivelly */
if ((d = reallocarray(NULL, 1, sizeof(*d))) == NULL)
err(1, NULL);
while ((linelen = getline(&line, &linesize, stdin)) != -1) {
*d = getdice(line);
if (d->rolls == 0) {
warnx("%s: malformed dice string", line);
exitval = EXIT_FAILURE;
} else {
rolldice(*d);
}
}
free(line);
if (ferror(stdin))
err(1, "stdin");
} else { /* run parsing the arguments */
if ((d = reallocarray(NULL, argc, sizeof(*d))) == NULL)
err(1, NULL);
for (i = 0; i < argc; i++) {
d[i] = getdice(*argv);
if ((d[i]).rolls == 0)
errx(1, "%s: malformed dice string", *argv);
argv++;
}
for (i = 0; i < argc; i++)
rolldice(d[i]);
}
free(d);
if (ferror(stdout))
err(1, "stdout");
return exitval;
}
/* get a random roll given a dice structure */
static void
rolldice(struct dice d)
{
int i, j, min, drop;
int *roll, rollcount, rollsum;
if ((roll = reallocarray(NULL, d.dice, sizeof(*roll))) == NULL)
err(1, NULL);
rollcount = 1;
while (d.rolls-- > 0) {
rollsum = 0;
if (separate)
printf("Roll #%d: (", rollcount++);
/* get random values */
for (i = 0; i < d.dice; i++) {
roll[i] = 1 + arc4random() % d.faces;
rollsum += roll[i];
if (separate)
printf("%d%s", roll[i], (i == d.dice-1) ? "" : " ");
}
/* drop smallest values */
drop = d.drop;
while (drop-- > 0) {
min = INT_MAX;
for (i = 0; i < d.dice; i++) {
if (roll[i] != 0 && min > roll[i]) {
min = roll[i];
j = i;
}
}
rollsum -= roll[j];
if (separate)
printf(" -%d", roll[j]);
}
/* sum rolls, apply multiplier and modifier */
rollsum = rollsum * d.multiplier + d.modifier;
if (separate) {
printf(")");
if (d.multiplier != 1)
printf(" * %d", d.multiplier);
if (d.modifier != 0)
printf(" %c %u", (d.modifier < 0) ? '-' : '+', abs(d.modifier));
printf(" = ");
}
/* print final roll */
printf("%d%c", rollsum, (d.rolls == 0 || separate) ? '\n' : ' ');
}
free(roll);
}
/* get dice in format [#x][#]d[#|%][*#][+#|-#][s#], where # is a number */
static struct dice
getdice(char *s)
{
struct dice d;
int n, sign;
/* set number of rolls */
if ((n = getnumber(&s)) < 0)
goto error;
d.rolls = DEFROLLS;
if (*s == 'x') {
d.rolls = (n == 0) ? DEFROLLS : n;
s++;
if (n < 1)
goto error;
if ((n = getnumber(&s)) < 0)
goto error;
}
/* set number of dices */
if (*s != 'd')
goto error;
d.dice = (n == 0) ? DEFDICE : n;
n = 0;
s++;
/* set number of faces */
if (*s == '%') {
n = 100;
s++;
}
else
if ((n = getnumber(&s)) < 0)
goto error;
d.faces = (n == 0) ? DEFFACES : n;
n = 0;
/* set multiplier */
if (*s == '*') {
s++;
if ((n = getnumber(&s)) < 1)
goto error;
}
d.multiplier = (n == 0) ? DEFMULTIPLIER : n;
n = 0;
/* set modifier */
if (*s == '+' || *s == '-') {
sign = (*s++ == '-') ? -1 : 1;
if ((n = getnumber(&s)) < 1)
goto error;
}
d.modifier = (n == 0) ? DEFMODIFIER : sign * n;
n = 0;
/* set number of drops */
if (*s == 's') {
s++;
if ((n = getnumber(&s)) < 1)
goto error;
}
d.drop = (n == 0) ? DEFDROP : n;
if (d.drop >= d.dice)
goto error;
if (*s != '\0' && *s != '\n')
goto error;
return d;
error:
return (struct dice) {0, 0, 0, 0, 0, 0};
}
/* get number from *s; return -1 in case of overflow, return 0 by default */
static int
getnumber(char **s)
{
int n;
n = 0;
while (isdigit(**s)) {
if (n > (INT_MAX - 10) / 10)
return -1;
else
n = n * 10 + **s - '0';
(*s)++;
}
return n;
}
static void
usage(void)
{
(void) fprintf(stderr, "usage: rolldice [-s] [dice-string...]\n");
exit(EXIT_FAILURE);
}
</code></pre>
<p>Is my solution portable? And is it well commented?<br>
I think I rely to much on BSD extensions, such as <a href="https://man.openbsd.org/err.3" rel="nofollow noreferrer">err(3)</a>, and on POSIX extensions, such as <a href="https://man.openbsd.org/getopt.3" rel="nofollow noreferrer">getopt(3)</a>. It must be compiled with <code>-lbsd</code> on Linux. Is this bad?</p>
<p>Is my code comparable to Stevie's? Or is it worse?<br>
Please, see also <a href="https://github.com/sstrickl/rolldice" rel="nofollow noreferrer">Stevie's rolldice</a>, and compare my code to his.</p>
<p>I think Stevie's rolldice contains serious input bugs, such as accepting any string not containing <code>d</code> as <code>1d6</code>, for example <code>rolldice foo</code> is the same as <code>rolldice 1d6</code> for Stevie's. And his implementation accepts multiple modifiers, but only uses the last one (<code>rolldice 1d6-3+2+1</code> is the same as <code>rolldice 1d6+1</code>). My version does not have those bugs.</p>
<p>(Note: I had access to Stevie's rolldice program before writing mine, but I have only seen Stevie's code after finalizing mine, which I wrote from scratch).</p>
<p>EDIT: After reading the answers, I've refactored the code and written a <a href="https://pastebin.com/raw/DNTNReBA" rel="nofollow noreferrer">new version of rolldice(6)</a>.</p>
|
[] |
[
{
"body": "<blockquote>\n<p>Is it well commented?</p>\n</blockquote>\n<p>Generally yes, the only place I might add more comments is to explain the fields in the structure.</p>\n<blockquote>\n<p>Is my solution portable?</p>\n</blockquote>\n<p>No, it will not port to Windows easily because of the use of <code>libbsd</code> and the use of the <code>unistd.h</code> header file.</p>\n<p>To improve portability it is also important to get comfortable with the memory allocation functions <code>void* malloc(size_t size)</code>, <code>void* calloc( size_t num, size_t size )</code> and <code>void *realloc( void *ptr, size_t new_size )</code>. Use the standard C library function <code>char *fgets( char *restrict str, int count, FILE *restrict stream )</code> instead of <code>getline()</code>.</p>\n<h1>Complexity of the Functions</h1>\n<p>There are at least 2 sub-functions that could be pulled out of <code>main()</code>, the first is processing the command line arguments, and the second is handling the use input.</p>\n<p>The function <code>rolldice(struct dice d)</code> is also too complex, there are 2 or 3 sub-functions in <code>rolldice</code> as well.</p>\n<p>There is also a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> that applies here. The Single Responsibility Principle states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:55:04.583",
"Id": "469744",
"Score": "0",
"body": "What could be a good alternative to libbsd's arc4random? stdlib's random(3) and rand(3) needs to be seeded, if I seed them with srand(time(NULL)), I have to wait a whole second to use rolldice again, since it just reseed after each full second. Is there any way I can reseed it more frequently?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:37:42.737",
"Id": "469756",
"Score": "0",
"body": "You only need to seed rand once at the beginning of the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:39:40.977",
"Id": "469759",
"Score": "0",
"body": "I know. But when I run the program twice at the same second, both runs will seed the same `time(NULL)`, if I seed it with `srand(time(NULL))`. Thus generating the same random numbers on each run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:31:32.933",
"Id": "469764",
"Score": "2",
"body": "@barthooper Use `srand(time(NULL) ^ getpid())` or the like."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:28:51.997",
"Id": "239445",
"ParentId": "239434",
"Score": "2"
}
},
{
"body": "<p>Very nicely code.</p>\n\n<p>Only some nits.</p>\n\n<p><strong>Help</strong></p>\n\n<p>\"I wrote a manual page for it\" --> Perhaps it, or a condensed version for option <code>-h</code>?</p>\n\n<pre><code> case 'h':\n printf(\"blah blah\\n);\n exit (EXIT_SUCCESS);\n</code></pre>\n\n<p><strong>> vs <</strong></p>\n\n<p>Conceptually, when looking for \"smallest values\", I'd like to find a <code><</code>. Perhaps:</p>\n\n<pre><code> // if (roll[i] != 0 && min > roll[i]) {\n if (roll[i] != 0 && roll[i] < min) {\n</code></pre>\n\n<p><strong>Theoretical UB</strong></p>\n\n<p>If for <em>some reason</em> <code>if (roll[i] != 0 && min > roll[i])</code> is never true, <code>j</code> remains uninitialized and UB later in <code>rollsum -= roll[j];</code>.</p>\n\n<p>Recommend to declare <code>j</code> in the <code>while</code> loop and initialize it.</p>\n\n<p><strong>Theoretical UB</strong></p>\n\n<p>Code relies on <code>modifier</code> never getting/having the value of <code>INT_MIN</code> - which of course it should not with sane input. But let's have some fun.</p>\n\n<p>The 2 lines incurs UB when <code>INT_MIN</code> is involved.</p>\n\n<pre><code>d.modifier = (n == 0) ? DEFMODIFIER : sign * n;\nprintf(\" %c %u\", (d.modifier < 0) ? '-' : '+', abs(d.modifier));\n</code></pre>\n\n<p><code>getnumber(char **s)</code> also has UB potential (<code>n = n * 10 + **s - '0';</code> can still overflow) with input for values near/above <code>INT_MAX</code>.</p>\n\n<p>Candidate fix/improve for a full range <code>getnumber</code></p>\n\n<pre><code>// No reason to pass `char **`, pass a `char *`\n// Moving sign detection here too.\nstatic int getnumber(const char *s) {\n int n = 0;\n int sign = *s;\n if (size == '-' || size == '+') s++;\n\n // As there are more neg int than pos int, code accumulates on the neg side\n while (isdigit((unsigned char) *s)) { // Cast to avoid UB of *s < 0\n int digit = *s - '0';\n if (n <= INT_MIN/10 && (n < INT_MIN/10 || digit > -(INT_MIN%10))} {\n return -1;\n }\n n = n*10 - digit;\n }\n\n if (sign != '-') {\n if (n < -INT_MAX) {\n return -1;\n }\n n = -n;\n }\n return n;\n}\n</code></pre>\n\n<p>GTG</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:57:25.583",
"Id": "469745",
"Score": "0",
"body": "The program does support -h. When passing -h (or any other option other than -s) it will show usage()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:03:12.023",
"Id": "469746",
"Score": "1",
"body": "@barthooper Yes, I see that now. Detail idea: For `getopt()`, I like the default to result in a `usage()` and a prompt `EXIT_FAILURE`, whereas `-h` results in `usage()` and `EXIT_SUCCESS`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:21:17.360",
"Id": "469749",
"Score": "0",
"body": "I am following suckless philosophy and OpenBSD practice of considering a dedicated `-h` bloat, since the program can handle it by default without a special option. Most UNIX programs (except the GNU ones) do not have -h but will show `usage()` when calling with `-h`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:28:23.377",
"Id": "469763",
"Score": "0",
"body": "Do you think it would be better if I gather all `separate`'s `printf` at the final of `rolldice()` and better the readability at the price of adding another, redundant loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T15:23:21.130",
"Id": "470334",
"Score": "0",
"body": "You should never print usage in response to an incorrect call line. A simple, succinct error message is far better. If you want to treat an incorrect call as a request for usage, then print it to stdout and do not consider it an error. (IMO, that is only appropriate if called with no arguments.) https://wrp.github.io/blog/2020/02/21/succinct-err-messages.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T17:18:16.663",
"Id": "470341",
"Score": "0",
"body": "@WilliamPursell Agree that incorrect usage should not result in a long response. Will ponder the other ideas."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:38:24.613",
"Id": "239483",
"ParentId": "239434",
"Score": "3"
}
},
{
"body": "<h1>Portability</h1>\n<p>Your code is mostly portable. I would say to toss the use of BSD extensions. Here's an implementation of <code>reallocarray</code>:</p>\n<pre><code>void *reallocarray(void *p, size_t n, size_t sz)\n{\n if(n > PTRDIFF_MAX/sz)\n {\n /* overflow; avoid undefined behavior\n for pointer subtractions */\n return NULL;\n }\n return realloc(p, n * sz);\n}\n</code></pre>\n<p>For the functions from <code>err.h</code>, you'll have to go in and manually replace those with their equivalents. See also <a href=\"https://man.openbsd.org/err\" rel=\"nofollow noreferrer\">the spec</a>.</p>\n<p>I'd say that using POSIX is fine; on Windows, there are plenty of drop-in replacements for <code>getopt</code> and <code>getline</code>.</p>\n<h1>Consistency</h1>\n<p>In some places you're using <code>1</code> (<code>err</code>, <code>errx</code>), while in others you're using <code>EXIT_FAILURE</code>. If you plan on using POSIX for the long-term, I suggest 1. Otherwise, use <code>EXIT_FAILURE</code>.</p>\n<h1>Typos</h1>\n<p>"ommited" should be "omitted".<br />\n"dices" should be "dice".</p>\n<p>These aren't that big of a problem but bad spelling and grammar are my pet peeve :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-10T00:01:23.513",
"Id": "471176",
"Score": "1",
"body": "`err(1)`, `warn(1)` and related functions come in handy and are very convenient, I wonder why they are not specified by POSIX. On the typos, English is not my native language, but I swear they are not that frequent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-10T00:02:37.613",
"Id": "471177",
"Score": "0",
"body": "@barthooper The typos aren't frequent. You're doing well with spelling and grammar otherwise."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-08T15:05:12.387",
"Id": "240146",
"ParentId": "239434",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239483",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T08:51:02.913",
"Id": "239434",
"Score": "4",
"Tags": [
"beginner",
"c",
"random",
"role-playing-game"
],
"Title": "A dice roller in C"
}
|
239434
|
<p>Recently I was learning about TypeList and its algorithms in C++. When reading about its uses i got to know that TypeList along with the help of ClassHierarchy generators can be used to create Tuple Type in C++ (Andrei Alexandrescu). So i tried to write an implementation of it based on ClassHierarchy generator which is given below</p>
<p><strong>Hierarchy Generator :</strong> </p>
<pre><code> // Class Hierarchy Generator : This class acts as a code generator for many different uses ( like tuple )
// Input : TypeList, Holder(Holds a value of required Type)
// Output : A type that has publicly inherited itself from Holders of all the types in TypeList
template<class TypeList, template<class> class Holder>
struct HierarchyGen;
template<class AtomicType, template<class> class Holder>
struct HierarchyGen : public Holder<AtomicType> {
// Leftbase in all case represents the value Holder
typedef Holder<AtomicType> LeftBase;
};
template<class Head,class Tail, template<class>class Holder>
struct HierarchyGen < TypeList<Head, Tail>, Holder> : public HierarchyGen<Head, Holder>, public HierarchyGen<Tail, Holder> {
typedef HierarchyGen<Head,Holder> LeftBase;
typedef HierarchyGen<Tail,Holder> RightBase;
};
// If null type inherit nothing
template< template<class>class Holder>
struct HierarchyGen< NullType, Holder> {};
</code></pre>
<p><strong>At :</strong> Recurses through a Hierarchy and gets the type at given index</p>
<pre><code>//At : This structure helps us in getting the type at given index
// Input : HierarchyGen , index
// Output : The type at index
// Algorithm:
/*
if index is 0 then
Result = current_Hierarchygen::LeftBase
else
Result = At<current_Hierarchygen::RightBase , index-1>
*/
// Primary template
template<class hierarchgen, unsigned int index>
struct At;
template<class hierarchgen, unsigned int index>
struct At {
typedef typename At<typename hierarchgen::RightBase, index - 1>::Result Result;
};
template<class hierarchgen>
struct At<hierarchgen,0> {
typedef typename hierarchgen::LeftBase Result;
};
</code></pre>
<p><strong>Get :</strong> Used to fetch value from a tuple</p>
<pre><code>// Functions cannot be partially specialized Hence the type2type and int2type trick is used
template< class Hierarchy, class Result>
inline Result& Get_Helper(Hierarchy& obj, type_to_type<Result>, int2type<0>){
// Assign main object to the required type ( Perticular value instance ( Holder) will be then accessed )
typename Hierarchy::LeftBase& subobj= obj;
return subobj;
}
template<class Hierarchy,class Result, unsigned index>
inline Result& Get_Helper(Hierarchy& obj, type_to_type<Result> dummy, int2type<index>) {
// Its traversing a hierarchy recursively
typename Hierarchy::RightBase& subobj = obj;
return Get_Helper(subobj, dummy, int2type<index - 1>());
}
template<unsigned index, class Hierarchy>
typename At<Hierarchy, index>::Result::holding_type& Get(Hierarchy& obj) {
typedef typename At<Hierarchy, index>::Result Result;
return Get_Helper(obj, type_to_type<Result>(), int2type<index>()).value;
}
</code></pre>
<p><strong>Usage :</strong></p>
<pre><code>template<class TypeList>
using tuple = HierarchyGen < TypeList,holder>;
//...
tuple<TYPELIST_3(int,int,int)> my_tuple;
Get<0>(my_tuple) = 4;
Get<1>(my_tuple) = 8;
Get<2>(my_tuple) = 7;
std::cout << " tuple<int,int,int> {4,8,7) :" << Get<0>(my_tuple)<<" "<< Get<1>(my_tuple)<<" "<< Get<2>(my_tuple);
Get<0>(my_tuple) = 9;
Get<1>(my_tuple) = 9;
Get<2>(my_tuple) = 9;
std::cout << "\nAfter Modifying :" << Get<0>(my_tuple) << " " << Get<1>(my_tuple) << " " << Get<2>(my_tuple);
</code></pre>
<p>I haven't looked at the implementations of tuple in Loki or Boost since i was just practising template metaprogramming. Is there something that I can improve? I am aware of the fact that variadic templates and parameter packs ease the task of creating a tuple type. Also in modern C++ do typelist have a use ? </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T11:37:38.693",
"Id": "239436",
"Score": "1",
"Tags": [
"c++",
"c++11",
"c++98"
],
"Title": "Old Style Implementation of Tuple in C++"
}
|
239436
|
<p>I worked out a <code>zip</code> operator similar to <a href="https://docs.python.org/3.3/library/functions.html#zip" rel="noreferrer">Python's</a>, because I didn't find one in <code>std</code>. It allows to use range-based <code>for</code> loops to iterate at once over several equal-length containers (arrays, counters... anything that has an iterator and a static length). It should be safe (never exceed the iterator's capacity), be able to modify the content of the container in-place when possible, and have no run-time overhead compared to manually incrementing the iterators.</p>
<p>Some things still look a bit fishy to me and I also wonder if all my naming/implementation choices adhere the <code>std</code> look-and-feel. Examples of use:</p>
<pre><code> std::array a = {1,2,3,4};
std::array b = {4,3,2,1};
for (auto [i, j, k] : zip(a, b, a)) {
std::cout << i << " " << j << " " << k << std::endl;
i = 42; // we can overwrite the values of a
}
//// This one doesn't work yet:
// for (auto [i, j] : zip(a, {4, 3, 2, 1})) {
// std::cout << i << " " << j << std::endl;
// }
</code></pre>
<p>With it comes a simple <code>range</code> class that allows to include counters in the iterations:</p>
<pre><code> // x takes the value of array a, and i counts from 0 to 3
for (auto [x, i] : zip(a, range<4>())) {
std::cout << i << " " << x << std::endl;
}
</code></pre>
<p>Note here that the arguments to <code>zip</code> aren't necessarily <em>l-values</em>.</p>
<p>Here is my implementation:</p>
<pre><code>// inductive case
template<typename T, typename... Ts>
struct zip : public zip<Ts...> {
static_assert(std::tuple_size<T>::value == std::tuple_size<zip<Ts...>>::value,
"Cannot zip over structures of different sizes");
using head_value_type = std::tuple<typename T::value_type&>;
using tail_value_type = typename zip<Ts...>::value_type;
using value_type = decltype(std::tuple_cat(std::declval<head_value_type>(),
std::declval<tail_value_type>()));
zip(T& t, Ts&... ts) : zip<Ts...>(ts...), t_(t) {}
zip(T& t, Ts&&... ts) : zip<Ts...>(ts...), t_(t) {}
zip(T&& t, Ts&... ts) : zip<Ts...>(ts...), t_(t) {}
zip(T&& t, Ts&&... ts) : zip<Ts...>(ts...), t_(t) {}
struct iterator {
using head_iterator = typename T::iterator;
using tail_iterator = typename zip<Ts...>::iterator;
head_iterator head;
tail_iterator tail;
bool operator!=(iterator& that) { return head != that.head; }
void operator++() { ++head; ++tail; }
value_type operator*() {
return std::tuple_cat<head_value_type, tail_value_type>(*head, *tail);
}
iterator(head_iterator h, tail_iterator t) : head(h), tail(t) {}
};
iterator begin() { return iterator(t_.begin(), zip<Ts...>::begin()); }
iterator end() { return iterator(t_.end(), zip<Ts...>::end()); }
T& t_;
};
// base case
template<typename T>
struct zip<T> {
using value_type = std::tuple<typename T::value_type&>;
using iterator = typename T::iterator;
zip(T&& t) : t_(t) {};
zip(T& t) : t_(t) {};
iterator begin() { return t_.begin(); }
iterator end() { return t_.end(); }
private:
T& t_;
};
// must implement tuple_size to check size equality
template<typename T, typename... Ts>
struct std::tuple_size<zip<T, Ts...>> {
static constexpr int value = std::tuple_size<T>::value;
};
</code></pre>
<p>What looks fishy/over-complicated:</p>
<ul>
<li>the constructors to cover all kinds of arguments (l/r-value/references)</li>
<li>the mangling of tuple types</li>
<li>bonus: why doesn't my second example compile?</li>
</ul>
<p>For completeness, here is my implementation of the <code>range</code> class:</p>
<pre><code>template<class T, T BEG, T END, T STEP>
struct Range {
Range() {};
using iterator = Range;
using value_type = T;
bool operator!=(iterator that) { return this->val_ < that.val_; }
void operator++() { val_ += STEP; }
int& operator*() { return val_;}
iterator begin() { return *this; }
iterator end() { return Range(END); }
private:
Range(int val) : val_(val) {}
T val_ = BEG;
};
template<class T, T BEG, T END, T STEP>
struct std::tuple_size<Range<T, BEG, END, STEP>> {
static constexpr int value = (END - BEG) / STEP;
};
template<class T, T BEG, T END, T STEP>
static auto range() { return Range<T, BEG, END, STEP>(); };
template<int BEG, int END, int STEP=1>
static auto range() { return Range<int, BEG, END, STEP>(); };
template<int END>
static auto range() { return Range<int, 0, END, 1>(); };
</code></pre>
<p>Any feedback will be much appreciated! Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T12:03:23.717",
"Id": "469616",
"Score": "0",
"body": "Welcome to Code Review. This looks nice. Can you post a small example program that uses it, so that we can verify that it compiles and runs correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T13:43:35.367",
"Id": "469622",
"Score": "0",
"body": "Hello and thanks. I had some examples at the top of the post; the whole code should compile if you put the 3 chunks in the right order. Would you like to see some other ones? or more concrete use cases?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T13:45:35.667",
"Id": "469623",
"Score": "0",
"body": "I mean something like this https://wandbox.org/permlink/XrF354DmZirvbpUl"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T13:47:06.163",
"Id": "469624",
"Score": "0",
"body": "Ah ok, thanks for doing it."
}
] |
[
{
"body": "<h1><code>zip</code></h1>\n\n<p>Right now, your <code>zip</code> uses the tuple protocol. It probably makes more sense to use the range protocol instead, to support cases like this:</p>\n\n<pre><code>std::vector a{1, 2, 3, 4};\nstd::vector b{5, 6, 7, 8};\nfor (auto [x, y] : zip(a, b)) {\n std::cout << x << ' ' << y << '\\n';\n}\n</code></pre>\n\n<p>These constructors:</p>\n\n<pre><code>zip(T& t, Ts&... ts) : zip<Ts...>(ts...), t_(t) {}\nzip(T& t, Ts&&... ts) : zip<Ts...>(ts...), t_(t) {}\nzip(T&& t, Ts&... ts) : zip<Ts...>(ts...), t_(t) {}\nzip(T&& t, Ts&&... ts) : zip<Ts...>(ts...), t_(t) {}\n</code></pre>\n\n<p>mandate that all arguments other than the first have the same. You also convert everything to lvalues, because an id-expression that refer to an rvalue reference is an lvalue (!) — this is because the original purpose of rvalue references were to capture rvalues and treat them like normal objects, not to forward rvalues.</p>\n\n<p>The <code>iterator</code> class is also some required operations: associated types (<code>iterator_category</code>, <code>difference_type</code>, etc.), <code>==</code>, postfix <code>++</code>, etc. Also consider supporting random access iterator functionalities if the zipped ranges support them. We'll come back to this later.</p>\n\n<p>I would also probably implement the <code>zip</code> without recursion, to reduce the compile-time overhead of nested template class instantiations. So the end result roughly looks like this: (not comprehensively tested, may have bugs; for simplicity, only random access ranges are supported)</p>\n\n<pre><code>#include <exception>\n#include <iterator>\n#include <tuple>\n\nnamespace detail {\n using std::begin, std::end;\n\n template <typename Range>\n struct range_traits {\n using iterator = decltype(begin(std::declval<Range>()));\n using value_type = typename std::iterator_traits<iterator>::value_type;\n using reference = typename std::iterator_traits<iterator>::reference;\n };\n\n template <typename... Its>\n class zip_iterator {\n public:\n // technically lying\n using iterator_category = std::common_type_t<\n typename std::iterator_traits<Its>::iterator_category...\n >;\n using difference_type = std::common_type_t<\n typename std::iterator_traits<Its>::difference_type...\n >;\n using value_type = std::tuple<\n typename std::iterator_traits<Its>::value_type...\n >;\n using reference = std::tuple<\n typename std::iterator_traits<Its>::reference...\n >;\n using pointer = std::tuple<\n typename std::iterator_traits<Its>::pointer...\n >;\n\n constexpr zip_iterator() = default;\n explicit constexpr zip_iterator(Its... its)\n : base_its{its...}\n {\n }\n\n constexpr reference operator*() const\n {\n return std::apply([](auto&... its) {\n return reference(*its...);\n }, base_its);\n }\n constexpr zip_iterator& operator++()\n {\n std::apply([](auto&... its) {\n (++its, ...);\n }, base_its);\n return *this;\n }\n constexpr zip_iterator operator++(int)\n {\n return std::apply([](auto&... its) {\n return zip_iterator(its++...);\n }, base_its);\n }\n constexpr zip_iterator& operator--()\n {\n std::apply([](auto&... its) {\n (--its, ...);\n }, base_its);\n return *this;\n }\n constexpr zip_iterator operator--(int)\n {\n return std::apply([](auto&... its) {\n return zip_iterator(its--...);\n }, base_its);\n }\n constexpr zip_iterator& operator+=(difference_type n)\n {\n std::apply([=](auto&... its) {\n ((its += n), ...);\n }, base_its);\n return *this;\n }\n constexpr zip_iterator& operator-=(difference_type n)\n {\n std::apply([=](auto&... its) {\n ((its -= n), ...);\n }, base_its);\n return *this;\n }\n friend constexpr zip_iterator operator+(const zip_iterator& it, difference_type n)\n {\n return std::apply([=](auto&... its) {\n return zip_iterator(its + n...);\n }, it.base_its);\n }\n friend constexpr zip_iterator operator+(difference_type n, const zip_iterator& it)\n {\n return std::apply([=](auto&... its) {\n return zip_iterator(n + its...);\n }, it.base_its);\n }\n friend constexpr zip_iterator operator-(const zip_iterator& it, difference_type n)\n {\n return std::apply([=](auto&... its) {\n return zip_iterator(its - n...);\n }, it.base_its);\n }\n constexpr reference operator[](difference_type n) const\n {\n return std::apply([=](auto&... its) {\n return reference(its[n]...);\n }, base_its);\n }\n\n // the following functions assume usual random access iterator semantics\n friend constexpr bool operator==(const zip_iterator& lhs, const zip_iterator& rhs)\n {\n return std::get<0>(lhs.base_its) == std::get<0>(rhs.base_its);\n }\n friend constexpr bool operator!=(const zip_iterator& lhs, const zip_iterator& rhs)\n {\n return !(lhs == rhs);\n }\n friend constexpr bool operator<(const zip_iterator& lhs, const zip_iterator& rhs)\n {\n return std::get<0>(lhs.base_its) < std::get<0>(rhs.base_its);\n }\n friend constexpr bool operator>(const zip_iterator& lhs, const zip_iterator& rhs)\n {\n return rhs < lhs;\n }\n friend constexpr bool operator<=(const zip_iterator& lhs, const zip_iterator& rhs)\n {\n return !(rhs < lhs);\n }\n friend constexpr bool operator>=(const zip_iterator& lhs, const zip_iterator& rhs)\n {\n return !(lhs < rhs);\n }\n private:\n std::tuple<Its...> base_its;\n };\n}\n\ntemplate <typename... Ranges>\nclass zip {\n static_assert(sizeof...(Ranges) > 0, \"Cannot zip zero ranges\");\npublic:\n using iterator = detail::zip_iterator<\n typename detail::range_traits<Ranges>::iterator...\n >;\n using value_type = typename iterator::value_type;\n using reference = typename iterator::reference;\n\n explicit constexpr zip(Ranges&&... rs)\n : ranges{std::forward<Ranges>(rs)...}\n {\n }\n constexpr iterator begin()\n {\n return std::apply([](auto&... rs) {\n return iterator(rs.begin()...);\n }, ranges);\n }\n constexpr iterator end()\n {\n return std::apply([](auto&... rs) {\n return iterator(rs.end()...);\n }, ranges);\n }\nprivate:\n std::tuple<Ranges...> ranges;\n};\n\n// by default, rvalue arguments are moved to prevent dangling references\ntemplate <typename... Ranges>\nexplicit zip(Ranges&&...) -> zip<Ranges...>;\n</code></pre>\n\n<p>Let's hope that <a href=\"https://wg21.link/P1858\" rel=\"nofollow noreferrer\">P1858 Generalized pack declaration and usage</a> gets accepted so that we can eliminate the tons of invocations of <code>std::apply</code> ...</p>\n\n<h1><code>range</code></h1>\n\n<p>Similar to <code>zip</code>, <code>range</code> operates on a tuple basis — the parameters are passed as template arguments, and <code>tuple_size</code> is provided. This would limit the usefulness of it, because runtime ranges (e.g., <code>range(vector.size())</code>) are not possible.</p>\n\n<p>You choose to make <code>range</code> its own iterator type, which is not without <a href=\"https://en.cppreference.com/w/cpp/filesystem/directory_iterator/begin\" rel=\"nofollow noreferrer\">precedent</a> in the standard library. However, this will cause confusion once you add more functionality to <code>range</code>.</p>\n\n<p>A more sophisticated comparison operator that treats sentinel (end) values specially takes the sign of <code>step</code> into account allows for commutative comparison and negative steps.</p>\n\n<p>So the end result may look like this: (concept verification, overflow checking, etc. are omitted for simplicity)</p>\n\n<pre><code>namespace detail {\n template <typename T>\n class range_iterator {\n T value{0};\n T step{1};\n bool sentinel{false};\n public:\n // lying again\n using iterator_category = std::forward_iterator_tag;\n using difference_type = std::intmax_t;\n using value_type = T;\n using reference = T;\n using pointer = T*;\n\n constexpr range_iterator() = default;\n // sentinel\n explicit constexpr range_iterator(T v)\n : value{v}, sentinel{true}\n {\n }\n explicit constexpr range_iterator(T v, T s)\n : value{v}, step{s}\n {\n }\n\n constexpr reference operator*() const\n {\n return value;\n }\n constexpr range_iterator& operator++()\n {\n value += step;\n return *this;\n }\n constexpr range_iterator operator++(int)\n {\n auto copy{*this};\n ++*this;\n return copy;\n }\n friend constexpr bool operator==(const range_iterator& lhs, const range_iterator& rhs)\n {\n if (lhs.sentinel && rhs.sentinel) {\n return true;\n } else if (lhs.sentinel) {\n return rhs == lhs;\n } else if (lhs.step > 0) {\n return lhs.value >= rhs.value;\n } else if (lhs.step < 0) {\n return lhs.value <= rhs.value;\n } else {\n return lhs.value == rhs.value;\n }\n // C++20: return (lhs.value <=> rhs.value) == (step <=> 0); from third branch\n }\n friend constexpr bool operator!=(const range_iterator& lhs, const range_iterator& rhs)\n {\n return !(lhs == rhs);\n }\n };\n}\n\ntemplate <typename T>\nclass range {\n T first{0};\n T last{};\n T step{1};\npublic:\n using value_type = T;\n using iterator = detail::range_iterator<T>;\n\n explicit constexpr range(T e)\n : last{e}\n {\n }\n explicit constexpr range(T b, T e, T s = T{1})\n : first{b}, last{e}, step{s}\n {\n }\n constexpr iterator begin() const\n {\n return iterator{first, step};\n }\n constexpr iterator end() const\n {\n return iterator{last};\n }\n constexpr T size() const\n {\n return (last - first) / step;\n }\n};\n</code></pre>\n\n<p>You may also consider implementing <code>enumerate</code> based on <a href=\"https://docs.python.org/3.8/library/functions.html?highlight=enumerate#enumerate\" rel=\"nofollow noreferrer\">Python's</a>, which comes in handy when accessing sequences by index:</p>\n\n<pre><code>// again, rvalue arguments are copied by default\ntemplate <typename Sequence>\nauto enumerate(Sequence&& seq)\n{\n using std::begin, std::end;\n return zip(range(end(seq) - begin(seq)), std::forward<Sequence>(seq));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T20:33:32.313",
"Id": "469661",
"Score": "0",
"body": "Thank you very much @L. F. Your answer is a little bit out of my league for several reasons so I'm going to need some time to digest it, but I'm glad I have new material to learn!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T01:39:41.790",
"Id": "469680",
"Score": "0",
"body": "@mqtthiqs OK, I've finished `ranges`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-17T07:48:35.567",
"Id": "505534",
"Score": "0",
"body": "Almost one year after I finally get back around to this. Thanks again @L. F. for this enlightening review, I learned a lot."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T14:33:49.957",
"Id": "239443",
"ParentId": "239437",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239443",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T11:57:36.223",
"Id": "239437",
"Score": "5",
"Tags": [
"c++",
"template",
"iterator",
"c++17",
"variadic"
],
"Title": "`zip` operator to iterate on multiple container in a sign"
}
|
239437
|
<p>I made this encryption program in Python.</p>
<p>I don't have much experience (or any experience at all) about encryption (since I just gave my 9th grade finals), but I had this idea about an algorithm some time back which would enable the user to encrypt words following an algorithm where the program would follow this process for each letter of the entered word; pseudocode:</p>
<pre class="lang-none prettyprint-override"><code>Let the variable x be the position of the alphabet in the list of alphabets sorted alphabetically
Let the variable y be the position of the alphabet in the entered word
For example, if the user enters 'abcd', the program would find x and y for a, b, c and d one by one
Then, it would find the variable z = 26-x+y and z would be the position of the alphabet in the code
in the list of alphabets
In abcd : for a - x = 1, y = 1, so, z = 26-1+1 = 26, so coded alphabet = 26th alphabet = z
Similarly, all of a,b,c and d will have coded alphabets as 'z'
So, 'abcd' will be coded as 'zzzz'
</code></pre>
<p>Here's the Python code:</p>
<pre><code>alphabets =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
# Defining all sorts of functions
def position(tofind,source):
size = len(source)
for i in range(0,size,1):
if (source[i] == tofind):
p = i + 1
break
return p
def encrypt(a):
output = []
sizea = len(a)
for i in range(0,sizea,1):
x = i+1
y = position(a[i],alphabets)
z = 26-x+y
if (z>26):
z = z % 26
element = alphabets[z-1]
output.append(element)
return output
def converttolist(text):
size = len(text)
l = []
for i in range(0,size,1):
l.append(text[i])
return l
# The main program
print ()
print ("NOTE : Please enter all the alphabets in lowercase...")
print ()
given = str(input("Please enter the word to be coded : "))
givenlist = converttolist(given)
outputlist = encrypt(givenlist)
print ()
print ("The code for ",given," is :-")
outputlistlength = len(outputlist)
for i in range(0,outputlistlength,1):
print (outputlist[i],end = "")
</code></pre>
<p>Let me know what you think about it.</p>
|
[] |
[
{
"body": "<h2>A warning</h2>\n\n<p>As a toy this is fine, but please do not use it (or encourage others to use it) for real cryptographic application. It is fun as an exercise, but will not be sufficiently strong to protect you against certain common attacks.</p>\n\n<h2>Strings as sequences</h2>\n\n<p>In Python, a string is a sequence of one-character strings. So you don't need to represent it as a list of strings, because for your purposes that's what a string already is:</p>\n\n<pre><code>alphabets = 'abcdefghijklmnopqrstuvwxyz'\n</code></pre>\n\n<p>That said, you can replace the entire thing with <a href=\"https://docs.python.org/3/library/string.html#string.ascii_lowercase\" rel=\"nofollow noreferrer\"><code>string.ascii_lowercase</code></a>:</p>\n\n<pre><code>from string import ascii_lowercase\nalphabets = ascii_lowercase\n</code></pre>\n\n<h2>Position</h2>\n\n<p>This whole function can be replaced with:</p>\n\n<pre><code>source.index(to_find)\n</code></pre>\n\n<h2>Parens</h2>\n\n<p>We aren't in C/Java, so this:</p>\n\n<pre><code>if (z>26):\n</code></pre>\n\n<p>does not need parentheses.</p>\n\n<h2>Magic numbers</h2>\n\n<p>Do not hard-code 26 here:</p>\n\n<pre><code>z = z % 26\n</code></pre>\n\n<p>Instead, use <code>len(alphabets)</code>. Also, use in-place modulus:</p>\n\n<pre><code>z %= len(alphabets)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:54:18.657",
"Id": "469642",
"Score": "1",
"body": "Thank you for the accept, but it might be a little hasty! I suggest that you wait for a day or so to see what other advice you get."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:55:49.957",
"Id": "469643",
"Score": "0",
"body": "Thanks a lot, a query though, the point that you made 'don't hard-code 26' was for flexibility, right? Because if I upgrade the program someday to include more characters such as periods or commas, then I won't have to change the number 26 every time. Got it, thanks again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:08:01.790",
"Id": "469647",
"Score": "2",
"body": "That's right. Generally, avoiding magic number is more maintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:13:03.123",
"Id": "469648",
"Score": "0",
"body": "Okay, thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:01:46.117",
"Id": "469784",
"Score": "0",
"body": "Why do you recommend in-place operators?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:07:20.650",
"Id": "469786",
"Score": "1",
"body": "It's shorter and simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T19:13:52.933",
"Id": "469809",
"Score": "0",
"body": "@Rajdeep_Sindhu I prefer `len(alphabets)` instead of hardcoded `26` because it's more readable. You know where the value is coming from, what its purpose is, what's going through the programmer's head. The reader doesn't have to work out themselves how `26` was generated. Even if you KNOW that you will never upgrade the program, avoid hardcoding magic numbers."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:49:10.323",
"Id": "239454",
"ParentId": "239442",
"Score": "6"
}
},
{
"body": "<p>I think it's a nice project. I would say that the main things for you to work on is getting further acquainted with Python's standard library and with standard practices, which is what most of my advice will be surrounding.</p>\n\n<h1>Minor improvements</h1>\n\n<p>For your alphabet, you could use <code>ascii_lowercase</code> from string, i.e.: </p>\n\n<pre><code>from string import ascii_lowercase\nalphabet = [character for character in ascii_lowercase]\n</code></pre>\n\n<hr>\n\n<p>Unless I'm misreading, your function <code>position()</code> looks like an attempt at recreating <code>list.index(value)</code> (or in your case <code>source.index(tofind)</code>).</p>\n\n<hr>\n\n<p>\"Unneeded\" variables can sometimes make sense if they improve readability, but your function:</p>\n\n<pre><code>def converttolist(text):\n size = len(text)\n l = []\n for i in range(0,size,1):\n l.append(text[i])\n return l\n</code></pre>\n\n<p>would be just as readable if written as:</p>\n\n<pre><code>def converttolist(text):\n l = []\n for i in range(0,len(text),1):\n l.append(text[i])\n return l\n</code></pre>\n\n<p>and while we're on that particular function, I would strongly recommend having a look at list comprehension---it's both faster and cleaner. Your function would then become:</p>\n\n<pre><code>def convert_to_list(text: str) -> list:\n return [text[i] for i in range(len(txt)]\n</code></pre>\n\n<p>but I should add that, for cases like this, even better is to just use in-line built-ins like <code>str.split()</code> or <code>[character for character in text]</code>.</p>\n\n<hr>\n\n<p>You don't need to write <code>str(input(<whatever>))</code> since <code>input</code> <a href=\"https://docs.python.org/3/library/functions.html#input\" rel=\"noreferrer\">already returns a string</a>.</p>\n\n<hr>\n\n<p>The function <code>range()</code> defaults to step-size 1, so writing <code>range(start, end, 1)</code> is unnecessary.</p>\n\n<hr>\n\n<p>I would also recommend using a <code>main</code> function for your main loop. You could move all of the stuff in the bottom into a <code>if __name__ == \"__main__\":</code>, which also would allow you to load in this python script into other programs.</p>\n\n<h2>Naming</h2>\n\n<p>Remember that <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"noreferrer\">Readability counts</a>. The standard in python is to use <code>snake_case</code> for variable names, but more importantly ensure that your names make the variables' purpose clear; avoid names like <code>x</code> and <code>sizea</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:54:03.327",
"Id": "239455",
"ParentId": "239442",
"Score": "7"
}
},
{
"body": "<p>Going to run through this code making edits and explain as I go:</p>\n\n<ol>\n<li><p>You only ever use <code>position</code> to find the position within the <code>alphabet</code>; I think it'd be clearer to just make this function's purpose more specific and call it something like <code>index_in_alphabet</code>.</p></li>\n<li><p>Having narrowed and defined the purpose of this function, it can be implemented much more simply by subtracting the character values:</p></li>\n</ol>\n\n<pre><code>def index_in_alphabet(letter: str) -> int:\n \"\"\"Converts a lowercase letter to an index from 1-26.\"\"\"\n return 1 + ord(letter) - ord('a')\n</code></pre>\n\n<ol start=\"3\">\n<li><p>We probably also want it to raise an exception instead of returning an out-of-bounds value if <code>letter</code> isn't a lowercase letter. <code>assert</code> is an easy way to do that.</p></li>\n<li><p>Similarly to how I used <code>ord</code> to replace <code>alphabets</code> for finding the index, you can use <code>chr</code> to replace it for generating the character from the index:</p></li>\n</ol>\n\n<pre><code> element = chr(ord('a') + z - 1) # instead of alphabet[z-1]\n</code></pre>\n\n<ol start=\"5\">\n<li>Your entire <code>converttolist</code> function can be replaced with just:</li>\n</ol>\n\n<pre><code>def converttolist(text: str) -> List[str]:\n return list(text)\n</code></pre>\n\n<p>which of course in turn means that instead of <code>converttolist()</code> you can just use <code>list()</code>.</p>\n\n<ol start=\"6\">\n<li><p>Instead of making the caller convert the input to and from a list, you could just do it inside the function (so you accept a string and return a string). In fact, you don't need to convert anything to a list in the first place, because you can already index a string the same way you index a list!</p></li>\n<li><p>Use <code>if __name__ == '__main__':</code> to indicate which part of your module is the \"main program\". This is the standard convention for Python and it has a practical purpose: if something else imports your module, whatever you put inside that <code>if</code> block won't get executed at import time (which is good).</p></li>\n<li><p>The comment <code>defining all sorts of functions</code> isn't very helpful to the reader; a better use of comments is to explain what each function does!</p></li>\n<li><p>Going to just kinda proofread some of the formatting here -- there are odd spaces and unnecessarily parentheses in some spots.</p></li>\n<li><p>Eliminate unneeded variables!</p></li>\n</ol>\n\n<p>Here's the code I ended up with:</p>\n\n<pre><code>def index_in_alphabet(letter: str) -> int:\n \"\"\"Converts a lowercase letter to an index from 1-26.\"\"\"\n index = 1 + ord(letter) - ord('a') \n assert 1 <= index <= 26\n return index\n\ndef encrypt(a: str) -> str:\n \"\"\"Returns the encrypted version of the input string.\"\"\"\n output = \"\"\n for i in range(len(a)):\n x = i + 1\n y = index_in_alphabet(a[i])\n z = 26 - x + y\n if z > 26:\n z %= 26\n output += chr(z - 1 + ord('a'))\n return output\n\nif __name__ == '__main__':\n print()\n print(\"NOTE : Please enter all the alphabets in lowercase...\")\n print()\n given = str(input(\"Please enter the word to be coded: \"))\n print()\n print(\"The code for\", given, \"is:\", encrypt(given))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:55:58.093",
"Id": "469653",
"Score": "0",
"body": "Thanks, so, I basically gotta make my code shorter and more efficient, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T19:36:55.700",
"Id": "469657",
"Score": "6",
"body": "Efficiency is also important, but most of my changes are about making the code easier to read, which is hugely valuable in the real world. The easier it is to read and understand your code, the easier it is to identify bugs, or to add new features to it. The best way to get better at writing code that's easy to read is to ask for reviews from other people, exactly like you did!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T20:11:22.487",
"Id": "469660",
"Score": "0",
"body": "Thanks, I'm grateful to you for helping me :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:38:12.780",
"Id": "469757",
"Score": "3",
"body": "I think the alphabet version is better since it's more flexible. Once the encryption goes beyond [a-z] your suggestion is harder to update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:26:47.600",
"Id": "469778",
"Score": "1",
"body": "Maybe! I feel like they teach you in school to make everything as \"flexible\" as possible, and for a long time I approached coding that way, but it's not necessarily always the right approach. I decided several years ago to fully embrace the principle of YAGNI and have no regrets. It's always easier to start simple and add complexity when needed than to start complex in the hope you'll have less work to do later."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:53:10.310",
"Id": "239462",
"ParentId": "239442",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "239462",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T13:53:21.697",
"Id": "239442",
"Score": "12",
"Tags": [
"python",
"beginner",
"algorithm"
],
"Title": "A simple encryption program using Python"
}
|
239442
|
<p>I'm developing a <a href="https://github.com/Stranger6667/jsonschema-rs" rel="nofollow noreferrer">Rust library</a> that implements JSONSchema validation (Drafts 7 fully works at the moment). I have Rust-specific questions and concerns about my implementation.</p>
<p>It works by compiling the input schema first and validating the data after it:</p>
<pre><code>use jsonschema::{JSONSchema, Draft};
use serde_json::json;
let schema = json!({"maxLength": 5});
let instance = json!("foo");
let compiled = JSONSchema::compile(&schema, Some(Draft::Draft7));
let result = compiled.validate(&instance);
</code></pre>
<p><strong>Main points</strong>:</p>
<ul>
<li>Input schema is parsed into a tree of structs that implement a common trait -
<code>Validate</code> that provides <code>validate</code> method (<a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/keywords/mod.rs#L40" rel="nofollow noreferrer">code</a>);</li>
<li>Each struct in this tree have different members that may refer to the original schema (e.g. holding a vector of strings for "required" keyword) or have some computed values, e.g. regex (<a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/keywords/properties.rs#L8" rel="nofollow noreferrer">example</a>);</li>
<li>During validation, the input value is passed to this tree and it is validated by specific nodes (<a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/validator.rs#L42" rel="nofollow noreferrer">code</a>);</li>
<li><code>validate</code> returns <code>Result<(), ValidationError></code>, where the error case contains data needed for displaying errors. This data is copied from schema or instance or constructed dynamically <a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/keywords/property_names.rs#L28" rel="nofollow noreferrer">somewhere</a> in the tree;</li>
<li>When resolving a reference, a <code>Cow</code> is <a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/resolver.rs#L50" rel="nofollow noreferrer">returned</a>. <code>Borrowed</code> for cases when the referenced document exists in <code>instance</code> and <code>Owned</code> when it is loaded from a remote location (e.g. <code>{"$ref": "http://localhost/schema.json"}</code>);</li>
<li>A new validation <a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/keywords/ref_.rs#L27" rel="nofollow noreferrer">tree</a> is generated for resolved schemas and validation goes further with this new tree;</li>
</ul>
<p><strong>My concerns</strong>:</p>
<ol>
<li><code>Validate</code> trait. Is it a good approach to build a validation tree? What are the alternatives for such a case?</li>
<li>Is it possible to avoid copying to <code>ValidationError</code> and use references when possible? In some cases, objects are generated / loaded from a remote location, during validation and have different lifetime than schema or instance. In this case, probably the data should be owned - is it possible to have <code>ValidationError</code> working for both cases?</li>
</ol>
<p><strong>Code</strong></p>
<p>Trait (<a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/keywords/mod.rs#L40" rel="nofollow noreferrer">actual code</a>):</p>
<pre><code>pub trait Validate<'a>: Send + Sync + 'a {
fn validate(&self, schema: &JSONSchema, instance: &Value) -> ValidationResult;
fn name(&self) -> String;
}
impl<'a> Debug for dyn Validate<'a> + Send + Sync + 'a {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
f.write_str(&self.name())
}
}
pub type ValidationResult = Result<(), error::ValidationError>;
pub type CompilationResult<'a> = Result<BoxedValidator<'a>, error::CompilationError>;
pub type BoxedValidator<'a> = Box<dyn Validate<'a> + Send + Sync + 'a>;
pub type Validators<'a> = Vec<BoxedValidator<'a>>;
</code></pre>
<p><code>ValidationError</code> (<a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/error.rs#L24" rel="nofollow noreferrer">actual code</a>):</p>
<pre><code>#[derive(Debug)]
pub struct ValidationError {
kind: ValidationErrorKind,
}
#[derive(Debug)]
pub enum ValidationErrorKind {
FalseSchema(Value),
// ...
}
</code></pre>
<p>Validation node example (<a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/src/keywords/properties.rs#L8" rel="nofollow noreferrer">actual code</a>):</p>
<pre><code>pub struct PropertiesValidator<'a> {
properties: Vec<(&'a String, Validators<'a>)>,
}
impl<'a> PropertiesValidator<'a> {
pub(crate) fn compile(
schema: &'a Value,
context: &CompilationContext,
) -> CompilationResult<'a> {
match schema {
Value::Object(map) => {
let mut properties = Vec::with_capacity(map.len());
for (key, subschema) in map {
properties.push((key, compile_validators(subschema, context)?));
}
Ok(Box::new(PropertiesValidator { properties }))
}
_ => Err(CompilationError::SchemaError),
}
}
}
impl<'a> Validate<'a> for PropertiesValidator<'a> {
fn validate(&self, schema: &JSONSchema, instance: &Value) -> ValidationResult {
if let Value::Object(item) = instance {
for (name, validators) in self.properties.iter() {
if let Some(item) = item.get(*name) {
for validator in validators {
validator.validate(schema, item)?
}
}
}
}
Ok(())
}
// ...
}
</code></pre>
<p><a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=30e02dbd1d2354c127d9f3cbba2b99f3" rel="nofollow noreferrer">Playground</a> for a smaller version;</p>
<p><a href="https://github.com/Stranger6667/jsonschema-rs/blob/master/Cargo.toml" rel="nofollow noreferrer">Dependencies</a></p>
<p><strong>Rust version</strong>: 1.42.0</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:02:19.140",
"Id": "239444",
"Score": "2",
"Tags": [
"rust",
"library"
],
"Title": "JSONSchema validation implementation in Rust"
}
|
239444
|
<p>I was working on a code challenge with the following description:</p>
<blockquote>
<p>Given an array of positive or negative integers</p>
<p><code>I= [i1,..,in]</code></p>
<p>you have to produce a sorted array P of the form</p>
<p><code>[ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...]</code></p>
<p>Example: <code>I = [12, 15]; //result = [[2, 12], [3, 27], [5, 15]]</code></p>
</blockquote>
<p>So I created an algorithm that does exactly that, but I have some performance issues. On the code challenge website (Codewars), my algorithm times out for fairly large integers, <code>173471</code> being a specific example.</p>
<p>One issue I am aware of with the algorithm and want to improve is that my current method for generating primes simply takes the largest number in the input array, and generates primes up to that number, but rarely do I need that many primes. I have not found a full proof way of creating the full list of possible primes otherwise, however. A second issue is that I have a loop running within my loop, to check which numbers in the input have factors in the list of primes I generated. If I could somehow reduce it to one loop, that would reduce the complexity.</p>
<p>Anyway all of that aside, here is my algorithm:</p>
<pre><code>// Function that returns a collection of primes up to a given number
const sieveOfEratosthenes = (int) => {
// Initialize some values
const primes = [...Array(int + 1).keys()].slice(2);
const sqrtCeil = Math.sqrt(int);
let p = primes[0];
let pIndex = 0;
let factor = 2;
// Until index refers to the last element, sieve primes
while (primes[pIndex] < sqrtCeil) {
const productIndex = primes.indexOf(factor * p);
if (productIndex > -1) {
primes.splice(productIndex, 1);
}
factor += 1;
if (factor * p > primes[primes.length - 1]) {
factor = 2;
pIndex += 1;
p = primes[pIndex];
}
}
return primes;
};
function sumOfDivided(lst) {
// If the input is empty, return an empty list
if (lst.length === 0) {
return [];
}
// Generate primes with a ceiling of the highest number in the input,
// accounting for negative numbers
const primes = sieveOfEratosthenes(
Math.max(...lst.map((int) => (int < 0 ? int * -1 : int)))
);
// Reduce primes array to array of tuples, value one being being the prime,
// value two being the sum of numbers it was a prime factor for in the input
return primes.reduce((acc, prime) => {
// Initialize values
let sum = 0;
let primeFactorCount = 0;
// Check if each integer in the input had this prime as a factor
for (let int of lst) {
if (prime > int && int > 0) {
continue;
}
if (int % prime === 0) {
sum += int;
primeFactorCount += 1;
}
}
// If at least one number matched, add the tuple to the array
if (primeFactorCount > 0) {
return [...acc, [prime, sum]];
}
return acc;
}, []);
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T19:47:44.613",
"Id": "469659",
"Score": "0",
"body": "Running your example the slowness is caused by your sieve implementation, which does indeed look a bit funny to me and is far slower than it is supposed to be. I would imagine, though JS does do some clever tricks so it's hard to say, that it's due to primes.splice(productIndex, 1). I would suggest finding a more typical implementation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:43:21.860",
"Id": "469668",
"Score": "0",
"body": "I think you are probably right, the array manipulation seems to ruin the performance."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:40:16.183",
"Id": "239447",
"Score": "1",
"Tags": [
"javascript",
"performance",
"primes"
],
"Title": "\"Sum by factors\" algorithm improvement"
}
|
239447
|
<h1>Introduction</h1>
<p>I am developing a dynamical system simulation/animation framework, which
provides three abstract base classes, <code>DynamicalSystem</code>, <code>Visualisation</code> and
<code>Animation</code>, from which clients can derive concrete classes for the purposes of
animating dynamical (physical) systems in 3D (and 2D).</p>
<p>The <code>DynamicalSystem</code> abstract class strips away all unnecessary details from a
real physical system. In essence it blueprints a representation of the ordinary
differential equation system for the physical system. It has two member
variables: a <code>dimension_</code> and a <code>state_</code> vector. The pure virtual function
<code>stateDerivative(...)</code> is to be overridden in the derived class whose duty it is
to provide all the <em>physical</em> detail necessary to model the dynamical system.</p>
<p>The <code>Visualisation</code> abstract base class blueprints the interface for a graphical
visualisation of the physical system (using OpenGL, typically). It has member
variables representing a rendering target, and near and far clip plane distances
(absolute values). The pure virtual functions <code>display(...)</code> and <code>step(...)</code> are to
be overridden in the derived class whose duty it is to provide all the <em>geometric</em>
detail necessary to model the dynamical system.</p>
<p>The Animation base class blueprints the interface for an animation. It contains
pointers to abstract base classes <code>DynamicalSystem</code> and <code>Visualisation</code>, and a pointer to a <code>GraphicsWindow</code> object (I have written
a <code>GraphicsWindow</code> class providing a thin veneer over SDL2. Code available on my GitHub -- link below.). It contains pure
virtual functions <code>handleKeys(...)</code> and <code>handleMouse(...)</code> which the deriving class
overrides to process user (window) events. It handles the deallocation
(destruction) of the objects pointed to by the <code>DynamicalSystem</code>, <code>Visualisation</code> and <code>GraphicsWindow</code> base class pointers much like a smart triple pointer.</p>
<p>The code for these classes is provided below, as well as a concrete
implementation for a simple molecular dynamics animation for example and completeness. The complete code with build instructions can be found at
my GitHub
<a href="https://github.com/Richard-Mace/MolecularDynamics" rel="nofollow noreferrer"><a href="https://github.com/Richard-Mace/MolecularDynamics" rel="nofollow noreferrer">https://github.com/Richard-Mace/MolecularDynamics</a></a>.</p>
<p>Since this is perhaps my first attempt at "medium scale" object-oriented design,
I would appreciate comments and suggestions for improvements. In particular, I
know that the (derived?) animation object should be a singleton to avoid multiple
instances. To my mind, the (abstract) base class Animation should <em>ensure this
behaviour</em> by being a singleton itself. However, I cannot see an elegant way to
achieve this through inheritance, and I would appreciate your opinions on how or
whether this could be achieved, and whether it is worth it in terms of effort
and potential code "uglification". (I know that singletons are a contentious
issue. I am asking out of curiosity and to learn.)</p>
<p>The code is fairly long and, as already mentioned, can be downloaded from my GitHub at the
link above (build instructions provided there). Below I have provided the code for the abstract base classes, then below that the code for an example molecular dynamics animation using these
classes. I include the latter as an example of intended usage, for completeness. A full review would be an onerous task, but I would appreciate comments on the design of the base classes
and how they might be improved.</p>
<p>Thank you in advance for your time.</p>
<h1>Example main function</h1>
<p>main.cpp</p>
<pre><code>#include "GraphicsWindow.h"
#include "MoleculeSystem.h"
#include "MoleculeVisualisation.h"
#include "MoleculeAnimation.h"
int main() {
MoleculeSystem::Extents extents {-20.0, 20.0, -20.0, 20.0, -20.0, 20.0};
MoleculeSystem::LoadType loadType {MoleculeSystem::LoadType::SOLID};
GraphicsWindow::Type windowType {GraphicsWindow::Type::FULLSCREEN};
MoleculeAnimation molecules(100, extents, loadType, windowType);
molecules.run();
return 0;
}
</code></pre>
<h1>Abstract base classes (framework)</h1>
<h2>Animation</h2>
<p>Animation.h </p>
<pre><code>#ifndef ANIMATION_H
#define ANIMATION_H
#include "DynamicalSystem.h"
#include "Visualisation.h"
class Animation {
public:
Animation(DynamicalSystem*, Visualisation*, GraphicsWindow*);
virtual ~Animation();
void setInitialTime(double);
double getInitialTime() const;
virtual void step(double, double);
virtual void run();
virtual bool handleKeys(const GraphicsWindow::Event&) = 0;
virtual bool handleMouse(const GraphicsWindow::Event&) = 0;
protected:
DynamicalSystem* ptrSystem_;
Visualisation* ptrVisualisation_;
GraphicsWindow* ptrWindow_;
double timeInitial_;
};
#endif /* ANIMATION_H */
</code></pre>
<p>Animation.cpp</p>
<pre><code>#include "Animation.h"
#include <chrono>
#include <iostream>
Animation::Animation(DynamicalSystem* system, Visualisation* visualiser,
GraphicsWindow* window)
: ptrSystem_(system)
, ptrVisualisation_(visualiser)
, ptrWindow_(window)
, timeInitial_(0.0) {
// empty
}
// ~Animation:
//
// Destructor for the Animation class.
//
// NOTE: The Animation object is responsible for the DELETION of the
// GraphicsWindow object, the Visualisation object and the DynamicalSystem
// object. In effect is behaves like a smart triple pointer!
//
Animation::~Animation() {
delete ptrWindow_;
delete ptrVisualisation_;
delete ptrSystem_;
}
/*
* setInitialTime
*
* Sets the initial time, t_0, for the animation.
*
*/
void Animation::setInitialTime(double time) {
timeInitial_ = time;
}
/*
* getInitialTime()
*
* Returns the initial time, t_0.
*
*/
double Animation::getInitialTime() const {
return timeInitial_;
}
// step()
//
// The main sequence of calls in run(). Can be overridden in derived classes
// to provide additional functionality.
void Animation::step(double t1, double t2) {
ptrVisualisation_->display(ptrSystem_);
ptrSystem_->step(t1, t2);
ptrVisualisation_->step(t1, t2);
}
/*
* run()
*
* The main Animation loop.
*
* Will return if the user closes the window, or if either handleKeys() or
* handleMouse() returns false.
*
*/
void Animation::run() {
std::chrono::time_point<std::chrono::steady_clock> timeNow;
std::chrono::time_point<std::chrono::steady_clock> timeStart;
timeStart = timeNow = std::chrono::steady_clock::now();
double timeLast = timeInitial_;
while (true) {
GraphicsWindow::Event event;
while (ptrWindow_->pollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return; // exit run loop
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
if (!handleKeys(event)) { // return false to exit run loop
return;
}
break;
case SDL_MOUSEMOTION:
if (!handleMouse(event)) { // return false to exit run loop
return;
}
break;
default:
break;
}
}
std::chrono::duration<double> elapsed_seconds = timeNow - timeStart;
double time = elapsed_seconds.count() + timeInitial_;
step(timeLast, time);
timeLast = time;
timeNow = std::chrono::steady_clock::now();
}
}
</code></pre>
<h2>Visualisation</h2>
<p>Visualisation.h</p>
<pre><code> #ifndef VISUALISATION_H
#define VISUALISATION_H
#include "GraphicsWindow.h"
#include "DynamicalSystem.h"
class Visualisation {
public:
Visualisation(GraphicsWindow*, double, double);
virtual ~Visualisation();
virtual void display(const DynamicalSystem*) const = 0;
virtual void step(double, double) = 0;
virtual void setRenderTarget(GraphicsWindow*);
virtual GraphicsWindow* getRenderTarget() const;
protected:
GraphicsWindow* ptrRenderTarget_;
double nearClip_;
double farClip_;
// utility function
bool init_opengl();
};
#endif /* VISUALISATION_H */
</code></pre>
<p>Visualisation.cpp</p>
<pre><code>#include "Visualisation.h"
#include <GL/glu.h>
#include <iostream>
#include <stdexcept>
Visualisation::Visualisation(GraphicsWindow* ptrRenderTarget, double nearClip,
double farClip)
: ptrRenderTarget_(ptrRenderTarget)
, nearClip_(nearClip)
, farClip_(farClip) {
if (ptrRenderTarget_ != nullptr) {
bool status = init_opengl();
if (status == false) {
throw std::runtime_error{"Visualisation: could not initialise OpenGL"};
}
}
}
Visualisation::~Visualisation() {
ptrRenderTarget_ = nullptr;
nearClip_ = farClip_ = 0.0;
}
GraphicsWindow* Visualisation::getRenderTarget() const {
return ptrRenderTarget_;
}
void Visualisation::setRenderTarget(GraphicsWindow* ptrRenderTarget) {
if (ptrRenderTarget != nullptr) {
ptrRenderTarget_ = ptrRenderTarget;
bool status = init_opengl();
if (status == false) {
throw std::runtime_error{"setRenderTarget: could not initialise OpenGL!\n"};
}
}
}
///////////////////////////////////////////////////////////////////////////////
// protected member functions //
///////////////////////////////////////////////////////////////////////////////
bool Visualisation::init_opengl() {
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glViewport(0, 0, static_cast<GLsizei>(ptrRenderTarget_->widthPixels()),
static_cast<GLsizei>(ptrRenderTarget_->heightPixels()));
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,
static_cast<GLfloat>(ptrRenderTarget_->widthPixels()) /
static_cast<GLfloat>(ptrRenderTarget_->heightPixels()),
static_cast<GLfloat>(nearClip_),
static_cast<GLfloat>(farClip_));
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glEnable(GL_LIGHTING);
return true;
}
</code></pre>
<h2>DynamicalSystem</h2>
<p>DynamicalSystem.h</p>
<pre><code>#ifndef DYNAMICALSYSTEM_H
#define DYNAMICALSYSTEM_H
#include <cstddef>
#include <vector>
class DynamicalSystem {
public:
explicit DynamicalSystem(std::size_t);
virtual ~DynamicalSystem() = default;
std::size_t getDimension() const;
const double* getStatePtr() const;
virtual std::vector<double>
stateDerivative(double, std::vector<double>&) = 0;
virtual void step(double, double);
void setAccuracy(double);
double getAccuracy() const;
protected:
static constexpr double kDefaultAccuracyGoal_ = 1.0e-8; // integration
// accuracy goal
std::size_t dimension_; // dimension (deg. of freedom) of system
std::vector<double> state_; // state vector (q_1,..,q_n,p_1,..,p_n)
double stepper_accuracy_; // integration accuracy
// helper functions for system ODE integration
void RungeKuttaCashKarp(double t, double deltat,
const std::vector<double>& currDerivative,
std::vector<double>& newState,
std::vector<double>& stateError);
void RungeKuttaQualityControlled(double t,
double deltaTry,
double epsAcc,
const std::vector<double>& stateDerivative,
const std::vector<double>& stateScale,
double& deltaDid,
double& deltaNext);
void ODEIntegrate(double t1, double t2, double accuracy);
};
#endif /* DYNAMICALSYSTEM_H */
</code></pre>
<p>DynamicalSystem.cpp</p>
<pre><code>#include "DynamicalSystem.h"
#include <iostream>
#include <cmath>
// Constructor
//
DynamicalSystem::DynamicalSystem(std::size_t dimension)
: dimension_(dimension)
, stepper_accuracy_(kDefaultAccuracyGoal_) {
state_.resize(2 * dimension_);
}
// Return the dimension of the dynamical system.
//
// The dimension is equivalent to the number of degrees of freedom of the
// system. The order of the ordinary differential equation system corresponding
// to a DynamicalSystem is 2 * dimension.
//
std::size_t DynamicalSystem::getDimension() const {
return dimension_;
}
// Return a read-only pointer to the beginning of the system state vector.
const double* DynamicalSystem::getStatePtr() const {
return state_.data();
}
// Integrate the system differential equations from time t1 to time t2.
void DynamicalSystem::step(double t1, double t2) {
ODEIntegrate(t1, t2, stepper_accuracy_);
}
// Set integration accuracy.
void DynamicalSystem::setAccuracy(double accuracy) {
stepper_accuracy_ = accuracy;
}
// Get integration accuracy.
double DynamicalSystem::getAccuracy() const {
return stepper_accuracy_;
}
///////////////////////////////////////////////////////////////////////////////
// private helper/utility member functions //
///////////////////////////////////////////////////////////////////////////////
// RungeKuttaCashKarp:
//
// Given a vector currDerivative containing the time derivative of the system
// state vector (state_) at time t, executes a low-level Runge-Kutta-Cash-Karp
// step that reads the current member state_ (vector) of the dynamical system
// at time t and returns in the vector argument newState the new state of the
// system at time t + deltat. The member variable state_ is NOT changed. An
// estimate for the error in the solution is returned in argument stateError.
//
// This function uses the pure virtual member function stateDerivative(), which
// must be overriden in the derived class. The function
// std::vector<double> stateDerivative(double t, std::vector<double>& state)
// must return the time derivative at time t of an ARBITRARY given state vector,
// state (at time t). The stateDerivative function effectively defines the
// first order ordinary differential equation system governing the dynamics of
// the dynamical system (derived from abstract base class DynamicalSystem) being
// modelled.
//
// REFERENCE: Numerical Recipes in C, p. 713.
//
void DynamicalSystem::RungeKuttaCashKarp(
double t,
double deltat,
const std::vector<double>& currDerivative,
std::vector<double>& newState,
std::vector<double>& stateError) {
const double A2 = 0.2, A3 = 0.3, A4 = 0.6, A5 = 1.0,
A6 = 0.875, B21 = 0.2, B31 = 3.0 / 40.0,
B32 = 9.0 / 40.0, B41 = 0.3, B42 = -0.9,
B43 = 1.2, B51 = -11.0 / 54.0, B52 = 2.5,
B53 = -70.0 / 27.0, B54 = 35.0 / 27.0,
B61 = 1631.0 / 55296.0, B62 = 175.0 / 512.0,
B63 = 575.0 / 13824.0, B64 = 44275.0 / 110592.0,
B65 = 253.0 / 4096.0,
C1 = 37.0 / 378.0, C3 = 250.0 / 621.0,
C4 = 125.0 / 594.0, C6 = 512.0 / 1771.0,
DC1 = C1 - 2825.0 / 27648.0,
DC3 = C3 - 18575.0 / 48384.0,
DC4 = C4 - 13525.0 / 55296.0,
DC5 = -277.0 / 14336.0, DC6 = C6 - 0.25;
std::size_t order = 2 * dimension_;
// First step. We already have the derivs in currDerivative, so needn't
// call stateDerivative here...
std::vector<double> tempState(order);
for (std::size_t i = 0; i < order; ++i) {
tempState[i] = state_[i] + B21 * deltat * currDerivative[i];
}
// Second step
std::vector<double> ak2 = stateDerivative(t + A2 * deltat, tempState);
for (std::size_t i = 0; i < order; ++i) {
tempState[i] = state_[i] + deltat * (B31 * currDerivative[i]
+ B32 * ak2[i]);
}
// Third step
std::vector<double> ak3 = stateDerivative(t + A3 * deltat, tempState);
for (std::size_t i = 0; i < order; ++i) {
tempState[i] = state_[i] + deltat * (B41 * currDerivative[i]
+ B42 * ak2[i] + B43 * ak3[i]);
}
// Fourth step
std::vector<double> ak4 = stateDerivative(t + A4 * deltat, tempState);
for (std::size_t i = 0; i < order; ++i) {
tempState[i] = state_[i] + deltat * (B51 * currDerivative[i]
+ B52 * ak2[i] + B53 * ak3[i] + B54 * ak4[i]);
}
// Fifth step
std::vector<double> ak5 = stateDerivative(t + A5 * deltat, tempState);
for (std::size_t i = 0; i < order; ++i) {
tempState[i] = state_[i] + deltat * (B61 * currDerivative[i]
+ B62 * ak2[i] + B63 * ak3[i] + B64 * ak4[i] + B65 * ak5[i]);
}
// Evaluate the new state
std::vector<double> ak6 = stateDerivative(t + A6 * deltat, tempState);
for (std::size_t i = 0; i < order; ++i) {
newState[i] = state_[i] + deltat * (C1 * currDerivative[i] + C3 * ak3[i]
+ C4 * ak4[i] + C6 * ak6[i]);
}
// The error is estimated as the difference between the
// fourth and fifth order Runge-Kutta methods
for (std::size_t i = 0; i < order; ++i) {
stateError[i] = deltat * (DC1 * currDerivative[i] + DC3 * ak3[i]
+ DC4 * ak4[i] + DC5 * ak5[i] + DC6 * ak6[i]);
}
}
// Quality controlled Runge-Kutta-Cash-Karp step.
//
// Used by ODEIntegrate to integrate the ODE system defined in virtual member
// function stateDerivative(...) from time t to t + Delta, where Delta is
// determined by accuracy and convergence conditions. The actual value of Delta
// used is returned in variable deltaDid, and a guess for Delta to be used in
// the next integration step is returned in deltaNext.
//
// This function updates the member variable state_, representing the current
// system state vector.
void DynamicalSystem::RungeKuttaQualityControlled(
double t,
double deltaTry,
double epsAcc,
const std::vector<double>& stateDerivative,
const std::vector<double>& stateScale,
double& deltaDid,
double& deltaNext) {
const double k_safety = 0.9;
const double k_pow_grow = -0.2;
const double k_pow_shrink = -0.25;
const double k_error_cond = 1.89e-4;
std::size_t order = 2 * dimension_;
std::vector<double> stateError(order);
std::vector<double> newState(order);
double delta = deltaTry;
double errorMax = 0.0;
do {
RungeKuttaCashKarp(t, delta, stateDerivative, newState, stateError);
// Evaluate the error
errorMax = 0.0;
for (std::size_t i = 0; i < order; ++i) {
errorMax = std::max(errorMax, fabs(stateError[i] / stateScale[i]));
}
errorMax /= epsAcc;
if (errorMax > 1.0) {
double deltaTemp = k_safety * delta * pow(errorMax, k_pow_shrink);
delta = copysign(std::max(fabs(deltaTemp), 0.1 * fabs(delta)), delta);
if (t + delta == t) {
std::cerr <<"RungeKuttaQualityControlled: stepsize underflow!"
<< '\n';
}
}
} while (errorMax > 1.0);
// We have a solution of the required accuracy. Set next stepsize.
if (errorMax > k_error_cond) {
deltaNext = k_safety * delta * pow(errorMax, k_pow_grow);
}
else {
deltaNext = 0.5 * delta;
}
// Transfer the new state vector to the member state_.
deltaDid = delta;
for (std::size_t i = 0; i < order; ++i) {
state_[i] = newState[i];
}
}
// High-level adaptive ode integrator. Integrates the ODE system defined in
// virtual member function stateDerivative(...) from time t1 to time t2, where
// usually t2 > t1. The member variable state_ representing the current system
// state vector is updated by this function (through calls to
// RungeKuttaQualityControlled(...)).
void DynamicalSystem::ODEIntegrate(double t1, double t2, double accuracy) {
const double k_tiny = 1.0e-30;
std::size_t order = 2 * dimension_;
double delta = 0.1;
double t = t1;
double deltaDid;
double deltaNext;
std::vector<double> stateDot(order);
std::vector<double> stateScale(order);
do {
stateDot = stateDerivative(t, state_);
for (std::size_t i = 0; i < order; ++i) {
stateScale[i] = fabs(state_[i]) + fabs(delta * stateDot[i]) + k_tiny;
}
RungeKuttaQualityControlled(t, delta, accuracy, stateDot, stateScale,
deltaDid, deltaNext);
t += deltaDid;
delta = deltaNext;
// make sure we don't overshoot
if (t + delta > t2) {
delta = t2 - t;
}
} while (t < t2);
}
</code></pre>
<h1>Derived concrete classes (molecular dynamics example)</h1>
<h2>MoleculeAnimation</h2>
<p>MoleculeAnimation.h</p>
<pre><code>#ifndef MOLECULEANIMATION_H
#define MOLECULEANIMATION_H
#include "Animation.h"
#include "MoleculeSystem.h"
#include "MoleculeVisualisation.h"
class MoleculeAnimation : public Animation {
public:
MoleculeAnimation(std::size_t, const MoleculeSystem::Extents&,
MoleculeSystem::LoadType, GraphicsWindow::Type);
~MoleculeAnimation();
virtual bool handleKeys(const GraphicsWindow::Event&) override;
virtual bool handleMouse(const GraphicsWindow::Event&) override;
// Clients of MoleculeSystem
void expand();
void contract();
void heat();
void cool();
void toggleGravity();
// Clients of MoleculeVisualisation
void toggleCameraMotion();
void toggleCameraDirection();
void toggleCameraZoom();
void changeColour();
private:
static const std::size_t kDoF_ = 3;
static const std::size_t kDefaultWidth_ = 1920;
static const std::size_t kDefaultHeight_ = 1080;
static constexpr double kDefaultNearClip_ = 1.0;
static constexpr double kDefaultFarClip_ = 200.0;
static constexpr double kDefaultAccuracyGoal_ = 5.0e-5;
};
#endif /* MOLECULEANIMATION_H */
</code></pre>
<p>MoleculeAnimation.cpp</p>
<pre><code>#include "MoleculeAnimation.h"
#include <iostream>
#include <stdexcept>
/*
* MoleculeAnimation:
*
* Constructor for the MoleculeAnimation class.
*
* NOTE: the deallocation of the MoleculeSystem, MoleculeVisualisation and
* GraphicsWindow objects dynamically allocated here is handled (smartly)
* by the Animation class destructor.
*/
MoleculeAnimation::MoleculeAnimation(std::size_t numMolecules,
const MoleculeSystem::Extents& extents,
MoleculeSystem::LoadType loadType,
GraphicsWindow::Type windowType)
: Animation(new MoleculeSystem(numMolecules, kDoF_, extents, loadType),
nullptr,
new GraphicsWindow) {
if (!ptrWindow_->isInitialised()) {
throw std::runtime_error{"MoleculeAnimation: could not init window"};
}
ptrWindow_->setTitle("Molecular Dynamics Animation");
bool success = true;
if (windowType == GraphicsWindow::Type::WINDOWED) {
success = ptrWindow_->open(kDefaultWidth_, kDefaultHeight_);
}
else {
success = ptrWindow_->open();
}
if (!success) {
throw std::runtime_error{"MoleculeAnimation: could not open window"};
}
ptrSystem_->setAccuracy(kDefaultAccuracyGoal_);
// Create a molecule visualisation for the system. This must be done
// only after a GraphicsWindow has been successfully opened.
ptrVisualisation_ = new MoleculeVisualisation(ptrWindow_, kDefaultNearClip_,
kDefaultFarClip_);
}
MoleculeAnimation::~MoleculeAnimation() {
std::cout << "MoleculeAnimation: Destructor." << '\n';
}
/*
* handleKeys:
*
* The keyboard event processing handler.
*
*/
bool MoleculeAnimation::handleKeys(const GraphicsWindow::Event& event) {
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_ESCAPE:
return false;
break;
case SDLK_UP:
heat();
break;
case SDLK_DOWN:
cool();
break;
case SDLK_LEFT:
contract();
break;
case SDLK_RIGHT:
expand();
break;
case SDLK_g:
toggleGravity();
break;
case SDLK_p:
toggleCameraMotion();
break;
case SDLK_z:
toggleCameraZoom();
break;
case SDLK_r:
toggleCameraDirection();
break;
case SDLK_c:
changeColour();
break;
default:
break;
}
}
return true;
}
/*
* handleMouse:
*
* The mouse event processing handler. Presently not used.
*
*/
bool MoleculeAnimation::handleMouse(const GraphicsWindow::Event& event) {
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Molecule System (physical) effects //
///////////////////////////////////////////////////////////////////////////////
/*
* expand()
*
* Expand the system container (indefinitely) without volume checks.
*
*/
void MoleculeAnimation::expand() {
MoleculeSystem::Extents extents =
dynamic_cast<MoleculeSystem*>(ptrSystem_)->getExtents();
double speed = 0.1;
extents.xmin -= speed * MoleculeVisualisation::kMoleculeRadius_;
extents.xmax += speed * MoleculeVisualisation::kMoleculeRadius_;
extents.ymin -= speed * MoleculeVisualisation::kMoleculeRadius_;
extents.ymax += speed * MoleculeVisualisation::kMoleculeRadius_;
extents.zmin -= speed * MoleculeVisualisation::kMoleculeRadius_;
extents.zmax += speed * MoleculeVisualisation::kMoleculeRadius_;
dynamic_cast<MoleculeSystem*>(ptrSystem_)->setExtents(extents);
}
/*
* contract()
*
* Contract the system container until the volume equals the number of molecules
* times the volume of a cube with side length equal to the molecule diameter.
*
* TODO: Small volumes create stress on the integration routines, whose accuracy
* has been minimised for speed. Think about how better to deal with low volumes
* and high energy density. Perhaps limit the contraction by keeping track of
* total energy.
*/
void MoleculeAnimation::contract() {
MoleculeSystem* ptrMolySys = dynamic_cast<MoleculeSystem*>(ptrSystem_);
MoleculeSystem::Extents extents = ptrMolySys->getExtents();
double volume = (extents.xmax - extents.xmin)
* (extents.ymax - extents.ymin)
* (extents.zmax - extents.zmin);
double r = MoleculeVisualisation::kMoleculeRadius_;
double num = static_cast<double>(ptrMolySys->getNumber());
// Minimum volume corresponds to each molecule confined to a cube
// of side length equal to 2 * r.
double volume_min = 8.0 * r * r * r * num;
// Don't allow unlimited squashing.
if (volume <= volume_min) {
return;
}
double speed = -0.1;
extents.xmin -= speed * MoleculeVisualisation::kMoleculeRadius_;
extents.xmax += speed * MoleculeVisualisation::kMoleculeRadius_;
extents.ymin -= speed * MoleculeVisualisation::kMoleculeRadius_;
extents.ymax += speed * MoleculeVisualisation::kMoleculeRadius_;
extents.zmin -= speed * MoleculeVisualisation::kMoleculeRadius_;
extents.zmax += speed * MoleculeVisualisation::kMoleculeRadius_;
ptrMolySys->setExtents(extents);
}
/*
* toggleGravity()
*
* Alternatively turn on and turn off the gravitational field of an external
* (planetary, say) system.
*/
void MoleculeAnimation::toggleGravity() {
MoleculeSystem* ptrMolySys = dynamic_cast<MoleculeSystem*>(ptrSystem_);
if (ptrMolySys->getGravitationalAcceleration() == 0.0) {
ptrMolySys->setGravitationalAcceleration(0.01);
}
else {
ptrMolySys->setGravitationalAcceleration(0.0);
}
}
/*
* heat()
*
* Simulate the effects of heating the molecule system, simply by scaling
* the velocity of each molecule by a pre-determined factor.
*
* This is a bit artificial and should be replaced by a process in which each
* molecule's velocity is perturbed by an amount determined by deviates from a
* 3D Gaussian distribution with a given temperature.
*/
void MoleculeAnimation::heat() {
dynamic_cast<MoleculeSystem*>(ptrSystem_)->scaleVelocities(1.05);
}
/*
* cool()
*
* Simulate the effects of cooling the molecule system, simply by scaling
* the velocity of each molecule by a pre-determined factor. See comments for
* member function heat().
*/
void MoleculeAnimation::cool() {
dynamic_cast<MoleculeSystem*>(ptrSystem_)->scaleVelocities(0.95);
}
///////////////////////////////////////////////////////////////////////////////
// Visualisation effects //
///////////////////////////////////////////////////////////////////////////////
/*
* toggleCameraMotion:
*
* Alternatively stop or start the camera orbit.
*/
void MoleculeAnimation::toggleCameraMotion() {
dynamic_cast<MoleculeVisualisation*>(ptrVisualisation_)->toggleCameraMotion();
}
/*
* toggleCameraDirection()
*
* Reverses the direction of motion of the camera in its orbit.
*
*/
void MoleculeAnimation::toggleCameraDirection() {
dynamic_cast<MoleculeVisualisation*>(ptrVisualisation_)->toggleCameraDirection();
}
/*
* toggleCameraZoom()
*
* Alternatively zooms in and out of the scene.
*
*/
void MoleculeAnimation::toggleCameraZoom() {
dynamic_cast<MoleculeVisualisation*>(ptrVisualisation_)->toggleCameraZoom();
}
/*
* changeColour()
*
* Cycles through a stack of pre-set materials (colours).
*
*/
void MoleculeAnimation::changeColour() {
MoleculeVisualisation *ptrMolyVis =
dynamic_cast<MoleculeVisualisation*>(ptrVisualisation_);
std::size_t num = ptrMolyVis->getNumMaterials();
std::size_t currIndex = ptrMolyVis->getMaterialIndex();
std::size_t newIndex = (currIndex + 1) % num;
ptrMolyVis->setMaterialIndex(newIndex);
}
</code></pre>
<h2>MoleculeVisualisation</h2>
<p>MoleculeVisualisation.h</p>
<pre><code>#ifndef MOLECULEVISUALISATION_H
#define MOLECULEVISUALISATION_H
#include "GraphicsWindow.h"
#include "Visualisation.h"
#include "MoleculeSystem.h"
class MoleculeVisualisation : public Visualisation {
public:
struct Light {
GLfloat ambient_[4];
GLfloat diffuse_[4];
GLfloat specular_[4];
GLfloat position_[4];
};
struct Material {
GLfloat ambient_[4];
GLfloat diffuse_[4];
GLfloat specular_[4];
GLfloat shininess_;
};
MoleculeVisualisation(GraphicsWindow*, double, double);
virtual ~MoleculeVisualisation() override;
void setFocalPoint(double, double, double);
void getFocalPoint(double*, double*, double*) const;
void setAmbientLight(GLfloat, GLfloat, GLfloat);
void addLight(const Light&);
void setMaterialIndex(std::size_t);
std::size_t getMaterialIndex() const;
std::size_t getNumMaterials() const;
virtual void display(const DynamicalSystem*) const override;
virtual void step(double, double) override;
void toggleCameraMotion();
void toggleCameraZoom();
void toggleCameraDirection();
static constexpr double kMoleculeRadius_ = 0.5; // Radius -- don't change.
private:
static const int kSphereSegments_ = 20; // For sphere tessellation.
static const int kNumLines_ = 60; // For the surface plane.
static constexpr double kZoomFactor_ = 0.3; // Simulates camera zoom.
bool cameraPaused_;
double cameraDirection_;
double cameraZoomFactor_;
double cameraPosition_[3];
double focalPoint_[3];
std::vector<Material> materials_;
std::size_t materialIndex_;
unsigned int numLights_;
// utility functions
void draw_box(const MoleculeSystem::Extents&) const;
void orbit_camera(double, double);
void init_material_buffer();
};
#endif /* MOLECULEVISUALISATION_H */
</code></pre>
<p>MoleculeVisualisation.cpp</p>
<pre><code>#include "GraphicsWindow.h"
#include "MoleculeVisualisation.h"
#include <iostream>
#include <GL/gl.h>
#include <GL/glu.h>
MoleculeVisualisation::MoleculeVisualisation(GraphicsWindow* ptrRenderTarget,
double nearClip, double farClip)
: Visualisation(ptrRenderTarget, nearClip, farClip)
, cameraPaused_(false)
, cameraDirection_(1.0)
, cameraZoomFactor_(1.0)
, cameraPosition_{0.0, 18.0, 75.0}
, focalPoint_{0.0, 0.0, 0.0}
, materialIndex_(0)
, numLights_(0) {
setAmbientLight(0.4f, 0.4f, 0.4f);
Light default_light { {0.5f, 0.5f, 0.5f, 1.0f},
{0.6f, 0.6f, 0.6f, 1.0f},
{0.6f, 0.6f, 0.6f, 1.0f},
{0.0f, 40.0f, 20.0f, 1.0f} };
addLight(default_light);
Light second_light { {0.5f, 0.5f, 0.5f, 1.0f},
{0.6f, 0.6f, 0.6f, 1.0f},
{0.6f, 0.6f, 0.6f, 1.0f},
{0.0f, 40.0f, -20.0f, 1.0f} };
addLight(second_light);
init_material_buffer();
}
MoleculeVisualisation::~MoleculeVisualisation() {
numLights_ = 0;
std::cout << "MoleculeVisualisation: Destructor." << '\n';
}
void MoleculeVisualisation::setFocalPoint(double x, double y, double z) {
focalPoint_[0] = x;
focalPoint_[1] = y;
focalPoint_[2] = z;
}
void MoleculeVisualisation::getFocalPoint(double* x, double* y,
double* z) const {
*x = focalPoint_[0];
*y = focalPoint_[1];
*z = focalPoint_[2];
}
void MoleculeVisualisation::setAmbientLight(GLfloat r, GLfloat g, GLfloat b) {
GLfloat ambient[] = {r, g, b, 1.0f};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambient);
}
void MoleculeVisualisation::addLight(const Light& light) {
bool fail = false;
unsigned int flag = 0;
switch (numLights_) {
case 0:
flag = GL_LIGHT0;
break;
case 1:
flag = GL_LIGHT1;
break;
case 2:
flag = GL_LIGHT2;
break;
case 3:
flag = GL_LIGHT3;
break;
case 4:
flag = GL_LIGHT4;
break;
case 5:
flag = GL_LIGHT5;
break;
case 6:
flag = GL_LIGHT6;
break;
case 7:
flag = GL_LIGHT7;
break;
default:
std::cerr <<"MoleculeVisualisation: Cannot add light. Too many lights"
<< std::endl;
fail = true;
break;
}
if (!fail) {
glLightfv(flag, GL_AMBIENT, light.ambient_);
glLightfv(flag, GL_DIFFUSE, light.diffuse_);
glLightfv(flag, GL_SPECULAR, light.specular_);
glLightfv(flag, GL_POSITION, light.position_);
glEnable(flag);
++numLights_;
}
}
void MoleculeVisualisation::setMaterialIndex(std::size_t index) {
if (index <= materials_.size()) {
materialIndex_ = index;
}
}
std::size_t MoleculeVisualisation::getMaterialIndex() const {
return materialIndex_;
}
std::size_t MoleculeVisualisation::getNumMaterials() const {
return materials_.size();
}
void MoleculeVisualisation::display(const DynamicalSystem* ptrSystem) const {
// Clear (fill) the frame and depth (z-) buffers.
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Follow a molecule for fun. A bit jiggly. Experiment with it.
//const double* ptrState = ptrSystem->getStatePtr();
//setFocalPoint(ptrState[0], ptrState[1], ptrState[2]);
// Set up eye (coordinate system) transformations.
gluLookAt(cameraPosition_[0], cameraPosition_[1], cameraPosition_[2],
focalPoint_[0], focalPoint_[1], focalPoint_[2], 0.0, 1.0, 0.0);
// Draw the confining box.
MoleculeSystem::Extents extents =
dynamic_cast<const MoleculeSystem*>(ptrSystem)->getExtents();
draw_box(extents);
// Set the material properties for all molecules.
glMaterialfv(GL_FRONT, GL_SPECULAR, materials_[materialIndex_].specular_);
glMaterialfv(GL_FRONT, GL_AMBIENT, materials_[materialIndex_].ambient_);
glMaterialfv(GL_FRONT, GL_DIFFUSE, materials_[materialIndex_].diffuse_);
glMaterialf(GL_FRONT, GL_SHININESS, materials_[materialIndex_].shininess_);
const double* ptrMolecule = ptrSystem->getStatePtr();
const size_t degreesOfFreedom =
dynamic_cast<const MoleculeSystem*>(ptrSystem)->getDegreesOfFreedom();
GLUquadric* ptr_sphere = gluNewQuadric();
const size_t numMolecules =
dynamic_cast<const MoleculeSystem*>(ptrSystem)->getNumber();
for (size_t i = 0; i < numMolecules; ++i) {
GLfloat x = static_cast<GLfloat>(ptrMolecule[0]);
GLfloat y = static_cast<GLfloat>(ptrMolecule[1]);
GLfloat z = static_cast<GLfloat>(ptrMolecule[2]);
// Position and draw molecule.
glPushMatrix();
glTranslatef(y, z, x);
gluSphere(ptr_sphere, kMoleculeRadius_, kSphereSegments_,
kSphereSegments_);
glPopMatrix();
ptrMolecule += degreesOfFreedom;
}
gluDeleteQuadric(ptr_sphere);
// Swap backbuffer with frontbuffer.
ptrRenderTarget_->swapBuffers();
}
void MoleculeVisualisation::step(double t1, double t2) {
orbit_camera(t1, t2);
}
void MoleculeVisualisation::toggleCameraMotion() {
cameraPaused_ = !cameraPaused_;
}
void MoleculeVisualisation::toggleCameraZoom() {
if (cameraZoomFactor_ == 1.0) {
cameraZoomFactor_ = kZoomFactor_;
}
else {
cameraZoomFactor_ = 1.0;
}
}
void MoleculeVisualisation::toggleCameraDirection() {
if (cameraDirection_ == 1.0) {
cameraDirection_ = -1.0;
}
else {
cameraDirection_ = 1.0;
}
}
///////////////////////////////////////////////////////////////////////////////
// private utility functions //
///////////////////////////////////////////////////////////////////////////////
void MoleculeVisualisation::draw_box(
const MoleculeSystem::Extents& extents) const {
GLfloat spec1[] = {0.9f, 0.9f, 0.9f, 1.0f};
GLfloat amb1[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat diff1[] = {1.0f, 1.0f, 1.0f, 1.0f};
GLfloat shin1[] = {32.0f};
glMaterialfv(GL_FRONT, GL_SPECULAR, spec1);
glMaterialfv(GL_FRONT, GL_SHININESS, shin1);
glMaterialfv(GL_FRONT, GL_AMBIENT, amb1);
glMaterialfv(GL_FRONT, GL_DIFFUSE, diff1);
// Account for the finite size of the "point" molecules
GLfloat xmin = static_cast<GLfloat>(extents.xmin) - kMoleculeRadius_;
GLfloat xmax = static_cast<GLfloat>(extents.xmax) + kMoleculeRadius_;
GLfloat ymin = static_cast<GLfloat>(extents.ymin) - kMoleculeRadius_;
GLfloat ymax = static_cast<GLfloat>(extents.ymax) + kMoleculeRadius_;
GLfloat zmin = static_cast<GLfloat>(extents.zmin) - kMoleculeRadius_;
GLfloat zmax = static_cast<GLfloat>(extents.zmax) + kMoleculeRadius_;
glBegin(GL_LINES);
glVertex3f(xmin, ymin, zmin);
glVertex3f(xmax, ymin, zmin);
glVertex3f(xmax, ymin, zmin);
glVertex3f(xmax, ymax, zmin);
glVertex3f(xmax, ymax, zmin);
glVertex3f(xmin, ymax, zmin);
glVertex3f(xmin, ymax, zmin);
glVertex3f(xmin, ymin, zmin);
glVertex3f(xmin, ymin, zmax);
glVertex3f(xmax, ymin, zmax);
glVertex3f(xmax, ymin, zmax);
glVertex3f(xmax, ymax, zmax);
glVertex3f(xmax, ymax, zmax);
glVertex3f(xmin, ymax, zmax);
glVertex3f(xmin, ymax, zmax);
glVertex3f(xmin, ymin, zmax);
glVertex3f(xmin, ymin, zmin);
glVertex3f(xmin, ymin, zmax);
glVertex3f(xmax, ymin, zmin);
glVertex3f(xmax, ymin, zmax);
glVertex3f(xmax, ymax, zmin);
glVertex3f(xmax, ymax, zmax);
glVertex3f(xmin, ymax, zmin);
glVertex3f(xmin, ymax, zmax);
// draw floor
GLfloat deltax = 20.5f / 4.0f;
GLfloat deltay = 20.5f / 4.0f;
GLfloat col_green[] {0.0f, 0.25f, 0.0f, 1.0f};
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, col_green);
for (int i = 0; i < kNumLines_; ++i) {
glVertex3f(i * deltax, zmin - 0.1f, -kNumLines_ * deltay);
glVertex3f(i * deltax, zmin - 0.1f, kNumLines_ * deltay);
glVertex3f(-kNumLines_ * deltax, zmin - 0.1f, i * deltay);
glVertex3f(kNumLines_ * deltax, zmin - 0.1f, i * deltay);
}
for (int i = 1; i < kNumLines_; ++i) {
glVertex3f(-i * deltax, zmin - 0.1f, -kNumLines_ * deltay);
glVertex3f(-i * deltax, zmin - 0.1f, kNumLines_ * deltay);
glVertex3f(-kNumLines_ * deltax, zmin - 0.1f, -i * deltay);
glVertex3f(kNumLines_ * deltax, zmin - 0.1f, -i * deltay);
}
glEnd();
}
void MoleculeVisualisation::orbit_camera(double t1, double t2) {
const double k_cam_max_r = 50.0;
const double k_cam_min_r = 30.0;
const double k_cam_max_z = 30.0;
const double k_slow = 0.5;
static double cam_time = 0.0;
double delta_t;
if (cameraPaused_) {
delta_t = 0.0;
}
else {
delta_t = t2 - t1;
}
if (cameraDirection_ == -1.0) {
delta_t *= -1.0;
}
cam_time += delta_t;
double r = k_cam_max_r + (k_cam_max_r - k_cam_min_r) *
cos(0.1 * cam_time * k_slow);
cameraPosition_[0] = cameraZoomFactor_ * r * cos(0.6 * cam_time * k_slow);
cameraPosition_[2] = cameraZoomFactor_ * r * sin(0.3 * cam_time * k_slow);
cameraPosition_[1] = cameraZoomFactor_ * k_cam_max_z *
(sin(0.5 * cam_time * k_slow) + 1.02);
}
/*
* init_material_buffer:
*
* Defines a few pre-set materials for the user to cycle through, if desired.
*
*/
void MoleculeVisualisation::init_material_buffer() {
Material def_mat { {0.5f, 0.1995f, 0.0745f, 1.0f},
{0.75164f, 0.60648f, 0.22648f, 1.0f},
{0.9f, 0.9f, 0.9f, 1.0f},
32.0f };
materials_.push_back(def_mat);
Material emerald { {0.0215f, 0.1745f, 0.0215f, 1.0f},
{0.07568f, 0.61424f, 0.07568f, 1.0f},
{0.633f, 0.727811f, 0.633f, 1.0f},
76.8f };
materials_.push_back(emerald);
Material obsidian { {0.05375f, 0.05f, 0.06625f, 1.0f},
{0.18275f, 0.17f, 0.22525f, 1.0f},
{0.332741f, 0.328634f, 0.346435f, 1.0f},
38.4f };
materials_.push_back(obsidian);
Material ruby { {0.1745f, 0.01175f, 0.01175f, 1.0f},
{0.61424f, 0.04136f, 0.04136f, 1.0f},
{0.727811f, 0.626959f, 0.626959f, 1.0f},
76.8f };
materials_.push_back(ruby);
Material chrome { { 0.25f, 0.25f, 0.25f, 1.0f},
{0.4f, 0.4f, 0.4f, 1.0f},
{0.774597f, 0.774597f, 0.774597f, 1.0f},
76.8f };
materials_.push_back(chrome);
Material cyan_plastic{ {0.0f, 0.1f, 0.06f, 1.0f},
{0.0f, 0.50980392f, 0.50980392f, 1.0f},
{0.50196078f, 0.50196078f, 0.50196078f, 1.0f},
32.0f };
materials_.push_back(cyan_plastic);
Material copper { {0.19125f, 0.0735f, 0.0225f, 1.0f},
{0.7038f, 0.27048f, 0.0828f, 1.0f},
{0.25677f, 0.137622f, 0.086014f, 1.0f},
12.8f };
materials_.push_back(copper);
}
</code></pre>
<h2>MoleculeSystem</h2>
<p>MoleculeSystem.h</p>
<pre><code>#ifndef MOLECULESYSTEM_H
#define MOLECULESYSTEM_H
#include "DynamicalSystem.h"
class MoleculeSystem : public DynamicalSystem {
public:
struct Extents {
double xmin;
double xmax;
double ymin;
double ymax;
double zmin;
double zmax;
};
enum class LoadType {SOLID, LIQUID, GAS};
MoleculeSystem(std::size_t, std::size_t, const Extents&, LoadType);
~MoleculeSystem();
virtual std::vector<double>
stateDerivative(double, std::vector<double>&) override;
void step(double t1, double t2) override;
void setGravitationalAcceleration(double);
double getGravitationalAcceleration() const;
std::size_t getNumber() const;
std::size_t getDegreesOfFreedom() const;
Extents getExtents() const;
void setExtents(const MoleculeSystem::Extents&);
void scaleVelocities(double factor);
private:
static constexpr double kKineticMax_ = 10.0;
static constexpr double kCoordinationNumber_ = 2.0;
static constexpr double kKToverEpsilonGas_ = 2.0;
static constexpr double kKToverEpsilonLiquid_ = 0.8;
static constexpr double kKToverEpsilonSolid_ = 1.0e-5;
std::size_t numMolecules_; // number of molecules
std::size_t numDegreesOfFreedom_; // number of DoF per molecule
Extents extents_; // container extents in x-, y-, z-directions
double gravitationalAcceleration_; // external gravitational field g
// private helper functions
void initRandom(double);
void initLatticeHCP(double);
void applyBoundaryConditions();
};
#endif /* MOLECULESYSTEM_H */
</code></pre>
<p>MoleculeSystem.cpp (see GitHub)</p>
|
[] |
[
{
"body": "<h2>Ownership</h2>\n\n<p>This:</p>\n\n<pre><code>// NOTE: The Animation object is responsible for the DELETION of the \n// GraphicsWindow object, the Visualisation object and the DynamicalSystem\n// object. In effect is behaves like a smart triple pointer!\n//\n\nAnimation::~Animation() {\n delete ptrWindow_;\n delete ptrVisualisation_;\n delete ptrSystem_;\n</code></pre>\n\n<p>sets off alarm bells. There are new methods for C++ to safely transfer ownership of a pointer; it used to be <code>auto_ptr</code> and now <code>unique_ptr</code> is recommended. Among other things, it will greatly simplify your destructor. Further reading: <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/memory/unique_ptr</a></p>\n\n<p>Even if you didn't use an autopointer, these:</p>\n\n<pre><code>DynamicalSystem* ptrSystem_;\nVisualisation* ptrVisualisation_;\nGraphicsWindow* ptrWindow_;\n</code></pre>\n\n<p>can be made <code>const</code> (the pointer itself does not change), i.e.</p>\n\n<pre><code>DynamicalSystem *const ptrSystem_;\nVisualisation *const ptrVisualisation_;\nGraphicsWindow *const ptrWindow_;\n</code></pre>\n\n<h2>Boolean expressions</h2>\n\n<pre><code>if (status == false) {\n</code></pre>\n\n<p>should simply be</p>\n\n<pre><code>if (!status) {\n</code></pre>\n\n<h2>Structured coordinates</h2>\n\n<p>This:</p>\n\n<pre><code>const double* ptrMolecule = ptrSystem->getStatePtr();\n// ...\n\n GLfloat x = static_cast<GLfloat>(ptrMolecule[0]);\n GLfloat y = static_cast<GLfloat>(ptrMolecule[1]);\n GLfloat z = static_cast<GLfloat>(ptrMolecule[2]); \n</code></pre>\n\n<p>seems like a misuse of unsafe pointer references. The moment that you return a pointer, you lose information about the size of the array. In this particular case, if you were to keep it as a <code>const</code> reference to a vector, you could still index into it - but the indexing would have bounds-checking safety.</p>\n\n<h2>Templating</h2>\n\n<p>You may want to consider making the degree of freedom of <code>DynamicalSystem</code> an integer template parameter. That way, children such as <code>MoleculeSystem</code> can quickly and simply declare the DOF in the inheritance clause, and you can use a simple array instead of a <code>vector</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:13:19.260",
"Id": "469717",
"Score": "0",
"body": "Thank you for your detailed review. Regarding ownership, I am aware of \nunique_ptr and RAII, but I think that my Animation constructor and Destructor\nwork, in principle, precisely as a unique_ptr. In effect, the Animation object\nis a wrapper around three base class pointers (owning resources) such that, when \nthe Animation object (the wrapper) goes out of scope, the resources are \nautomatically deleted by invoking the destructor of the type to which the enclosed pointers point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:14:04.917",
"Id": "469718",
"Score": "0",
"body": "I stand to be corrected, but (polymorphism aside) that is my understanding of \nhow unique pointers are designed and work, perhaps with a bit more \nsophistication in the case of std::unique_ptr. I agree that const should have \nbeen used. Thank you for pointing this out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:14:31.633",
"Id": "469719",
"Score": "0",
"body": "Regarding the returning of a const double* instead of const vector<double>&, I \nagree. My oversight; I shall correct this in the next version.\n\nRegarding templating and use of std::array, I think that this is a good idea. \nI shall consider the implications in the next version. Thank you once again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:33:52.180",
"Id": "239460",
"ParentId": "239448",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T16:00:29.523",
"Id": "239448",
"Score": "3",
"Tags": [
"c++",
"animation",
"physics",
"polymorphism"
],
"Title": "Dynamical system animation framework"
}
|
239448
|
<p>I have a college assignment to implement a class called sorter, whose object is a sorted vector (the user is allowed to sort it by the method he/she desires). I have been able to implement it as following. Please review it and suggest me the changes I should make to make it efficient.</p>
<pre><code>template <typename T>
class Sorter {
std::vector<T> vector;
int count(T* array) {
register int i = 0;
while (*(array + i)) {
i++;
}
i--;
return i;
}
void swap(T& t1, T& t2) {
T temp = t1;
t1 = t2;
t2 = temp;
}
void bubbleSort() {
for (int i = 0; i < vector.size(); i++) {
for (int j = 0; j < vector.size() - 1; j++) {
if (vector[j] > vector[j + 1]) {
swap(vector[j], vector[j + 1]);
}
}
}
}
std::vector<T> mergeSort(std::vector<T> vec) {
int begin = 0;
int end = vec.size() - 1;
auto combine = [=](std::vector<T> lv, std::vector<T> rv) {
std::vector<T> retVec;
int i = 0;
int j = 0;
while (i < lv.capacity() && j < rv.capacity()) {
if (lv[i] < rv[j]) {
retVec.push_back(lv[i]);
i++;
}
else {
retVec.push_back(rv[j]);
j++;
}
}
while (i < lv.capacity()) {
retVec.push_back(lv[i]);
i++;
}
while (j < rv.capacity()) {
retVec.push_back(rv[j]);
j++;
}
return retVec;
};
if (vec.size() == 1) {
return vec;
}
int mid = (begin + end) / 2;
auto it = vec.begin();
std::vector<T> left = mergeSort(std::vector<T>(it, it + mid + 1));
std::vector<T> right = mergeSort(std::vector<T>(it + mid + 1, vec.end()));
return combine(left, right);
}
void sort() {
std::cout << "Choose your option:" << "\n";
std::cout << "1. bubblesort" << "\n";
std::cout << "2. mergesort" << "\n";
int op = 2;
//std::cin >> op;
switch (op) {
case 1:
bubbleSort();
break;
case 2:
vector = mergeSort(vector);
break;
}
}
public:
Sorter() = delete;
Sorter(std::vector<T> vec) : vector(vec) {
sort();
}
Sorter(T* array) {
int num = count(array);
for (int i = 0; i < num; i++) {
this->vector.push_back(*(array + i));
}
sort();
}
std::vector<T> getSorted() {
return vector;
}
};
</code></pre>
<p>The updated version is always available at <a href="https://github.com/kesarling/cpp-projects/blob/master/algorithms.h" rel="nofollow noreferrer">this link</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T16:54:10.390",
"Id": "469637",
"Score": "2",
"body": "How much testing of this code have you done? There are several nonobivous problems with it that may be revealed by testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:22:16.140",
"Id": "469699",
"Score": "1",
"body": "I still haven't tested it with any object types, like vector or lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:07:33.620",
"Id": "470073",
"Score": "0",
"body": "I've refactored the class. And also added a `quicksort` function. Am I supposed to post it as a new question with this one linking to that (and that one linking to this) or do I update the code here itself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T20:07:55.950",
"Id": "470155",
"Score": "0",
"body": "Post your updated code in a new question (since you've already received answers to this one)."
}
] |
[
{
"body": "<p><strong>READABILITY</strong></p>\n\n<p>Function: <code>int count(T* array)</code></p>\n\n<p>I don't prefer this way of acessing a (T) <code>while(*(array+i))</code>, because of readability reasons. Better way: <code>while(array[i])</code></p>\n\n<p><strong>PERFORMANCE</strong></p>\n\n<p>Function: <code>void swap(T& t1, T& t2)</code></p>\n\n<p>Faster way is to use XOR (^) swap algorithm. it is faster and small amout of memory is used.</p>\n\n<pre><code>if (t1 != t2)\n {\n *t1 ^= *t2;\n *t2 ^= *t1;\n *t1 ^= *t2;\n }\n</code></pre>\n\n<p>and function declaration should be <code>inline void swap(T& t1, T& t2)</code></p>\n\n<p>Function: <code>std::vector<T> getSorted()</code></p>\n\n<p>Should be <code>inline std::vector<T> getSorted()</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:56:00.373",
"Id": "469644",
"Score": "5",
"body": "I wouldn't recommend an xor swap not least because it won't for lots of types and this code looks like it expects to sort a vector of any type. See https://stackoverflow.com/questions/10549155/why-swap-doesnt-use-xor-operation-in-c for more reasons."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T00:46:56.270",
"Id": "469674",
"Score": "2",
"body": "Also there are bigger problems, namely that `count` usually reads past the end of the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:11:42.333",
"Id": "469681",
"Score": "4",
"body": "The XOR algorithm is much slower and uses no less memory than the normal swap. But a bigger problem is that `swap(a, a)` will result in `a = 0`. And marking functions defined in the class has zero use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:31:09.547",
"Id": "469702",
"Score": "1",
"body": "Also, I feel, it is better to call Pointer declared arrays as *(array+i) instead of array[i]. This helps in emphasizing that the array has been declared as a pointer and allocated dynamically, instead of static allocation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:13:49.230",
"Id": "469846",
"Score": "0",
"body": "Oops, I meant \"marking functions defined in the class `inline`\" in my last comment ... Sorry"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T10:56:04.823",
"Id": "469866",
"Score": "0",
"body": "@L.F. What I usually do in such situations is, I copy the comment, delete it and paste it with corrections"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:09:13.627",
"Id": "239452",
"ParentId": "239449",
"Score": "-2"
}
},
{
"body": "<ul>\n<li><p>In the sort() function its currently hardcoded to merge sort which I assume is not intentional. However, if you do allow the user to give an input you should do some error checking. You'll currently get unexpected behaviour if the user enters anything other than 1 or 2.</p></li>\n<li><p>You should use std::swap rather than implementing your own swap function. Some types can make optimisations over what you've done.</p></li>\n<li><p>From a design point of view I would argue that c++ is not an inherently object oriented language and that bubblesort and mergesort should be free functions taking a pair of iterators, to allow them to be more easily reused. You've pretty much done this for merge sort already, it uses none of the members of the Sorter class so could just be made a free function.</p></li>\n<li><p>Your bubble sort implementation is inefficient. It should check if the vector is sorted after each pass, rather than doing the outer loops you could do <code>while(!isSorted(vector))</code> or similar.</p></li>\n<li><p>Merge sort has a very big lambda in it for combine. From a readability point of view I would pull that out into a separate function.</p></li>\n<li><p>Both mergesort and bubblesort use indices with operator[] to get the elements from the vector. The preferred way to do this in c++ is using iterators, see <a href=\"https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices\">https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices</a></p></li>\n<li><p>In <code>count()</code> register is deprecated (and strictly is removed since c++17). You should probably avoid using it to improve compatibility.</p></li>\n<li><p>I would need to think about it more, but I question if <code>while (*(array + i))</code> in count will always behave as expected. You assume that the array has an end sentinel value that will dereference to null. I don't that's guaranteed. As far as I know there is not an easy way to get the size from a c style array. The normal way to handle this is to require the user to pass in the size as well. </p></li>\n<li><p><strong>Update</strong> on capacity(). Your use of capacity() in the merge sort is not correct. You should use size() instead. size() tells you the number of elements currently in the vector whereas capacity() tells you how many elements the vector reserved space for internally. i.e. if you insert more than this number of things into the vector it will internally reserve more space and do reallocate all the elements. It's important to note that the capacity can be greater than the number of elements in the vector. In your case it works ok as the constructor with a pair of iterators initialises the capacity equal to the size. However, I don't think this is guaranteed and is complier dependant. To see the difference try the following code:</p></li>\n</ul>\n\n<pre><code> std::vector<int> v;\n std::cout << 0 << \" \" << v.size() << \" \" << v.capacity() <<\"\\n\";\n for( int i = 0; i < 10; ++i)\n {\n v.push_back(i);\n std::cout << i << \" \" << v.size() << \" \" << v.capacity() <<\"\\n\";\n }\n\n0 0 0\n0 1 1\n1 2 2\n2 3 4\n3 4 4\n4 5 8\n5 6 8\n6 7 8\n7 8 8\n8 9 16\n9 10 16\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T00:49:13.027",
"Id": "469675",
"Score": "0",
"body": "`while (*(array + i))` is definitely wrong, it assumes there's a sentinel value that can be converted to a `false`. Definitely not guaranteed, and usually doesn't even compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T00:50:17.553",
"Id": "469676",
"Score": "0",
"body": "Also the `combine` method makes unnecessary copies of its inputs, but switching to iterators will automatically handle that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T00:51:10.147",
"Id": "469677",
"Score": "0",
"body": "And `combine` checks vectors capacity instead of size"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T00:51:44.267",
"Id": "469678",
"Score": "1",
"body": "`(begin + end) / 2` risks overflow, but that's more of an edge case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T00:53:41.937",
"Id": "469679",
"Score": "0",
"body": "`for (int i = 0; i < num; i++) { this->vector.push_back(*(array + i)); }` should just use `vector.assign(array+0, array+num);`, to have only one allocation instead of many."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:08:26.267",
"Id": "469694",
"Score": "0",
"body": "@MooingDuck, I didn't understand why `(begin + end) / 2` risks overflow. Also, this was told to me some days ago by a classmate, and he told me to use something else instead (which I don't remember now)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:14:05.953",
"Id": "469695",
"Score": "0",
"body": "Regarding std::vector::capacity, and std::vector::size, I read https://stackoverflow.com/questions/6296945/size-vs-capacity-of-a-vector. I got the difference. However, when I code the example in visual studio, in the 4th answer, in fact, even with more (or less) `push_back()` calls, both size and capacity always return same number. Is this a `compiler thing` or am I not able to grasp the concept?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:18:50.140",
"Id": "469698",
"Score": "1",
"body": "@nivag, I agree with your opinion completely. However, I always wondered about point 6 you have mentioned, from like when I learned c++. I know that std::vector::begin will return me an iterator pointing to the first element and then, to point to the, umm.. lets say third element (any element in-between actually), I will have to increment the iterator that many times. This is not as simple as saying `std::vector<int> v = { 1,2,3,4,5 }; std::cout << v[3]`. So, is there any equivalent function in c++ which will return me an iterator directly pointing to nth element? If there is, how do I use it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:09:24.283",
"Id": "469715",
"Score": "1",
"body": "If you really want a particular element v[3] can be fine, but in your case you are mainly just looping through all the elements. Also vector has a random access iterator so supports e.g. `v.begin()+3` if needed. I did mean to say something about capacity but ran out of time yesterday. I'll try and add something later if no one else does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T17:11:08.353",
"Id": "469797",
"Score": "1",
"body": "@cpplover: Well, if the array has 1.5 million entries, and `begin` is 1,499,999,999, and `end` if 1,500,000,000, then `begin+end` is 2,999,999,999, but the maximum that fits in an int is 2,147,483,648, so `begin+end` will result in an unspecified number, usually -852,516,351. Then -852,516,351/2 is -426,258,175, so your code will try to access index -426,258,175 of the array. `int mid = begin/2 + end/2;` doesn't have this overflow problem."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:44:59.403",
"Id": "239453",
"ParentId": "239449",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "239453",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T16:03:27.167",
"Id": "239449",
"Score": "4",
"Tags": [
"c++",
"performance",
"object-oriented",
"template",
"vectors"
],
"Title": "What changes should I implement in my templated sorter class so that it performs efficiently?"
}
|
239449
|
<p>I've wrote a piece of code today that really make me sick about:</p>
<pre><code>if ( account.plan_id ) {
const featuresToCheck = [];
for (const vertical of Object.keys(account.account_settings.enabled_features)) {
for (const feature of Object.keys(account.account_settings.enabled_features[vertical])){
featuresToCheck.push(`${vertical}.${feature}`);
}
}
planService.filterFeatures(account.plan_id.id,featuresToCheck).then((filtered) => {
filtered.forEach((feature) => {
const [ vert , feat] = feature.split('.');
out.account_settings.enabled_features[vert][feat].is_active = false;
});
customFieldsService.getAccountCustomFields(account_id, out)
.then(function(){
return cb();
})
.fail(cb);
});
} else {
customFieldsService.getAccountCustomFields(account_id, out)
.then(function(){
return cb();
})
.fail(cb);
}
</code></pre>
<p>Which could be best practice to handle cases like this? Unfortunately I cannot transform it in async/await.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T07:10:01.693",
"Id": "469853",
"Score": "2",
"body": "Please heed [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) In particular, title your question for what the code is to accomplish. Edit into the question what will it be used for and how. Can you put a finger on what in particular you don't like about the code presented?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T15:02:45.017",
"Id": "470125",
"Score": "0",
"body": "Hi, sorry for my mistake. yes, the part i don't like at all is the repetition of the code ```customFieldsService.getAccountCustomFields``` . Thanks all for the help and clarification"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T05:59:59.840",
"Id": "470492",
"Score": "0",
"body": "Why don't you simply extract it out of the if-else? Right in front of the `.fail(cb)` on the almost last line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T20:28:57.253",
"Id": "470861",
"Score": "0",
"body": "What does this code do? Please add a description so people can easily understand what it is doing."
}
] |
[
{
"body": "<p>If the part you don't like it the repetition of calling <code>customFieldsServer.getAccountCustomFields(...)</code> in two separate places, then you can avoid that without using <code>async/await</code> like this by create a common promise variable that each branch of the if/else fills in so after the if/else progress can continue using the common promise:</p>\n\n<pre><code>let p;\nif ( account.plan_id ) {\n const featuresToCheck = [];\n for (const vertical of Object.keys(account.account_settings.enabled_features)) {\n for (const feature of Object.keys(account.account_settings.enabled_features[vertical])){\n featuresToCheck.push(`${vertical}.${feature}`);\n }\n }\n p = planService.filterFeatures(account.plan_id.id,featuresToCheck).then((filtered) => {\n filtered.forEach((feature) => {\n const [ vert , feat] = feature.split('.');\n out.account_settings.enabled_features[vert][feat].is_active = false;\n });\n });\n} else {\n p = Promise.resolve();\n}\np.then(() => {\n customFieldsService.getAccountCustomFields(account_id, out).then(function(){\n return cb();\n }).fail(cb);\n});\n</code></pre>\n\n<hr>\n\n<p>But, this would be simpler if you could use <code>async/await</code> and if your promises were standard-type promises (the <code>.fail()</code> you were using is non-standard):</p>\n\n<pre><code>try {\n if ( account.plan_id ) {\n const featuresToCheck = [];\n for (const vertical of Object.keys(account.account_settings.enabled_features)) {\n for (const feature of Object.keys(account.account_settings.enabled_features[vertical])){\n featuresToCheck.push(`${vertical}.${feature}`);\n }\n }\n let filtered = await planService.filterFeatures(account.plan_id.id,featuresToCheck);\n filtered.forEach((feature) => {\n const [ vert , feat] = feature.split('.');\n out.account_settings.enabled_features[vert][feat].is_active = false;\n });\n }\n await customFieldsService.getAccountCustomFields(account_id, out);\n cb();\n} catch(e) {\n cb(e);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T23:27:45.910",
"Id": "239474",
"ParentId": "239457",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239474",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:11:10.260",
"Id": "239457",
"Score": "-1",
"Tags": [
"javascript",
"node.js",
"promise"
],
"Title": "JavaScript promise optional chaining"
}
|
239457
|
<p>I've created the following program to assist me in some template stuff I'm working on.</p>
<p>The function <code>get_type</code> returns 0, 1, 2, 3 or <code>nullopt</code> corresponding to which <code>group</code> the argument <code>T</code> belongs to.</p>
<p>This is my first template style project, so I'm looking for any critique possible. (Note the functions are marked <code>static</code> intentionally, as this will only be used inside this particular file, and should not be visible to users.)</p>
<pre><code>namespace ae
{
namespace details
{
template <class T>
[[nodiscard]]
static inline constexpr auto is_integer() noexcept
{
return std::is_same_v<T, short>
|| std::is_same_v<T, int>
|| std::is_same_v<T, long>
|| std::is_same_v<T, long long>
|| std::is_same_v<T, unsigned short>
|| std::is_same_v<T, unsigned int>
|| std::is_same_v<T, unsigned long>
|| std::is_same_v<T, unsigned long long>;
}
template <class T>
[[nodiscard]]
static inline constexpr auto is_floating_point() noexcept
{
return std::is_same_v<T, float>
|| std::is_same_v<T, double>
|| std::is_same_v<T, long double>;
}
template <class T>
[[nodiscard]]
static inline constexpr auto is_charachter() noexcept
{
return std::is_same_v<T, char>
|| std::is_same_v<T, unsigned char>
|| std::is_same_v<T, wchar_t>;
}
template <class T>
[[nodiscard]]
static inline constexpr auto is_boolean() noexcept
{
return std::is_same_v<T, bool>;
}
// Returns 0 for integer, 1 for floating_point,
// 2 for charachter, 3 for boolean, and nullopt otherwise
template <class T>
[[nodiscard]]
static inline constexpr auto get_type() noexcept
{
if constexpr (is_integer<T>())
return std::optional<unsigned int>(0u);
else if constexpr (is_floating_point<T>())
return std::optional<unsigned int>(1u);
else if constexpr (is_charachter<T>())
return std::optional<unsigned int>(2u);
else if constexpr (is_boolean<T>())
return std::optional<unsigned int>(3u);
else return std::nullopt;
}
}
}
</code></pre>
<p>Example usage</p>
<pre><code>template <typename T>
static typename std::enable_if<ae::details::is_integer<T>(), T>::type test()
{
// Do something if T is integer
}
template <typename T>
static typename std::enable_if<ae::details::is_charachter<T>(), T>::type test()
{
// Do something if T is charachter
}
int main()
{
test<int>(); //..
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:51:07.180",
"Id": "469652",
"Score": "1",
"body": "Add a real test / use case please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T19:11:29.737",
"Id": "469656",
"Score": "1",
"body": "Added a quick example usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:48:29.080",
"Id": "469708",
"Score": "1",
"body": "The `Example usage` from your first addition leaves me none the wiser."
}
] |
[
{
"body": "<p>In <code>is_charachter</code> (which is misspelled; it should be <code>is_character</code>), you left out <code>signed char</code> (which is a distinct type from <code>char</code>). The same applies for all of the fixed width types (<code>char8_t</code>, <code>char16_t</code>, <code>char32_t</code>).</p>\n\n<p><code>get_type</code> returns some arbitrary magic number values. You could create named constants to represent the type. If you add a \"unknown_type\" value, then you wouldn't need to use <code>std::optional</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:11:15.523",
"Id": "239467",
"ParentId": "239461",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239467",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T18:45:48.633",
"Id": "239461",
"Score": "2",
"Tags": [
"c++",
"c++17",
"template-meta-programming"
],
"Title": "Group built in types to category"
}
|
239461
|
<p>below code takes data (<em>email,password,user type</em>) from <code>$_POST[]</code> and use them to search whether a user exists on the database. If yes sends a JSON object to the client and also stores cookies on the browser. </p>
<p>I have two user types and have them stored in two tables in my database.</p>
<ul>
<li>User_Table</li>
<li>Driver_Table</li>
</ul>
<p>I need to change the database tables depending on the user type because I have used common <code>SQL</code> statement for both.
For that, I have implemented <code>selection($userType)</code> in <code>credentials.php</code> </p>
<hr>
<p><strong>SQL Statement</strong></p>
<p><em><code>$sql = "SELECT * FROM $credentials->userTable WHERE email='$credentials->email'";</code></em></p>
<hr>
<p><code>./lib/database.php</code> contains the database connection details and connects to the database.</p>
<p><strong>in</strong> <strong>Log_In.php</strong></p>
<pre><code>include "./lib/user.php";
include "./lib/credentials.php";
include "./lib/database.php";
$userDetails = json_decode($_POST["m"]);
$credentials = new credentials($userDetails);
$sql = "SELECT * FROM $credentials->userTable WHERE email='$credentials->email'";
$result = $conn->query($sql);
//checking the user details
if($result->num_rows === 1) {
$details = $result->fetch_assoc();
$validate = password_verify($credentials->password,$details["userPassword"]);
if($validate === TRUE){
if($login_record === TRUE){
$user = new user($details);
$user->userType = $credentials->userType;
$user->loggedInStatus = true;
$credentials->setCookies($user);
echo json_encode($user);
$conn->close();
}
}
else {
echo "error";
$conn->close();
}
}
</code></pre>
<p><strong>In credentials.php</strong></p>
<pre><code>class credentials {
public function __construct ($credentials) {
$this->email = $credentials->email;
$this->password = $credentials->password;
$this->userType = $credentials->userType;
$this->userTable = $this->selection ($credentials->userType);
}
public function selection ($userType) {
if ($userType === 'driver') {
return "Driver_Details";
}
if ($userType === 'passenger') {
return "User_Details";
}
}
public function setCookies ($user) {
foreach ($user as $key => $value) {
setcookie($key,$value,time()+86400,"/");
}
setcookie("t",time(),time()+86400,"/");
}
}
</code></pre>
<p><strong>in user.php</strong></p>
<pre><code>class user {
public function __construct ($details) {
$this->userName = $details["name"];
$this->userLocation = $details["country"];
$this->userId = $details["User_ID"];
$this->loggedInStatus = false;
if (isset($details["driverVehicle"])) {
$this->userVehicle = $details["driverVehicle"];
}
}
}
</code></pre>
<p><strong>I need to check the type of user and change the tables to use more than one time in different php files.</strong></p>
<p>I'm looking for some expert ideas and suggestions on a better way to change the database table depending on the user type. Mostly because I need to use that on more different php files.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T23:05:39.757",
"Id": "469672",
"Score": "1",
"body": "So you need help changing the functionality of this script? ...that's not what we do here -- we review code that works exactly as required. Of course, I should also say that injecting submission variables into your query is not a secure/stable practice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T04:42:33.473",
"Id": "469691",
"Score": "1",
"body": "mickmackusa This code is working as required. I'm looking for some ideas about changing the ´´´´user table´´´´ depending on user type. Using it on many php files a good practice? How should i set submission variables to my sql?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T19:15:21.843",
"Id": "239463",
"Score": "1",
"Tags": [
"algorithm",
"php",
"api",
"database"
],
"Title": "Checking if a user exists on the database and return user in JSON format"
}
|
239463
|
<p>I wrote code that stores an AWS Organization tree in a tree data structure in Rust. From the tree, I use a slightly modified preorder traversal algorithm to print all of the accounts in the organization in a table, while keeping track of all ancestors for each account.</p>
<p>AWS Organizations are composed of a root organizational unit (OU), which can contain other OUs or accounts. OUs can contain OUs or Accounts. In tree parlance, accounts are necessarily leaf nodes, while OUs can be branches or leaves. There is no ordering defined on the tree.</p>
<p>In my code, I represent an AWS organization as a tree data structure. I want to be able to output the names and, OU membership of all accounts in the organization. Say we had the following tree:</p>
<pre><code> R
/ \
/ \
OU1 A4
/ \
/ \
OU11 A3
/ \
/ \
A1 A2
</code></pre>
<p>The algorithm would print something like:</p>
<pre><code>A4
OU1:A3
OU1:OU11:A2
OU1:OU11:A1
</code></pre>
<p>To achieve that, I use a slightly modified iterative preorder traversal, with an additional variable that I called <code>height_stack</code>. This stack keeps track of the number of children that we have left to pop in this branch. When we push a branch to the stack, we push the number of children that the branch has to the height_stack. We decrement the last element of that height stack every time we pop the stack. At the end of each iteration, we check whether the last element of the height stack is zero, in which case we pop all zero elements of the height stack.</p>
<p>Below is the code I came up with. I show both the recursive construction of the tree (<code>recursively_build_account_tree</code>) and the traversal (<code>list_accounts_per_ou</code>), as the algorithm assumes that OUs come before accounts in the children <code>Vec</code>. </p>
<p>Is there a better algorithm to do this for a tree with an unknown number of children by node? (I know there is a lot of Rusoto boilerplate, hopefully it doesn't make the code too hard to read.)</p>
<pre class="lang-rust prettyprint-override"><code>use comfy_table::{Attribute, Cell, ContentArrangement, Row, Table, TableComponent};
use rusoto_organizations::{
Account, DescribeAccountRequest, DescribeOrganizationalUnitRequest, ListChildrenRequest,
ListRootsRequest, OrganizationalUnit, Organizations, OrganizationsClient, Root,
};
use std::{thread, time};
/// In an AWS Organizations, each node of the account tree can either be an OU or an account.
#[derive(Debug)]
enum OrgNode {
Ou(OrganizationalUnit),
Account(Account),
}
/// m-ary tree to represent the AWS organization.
#[derive(Debug)]
struct OrgTree {
root: OrgNode,
children: Option<Vec<Box<OrgTree>>>,
}
impl OrgTree {
pub fn new(root: OrgNode) -> OrgTree {
OrgTree {
root: root,
children: None,
}
}
}
/// Starting from a root of the AWS Organization, we first request all of its child OUs, and then
/// all of its child accounts. This ensures that preorder traversal list all accounts that belong
/// to an OU before listing accounts that belong to nested OUs.
///
/// The `thread::sleep` in the loops are necessary to not hit AWS Organizations' API limits.
///
/// # Example
///
/// Say we had the following tree:
/// ```ascii
///
/// R
/// / \
/// / \
/// OU A
/// / | \
/// / | \
/// / | \
/// OU A1 A2
/// ```
/// Preorder traversal would print nodes in this order:
/// * R:A
/// * R:OU:A2
/// * R:OU:A1
fn recursively_build_account_tree(client: &OrganizationsClient, node: &mut OrgTree) {
match &node.root {
OrgNode::Ou(v) => {
let list_children_request = ListChildrenRequest {
parent_id: v.id.as_ref().unwrap().to_string(),
child_type: "ORGANIZATIONAL_UNIT".to_string(),
max_results: None,
next_token: None,
};
let list_children_response = client
.list_children(list_children_request)
.sync()
.unwrap()
.children
.unwrap();
if list_children_response.len() > 0 {
node.children = Some(Vec::new());
for element in list_children_response.iter() {
// Describe the OU.
let describe_org_unit_request = DescribeOrganizationalUnitRequest {
organizational_unit_id: element.id.as_ref().unwrap().to_string(),
};
let describe_org_unit_response = client
.describe_organizational_unit(describe_org_unit_request)
.sync()
.unwrap()
.organizational_unit
.unwrap();
if let Some(v) = &mut node.children {
v.push(Box::new(OrgTree::new(OrgNode::Ou(
describe_org_unit_response,
))));
thread::sleep(time::Duration::from_millis(200));
}
}
}
// Request accounts in this OU.
let list_children_request = ListChildrenRequest {
parent_id: v.id.as_ref().unwrap().to_string(),
child_type: "ACCOUNT".to_string(),
max_results: None,
next_token: None,
};
let list_children_response = client
.list_children(list_children_request)
.sync()
.unwrap()
.children
.unwrap();
if list_children_response.len() > 0 {
match &mut node.children {
Some(_) => (),
None => {
node.children = Some(Vec::new());
}
}
for element in list_children_response {
let describe_account_request = DescribeAccountRequest {
account_id: element.id.unwrap(),
};
let describe_account_response = client
.describe_account(describe_account_request)
.sync()
.unwrap()
.account
.unwrap();
node.children
.as_mut()
.unwrap()
.push(Box::new(OrgTree::new(OrgNode::Account(
describe_account_response,
))));
thread::sleep(time::Duration::from_millis(200));
}
}
// Recursively build the tree.
match &mut node.children {
Some(v) => {
for element in v {
recursively_build_account_tree(client, &mut *element);
}
}
None => (),
};
}
OrgNode::Account(_) => (),
}
}
/// Fetches all of the accounts in the AWS Organizations and outputs
/// them in a Markdown-compatible table.
pub fn list_accounts_per_ou(client: &OrganizationsClient) -> Table {
let root_request = ListRootsRequest {
max_results: None,
next_token: None,
};
let root: Root = client
.list_roots(root_request)
.sync()
.unwrap()
.roots
.unwrap()[0]
.clone();
// Coerce the root into an OU (kinda cheating).
let root_as_ou = OrganizationalUnit {
arn: root.arn,
id: root.id,
name: root.name,
};
let mut org_tree = OrgTree::new(OrgNode::Ou(root_as_ou));
// Recursively build the account tree.
match &org_tree.root {
OrgNode::Ou(_) => {
recursively_build_account_tree(&client, &mut org_tree);
}
_ => panic!(
"The root node should be an OU, no whathever it is: {:?}",
org_tree
),
}
let mut table = Table::new();
const MARKDOWN: &str = "|| |-||| ";
table.load_preset(MARKDOWN).set_header(vec![
Cell::new("Account name").add_attribute(Attribute::Bold),
Cell::new("Account ID").add_attribute(Attribute::Bold),
Cell::new("OU name").add_attribute(Attribute::Bold),
Cell::new("Email").add_attribute(Attribute::Bold),
]);
// When printin the accounts, I print the account's parent OUs' names.
// To do that, I need to keep of how deep I am in the tree struture, and
// what the parent OUs are.
//
// I use the a typical stack-based preorder traversal algorithm.
// To keep track of the OUs,, I define what I can an height stack that is vec that stores
// the degree of the node that we pop from the stack. Each time we push an OU, we push
// degree of that OU to the height stack. When we pop any node, we decrement the
// degree counter in the vec until it reaches 0, then we pop the stack. We pop
// until there are no non-zero counters.
let mut stack: Vec<&OrgTree> = Vec::new();
let mut height_stack: Vec<usize> = Vec::new();
let mut res: Vec<&OrgTree> = Vec::new();
let mut ou_prefix: Vec<String> = Vec::new();
stack.push(&org_tree);
height_stack.push(1);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
println!("{:#?}", ou_prefix);
println!("{:#?}", height_stack);
if let Some(last) = height_stack.last_mut() {
*last -= 1;
}
match &node.root {
OrgNode::Ou(ou) => {
if let Some(ref children) = node.children {
ou_prefix.push(ou.name.as_ref().unwrap().to_string());
height_stack.push(children.len());
for elem in children {
stack.push(elem);
}
}
}
OrgNode::Account(account) => {
table.add_row(Row::from(vec![
account.name.as_ref().unwrap().to_string(),
account.id.as_ref().unwrap().to_string(),
build_ou_prefix(&ou_prefix),
account.email.as_ref().unwrap().to_string(),
]));
}
}
while let Some(0) = height_stack.last() {
height_stack.pop();
ou_prefix.pop();
}
}
table
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T20:07:25.040",
"Id": "239464",
"Score": "2",
"Tags": [
"algorithm",
"tree",
"rust"
],
"Title": "Traversing a tree with two types of nodes, while keeping track of all ancestors"
}
|
239464
|
<p>What do you think about this helper class to specify UTC time? It should also support an easy way to capture current time offsets. Let's say we expose it in API like this:</p>
<pre><code>interface IApi
{
void Start(Utc at);
}
</code></pre>
<p>Now it should go as:</p>
<pre><code>api.Start(new DateTime(2021, 01, 01)) // starts on 2021-01-01 UTC
api.Start(new TimeSpan(1, 0, 0)) // starts in one hour
api.Start(2000) // starts in 2 seconds
</code></pre>
<p>Library code is:</p>
<pre><code>struct Utc
{
public static Utc Now => 0;
public static implicit operator Utc(DateTime value) => new Utc(value);
public static implicit operator Utc(DateTimeOffset value) => value.UtcDateTime;
public static implicit operator Utc(TimeSpan value) => DateTime.UtcNow + value;
public static implicit operator Utc(int value) => TimeSpan.FromMilliseconds(value);
public static implicit operator DateTime(Utc utc) => utc.Time;
public static implicit operator DateTimeOffset(Utc utc) =>
new DateTimeOffset(utc, TimeSpan.Zero);
Utc(DateTime time) => Time = DateTime.SpecifyKind(time, DateTimeKind.Utc);
DateTime Time { get; }
}
</code></pre>
|
[] |
[
{
"body": "<p>In terms of conventions there is nothing to poke at there.</p>\n\n<p>Where I find that approach lacking is that it tries to merge two different concepts. Namely a point in time an a time difference (or offset). Another non .NET example that I can think of is swift which has <code>Date</code> and <code>TimeInterval</code>. <code>TimeInterval</code> being an alias for a double which represents the offset in seconds.</p>\n\n<p>Most libraries (.NET included) have distinct types to separate these two concepts.</p>\n\n<p>To illustrate where it goes wrong I would expect</p>\n\n<pre><code>Utc.Now == DateTime.Now\n</code></pre>\n\n<p>But it is not.</p>\n\n<p>I understand the convenience for have the common type and using the type system to enforce this for you but consumers of the API would have some trouble with it.</p>\n\n<p>Two alternatives: </p>\n\n<ol>\n<li>Use a built in library type. Either <code>DateTime</code> to specify the exact time of execution or <code>TimeSpan</code>.</li>\n</ol>\n\n<p>In this case <code>DateTime</code> provides the utility of <code>ToUniversalTime()</code> but that would require the implementer of the interface <code>IApi</code> to ensure that this is done. As long as you clearly document what you expect it is OK.</p>\n\n<p>An added benefit is that you don't have to reinvent the wheel and your code is now more portable between all .NET platforms. These types include <code>IComparable</code> and <code>IEquatable</code> already which is one less thing to worry about for the future.</p>\n\n<ol start=\"2\">\n<li>Keep the type <code>Utc</code> but make sure you keep the underlying type consistent to either by an offset or a fixed time.</li>\n</ol>\n\n<p>Either one works. I would lean to storing the backing data as <code>TimeSpan</code>. Converting a time to the time interval from when it was called.</p>\n\n<p>The implicit conversions in this case are a good idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T01:53:57.267",
"Id": "239479",
"ParentId": "239469",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239479",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:26:08.970",
"Id": "239469",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Specifying UTC time or current time offset"
}
|
239469
|
<p>I have two lists which are also having some duplicate elements , i am converting this list to map as key value pair with element index as the value for the key - element </p>
<p>List 1 : [1, 2, 3, 4, 5, 6, 7, 2] = > </p>
<p>MAP 1 (Map, List>) : {1=[0], 2=[1, 7], 3=[2], 4=[3], 5=[4], 6=[5], 7=[6]} </p>
<p>List 2 : [3, 3, 2, 4, 7] </p>
<p>= > MAP 2 (Map, List>) : {2=[2], 3=[0, 1], 4=[3], 7=[4]}</p>
<p>i am trying to collect matching keys from both of the maps and club it another map </p>
<p>For above two it would give the result : {[2]=[0, 1], [3]=[3], [6]=[4], [1, 7]=[2]}</p>
<p>Post this , i am taking the cartesian product of key , values and only retaining the unique elements </p>
<p>Final output [[0, 2], [1, 2], [3, 3], [4, 6], [2, 1], [2, 7]] . These is the indices of common elements </p>
<p>Below is the code that i have come up with to achieve this , is there any better way i can achieve the same . I feel it will be too much costly at run time for larger lists . </p>
<blockquote>
<pre><code> List<List<Integer>> cartesianProduct = new ArrayList<>();
List<String> distinct1 = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "2")
List<String> distinct2 = Arrays.asList["3", "3", "2", "4", "7"]
Map<String, List<Integer>> result1 = IntStream.range(0, distinct1.size()).boxed()
.collect(Collectors.groupingBy(i -> distinct1.get(i)));
Map<String, List<Integer>> result2 = IntStream.range(0, distinct2.size()).boxed()
.collect(Collectors.groupingBy(i -> distinct2.get(i)));
result1.entrySet().stream()
.filter(x -> result2.containsKey(x.getKey()))
.collect(Collectors.toMap(x -> x.getValue(), x -> result2.get(x.getKey())))
.entrySet().forEach(a1 -> a1.getValue().stream()
.forEach(b1 -> a1.getKey().stream().forEach(c1 -> cartesianProduct.add(Arrays.asList(b1, c1)))));
List<List<Integer>> listWithoutDuplicates = cartesianProduct.stream()
.distinct()
.collect(Collectors.toList());
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Firstly, try to make sure that code you post here compiles. Now you have missing semicolons on the lines</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>List<String> distinct1 = Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"2\")\nList<String> distinct2 = Arrays.asList[\"3\", \"3\", \"2\", \"4\", \"7\"] \n</code></pre>\n\n<p>and also the last of these two lines has <code>[...]</code> instead of <code>(...)</code>.</p>\n\n<p>It was also a bit difficult to actually figure out what your code was supposed to do, but I think I understand it now.</p>\n\n<p>It seems you want to create a list of pairs of some sort. So instead of ending with a <code>List<List<Integer>></code>, you can create a <code>Pair</code> class</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public final class Pair<S, T> {\n private final S left;\n private final T right;\n\n public Pair(S left, T right) {\n this.left = left;\n this.right = right;\n }\n\n public S left() {\n return left;\n }\n\n public T right() {\n return right;\n }\n\n // equals and hashCode\n ...\n}\n</code></pre>\n\n<p>and have a <code>List<Pair<Integer, Integer>></code> instead.</p>\n\n<p>Then you can create a method which given two <code>List</code>s creates the cartesian product</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public List<Pair<S, T>> cartesianProduct(List<S> firstList, List<T> secondList) {\n return firstList.stream()\n .flatMap(x -> secondList.stream().map(y -> new Pair<>(x, y)))\n .collect(Collectors.toList());\n}\n</code></pre>\n\n<p>During the construction of your cartesian list, you collect your intermediate results into a <code>Map</code>. This step is not needed as you can now immediately convert to a list of pairs. Also, it is usually not a good idea to have a <code>List</code> as keys of a <code>Map</code> as the <code>List</code> is mutable. <code>Map</code> expects the hash code of the keys to not change which is a possibility when using <code>Lists</code> as keys.</p>\n\n<p>Removing the <code>Map</code> step in the process we get</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>List<Pair<Integer, Integer>> listWithoutDuplicates = result1.entrySet().stream()\n .filter(x -> result2.containsKey(x.getKey()))\n .flatMap(x -> cartesianProducts(result2.get(x.getKey()), x.getValue()).stream())\n .distinct()\n .collect(Collectors.toList());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T08:56:07.547",
"Id": "239497",
"ParentId": "239470",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239497",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:27:07.220",
"Id": "239470",
"Score": "3",
"Tags": [
"java",
"stream",
"hash-map",
"lambda"
],
"Title": "Finding out the indices of common elements in two array lists having duplicate elements"
}
|
239470
|
<p>I made a struct that will loop through a list, and return the next element on calls to the Get() method.
It also allows to remove elements from the list by calling the Evict() method, and is safe for concurrent use.</p>
<p>I'd appreciate any feedback: what's ok, what's not, what could be improved or changed.</p>
<pre class="lang-golang prettyprint-override"><code>package generators
import (
"errors"
)
var (
ErrEmpty = errors.New("no elements were given")
ErrConflict = errors.New("found the same element twice")
)
// InfiniteWithEvict will circle through a list of elements until cancelled,
// allowing to remove elements if needed. It is safe for concurrent use.
// It needs to be created with NewInfiniteWithEvict(),
// started with
// InfiniteWithEvict.Start()
// and cancelled by calling the function returned by InfiniteWithEvict.Start().
type InfiniteWithEvict struct {
elems []interface{}
evictC chan interface{}
getC chan interface{}
indices map[interface{}]int
}
// NewInfiniteWithEvict returns an InfiniteWithEvict object.
// The contents of the slice elems will be modified by calls to Evict() method.
func NewInfiniteWithEvict(elems []interface{}) (*InfiniteWithEvict, error) {
if len(elems) == 0 {
return nil, ErrEmpty
}
m := make(map[interface{}]int)
for idx, elem := range elems {
if _, ok := m[elem]; ok {
return nil, ErrConflict
}
m[elem] = idx
}
return &InfiniteWithEvict{
elems: elems,
evictC: make(chan interface{}),
getC: make(chan interface{}),
indices: m,
}, nil
}
// Start starts the generator.
// Before calling start, calls to Get() and Evict() will block.
// It returns a function that must be called when you are sure that
// no more calls to Get() or Evict() will be made.
func (p *InfiniteWithEvict) Start() func() {
cancel := make(chan struct{})
go p.loop(cancel)
return func() {
cancel <- struct{}{}
}
}
// Get returns the next element of the list.
func (p *InfiniteWithEvict) Get() interface{} {
return <-p.getC
}
// Evict removes an element from the list.
func (p *InfiniteWithEvict) Evict(v interface{}) {
p.evictC <- v
}
func (p *InfiniteWithEvict) loop(cancel <-chan struct{}) {
i := 0
for {
select {
case <-cancel:
close(p.getC)
return
case v := <-p.evictC:
index, ok := p.indices[v]
if !ok {
continue
}
p.elems[index] = p.elems[len(p.elems)-1]
p.elems = p.elems[:len(p.elems)-1]
delete(p.indices, v)
if len(p.elems) == 0 {
continue
}
p.indices[p.elems[index]] = index
if i == len(p.elems) {
i = 0
}
case p.getC <- func() interface{} {
if len(p.elems) == 0 {
return nil
}
return p.elems[i]
}():
if i == len(p.elems)-1 {
i = 0
} else {
i = i + 1
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:30:22.493",
"Id": "469701",
"Score": "0",
"body": "that `case p.getC` is painful reading. dont forget us when writing code, simpler is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:36:47.380",
"Id": "469704",
"Score": "0",
"body": "the start function could be a private call from within the constructor call (who will not call start of this code when being used ?). On the other hand, a Done function gives end user the chance to kill it when needed. just use context.Context instead of non standard cancellation mechanism, IMHO. the p.getC case is racy. it consumes i and p.elems asynchronously."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:37:50.027",
"Id": "469705",
"Score": "0",
"body": "write down some tests, with concurrent cases, run them with -race flags, see what happens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T15:01:35.920",
"Id": "470415",
"Score": "0",
"body": "I honestly struggle to see the benefit of your approach. Why not simply use a `sync.Map`, or a simple wrapper around a slice or map with a `sync.RWMutex` to ensure safe concurrent use?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:33:14.433",
"Id": "239471",
"Score": "1",
"Tags": [
"go",
"concurrency",
"generator"
],
"Title": "infinite generator with eviction"
}
|
239471
|
<p>I have written an automatically encrypting text editor (<a href="https://github.com/1f604/sedit" rel="nofollow noreferrer">github link</a>). The reasons that I wrote this program instead of using vim + gpg are:</p>
<ol>
<li>It's more convenient than vim + gpg (user only needs to enter password once).</li>
<li>It's more secure than vim + gpg (see CVE-2010-2547 and CVE-2019-12735). </li>
<li>User cannot accidentally change the password of the file. </li>
<li>My program checks to see that the file written to disk can be decrypted again.</li>
<li>My program makes a copy of the file every time it is written to disk, and checks that the copy is bit-for-bit identical to the original, in order to protect against disk sector corruption. </li>
</ol>
<p>The reason I'm asking for a code review is to make sure I haven't messed up these properties somehow (especially the crypto, that's the part I'm most worried about), and also I would like to know what I can do to improve the security and reliability of my program against the most common threats such as bad input parsing (the same kind of errors as the Vim and GPG vulnerabilities mentioned above), disk sector failures and memory errors (due to not using ECC RAM). I also assume that I cannot defend against an adversary who is already running a program on the machine that can read the clipboard, log keystrokes, or read my process's memory. I also assume that python, tkinter, and pynacl are not backdoored, since the packages (other than python) are not signed. </p>
<p>If you don't have time to read through all the code, the most important functions I'd like to have reviewed are <code>encrypt</code>, <code>decrypt</code>, and <code>savefile</code>. </p>
<p>Crypto functions (<code>cryptotest.py</code>):</p>
<pre class="lang-py prettyprint-override"><code>import os
import base64
import nacl.pwhash
import nacl.secret
import nacl.utils
def _keygen(password: str): #key generation algorithm, not used outside this file
"""
Takes a password string and returns a key.
We don't need to salt the password since we're not storing it anywhere in any form.
Parameters are hardcoded so you don't have to store or pass them.
"""
password = password.encode('utf-8')
kdf = nacl.pwhash.argon2i.kdf
salt = b'1234567812345678' #salt must be exactly 16 bytes long
ops = 4 #OPSLIMIT_INTERACTIVE
mem = 33554432 #MEMLIMIT_INTERACTIVE
return kdf(nacl.secret.SecretBox.KEY_SIZE, password, salt,
opslimit=ops, memlimit=mem)
def encrypt(plaintext: str, password: str) -> bytes:
"""
pynacl includes the nonce (iv), tag, and ciphertext in the result from box.encrypt.
According to the pynacl docs, the returned value will be exactly 40 bytes longer
than the plaintext as it contains the 24 byte random nonce and the 16 byte MAC.
"""
plaintext = plaintext.encode('utf-8')
key = _keygen(password)
box = nacl.secret.SecretBox(key)
encrypted = box.encrypt(plaintext)
return encrypted
def decrypt(encrypted: bytes, password: str) -> str:
"""
We first decrypt the ciphertext using pynacl into a bytes object.
We then use Python's UTF-8 decoder to convert that to a string.
This function is only used in sopen.py. It is not used in screate.py.
WARNING: This function NEEDS to be wrapped in a try-catch block, because decryption and decoding can and will raise exceptions.
"""
key = _keygen(password)
box = nacl.secret.SecretBox(key)
plaintext = box.decrypt(encrypted)
plaintextstring = plaintext.decode('utf-8')
return plaintextstring
</code></pre>
<p>Create file function (<code>screate.py</code>):</p>
<pre class="lang-py prettyprint-override"><code>import os, sys, getpass
from cryptotest import encrypt
def getpassword() -> str:
"""
This function has been manually tested.
It successfully detects and exits when user enters a blank password,
or when the user enters 2 passwords that don't match.
"""
password1 = getpass.getpass("Enter a password: ")
password2 = getpass.getpass("Enter the password again: ")
if password1 != password2:
print("Passwords do not match.")
exit(1)
if not password1:
print("YOU MUST ENTER A PASSWORD!")
exit(1)
return password1
def createfile(filename: str) -> str:
# create the file
print("You will now be asked to enter a password for the new file.")
try:
password = getpassword()
except Exception as e:
print(e)
exit(1)
try:
with open(filename, 'xb') as f:
ciphertext = encrypt("You can write your stuff in this file.", password)
f.write(ciphertext)
print("File " + filename + " was successfully created.")
print("You can open the file with the following command:")
print(" python3 sopen.py " + filename)
except Exception as e:
print(e)
print("An error occurred while creating the file. See above.")
exit(1)
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: screate.py filename")
exit(0)
fn = sys.argv[1]
fn = os.path.abspath(fn) # just for insurance.
createfile(fn)
</code></pre>
<p>Open file function (<code>sopen.py</code>):</p>
<pre class="lang-py prettyprint-override"><code>import sys
import os.path, getpass
import shutil
import filecmp
import random
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
TEAL = '#008080'
BROWN = '#800000'
GREY = '#808080'
def goodmsg(msg):
print(bcolors.OKGREEN + msg + bcolors.ENDC)
def badmsg(msg):
print(bcolors.FAIL + msg + bcolors.ENDC)
def error_out(msg: str):
badmsg("Error: " + msg)
getpass.getpass("Press enter to exit.") # This is to capture the user's password if he enters it inadvertently.
exit(1)
if sys.version_info[0] < 3:
error_out("You must use Python 3")
from cryptotest import encrypt, decrypt
class WindowManager(object):
def getSearchboxContents(self):
return self.searchbox.get()
def getTextboxContents(self):
return self.text.get("1.0", "end-1c")
def savefile(self, event=None):
"""
When we save a file, we need to make sure it can be decrypted again.
To this end, we first try to save it in a tmp file, once that succeeds,
we then replace the original with the tmp file.
"""
plaintext = self.getTextboxContents()
self.curSavedFileContents = plaintext
# We need to check that we can open the file again. If not, we need to re-save the file.
# This loop exits once we've confirmed that we can decrypt the file we've just saved, or when we've tried 10 times.
# To this end, we use a temporary file so that we don't lose the original.
tempfilename = self.filename + ".tmp"
success = False
for i in range(10):
# Since we immediately close the file, this should force a write to disk on save.
with open(tempfilename, "wb") as f:
f.write(encrypt(plaintext, self.password))
# We then open the file to check if we can decrypt it.
with open(tempfilename, "rb") as f:
wholetext = f.read()
try:
if plaintext == decrypt(wholetext, self.password):
self.dirty = False
# We only change the window color after the file has been written to and closed successfully.
self.frame.configure(bg=TEAL)
goodmsg("Temp file saved successfully.")
success = True
break
except Exception as e:
badmsg(e)
badmsg("Error encountered trying to decrypt/decode file, see above.")
badmsg("This is attempt #" + str(i))
if success:
# successful, replace original file with tmp file.
# we also update the backup copy, and check that they are bit-for-bit identical.
os.remove(self.filename)
os.rename(tempfilename, self.filename)
goodmsg("Original successfully replaced by temp file.")
backupfilename = self.filename+".backup"
for _ in range(5):
shutil.copy(self.filename, backupfilename)
if not filecmp.cmp(self.filename, backupfilename):
badmsg("ERROR: backup file is not identical to original.")
else:
goodmsg("Backup file successfully saved and checked.")
break
else:
badmsg("Warning: File was not backed up.")
else:
# failed, delete temporary file.
os.remove(tempfilename)
badmsg("ERROR: FILE NOT SAVED.")
def checkUnsavedChanges(self, event=None):
# check if saving
# if not:
if self.dirty:
if messagebox.askyesno("Exit", "THERE ARE UNSAVED CHANGES! Do you want to quit the application?"):
if messagebox.askokcancel("Exit", "THERE ARE UNSAVED CHANGES!! ARE YOU SURE you want to quit the application?"):
win = tk.Toplevel()
win.title('warning')
message = "This will delete stuff"
tk.Label(win, text=message).pack()
buttons = [
tk.Button(win, text='No!', command=win.destroy),
tk.Button(win, text='Delete', command=self.root.destroy),
tk.Button(win, text='Noo!', command=win.destroy),
tk.Button(win, text='Don\'t delete!!', command=win.destroy)
]
random.shuffle(buttons)
for button in buttons:
button.pack()
else:
self.root.destroy()
def ismodified(self, event):
plaintext = self.getTextboxContents()
if plaintext != self.curSavedFileContents:
self.frame.configure(bg=BROWN)
self.dirty = True
else:
self.frame.configure(bg=TEAL)
self.dirty = False
self.text.edit_modified(0) # IMPORTANT - or <<Modified>> will not be called later.
def on_focus_out(self, event):
if event.widget == self.root:
self.frame.configure(bg=GREY)
def on_focus_in(self, event):
if event.widget == self.root:
if self.dirty:
self.frame.configure(bg=BROWN)
else:
self.frame.configure(bg=TEAL)
def focus_search(self, event):
self.searchbox.focus()
self.select_all_searchbox(event)
def clear_highlights(self, event):
self.in_search = False
self.srch_idx = '1.0'
self.text.tag_remove('found', '1.0', tk.END)
self.text.tag_remove('found_cur', '1.0', tk.END)
self.msglabel['text'] = ''
def search_highlight(self, s):
"""
Given a search string s, highlight all occurrances of it in the text.
"""
self.text.tag_remove('found', '1.0', tk.END)
if s:
idx = '1.0'
while 1:
idx = self.text.search(s, idx, nocase=1, stopindex=tk.END)
if not idx: break
lastidx = '%s+%dc' % (idx, len(s))
self.text.tag_add('found', idx, lastidx)
idx = lastidx
self.text.tag_config('found', background='magenta') #firefox search highlight colors
self.text.tag_raise("sel") # allow highlighted text to be seen over search highlights
def find_next(self, needle):
self.text.tag_remove('found_cur', '1.0', tk.END)
idx = self.text.search(needle, self.srch_idx, nocase=1, stopindex=tk.END)
if not idx:
self.srch_idx = '1.0'
self.msglabel['text'] = 'No more search results.'
return
self.msglabel['text'] = ''
lastidx = '%s+%dc' % (idx, len(needle))
self.srch_idx = lastidx
self.text.tag_add('found_cur', idx, lastidx)
self.text.tag_config('found_cur', foreground='red', background='green') #firefox search highlight colors
self.text.tag_raise("sel") # allow highlighted text to be seen over search highlights
self.text.see(idx) # scroll the textbox to where the found text is.
def text_search(self, event):
needle = self.getSearchboxContents()
if not self.in_search:
self.in_search = True
self.search_highlight(needle)
self.find_next(needle)
# This is to move the cursor to the end of the line when you click on some empty space at the end of the line.
# Default behavior is really annoying as it moves the cursor to the beginning of the next line if you click past half of the whitespace.
def on_text_click(self, event):
line = event.x
column = event.y
index = self.text.index("@%d,%d" % (event.x, event.y))
self.text.mark_set("insert", index)
# Select all the text in textbox
def select_all(self, event):
self.text.tag_add(tk.SEL, "1.0", tk.END)
return 'break'
# Select all the text in searchbox
def select_all_searchbox(self, event):
self.searchbox.select_range(0, tk.END)
return 'break'
# Select current line in textbox
def select_line(self, event):
tk.current_line = self.text.index(tk.INSERT)
self.text.tag_add(tk.SEL, "insert linestart", "insert lineend+1c")
return 'break'
#after(interval, self._highlight_current_line)
def __init__(self, root, filename, contents, password):
# initialize "global" variables
# These variables refer to the elements inside the UI
# For example, self.text refers to the main text box, self.searchbox refers to the search box, and so on.
self.root = root
self.filename = filename
self.curSavedFileContents = contents
self.password = password
self.dirty = False
self.frame = tk.Frame(root, bg=TEAL)
self.text = tkst.ScrolledText(
master=self.frame,
wrap='word', # wrap text at full words only
width=80, # characters
height=30, # text lines
bg='beige', # background color of edit area
undo=True
)
self.searchframe = tk.Frame(root)
self.searchlabel = tk.Label(self.searchframe, text='Search text:')
self.searchbox = tk.Entry(self.searchframe)
saveframe = tk.Frame(root)
self.msglabel = tk.Label(saveframe, text='')
# initialize text editor window UI
self.root.wm_title("sedit")
self.frame.pack(fill='both', expand='yes')
self.text.bind('<<Modified>>', self.ismodified)
self.root.bind("<FocusIn>", self.on_focus_in)
self.root.bind("<FocusOut>", self.on_focus_out)
self.searchlabel.pack(side=tk.LEFT)
self.searchbox.pack(side=tk.LEFT, expand=True, fill='both')
self.msglabel.pack(side=tk.LEFT)
self.searchframe.pack(fill=tk.X)
button = tk.Button(saveframe, text="Save", command=self.savefile, padx=8, pady=8)
button.pack(side=tk.RIGHT)
saveframe.pack(fill=tk.X)
# the padx/pady space will form a frame
self.text.pack(fill='both', expand=True, padx=8, pady=8)
self.text.insert('insert', contents)
self.frame.configure(bg=TEAL)
# On Mac, Command binds to the cmd key. On Windows it binds to the ctrl key.
self.root.bind_all("<Command-w>", self.checkUnsavedChanges)
self.root.bind_all("<Command-s>", self.savefile)
self.text.bind("<Command-a>", self.select_all)
self.text.bind("<Command-l>", self.select_line)
self.in_search = False
self.srch_idx = '1.0'
self.text.bind("<Command-f>", self.focus_search)
self.searchbox.bind("<Return>", self.text_search)
self.root.bind("<Escape>", self.clear_highlights)
self.searchbox.bind("<Command-a>", self.select_all_searchbox)
self.root.bind("<Button-1>", self.on_text_click)
self.root.protocol('WM_DELETE_WINDOW', self.checkUnsavedChanges) # root is your root window
def openfile(filename: str, password: str):
#1. Open file and try to decrypt it.
with open(filename,"rb") as f:
s = f.read()
contents = decrypt(s,password) # An exception here is fine as we can terminate here no problems.
#2. Main window setup
root=tk.Tk()
WindowManager(root, filename, contents, password)
#3. main loop
root.mainloop()
if __name__ == "__main__":
if len(sys.argv) != 2:
error_out("You must supply exactly one command line argument to open.py")
filename = sys.argv[1]
filename = os.path.abspath(filename) # just for insurance.
# Check if file exists
if not os.path.isfile(filename):
error_out("File not found.")
goodmsg("sedit: Found file "+filename+".")
password = getpass.getpass("Enter the password to decrypt the file: ")
# All these GUI imports take a while, so we only do it after the user enters the right password.
# This is to allow the user to enter the password immediately after starting this program.
import tkinter as tk
from tkinter import messagebox
import tkinter.scrolledtext as tkst
openfile(filename, password)
</code></pre>
<p>The <code>screate.py</code> and <code>sopen.py</code> files are intended to be run on their own, with a file name supplied as parameter. The user first creates a file using <code>screate.py filename</code> then he opens it with <code>sopen.py filename</code>, which will open the GUI. The keyboard shortcuts for the GUI are as follows:</p>
<ul>
<li>Ctrl-s to save file</li>
<li>Ctrl-w to close editor </li>
<li>Ctrl-a to select all</li>
<li>Ctrl-l to select current line </li>
<li>Ctrl-f to enter search mode and search text</li>
<li>Esc to exit search mode</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:48:15.633",
"Id": "469686",
"Score": "2",
"body": "_the packages (other than python) are not signed_ - They are on most versions of Linux package manager, including apt, during download. Not so much once they hit the hard drive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-17T00:36:50.693",
"Id": "472100",
"Score": "1",
"body": "There isn't too much to be seen when it comes to encryption. It uses NaCl and a password hash. Fine. I think quoting two security advisories to dismiss Vim + GPG is a bit shallow though. Any runtime will have security advisories."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T17:39:58.607",
"Id": "472584",
"Score": "0",
"body": "@MaartenBodewes Are you saying that Python (a language runtime) is comparable to Vim or GPG (applications written in C) in terms of vulnerability to exploitation? As far as I can see in my program there are 3 significant places for exploitation: pynacl's MAC verifier, pynacl's decryptor, and Python's UTF-8 decoder. I am under the impression that bugs in an application are usually much more likely to be due to a programming error in the application itself, or a library the application uses, rather than the language runtime that the application is running on. Please correct me if I'm wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:11:40.747",
"Id": "473269",
"Score": "1",
"body": "My comment is not a criticism on Python, which is fine for crypto, as long as native functions are used where side channel attacks and such are concerned (those are tricky to avoid in higher level languages). And for parsing structures and such (a major part of the functionality in PGP) I'd prefer a higher level language with memory protection. My point was that dismissing libraries because of bugs is dangerous. If you create your own, you will create your own bugs, possibly even dupes of earlier bugs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-13T12:22:39.397",
"Id": "475313",
"Score": "0",
"body": "I think you may have misunderstood the first of those two CVEs. Firstly, GnuPG 2.0.16 is kinda ancient at this point. Secondly, and more importantly, that vulnerability related specifically to GPGSM; which is the S/MIME engine of the GnuPG Project (as opposed to GPG, which is the OpenPGP engine). The vast majority of GnuPG users are also OpenPGP users and not S/MIME users, so they would not have been affected by this. Even back in the day when that CVE meant something."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T23:05:55.800",
"Id": "239473",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"security",
"cryptography",
"tkinter"
],
"Title": "Automatically encrypting text editor"
}
|
239473
|
<p>Inspired by <a href="https://puzzling.stackexchange.com/questions/95352/what-is-a-bff-word">this question</a> on <a href="https://puzzling.stackexchange.com/">Puzzling.StackExchange</a>, I've decided to write a small python script that determines if a word is a BFF Word. Below are the parameters, solved by Puzzling user <a href="https://puzzling.stackexchange.com/users/60644/stiv">Stiv</a>, also discussed in the program module docstring:</p>
<blockquote>
<p>If you remove two letters, you are left with an anagram of an animal which is a common household pet ("man's best friend", hence 'BFF' - Best Friends Forever). Furthermore, the non-BFF Words exhibit a different but related pattern - namely that if you remove two letters, you are left with an anagram of an animal which is not a common household pet!</p>
</blockquote>
<p>The main this I want improvements on is performance. I use <code>requests</code> to retrieve list of around 475k english words to determine if they are BFF words. I then use <a href="https://docs.python.org/2/library/itertools.html#itertools.permutations" rel="nofollow noreferrer"><code>itertools.permutations</code></a> to get all the possible combinations of the english word, based on the length of the pet it's being tested against, then test it against an already existing list of common/uncommon animals. </p>
<p>After about 15 minutes of running the program is still in the <code>ab...</code> part of the english words. I presume the part thats taking the longest is generating the permutations, so I'm wondering if there's any better way to do this.</p>
<p><strong>script.py</strong></p>
<pre><code>"""
A function that determines if a string is a BFF Word.
If you remove two letters, and the remaining letters are
an anagram for a household pet, then it's a BFF Word.
Example:
GOURD -> remove UR -> DOG = Common Pet
ALBINO -> remove AB -> LION = Uncommon Pet
HELLO -> remove any 2 -> None = Neither
"""
from enum import Enum
from itertools import permutations
import requests
REPOSITORY = "https://raw.githubusercontent.com/dwyl/english-words/master/words.txt"
COMMON_PET = ["dog", "cat", "lizard", "rabbit", "hamster", "fish"]
UNCOMMON_PET = ["bear", "rhino", "lion", "tiger", "viper", "hyena"]
class PetType(Enum):
COMMON = 1
UNCOMMON = 2
NEITHER = 3
def type_of_pet(word: str) -> PetType:
"""
Returns the type of pet that the passed word is.
"""
for pet in COMMON_PET:
for string in permutations(word, len(pet)):
if pet == ''.join(string):
return PetType.COMMON
for pet in UNCOMMON_PET:
for string in permutations(word, len(pet)):
if pet == ''.join(string):
return PetType.UNCOMMON
return PetType.NEITHER
def main():
req = requests.get(REPOSITORY)
if req.status_code == 200:
words = req.text.split()
for word in words:
print(f"Word: {word.lower()} | Type of Pet: {type_of_pet(word.lower())}")
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T03:22:53.657",
"Id": "469689",
"Score": "0",
"body": "This was fun to write a sample implementation."
}
] |
[
{
"body": "<p>The easiest speed-up I can think of is a letter-counting pass. In other words: apply <code>collections.Counter()</code> to the word in question, and keep a pre-computed tuple of <code>Counter</code>s for both pet types.</p>\n\n<p>The thing that's killing your performance is order - there are many, many, many re-ordered results from <code>permutations</code>, but they literally don't matter since you're dealing with an anagram. So when you compare with the <code>Counter</code>s suggested above, check to see that</p>\n\n<ul>\n<li>there are no letters that have increased, and</li>\n<li>the total decrease is exactly two.</li>\n</ul>\n\n<p>Here is a very rough implementation that seems to be fast-ish:</p>\n\n<pre><code>from collections import Counter\nimport requests\n\n\nclass Pet:\n __slots__ = ('name', 'counter', 'is_common', 'letters')\n def __init__(self, name: str, is_common: bool):\n self.name, self.is_common = name, is_common\n self.counter = Counter(self.name)\n self.letters = set(self.counter.keys())\n\n def matches(self, word: str) -> bool:\n if len(word) != 2 + len(self.name): return False\n wcounter = Counter(word)\n total = 0\n for letter in self.letters | set(wcounter.keys()):\n diff = wcounter[letter] - self.counter[letter]\n if diff < 0: return False\n total += diff\n if total > 2: return False\n return total == 2\n\n def __str__(self): return self.name\n\n\npets = [\n *(Pet(name, True) for name in ('dog', 'cat', 'lizard', 'rabbit', 'hamster', 'fish')),\n *(Pet(name, False) for name in ('bear', 'rhino', 'lion', 'tiger', 'viper', 'hyena')),\n]\n\nprint('Downloading...', end=' ')\nresp = requests.get('https://github.com/dwyl/english-words/blob/master/words.txt?raw=true')\nresp.raise_for_status()\nwords = resp.text.splitlines()\nprint(f'{len(words)} downloaded.')\n\nfor word in words:\n for pet in pets:\n if pet.matches(word.lower()):\n print(f'{word} -> {pet} = {\"Common\" if pet.is_common else \"Uncommon\"} Pet')\n</code></pre>\n\n<p>It can be sped up with the use of multiple threads, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:40:16.500",
"Id": "239484",
"ParentId": "239477",
"Score": "4"
}
},
{
"body": "<h3>Use The Rule</h3>\n<p>Don't search for words that match the rule! You already know the rule. Use it to generate the BFF words. That is, start with a common pet and filter out all the words that aren't two letters longer or that don't have all the letters in the common pet. The result is a list of the BFF words for that pet. The non-BFF words are generated using the same rule, but starting from an uncommon pet. Runs in about 125 ms.</p>\n<pre><code>import random\nfrom collections import Counter\n\nCOMMON_PET = ["dog", "cat", "lizard", "rabbit", "hamster", "fish"]\nUNCOMMON_PET = ["bear", "rhino", "lion", "tiger", "viper", "hyena"]\n\ndef BFF_word(pet, word_list):\n word_len = len(pet) + 2\n count = {letter:pet.count(letter) for letter in pet}\n\n# only keep words that have the right length, no punctuation,\n# and the right numbers of letters, and also don't contain\n# the common pet, e.g. 'rabbited' -> 'rabbit' (too easy). \nBFFs = [word for word in word_list\n if len(word) == word_len\n if word.isalpha()\n if all(count[letter]<=word.count(letter) for letter in count)\n if pet not in word\n ]\n\n\n # uncomment to see how many BFFs there are and the first few\n #print(pet, len(BFFs), BFFs[:5])\n\n return random.choice(BFFs)\n\n \ndef main():\n # I just used a local word list\n with open("/usr/share/dict/words") as f:\n words = [line.strip().lower() for line in f]\n\n print("BFF words")\n for pet in COMMON_PET:\n word = BFF_word(pet, words)\n print(f'{word} -> {pet}')\n\n print("non-BFF words")\n for pet in UNCOMMON_PET:\n word = BFF_word(pet, words)\n print(f'{word} -> {pet}')\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:08:29.600",
"Id": "469729",
"Score": "0",
"body": "I don't think this works for all edge cases. For a word like `\"rabbit\"` it is not enough that the BFF word is longer and has all letters in it. It needs to have at least *two* `\"b\"` in order to be valid, i.e. the count of each letter in `word` must be greater or equal to the count of each letter in `pet`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:12:07.797",
"Id": "469731",
"Score": "0",
"body": "An example of a matching word that should not match is `\"arbiters\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:13:33.507",
"Id": "469732",
"Score": "0",
"body": "Also, TIL that you can have multiple `if` in a list comprehension and don't have to chain them with `and`. Thought that would be a syntax error, but it works just fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T16:01:12.467",
"Id": "469791",
"Score": "0",
"body": "@Graipher, good catch. Fixed. With the bug, there are 42 reported BFF words for 'rabbit', of which only 3 are correct. Naturally, the one time I checked the output in detail, it randomly picked one of the correct answers."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:59:49.677",
"Id": "239492",
"ParentId": "239477",
"Score": "3"
}
},
{
"body": "<p>Now for something completely different: an implementation in C.</p>\n\n<p>This is somewhat simple and stupid, and for all intents and purposes it executes instantly. It does not have any hash maps or hash sets. It tracks, for each pet, a letter frequency counting array that is sparse - it technically tracks the whole ASCII-extended range for efficiency's sake.</p>\n\n<p>This makes some blatant assumptions:</p>\n\n<ul>\n<li>Locale is ignored</li>\n<li>Letter case is ignored</li>\n<li><code>words.txt</code> is assumed to have already been downloaded</li>\n<li>This is possibly only compatible with Unix-like operating systems due to the file calls</li>\n<li>Punctuation, spaces, etc. count as \"characters that can be removed\" to satisfy the criteria</li>\n</ul>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <fcntl.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <unistd.h>\n\n#define FILENAME \"words.txt\"\n\ntypedef struct {\n const bool common; // Is this a common pet?\n const char *name; // Pet's name, capitalized\n int len, // Length of pet's name, excluding null\n *counts; // Array of letter frequencies\n} Pet;\n\n// Assume ASCII everywhere; this is the number of symbols whose frequency we count\n#define N_COUNTS 256\n// The size of a frequency-counting array for the above character set\n#define N_COUNT_BYTES (N_COUNTS * sizeof(int))\n// The number of bytes if we only care about counting the upper-case alphabet\n#define BYTES_TO_Z ((1 + (int)'Z') * sizeof(int))\n// The number of letters that the word must lose to get to the pet name\n#define COUNT_DIFF 2\n\nstatic Pet pets[] = {\n { true, \"DOG\" },\n { true, \"CAT\" },\n { true, \"LIZARD\" },\n { true, \"RABBIT\" },\n { true, \"HAMSTER\" },\n { true, \"FISH\" },\n { false, \"BEAR\" },\n { false, \"RHINO\" },\n { false, \"LION\" },\n { false, \"TIGER\" },\n { false, \"VIPER\" },\n { false, \"HYENA\" },\n};\n#define N_PETS (sizeof(pets)/sizeof(Pet))\n\nstatic void init_pet(Pet *restrict pet) {\n pet->len = strlen(pet->name);\n\n pet->counts = aligned_alloc(16, BYTES_TO_Z);\n if (!pet->counts) {\n perror(\"Failed to allocate buffer\");\n exit(1);\n }\n memset(pet->counts, 0, BYTES_TO_Z);\n for (int i = 0; i < pet->len; i++)\n pet->counts[(uint8_t)pet->name[i]]++;\n}\n\nstatic bool compare(\n const Pet *restrict p, // The pet whose name we will compare\n const char *restrict word, // The dictionary word\n int wlen, // Length of the dictionary word\n int *restrict counts // Memory we use for count differences\n ) {\n // The word must have more letters than the pet, in total\n if (wlen != p->len + COUNT_DIFF)\n return false;\n\n memcpy(counts, p->counts, BYTES_TO_Z);\n\n for (const char *w = word; *w; w++) {\n // This difference is effectively:\n // frequency of this letter in pet - frequency of this letter in word\n // It starts off at the pet# and decreases.\n // Its permissible range for a valid word is -COUNT_DIFF <= c <= 0.\n int *c = counts + (uint8_t)*w;\n (*c)--;\n // Does the word have greater than COUNT_DIFF of this letter more than\n // the pet name?\n if (*c < -COUNT_DIFF)\n return false;\n }\n\n // There cannot be any counts left over that are positive. Loop over the\n // letters of the pet name, which in nearly all cases are unique; so this is\n // more efficient than looping over the whole alphabet.\n for (const char *c = p->name; *c; c++)\n if (counts[(uint8_t)*c] > 0)\n return false;\n\n return true;\n}\n\nstatic char *read_file(const char **restrict end) {\n int fdes = open(FILENAME, O_RDONLY);\n if (fdes == -1) {\n perror(\"Failed to open \" FILENAME);\n exit(1);\n }\n struct stat fs;\n if (fstat(fdes, &fs) == -1) {\n perror(\"Failed to get size of \" FILENAME);\n exit(1);\n }\n\n char *start = malloc(fs.st_size+1);\n if (!start) {\n perror(\"Failed to allocate dictionary buffer\");\n exit(1);\n }\n\n ssize_t nread = read(fdes, start, fs.st_size);\n if (nread != fs.st_size) {\n perror(\"Failed to read \" FILENAME);\n exit(1);\n }\n\n *end = start + fs.st_size;\n start[fs.st_size] = '\\0';\n return start;\n}\n\nstatic int upper_and_len(char *restrict str) {\n // Capitalize all letters, find non-printable newline\n int n;\n for (n = 0; str[n] >= ' '; n++)\n if (str[n] >= 'a' && str[n] <= 'z')\n str[n] &= ~('A' ^ 'a');\n str[n] = '\\0'; // Replace newline with null\n return n; // Return length of string to the null\n}\n\nint main() {\n for (Pet *p = pets; p < pets+N_PETS; p++)\n init_pet(p);\n\n int *counts = aligned_alloc(16, N_COUNT_BYTES);\n if (!counts) {\n perror(\"Failed to allocate working memory buffer\");\n exit(1);\n }\n\n const char *words_end;\n int wlen;\n for (char *word = read_file(&words_end); word < words_end; word += wlen + 1) {\n wlen = upper_and_len(word);\n for (Pet *p = pets; p < pets+N_PETS; p++)\n if (compare(p, word, wlen, counts))\n printf(\"%s -> %s = %s Pet\\n\",\n word, p->name, p->common ? \"Common\" : \"Uncommon\");\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T03:15:38.097",
"Id": "239541",
"ParentId": "239477",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239484",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T01:20:28.047",
"Id": "239477",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"combinatorics"
],
"Title": "BFF Word Finder"
}
|
239477
|
<p><a href="https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/" rel="nofollow noreferrer">https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/</a></p>
<blockquote>
<p>Given an array of integers nums and a positive integer k, find whether
it's possible to divide this array into sets of k consecutive numbers
Return True if its possible otherwise return False.</p>
<pre><code>Example 1:
Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].
Example 2:
Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].
Example 3:
Input: nums = [3,3,2,2,1,1], k = 3
Output: true
Example 4:
Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
1 <= k <= nums.length
</code></pre>
</blockquote>
<p>Please review for performance.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
/// </summary>
[TestClass]
public class DivideArrayinSetsofKConsecutiveNumbersTest
{
[TestMethod]
public void TestExample()
{
int[] nums = {1, 2, 3, 3, 4, 4, 5, 6};
int k = 4;
Assert.IsTrue(DivideArrayinSetsofKConsecutiveNumbers.IsPossibleDivide(nums, k));
}
[TestMethod]
public void TestFailed()
{
int[] nums = { 1, 2, 3,4};
int k = 3;
Assert.IsFalse(DivideArrayinSetsofKConsecutiveNumbers.IsPossibleDivide(nums, k));
}
}
public class DivideArrayinSetsofKConsecutiveNumbers
{
public static bool IsPossibleDivide(int[] nums, int k)
{
if (nums.Length % k != 0)
{
return false;
}
var dict = new SortedDictionary<int, int>();
foreach (var num in nums)
{
if (!dict.TryGetValue(num, out var value))
{
value = dict[num] = 0;
}
dict[num] = value+1;
}
for (int i = 0; i < nums.Length / k; i++)
{
int start = dict.FirstOrDefault(x=>x.Value >0).Key;
dict[start]--;
for (int j = 1; j < k; j++)
{
if (!dict.ContainsKey(start + j) || dict[start + j] < 1)
{
return false;
}
dict[start + j]--;
}
}
return true;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:38:36.113",
"Id": "469740",
"Score": "0",
"body": "I never get people who down vore without writing why"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T00:15:18.317",
"Id": "469836",
"Score": "0",
"body": "Not too familiar with c# but isn't the call to FirstOrDefault quite slow, like O(n) implying O(n^2)? I would suggest instead that you don't need a SortedDictionary, instead, just have a dictionary containing the counts, then sort the array and loop over that. That would be O(nlogn). I think there is an O(n) solution if you think about it, as actually I don't think you need to sort anything, simply make the dictionary of counts, start anywhere say at k, and go back until k-t isn't in the dictionary, then k-t+1 must be the start of a sequence, go up, then go back down again, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T06:55:39.620",
"Id": "469852",
"Score": "0",
"body": "I think you are right. The sorting has no meaning here"
}
] |
[
{
"body": "<p>Here's some C# in accordance with my first suggestion of sorting the array and looping.</p>\n\n<pre><code>public bool IsPossibleDivide(int[] nums, int k)\n{\n if (nums.Length % k != 0)\n {\n return false;\n }\n\n var dict = new Dictionary<int, int>();\n foreach (var num in nums)\n {\n if (!dict.TryGetValue(num, out var value))\n {\n value = dict[num] = 0;\n }\n\n dict[num] = value+1;\n }\n Array.Sort(nums);\n\n for (int i = 0; i < nums.Length; i++)\n {\n var currVal = nums[i];\n if(dict[currVal] > 0) \n {\n for(int j = 0; j < k; j++) \n {\n if(!dict.ContainsKey(currVal + j))\n {\n return false;\n }\n dict[currVal + j]--;\n }\n }\n }\n\n return true;\n}\n</code></pre>\n\n<p>This is significantly faster, and is <code>O(nlogn)</code>, as I say I think there's a <code>O(n)</code> solution but I'm not really sure of the exact details and I don't know much C#, probably I could write it in JS if you like.</p>\n\n<p>As I say, this </p>\n\n<p><code>int start = dict.FirstOrDefault(x=>x.Value >0).Key;</code></p>\n\n<p>looks bad to me because once you've done a good number of the consecutive numbers, it might start having to look through a lot of the dict.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T12:08:29.650",
"Id": "239554",
"ParentId": "239485",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239554",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T05:23:03.763",
"Id": "239485",
"Score": "1",
"Tags": [
"c#",
"programming-challenge",
"hash-map"
],
"Title": "LeetCode: Divide Array in Sets of K Consecutive Numbers C#"
}
|
239485
|
<p>Why did I make this? I'm building an interactive data structure visualization, and when certain errors are thrown from certain parts of the code, they are displayed on screen for the user. I have not included that displaying logic.</p>
<p>The if checks seem somewhat smelly to me, but they might be simple enough to the point that they're fine. I'm interested in best practices, ANY criticism is welcome.</p>
<pre><code>export class OutOfBoundsError extends AppError {
// AppError code is not included, but it is just an extremely simple
//abstract class I needed so I could instanceof to check whether a caught
// error was thrown by my own code
// If you want, pretend I'm extending JS's RangeError instead
constructor(valueName: 'length' | 'index' | 'position', value: number,
bounds?: {
lowerBoundInclusive?: number;
upperBoundInclusive?: number
}) {
super();
const lower = bounds?.lowerBoundInclusive;
const upper = bounds?.upperBoundInclusive;
if (lower === undefined) {
if (upper === undefined) {
this.message = `${valueName} of ${value} is out of bounds`;
} else {
this.message = `${valueName} must be less than or equal to ${upper} but\
${value} was given`;
}
} else {
if (upper === undefined) {
this.message = `${valueName} must be greater than or equal to ${lower}\
but ${value} was given`;
} else {
this.message = `${valueName} must be between ${lower} and ${upper} but\
${value} was given`;
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This seems good.<br>\nI noticed a couple of things, I will try to explain down below.</p>\n\n<ol>\n<li><strong>Lack of type definition</strong><br>\nFor the sake of readability, it would be great to have some type definitions to make the code look easier to read.</li>\n</ol>\n\n<pre><code>type ValueName = 'length' | 'index' | 'position';\n\ninterface Bounds {\n lowerBoundInclusive?: number;\n upperBoundInclusive?: number;\n}\n\nexport class OutOfBoundsError extends AppError {\n // ...\n\n constructor(name: ValueName, value: number, bounds?: Bounds) {\n // ...\n }\n}\n</code></pre>\n\n<p>Since <code>Bounds</code> is an structured type, it deserves to be an interface.<br>\nThe point of defining types is not just the code itself, helps in case of documentation, code hints (code completion, parameters information, ...) and reusability.<br>\nIn case of reusability, types should be separated from implementations.</p>\n\n<hr>\n\n<ol start=\"2\">\n<li><strong><code>message</code> internal property misplace</strong><br>\nInside your constructor, you are setting the value of <code>message</code>. Unlike Javascript, Typescript needs placeholders for internal properties.<br>\nMaybe you had, indeed. Your code does not compile, otherwise.<br>\nAnyways, internal properties must be declared between the class definition and its constructor.</li>\n</ol>\n\n<pre><code>export class OutOfBoundsError extends AppError {\n private message: string;\n\n constructor(name: ValueName, value: number, bounds?: Bounds) {\n // ...\n }\n}\n</code></pre>\n\n<hr>\n\n<ol start=\"3\">\n<li><strong>Truthy and falsy assertions</strong><br>\nAvoid checking with explicit <code>undefined</code>, use <code>if (value)</code> instead.<br>\nIf value is a <code>number</code> type and in fact you are expecting a <code>0</code> to be a valid value, Javascript will coerce it into a <code>false</code>. In that case, check your value like so</li>\n</ol>\n\n<pre><code>if (value != null) {\n // ...\n}\n</code></pre>\n\n<p>By checking with <code>null</code> with a single equal symbol, you are checking for <code>undefined</code> and <code>null</code>, as well.</p>\n\n<hr>\n\n<ol start=\"4\">\n<li><strong>Two or more depth levels</strong><br>\nFunctions should not have more than one depth level. Depth levels are done by using <code>if</code>, <code>for</code>, <code>while</code> and <code>switch</code>.<br>\nDepth levels don't apply to inner functions, object or array instantiations, ...</li>\n</ol>\n\n<pre><code>interface ErrorMessageArgs {\n value: number;\n upper?: number;\n lower?: number;\n}\n\nexport class OutOfBoundsError extends AppError {\n private message: string = ``;\n\n constructor(private name: ValueName, value: number, bounds?: Bounds) {\n super();\n\n const lower = bounds?.lowerBoundInclusive;\n const upper = bounds?.upperBoundInclusive;\n\n if (lower != null) {\n this.handleTruthyLower({value, upper});\n } else {\n this.handleFalsyLower({value, upper, lower});\n }\n }\n\n private handleFalsyLower = (args: ErrorMessageArgs) => {\n const { value, upper } = args;\n // ...\n }\n\n private handleTruthyLower = (args: ErrorMessageArgs) => {\n const { value, upper, lower } = args;\n // ...\n }\n}\n</code></pre>\n\n<p>I decide to define yet another interface to wrap the error message arguments. By doing this, I can define both functions as monadic functions (just because of Robert).</p>\n\n<blockquote>\n <p>The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification — and then shouldn’t be used anyway.<br>\n <strong>Robert C. Martin</strong></p>\n</blockquote>\n\n<hr>\n\n<ol start=\"5\">\n<li><strong><code>message</code> property protection</strong><br>\nI assume that a third party which manipulates this class is not allowed to modify the error message. It doesn't make any sense, in my opinion.<br>\nThat is why it may define a read-only access.</li>\n</ol>\n\n<pre><code>export class OutOfBoundsError extends AppError {\n private _message: string;\n\n constructor(private name: ValueName, value: number, bounds?: Bounds) {\n super();\n // ...\n }\n\n private handleFalsyLower = (args: ErrorMessageArgs) => {\n const { value, upper } = args;\n // ... message is filled\n }\n\n private handleTruthyLower = (args: ErrorMessageArgs) => {\n const { value, upper, lower } = args;\n // ... message is filled\n }\n\n get message() {\n return this._message;\n }\n}\n</code></pre>\n\n<p>Maybe, for more consistency, <code>_message</code> should be <code>protected</code> if <code>OutOfBoundsError</code> is not a sealed class.<br>\nAnd yes, I know that in some case you defined this <code>message</code> property inside the <code>AppError</code> class. I just mention, just in case.</p>\n\n<hr>\n\n<ol start=\"6\">\n<li><strong>Ternary operation</strong><br>\nThis is just a preference. When there is only one line to write inside the <code>if</code> and <code>else</code> statements, I just prefer a ternary operation. It seems cleaner to me.</li>\n</ol>\n\n<pre><code>export class OutOfBoundsError extends AppError {\n protected _message = ``;\n\n constructor(private name: ValueName, value: number, bounds?: Bounds) {\n super();\n\n const lower = bounds?.lowerBoundInclusive;\n const upper = bounds?.upperBoundInclusive;\n\n lower != null\n ? this.handleTruthyLower({value, upper})\n : this.handleFalsyLower({value, upper, lower});\n }\n\n private handleFalsyLower = (args: ErrorMessageArgs) => {\n const { value, upper } = args;\n this._message = upper != null\n ? `${this.name} must be less than or equal to ${upper} but\\\n ${value} was given`\n : `${this.name} of ${value} is out of bounds`;\n }\n\n private handleTruthyLower = (args: ErrorMessageArgs) => {\n const { value, upper, lower } = args;\n this._message = upper != null\n ? `${this.name} must be between ${lower} and ${upper} but\\\n ${value} was given`\n : `${this.name} must be greater than or equal to ${lower}\\\n but ${value} was given`;\n }\n\n get message() {\n return this._message;\n }\n}\n</code></pre>\n\n<p>Even for void function calls.</p>\n\n<p>Hope it helps and any suggestions are welcome.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T07:37:43.063",
"Id": "476600",
"Score": "0",
"body": "Thanks a lot for the thorough answer. Commenting on each of your points:\n- 1: I think its arguable whether the additional type/interface are necessary. It is already pretty readable/understandable as is, due to adequate variable naming, and the type/interface seem like over engineering and unnecessary boilerplate. I would agree if it were the case that they were used in any other place in the app (except calls to this constructor), which they are not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T07:38:20.220",
"Id": "476601",
"Score": "0",
"body": "- 2: As you hinted at in point 5, the message property does come from AppError (in fact AppError inherits it from JS's Error Class), so I didn't need to define it as you described. \n- 3: I don't need to check for null, as I am trusting TS's type system to not allow null to be passed in to those properties (they are not nullable). Checking only for undefined makes this more explicit and makes possible bugs wherein null is somehow passed to this function not fail silently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T07:38:46.540",
"Id": "476602",
"Score": "0",
"body": "- 4: I agree with this point, and like the idea of reducing the depth level; it does indeed make it a lot easier to follow.\n- 5: As previously mentioned, the message comes from JS's Error class, and I don't see a good reason to interfere with its public access.\n- 6: I agree with this one. Given point number 4 and the creation of additional methods, I agree that the use of ternaries makes it cleaner. I will mention that without point 4, the double with two depth levels would be quite harder to follow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T07:39:16.320",
"Id": "476603",
"Score": "0",
"body": "Finally, even though I currently only agree with points 4 and 6, they really are quite useful to me. Thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-24T19:32:22.610",
"Id": "476661",
"Score": "0",
"body": "Edit to my comment that starts with -4: ...double TERNARY with two depth..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T00:26:16.007",
"Id": "242056",
"ParentId": "239486",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T05:35:37.683",
"Id": "239486",
"Score": "1",
"Tags": [
"typescript"
],
"Title": "A custom error to be thrown when numeric values are out of bounds"
}
|
239486
|
<p>I am a beginner and trying to send data from AWS DynamoDB to Azure Queues. Note that this code will be invoked <strong>10,000 and alot more</strong>. Can you guys review it once.</p>
<pre><code>using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;
using Amazon.DynamoDBv2.Model;
using Microsoft.Azure.ServiceBus;
using System.Threading.Tasks;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace Lambda
{
public class Function
{
private static readonly JsonSerializer _jsonSerializer = new JsonSerializer();
public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
{
context.Logger.LogLine($"Beginning to process {dynamoEvent.Records.Count} records...");
foreach (var record in dynamoEvent.Records)
{
context.Logger.LogLine($"Event ID: {record.EventID}");
context.Logger.LogLine($"Event Name: {record.EventName}");
string streamRecordJson = SerializeStreamRecord(record.Dynamodb);
await Send(streamRecordJson);
context.Logger.LogLine($"DynamoDB Record:");
context.Logger.LogLine(streamRecordJson );
}
context.Logger.LogLine("Stream processing complete.");
}
private static async Task Send(string stream)
{
const string connectionString = "QUEUE END POINT";
string queueName = "QUEUE NAME";
ServiceBusConnectionStringBuilder svc = new ServiceBusConnectionStringBuilder(connectionString);
ServiceBusConnection svc1 = new ServiceBusConnection(svc);
var client = new QueueClient(svc1, queueName, ReceiveMode.PeekLock, RetryPolicy.Default);
var message = new Message(Encoding.UTF8.GetBytes(stream));
await client.SendAsync(message);
}
private string SerializeStreamRecord(StreamRecord streamRecord)
{
using (var writer = new StringWriter())
{
_jsonSerializer.Serialize(writer, streamRecord);
return writer.ToString();
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>If the connection and queue name are not changing per record then there is no reason to be creating a new client for each record in the loop. Especially for the amount of times stated in the original post.</p>\n\n<p>Move that to the constructor of the class.</p>\n\n<pre><code>public class Function {\n private static readonly JsonSerializer _jsonSerializer = new JsonSerializer();\n private readonly IQueueClient client;\n private const string connectionString = \"QUEUE END POINT\";\n private const string queueName = \"QUEUE NAME\";\n\n public Function() { \n ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(connectionString);\n ServiceBusConnection connection = new ServiceBusConnection(builder);\n client = new QueueClient(connection, queueName, ReceiveMode.PeekLock, RetryPolicy.Default);\n }\n\n public async Task FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context) {\n var logger = context.Logger;\n logger.LogLine($\"Beginning to process {dynamoEvent.Records.Count} records...\");\n\n foreach (var record in dynamoEvent.Records) {\n logger.LogLine($\"Event ID: {record.EventID}\");\n logger.LogLine($\"Event Name: {record.EventName}\");\n\n string streamRecordJson = SerializeStreamRecord(record.Dynamodb);\n await SendAsync(streamRecordJson);\n\n logger.LogLine($\"DynamoDB Record:\");\n logger.LogLine(streamRecordJson);\n }\n\n context.Logger.LogLine(\"Stream processing complete.\");\n }\n\n private Task SendAsync(string body) {\n var message = new Message(Encoding.UTF8.GetBytes(body));\n return client.SendAsync(message);\n }\n\n private string SerializeStreamRecord(StreamRecord streamRecord) {\n using (var writer = new StringWriter()) {\n _jsonSerializer.Serialize(writer, streamRecord);\n return writer.ToString();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T00:42:17.190",
"Id": "470034",
"Score": "0",
"body": "Do you think I should make the azure client static? Or doing that will create issues?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T00:55:00.367",
"Id": "470035",
"Score": "0",
"body": "@Unbreakable I that case you would need to make the function constructor static as well to avoid overrides but I do not see that as being an issue."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:53:37.553",
"Id": "239531",
"ParentId": "239489",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239531",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T05:59:39.297",
"Id": "239489",
"Score": "2",
"Tags": [
"c#",
".net",
"amazon-web-services"
],
"Title": "Send Data from DynamoDB to Lambda (C#) and to Azure Queue"
}
|
239489
|
<p>For a long period of time I worked on this code, mostly trying to understand it. That is the main reason for needed review. Second reason is simply that I would like to optimize it in any way you can find.</p>
<p>Side note: <strong>I have shortened the code as humanly possible</strong>.</p>
<p>Compilation of the below code:</p>
<pre class="lang-sh prettyprint-override"><code>g++-8 -O2 -std=c++17 -Wall -Wextra -Werror -Wpedantic -pedantic-errors getPixelColor.cpp -o getPixelColor $(pkg-config --cflags --libs x11)
</code></pre>
<hr>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <X11/Xlib.h>
#include <cmath> // round()
// https://stackoverflow.com/a/59663458/1997354
inline __attribute__((always_inline)) \
unsigned long MyXGetPixel(XImage * ximage, const int & x, const int & y)
{
return (*ximage->f.get_pixel)(ximage, x, y);
}
void MyGetPixelColor(Display * my_display, const int & x_coord, const int & y_coord, XColor * pixel_color)
{
XImage * screen_image = XGetImage(
my_display,
XRootWindow(my_display, XDefaultScreen(my_display)),
x_coord, y_coord,
1, 1,
AllPlanes,
XYPixmap
);
pixel_color->pixel = MyXGetPixel(screen_image, 0, 0);
XFree(screen_image);
XQueryColor(my_display, XDefaultColormap(my_display, XDefaultScreen(my_display)), pixel_color);
}
// usage
int main()
{
Display * my_display = XOpenDisplay(NULL);
XColor screen_pixel_color;
// in this example let's take [0,0] coordinates
MyGetPixelColor(my_display, 0, 0, & screen_pixel_color);
XCloseDisplay(my_display);
unsigned short raw_r_value = screen_pixel_color.red;
unsigned short raw_g_value = screen_pixel_color.green;
unsigned short raw_b_value = screen_pixel_color.blue;
std::cout
<< "R = " << round(raw_r_value / 256.0) << std::endl
<< "G = " << round(raw_g_value / 256.0) << std::endl
<< "B = " << round(raw_b_value / 256.0) << std::endl;
}
</code></pre>
<hr>
<h2>Unshortened || full code</h2>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <X11/Xlib.h>
#include <cmath> // round()
//#include <cstring>
//#include <cstdlib>
//#include <gdk/gdk.h>
//#include <gtk/gtk.h>
//#include <X11/Xutil.h>
//#include </usr/include/gtk-3.0/gtk/gtk.h>
//#include <ncurses.h>
class BasicCoordinates
{
private:
long long X;
long long Y;
public:
BasicCoordinates(const long long & _X, const long long & _Y)
{
X = _X;
Y = _Y;
}
long long getX()
{
return X;
}
long long getY()
{
return Y;
}
};
bool StringContainsInteger(const std::string & str)
// true : if the string contains an integer number (possibly starting with a sign)
// false: if the string contains some other character(s)
{
std::string::size_type str_len = str.length();
if (str_len == 0) return false;
bool sign_present = (str[0] == '-' || str[0] == '+');
if (str_len == 1 && sign_present) return false;
for (std::string::size_type i = 0; i < str_len; i++)
{
if (i == 0 && sign_present) continue;
if (! std::isdigit((unsigned char) str[i])) return false;
}
return true;
}
// https://stackoverflow.com/a/59663458/1997354
inline __attribute__((always_inline)) \
unsigned long MyXGetPixel(XImage * ximage, const int & x, const int & y)
{
return (*ximage->f.get_pixel)(ximage, x, y);
}
void MyGetPixelColor(Display * my_display, const int & x_coord, const int & y_coord, XColor * pixel_color)
{
XImage * screen_image = XGetImage(
my_display,
XRootWindow(my_display, XDefaultScreen(my_display)),
x_coord, y_coord,
1, 1,
AllPlanes,
XYPixmap
);
pixel_color->pixel = MyXGetPixel(screen_image, 0, 0);
XFree(screen_image);
XQueryColor(my_display, XDefaultColormap(my_display, XDefaultScreen(my_display)), pixel_color);
}
int main(const int argc, const char * argv[])
{
const int given_arguments_count = argc - 1;
if (given_arguments_count != 2)
{
std::cerr
<< "Fatal error occurred while checking\n"
<< "the number of given arguments\n"
<< "--------------------------------------\n"
<< "In the function : " << __func__ << std::endl
<< "At the command : " << "given_arguments_count\n"
<< "Given arguments : " << given_arguments_count << std::endl
<< "Error message : " << "This program is expecting exactly 2 arguments\n"
<< " being the X Y coordinates of a pixel on the screen\n";
return 1;
}
const std::string cli_argument_1 = argv[1];
if (! StringContainsInteger(cli_argument_1))
{
std::cerr
<< "Fatal error occurred while checking\n"
<< "if the first argument contains a number\n"
<< "----------------------------------------\n"
<< "In the function : " << __func__ << std::endl
<< "At the command : " << "StringContainsInteger\n"
<< "Input string : " << cli_argument_1 << std::endl
<< "Error message : " << "The first argument is not an integer number\n";
return 1;
}
const std::string cli_argument_2 = argv[2];
if (! StringContainsInteger(cli_argument_2))
{
std::cerr
<< "Fatal error occurred while checking\n"
<< "if the second argument contains a number\n"
<< "----------------------------------------\n"
<< "In the function : " << __func__ << std::endl
<< "At the command : " << "StringContainsInteger\n"
<< "Input string : " << cli_argument_2 << std::endl
<< "Error message : " << "The second argument is not an integer number\n";
return 1;
}
long long x_coord;
try
{
x_coord = std::stoll(cli_argument_1);
}
catch (const std::exception & input_exception)
{
std::cerr
<< "Fatal error occurred while converting\n"
<< "the first argument to an integer variable\n"
<< "-------------------------------------\n"
<< "In the function : " << __func__ << std::endl
<< "At the command : " << input_exception.what() << std::endl
<< "Input string : " << cli_argument_1 << std::endl
<< "Error message : " << "The first number argument is too big an integer\n";
return 1;
}
long long y_coord;
try
{
y_coord = std::stoll(cli_argument_2);
}
catch (const std::exception & input_exception)
{
std::cerr
<< "Fatal error occurred while converting\n"
<< "the second argument to an integer variable\n"
<< "--------------------------------------\n"
<< "In the function : " << __func__ << std::endl
<< "At the command : " << input_exception.what() << std::endl
<< "Input string : " << cli_argument_2 << std::endl
<< "Error message : " << "The second number argument is too big an integer\n";
return 1;
}
BasicCoordinates * pixel_coords = new BasicCoordinates(x_coord, y_coord);
std::cout << "X = " << pixel_coords->getX() << std::endl;
std::cout << "Y = " << pixel_coords->getY() << std::endl << std::endl;
Display * my_display = XOpenDisplay(NULL);
Screen * my_screen = XDefaultScreenOfDisplay(my_display);
const int screen_width = my_screen->width;
const int screen_height = my_screen->height;
if (x_coord >= screen_width)
{
std::cerr
<< "X coord bigger than the screen with\n"; // TEMP
return 1;
}
if (y_coord >= screen_height)
{
std::cerr
<< "Y coord bigger than the screen height\n"; // TEMP
return 1;
}
XWindowAttributes root_window_attributes;
XGetWindowAttributes(my_display, DefaultRootWindow(my_display), & root_window_attributes);
XColor screen_pixel_color;
MyGetPixelColor(my_display, x_coord, y_coord, & screen_pixel_color);
XCloseDisplay(my_display);
unsigned short raw_r_value = screen_pixel_color.red;
unsigned short raw_g_value = screen_pixel_color.green;
unsigned short raw_b_value = screen_pixel_color.blue;
/*
std::cout
<< "Raw Values" << std::endl
<< "R = " << raw_r_value << std::endl
<< "G = " << raw_g_value << std::endl
<< "B = " << raw_b_value << std::endl;
std::cout << std::endl;
*/
std::cout
// << "Normalized" << std::endl
<< "R = " << round(raw_r_value / 256.0) << std::endl
<< "G = " << round(raw_g_value / 256.0) << std::endl
<< "B = " << round(raw_b_value / 256.0) << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T07:56:20.493",
"Id": "469711",
"Score": "0",
"body": "Have you written this code yourself? There are indications in your question that you dont understand the code, even just to a degree. This would be off topic on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T08:07:53.343",
"Id": "469713",
"Score": "0",
"body": "@slepic I just partially copied and modified the MyGetPixelColor function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T17:52:04.913",
"Id": "469805",
"Score": "0",
"body": "For Code Review, you're not supposed to shorten your code. You're supposed to keep it understandable and readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T07:14:49.267",
"Id": "469854",
"Score": "0",
"body": "@S.S.Anne Full code added.."
}
] |
[
{
"body": "<h1>Use <code>XGetPixel()</code> instead of writing your own function</h1>\n\n<p>You should use the API provided to you by X libraries whenever possible. The implementation details might change over time, so your own copy of <code>XGetPixel()</code> might no longer be correct in the future. Granted, this is very unlikely in the case of Xlib, but it is good practice in general.</p>\n\n<h1>Don't pass by const reference unnecessarily</h1>\n\n<p>Don't pass small variables by const reference. You typically only do this for non-trivial types where the cost of passing by value is larger than passing by reference, for example <code>std::string</code>, <code>std::vector</code> and so on. You should never need a const reference for something like an <code>int</code>, <code>float</code> and so on. So:</p>\n\n<pre><code>void MyGetPixelColor(Display *my_display, int x_coord, int y_coord, XColor *pixel_color)\n{ ... }\n</code></pre>\n\n<h1>Return by value when appropriate</h1>\n\n<p>Functions that return some value should preferably <code>return</code> that value, instead of taking a pointer that will be written to. So I would rewrite your code to:</p>\n\n<pre><code>Xcolor MyGetPixelColor(Display *my_display, int x_coord, int y_coord)\n{\n Xcolor pixel_color;\n XImage *screen_image = ...;\n pixel_color->pixel = XGetPixel(screen_image, 0, 0);\n XFree(screen_image);\n XQueryColor(my_display, XDefaultColormap(my_display, XDefaultScreen(my_display)), pixel_color);\n\n return pixel_color;\n}\n</code></pre>\n\n<p>This doesn't cause extra copies of <code>Xcolor</code> to be made, since C++ compilers will use return value optimization here.</p>\n\n<h2>Use <code>\\n</code> instead of <code>std::endl</code></h2>\n\n<p>Avoid using <code>std::endl</code>, it is equivalent to <code>\\n</code> but it will also flush the output, which can hurt performance. See <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">this question</a> for more details.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:59:27.610",
"Id": "239514",
"ParentId": "239490",
"Score": "1"
}
},
{
"body": "<p>This class is much more complicated than it needs to be:</p>\n\n<blockquote>\n<pre><code>class BasicCoordinates\n{\nprivate:\n long long X;\n long long Y;\n\npublic:\n BasicCoordinates(const long long & _X, const long long & _Y)\n {\n X = _X;\n Y = _Y;\n }\n long long getX()\n {\n return X;\n }\n long long getY()\n {\n return Y;\n }\n\n};\n</code></pre>\n</blockquote>\n\n<p>A simple aggregate does the job and is more intuitive:</p>\n\n<pre><code>struct Coordinates {\n long long x;\n long long y;\n};\n</code></pre>\n\n<hr>\n\n<p>This function is also quite convoluted:</p>\n\n<blockquote>\n<pre><code>bool StringContainsInteger(const std::string & str)\n// true : if the string contains an integer number (possibly starting with a sign)\n// false: if the string contains some other character(s)\n{\n std::string::size_type str_len = str.length();\n if (str_len == 0) return false;\n\n bool sign_present = (str[0] == '-' || str[0] == '+');\n if (str_len == 1 && sign_present) return false;\n\n for (std::string::size_type i = 0; i < str_len; i++)\n {\n if (i == 0 && sign_present) continue;\n if (! std::isdigit((unsigned char) str[i])) return false;\n }\n\n return true;\n}\n</code></pre>\n</blockquote>\n\n<p>which is basically just:</p>\n\n<pre><code>bool StringContainsInteger(std::string_view str)\n{\n // C++20: str.starts_with('+') || str.starts_with('-')\n if (!str.empty() && (str[0] == '+' || str[0] == '-')) {\n str.remove_prefix(1);\n }\n return std::all_of(str.begin(), str.end(),\n [](unsigned char c) { return std::isdigit(c); });\n}\n</code></pre>\n\n<p>(note that <code>std::string_view</code> is preferable to <code>const std::string&</code> if all you want is read the characters in the string).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:30:14.653",
"Id": "469921",
"Score": "0",
"body": "I think StringContainsInteger is redundant anyway, one can use the second argument to [`std::stoll()`](https://en.cppreference.com/w/cpp/string/basic_string/stol) to check whether all characters in the string have been processed, and only accept the result if that is the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T02:24:43.700",
"Id": "469962",
"Score": "0",
"body": "@G.Sliepen Yes. It's better to use that directly since OP is calling `stoll` immediately after validating the string."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T08:51:48.847",
"Id": "239549",
"ParentId": "239490",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239549",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T06:03:01.007",
"Id": "239490",
"Score": "2",
"Tags": [
"c++",
"beginner",
"linux",
"c++17",
"x11"
],
"Title": "Get pixel color from screen in C++ on Linux"
}
|
239490
|
<p>I made this simple program that can solve every set of linear equations in two variables.</p>
<p>You just need to enter two linear equations of the form ax+by=c (without any unnecessary spaces) where 'a' is a positive integer (i.e. x should not have a negative coefficient) and b and c are just integers.</p>
<p>The program can also show outputs like "The two equations have no solution" or "the two equations have infinite solutions" if it is so...</p>
<p>I only used the knowledge of 9th and 10th grade Python along with the concept of functions to make this program and I will update it on the basis of the suggestions that I got from some great people in my last question. I will try to make it shorter, more readable and definitely more efficient soon, will post that too when done.</p>
<p>Here's the Python code :</p>
<pre><code>def getindex(a,b):
size = len(b)
status = 0
for i in range(0,size,1):
element = b[i]
if (element == a):
index = i
status = 1
break
if (status == 1):
return index
else:
return "not found"
def getstring(a,b,c):
string = c[a]
for i in range(a+1,b,1):
element = c[i]
string = string + element
return string
def lcm(a,b):
found = False
if (a>b):
larger = a
else:
larger = b
i = larger
while found == False:
if (i%a == 0) and (i%b == 0):
found = True
break
else:
i += larger
return i
print ()
print ("Please enter two equations of the form ax+by=c where a is a positive integer and b and c are integers...")
print ()
a = str(input("Please enter the first equation : "))
b = str(input("Please enter the second equation : "))
a = list(a)
b = list(b)
sizea = len(a)
sizeb = len(b)
# Getting a, b and c of equation one
symbolindexone = getindex('+',a)
equalindexone = getindex('=',a)
symbolstatusone = "positive"
if (symbolindexone == "not found"):
symbolindexone = getindex('-',a)
symbolstatusone = "negative"
xindexone = getindex('x',a)
yindexone = getindex('y',a)
a1 = getstring(0,xindexone,a)
if (a1 == 'x'):
a1 = 1
else:
a1 = int(a1)
b1 = getstring(symbolindexone+1,yindexone,a)
if (b1 == 'y'):
if (symbolstatusone == 'positive'):
b1 = 1
else:
b1 = -1
else:
b1 = int(b1)
if (symbolstatusone == "negative"):
b1 = -b1
c1 = getstring(equalindexone+1,sizea,a)
c1 = int(c1)
# getting a, b and c of equation two
symbolindextwo = getindex('+',b)
equalindextwo = getindex('=',b)
symbolstatustwo = 'positive'
if (symbolindextwo == 'not found'):
symbolindextwo = getindex('-',b)
symbolstatustwo = 'negative'
xindextwo = getindex('x',b)
yindextwo = getindex('y',b)
a2 = getstring(0,xindextwo,b)
if (a2 == 'x'):
a2 = 1
else:
a2 = int(a2)
b2 = getstring(symbolindextwo+1,yindextwo,b)
if (b2 == 'y'):
if (symbolstatustwo == 'positive'):
b2 = 1
else:
b2 = -1
else:
b2 = int(b2)
if (symbolstatustwo == 'negative'):
b2 = -b2
c2 = getstring(equalindextwo+1,sizeb,b)
c2 = int(c2)
# LCM and the final phase
lcma = lcm(a1,a2)
tmbone = lcma/a1
tmbtwo = lcma/a2
a1 *= tmbone
b1 *= tmbone
c1 *= tmbone
a2 *= tmbtwo
b2 *= tmbtwo
c2 *= tmbtwo
ratioa = a1/a2
ratiob = b1/b2
ratioc = c1/c2
print ()
if (ratioa == ratiob == ratioc):
print ("The equations that you entered have infinite solutions...")
elif ((ratioa == ratiob) and (ratioa != ratioc)):
print ("The equations that you entered have no solution...")
else:
ysolution = (c1-c2)/(b1-b2)
xsolution = ((c1)-(b1*ysolution))/(a1)
print ("The value of x is : ",xsolution)
print ("The value of y is : ",ysolution)
</code></pre>
<p>Let me know what you think</p>
<p>Thanks :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:10:39.557",
"Id": "469730",
"Score": "0",
"body": "Do you want to use built-in functions or not? There are functions in the Python library for `get_index` and `getstring`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:17:38.450",
"Id": "469734",
"Score": "0",
"body": "@DaniMesejo Of course I do but I don't have much knowledge about Python (yet), it hasn't even been one year since I began Python. The reason I began posting programs here is because I want to learn how I can make the program more efficient and I just found out yesterday about the built-in functions, I'm gonna use them in the other programs as soon as I learn more about them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:27:49.553",
"Id": "469738",
"Score": "0",
"body": "What is the function lcm suppose to do? Least Common Multiple?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:55:04.510",
"Id": "469743",
"Score": "0",
"body": "Yes, the program finds the coefficients of x in both the equations, finds the LCM, and then calculates how much to multiply both the equations by in order to equalize the coefficients of x so that it can eliminate x by subtracting the new equations and find the value of y. It then substitutes the value of y in one of the equations to find the value of x."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:09:33.153",
"Id": "469747",
"Score": "0",
"body": "Shouldn't the LCM greater that both numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:23:59.750",
"Id": "469751",
"Score": "0",
"body": "Oh, wait, something's wrong, but the program is working fine. I'll change the LCM function, thanks for pointing out..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:43:05.317",
"Id": "469760",
"Score": "0",
"body": "@DaniMesejo Fixed now...:)"
}
] |
[
{
"body": "<p>Some comments:</p>\n\n<ol>\n<li>Rename functions to follow the PEP8 naming convention, <a href=\"https://www.python.org/dev/peps/pep-0008/#id45\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>Do not use range to iterate over the a list of elements, iterate directly over it. If you need the index, as in your case, use <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\">enumerate</a>.</li>\n<li>No need to wrap the boolean clauses in parenthesis, moreover you can use the truth(y) values directly, see <a href=\"https://docs.python.org/3/library/stdtypes.html#truth-value-testing\" rel=\"nofollow noreferrer\">truth value testing</a>.</li>\n<li>Is possible add comments on what does the function does.</li>\n</ol>\n\n<p>After a first rewrite the code of your function should look something like this:</p>\n\n<pre><code>def get_index(a, b):\n \"\"\"Get the index of and element or else return 'not found' \"\"\"\n status = 0\n index = 0\n for i, element in enumerate(b):\n if element == a:\n index = i\n status = 1\n break\n if status:\n return index\n else:\n return \"not found\"\n\n\ndef get_string(a, b, c):\n \"\"\"Build a sub-string from c starting on a\"\"\"\n string = c[a]\n for i in range(a + 1, b, 1):\n element = c[i]\n string = string + element\n return string\n\n\ndef lcm(a, b):\n \"\"\"Find the least common multiple\"\"\"\n if a > b:\n larger = a\n else:\n larger = b\n i = larger\n while True:\n if (i % a == 0) and (i % b == 0):\n break\n else:\n i += larger\n return i\n\n\nif __name__ == \"__main__\":\n assert get_index(1, [1, 2, 3]) == 0\n assert get_index(1, [2, 3]) == \"not found\"\n assert get_string(0, 3, \"hello world\") == \"hel\"\n assert lcm(2, 5) == 10\n</code></pre>\n\n<p>I added some (basic) test, to validate any further change you could make in the future to this functions. </p>\n\n<p>The above comments are superficial, if you want speed and reliability use the functions provided by the standard library, in the end your functions should look like something like this:</p>\n\n<pre><code>from math import gcd\n\n\ndef get_index(a, b):\n \"\"\"Get the index of and element or else return 'not found' \"\"\"\n try:\n return b.index(a)\n except ValueError:\n return \"not found\"\n\n\ndef get_string(a, b, c):\n \"\"\"Build a sub-string from c starting on a\"\"\"\n return c[a:b]\n\n\ndef lcm(a, b):\n \"\"\"Find the least common multiple\"\"\"\n return abs(a * b) // gcd(a, b)\n</code></pre>\n\n<p>The <code>lcm</code> implementation uses the <code>gcd</code>, see more in the wikipedia <a href=\"https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor\" rel=\"nofollow noreferrer\">page</a>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T16:59:24.767",
"Id": "469796",
"Score": "1",
"body": "Thanks, awesome suggestions, I actually thought about the gcd method, because product of numbers = lcm*hcf but when I wrote the code, I found it to be even longer. Didn't know gcd was an in-built function, thanks for letting me know..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:06:43.100",
"Id": "239505",
"ParentId": "239493",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239505",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T07:10:56.260",
"Id": "239493",
"Score": "1",
"Tags": [
"python",
"beginner",
"mathematics"
],
"Title": "Linear Equation in Two Variables Solver using Python"
}
|
239493
|
<p>This is the first time that I have tried programming in such a general way using <code>c++</code>. I have tackled this pattern before in other languages such as <code>golang</code>, but this is my first attempt with cpp.</p>
Subscriber template
<pre><code>// class template for a subscriber that wishes to be informed of the
// occurrence of a particular event; the template parameter event type
// is the event of particular interest
template <typename EventType>
struct Subscriber {
virtual ~Subscriber() = default;
// default implementation of the event callback function
// not sure if it should be a pure virtual (for the compilation error notification)
// also possibly thinking about changing the signature to return a boolean
virtual void OnEventReceived(const EventType&) {};
};
</code></pre>
Container template
<pre><code>// class template for a subscribers container; the template parameter
// subscriber type is a subscriber of some event type (i.e. some object
// that would like to be notified when some event is triggered)
template <typename SubscriberType>
struct Subscribers {
protected:
// function template for the _attach method which expects
// a reference to a subscriber of some event; the subscriber
// will be added to the pool of subscribers
template <typename EventSubscriber>
void _attach(EventSubscriber& s) {
subscribers_.emplace_back(
std::reference_wrapper<EventSubscriber>(s)
);
}
// function template for the _detach method which expects
// a reference to a subscriber of some event; the subscriber
// will be removed from the pool of subscribers
template <typename EventSubscriber>
void _detach(EventSubscriber& s) {
// erase-remove idiom
subscribers_.erase(
std::remove_if(
subscribers_.begin(),
subscribers_.end(),
// mixed feelings about this
[&s](auto i) { return &i.get() == &s; }
),
subscribers_.end()
);
}
// function template for the _publish method which expects
// a const reference to an event of some type; the subscribers
// will be notified of the event trigger via their callback
// implementation
template <typename EventType>
void _publish(const EventType& e) {
for (auto s : subscribers_)
s.get().OnEventReceived(e);
}
private:
// using std::reference_wrapper since the subscribers are not owned by
// the subscribers container, it is merely keeping a pointer to them in
// order to notify of event occurrences
std::vector<std::reference_wrapper<SubscriberType>> subscribers_;
};
</code></pre>
Publisher template
<pre><code>// class template for an event publisher object; the template parameter
// event types is variadic so that the publisher instance may publish
// multiple type of events. The multiple inheritance extends the publisher
// to have a subscribers container for the specified event types.
template <typename... EventTypes>
struct Publisher : public Subscribers< Subscriber<EventTypes> >... {
// function template for the Attach method which expects an event type
// and a reference to some subscriber object that would like register
// for notification of the event type in question
template <typename EventType, typename EventSubscriber>
void Attach(EventSubscriber &s) {
this->Subscribers< Subscriber<EventType> >::_attach(s);
}
// function template for the Detach method which expects an event type
// and a reference to some subscriber object that would like unregister
// notifications of the event type in question
template <typename EventType, typename EventSubscriber>
void Detach(EventSubscriber &s) {
this->Subscribers< Subscriber<EventType> >::_detach(s);
}
// function template for the Publish method which expects a const reference
// to some type of event that will be broadcast to the currently registered
// subscribers of the event type in question
template <typename EventType>
void Publish(const EventType& e) {
this->Subscribers< Subscriber<EventType> >::_publish(e);
}
};
</code></pre>
includes / compilation / questions
<pre><code>#include <vector>
#include <algorithm>
#include <functional>
// compilation
// g++ -std=c++17 main.cpp -o main
// Question 1:
// should the default implementation of the event callback function stay or
// should be a pure virtual (for the compilation error notification)
// Question 2:
// should attach and detach interfaces be changed to variadic? if so then should
// the recursion take place in Publisher template or the Container template?
// Question 3:
// how to break this up into headers and implementation to maintain a need to
// know basis with other code?
// Question 4:
// thread safety? My assumption is to use mutex in the attach detach methods.
</code></pre>
Driver Code
<p>This is just some example usage to see it working not really representative of a particular direction. </p>
<pre><code>#include <iostream>
struct Event1 {
int x, y;
void print(std::ostream& os) const {
os << x << ' ' << y << '\n';
}
};
struct Event2 {
int a, b, c;
void print(std::ostream& os) const {
os << a << ' ' << b << ' ' << c << '\n';
}
};
struct SubOne : Subscriber<Event1>, Subscriber<Event2> {
void OnEventReceived(const Event2& e) override final {
e.print(std::cout);
};
void OnEventReceived(const Event1& e) override final {
e.print(std::cout);
};
};
int main(int argc, char** argv) {
Publisher<Event1, Event2> ePub{};
SubOne s1{};
SubOne s2{};
Event1 e1{2,3};
Event2 e2{30,21,55};
ePub.Attach<Event1>(s1);
ePub.Attach<Event1>(s2);
ePub.Attach<Event2>(s1);
ePub.Attach<Event2>(s2);
ePub.Publish(e1);
ePub.Publish(e2);
ePub.Detach<Event1>(s1);
ePub.Publish(e1);
return 0;
}
</code></pre>
<p>Love to hear any feedback, even outside of the scope the questions section.</p>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n\n<blockquote>\n <p>Should the default implementation of the event callback function stay or should be a pure virtual?</p>\n</blockquote>\n\n<p>There is no point in using the base class itself, so it's better to make it pure virtual. This way, bugs in the code where a base class is instantiated by accident are then caught by the compiler.</p>\n\n<blockquote>\n <p>Should attach and detach interfaces be changed to variadic? If so then should the recursion take place in Publisher template or the Container template?</p>\n</blockquote>\n\n<p>Since you are asking, the answer is most likely no. If you have no real need for variadic interfaces, I would keep things simple.</p>\n\n<blockquote>\n <p>How to break this up into headers and implementation to maintain a need to know basis with other code?</p>\n</blockquote>\n\n<p>It makes sense to have at least a <code>publisher.hpp</code> and a <code>subscriber.hpp</code>, since the various components of your application will need at least one of those two things. As it is now, the code is small enough that I would not split it further.</p>\n\n<blockquote>\n <p>Thread safety? My assumption is to use mutex in the attach detach methods.</p>\n</blockquote>\n\n<p>If you do that, you also need to lock the mutex in the publish method, since it will be iterating over the list of subscribers. But yes, if you expect that you will attach, detach and publish from different threads, I would certainly add mutexes.</p>\n\n<h1>Code review</h1>\n\n<p>The code is quite simple, and if it does exactly what you need, then it's already nice code. I just have these remarks:</p>\n\n<h2>Merge the <code>Subscribers</code> class into <code>Publisher</code></h2>\n\n<p>There is no good reason to have a separate class <code>Subscribers</code>, that just takes care of attaching and detaching, and then have <code>Attach()</code> and <code>Detach()</code> methods in <code>Publisher</code> that just wrap the methods from <code>Subscribers</code>.</p>\n\n<p>It would be different if you plan to be able to attach and detach multiple publishers to a given event type. Then you would want to have a separate class that represents the event queue where both publishers and subscribers can connect to.</p>\n\n<h2>Avoid names starting with underscores</h2>\n\n<p>Names starting with underscores are by convention reserved for the standard library. There are some exceptions, but it is best to just not use such names yourself.</p>\n\n<p>In most cases, it's not necessary at all. Why make a protected function named <code>_attach()</code>, when it is explicitly marked <code>protected</code> in the class definition?</p>\n\n<h2>Don't write <code>this-></code> unnecessarily</h2>\n\n<p>It's almost never necessary to write <code>this-></code> in C++. In the case of <code>Attach()</code> for example, you can just write:</p>\n\n<pre><code>void Attach(EventSubscriber &s) { \n Subscribers<Subscriber<EventType>>::_attach(s); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T17:53:43.017",
"Id": "469806",
"Score": "0",
"body": "Thanks for the feedback, I just wanted to address the explicit use of this->, really to get some clarification. I was reading a blog discussing the use of CRTP, which I don't know if I fully grasped the concept. But it mentioned that the was no guarantees when the template becomes specialized, so using this-> was a mechanism for ensuring functionality."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T21:31:37.133",
"Id": "469819",
"Score": "0",
"body": "Hm, I'm not sure about this. Your code seems to compile fine without `this->`, and I don't think you actually want to allow the code to compile when you create a specialization of `Subscribers` that doesn't have the `attach()` member function. But I'm not a language lawyer, maybe someone else can comment on this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:07:22.607",
"Id": "469826",
"Score": "0",
"body": "Lol language lawyer. I think you are right I didn't realize that the specialization of `Subscribers` would be the template where the issue would stem from. Yeah there isn't a use case at least that I can see now where one would need to create a specialization of `Subscribers`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:33:28.930",
"Id": "239513",
"ParentId": "239494",
"Score": "2"
}
},
{
"body": "<h1>Code Changes</h1>\n\n<p>Following the advice given, I have made the following changes.</p>\n\n<p><code>Base Subscriber Template</code></p>\n\n<p>The base callback method has been change to a pure virtual function. </p>\n\n<pre><code>virtual void OnEventReceived(const EventType&) = 0;\n</code></pre>\n\n<p><code>Container Template</code></p>\n\n<p>All the protected methods had the underscore prefix removed from the template function name.</p>\n\n<pre><code>void attach(EventSubscriber& s) { ... }\nvoid detach(EventSubscriber& s) { ... }\nvoid publish(const EventType& e) { ... }\n</code></pre>\n\n<p><code>Publisher Template</code></p>\n\n<p>Both the Attach and Detach method interfaces were changed to variadic template parameters and function parameters, and all methods had <code>this-></code> removed.</p>\n\n<pre><code>template <\n typename EventType,\n typename... MultiEvent,\n typename EventSubscriber,\n typename... MultiSubscriber\n>\nvoid Attach(EventSubscriber& s, MultiSubscriber&... ms) {\n Subscribers<Subscriber<EventType>>::attach(s);\n\n if constexpr (sizeof...(ms))\n Attach<EventType>(ms...);\n\n if constexpr (sizeof...(MultiEvent))\n Attach<MultiEvent...>(s, ms...);\n}\n\ntemplate <\n typename EventType,\n typename... MultiEvent,\n typename EventSubscriber,\n typename... MultiSubscriber\n>\nvoid Detach(EventSubscriber& s, MultiSubscriber&... ms) {\n Subscribers<Subscriber<EventType>>::detach(s);\n\n if constexpr (sizeof...(ms)) \n Detach<EventType>(ms...);\n\n if constexpr (sizeof...(MultiEvent))\n Detach<MultiEvent...>(s, ms...);\n}\n</code></pre>\n\n<p>This opens up a wide range of combinations in the user interface such as:</p>\n\n<pre><code>publisher.Attach<Event1, Event2>(sub1, sub2);\npublisher.Detach<Event1, Event2>(sub2);\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T23:51:20.090",
"Id": "239534",
"ParentId": "239494",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239513",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T08:12:29.877",
"Id": "239494",
"Score": "2",
"Tags": [
"c++",
"template",
"event-handling"
],
"Title": "Publisher Subscriber Pattern Template"
}
|
239494
|
<p>This is a program that can decrypt the codes that have been encrypted using the algorithm that <a href="https://codereview.stackexchange.com/questions/239442/a-simple-encryption-program-using-python">my previously posted encryption program</a> follows, you just need to enter the encrypted text from that program.</p>
<p>I got a lot of suggestions from people on the encryption post, I have tried to make this program as short as possible (in my efforts), I did not use the method they suggested to shorten functions because I don't want to use it without understanding how it works, I will implement it in my further programs as soon as I understand it...</p>
<p>Thank You for the suggestions on the previous program, it helped me reduce the length of this program by 16 lines.</p>
<p>Please let me know what you think about this program</p>
<p>Python Code :</p>
<pre><code>alphabets = 'abcdefghijklmnopqrstuvwxyz'
def position_in_alphabets(tofind):
for i in range(0,26):
if tofind == alphabets[i]:
position = i+1
break
return position
def decrypt(a):
output = ''
for i in range(0,len(a)):
character = a[i]
z = i+1
y = position_in_alphabets(character)
x = z+y-26
if x>len(alphabets):
x = x % len(alphabets)
alpha = alphabets[x-1]
output += alpha
return output
print ()
print ("NOTE : Please enter just lowercase characters (no special characters) and no spaces")
print ()
given = input("Please enter the word to be decrypted : ")
output = decrypt(given)
print ()
print ("The word which is coded as ",given," is : ",output)
</code></pre>
<p>Thank You :)</p>
|
[] |
[
{
"body": "<h1>Use built in methods!</h1>\n\n<p>Your <code>position_in_alphabets</code> function can be reduced to one line. In fact, replace <code>y = ...</code> with the following:</p>\n\n<pre><code>alphabets.index(character) + 1\n</code></pre>\n\n<p><a href=\"https://www.programiz.com/python-programming/methods/string/index\" rel=\"nofollow noreferrer\"><code>index</code></a> returns the first occurrence of the character in question. Since you're working with the alphabet, it will return the position of the character in that string. Then you just need to add one.</p>\n\n<h1>Never trust user input</h1>\n\n<p>Instead of trusting the user will only enter lowercase characters after telling them to do so, call <code>.lower()</code> on the <code>input</code> to change the string to all lowercase letters.</p>\n\n<p><hr>\n<em>I'm going to step through each line of the main function now.</em></p>\n\n<hr>\n\n<h1>f\"\" strings</h1>\n\n<p>I would use <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f\"\"</code></a> strings so you can directly format your variables in your strings. In this case, it reduces the clutter that <code>print(\"...\", var, \"...\", var, \"...\")</code> causes. It would instead be <code>print(f\"... {var} ... {var} ...\")</code>.</p>\n\n<h1>Naming conventions (<a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">PEP 8</a>)</h1>\n\n<p><code>a</code> isn't really a good parameter name. A variable/parameter name should represent what that variable is holding or is doing. I would use <code>string</code>, since you're working with them in this program.</p>\n\n<pre><code>def decrypt(string):\n</code></pre>\n\n<h1>Use enumerate</h1>\n\n<p><a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate</code></a> allows you to work through an iterable with the index and the value at that position in the iterable. It gets rid of having to <code>iterable[i]</code> and all that junk.</p>\n\n<pre><code>output = ''\nspaces = 0\nfor index, character in enumerate(string):\n</code></pre>\n\n<h1>Allowing spaces</h1>\n\n<p>Spaces are really easy to deal with. If the character is a space, simply add <code>\" \"</code> to the output and <a href=\"https://docs.python.org/3/reference/simple_stmts.html#continue\" rel=\"nofollow noreferrer\"><code>continue</code></a>, quite literally, to the next iteration.</p>\n\n<pre><code>if character == \" \":\n output += \" \"\n spaces += 1\n continue\n</code></pre>\n\n<h1>Compress your computations</h1>\n\n<p>Instead of having a bunch of one character variable names <code>x</code>, <code>y</code>, <code>z</code>, I would do all the computations in one step and assign them to a variable. I've done so, and used <code>position</code>, because that's what you're calculating.</p>\n\n<pre><code>position = (index + 1) + (alphabet.index(character) + 1) - 26\n</code></pre>\n\n<h1>Simplify your reassignments</h1>\n\n<p>Have a look at this:</p>\n\n<pre><code>if position > len(alphabet):\n position %= len(alphabet)\n</code></pre>\n\n<p>It's the same thing as <code>position = position % len(alphabet)</code>, but shorter (also called in place modulus). It also works for the other operators (<code>+-*/</code>).</p>\n\n<h1>Don't make variables you don't need</h1>\n\n<p>The sole purpose of <code>alpha</code> is to hold the value at the passed position in <code>alphabet</code>, then you add alpha to <code>output</code>. How about you just skip the first step and add it right to <code>output</code>?</p>\n\n<pre><code>output += alphabet[position - 1]\n</code></pre>\n\n<hr>\n\n<p>All in all, your final program looks like this:</p>\n\n<pre><code>alphabet = 'abcdefghijklmnopqrstuvwxyz'\n\ndef decrypt(string: str) -> str:\n output = ''\n spaces = 0\n for index, character in enumerate(string):\n if character == \" \":\n output += \" \"\n spaces += 1\n continue\n position = (index + 1) + (alphabet.index(character) + 1) - len(alphabet)\n if position > len(alphabet):\n position %= len(alphabet)\n output += alphabet[position - 1 - spaces]\n return output\n\nword = input(\"Please enter the word to be decrypted: \").lower()\noutput = decrypt(word)\nprint(f\"The word '{word}' decrypted is '{output}'\")\n</code></pre>\n\n<p>We use <code>spaces</code> to shift the index back for every space we've encountered.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T10:16:02.973",
"Id": "469722",
"Score": "0",
"body": "Thanks, it was really helpful, but there's one problem, the addition of the space feature interferes with the output, like the output for 'zzzz' is 'abcd', and if the user enters 'zz zz', then shouldn't the output be 'ab cd' instead of 'ab de' as it does in the version that you gave? I want a method in which the value of i does not increase by one when the character is [spcae], so we can count the number of spaces found and then reduce the value of i by the number of spaces...that should work, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T10:18:31.483",
"Id": "469723",
"Score": "0",
"body": "And that would require a counter, too, so what should I do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T10:25:00.080",
"Id": "469726",
"Score": "0",
"body": "I figured it out, we can create a variable number_of_spaces, let's say and every time the character is a space, we can increase the variable by one, and then change the second-last statement of decrypt() to : output+=alphabets[position-1-number_of_spaces], it works, now the output for \"zz zz\" is \"ab cd\", Thanks for the review"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T10:56:37.187",
"Id": "469728",
"Score": "1",
"body": "@Rajdeep_Sindhu I missed that, thanks for catching it. The code has been updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:43:00.297",
"Id": "469790",
"Score": "0",
"body": "I would have add type annotations @Linny . Great answer tho!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:35:57.223",
"Id": "239499",
"ParentId": "239495",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "239499",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T08:15:10.230",
"Id": "239495",
"Score": "5",
"Tags": [
"python",
"beginner",
"algorithm"
],
"Title": "A simple Decryption Program using Python"
}
|
239495
|
<p>I often see very long code lines like this:</p>
<pre><code><input type="email" name="email" autocomplete="email" id="email_address" value="<?= $block->escapeHtmlAttr($block->getFormData()->getEmail()) ?>" title="<?= $block->escapeHtmlAttr(__('Email')) ?>" class="input-text" data-mage-init='{"mage/trim-input":{}}' data-validate="{required:true, 'validate-email':true}">
</code></pre>
<p>Is it ok to break them down like:</p>
<pre><code><input type="email"
name="email"
autocomplete="email"
id="email_address"
value="<?= $block->escapeHtmlAttr($block->getFormData()->getEmail()) ?>"
title="<?= $block->escapeHtmlAttr(__('Email')) ?>"
class="input-text"
data-mage-init='{"mage/trim-input":{}}'
data-validate="{required:true, 'validate-email':true}"
>
</code></pre>
<p>Because this makes it much clearer and easier to read in my opinion.</p>
<p>I usually do this if there are more than about 80-100 chars.</p>
<hr>
<p>Validation with <a href="https://validator.w3.org/" rel="nofollow noreferrer">https://validator.w3.org/</a></p>
<p><a href="https://i.stack.imgur.com/2fyFn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2fyFn.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:07:38.973",
"Id": "469714",
"Score": "3",
"body": "Does it still work? Do HTML validators have a problem with it? If the first is a yes and the second a no, I'd recommend breaking it up over the original long line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T09:12:51.483",
"Id": "469716",
"Score": "0",
"body": "@Mast, yes it still works and it validates correctly. I think this answers the question :) Thank you!"
}
] |
[
{
"body": "<p>I'd already answered this in the comments (which I shouldn't, we got answer fields for this), but anyway...</p>\n<blockquote>\n<p>Because this makes it much clearer and easier to read in my opinion.</p>\n</blockquote>\n<p>Absolutely. And that's a good reason to do it. Your 80-100 character limit makes sense as well. 80 is considered a standard 'limit' of sorts in many languages (Python is famous for it, but back in the day punch cards and teletypes were already limited to 80 columns).</p>\n<p>Google's <a href=\"https://google.github.io/styleguide/htmlcssguide.html#HTML_Line-Wrapping\" rel=\"nofollow noreferrer\">HTML style guide</a> states:</p>\n<blockquote>\n<p>Break long lines (optional).</p>\n<p>While there is no column limit recommendation for HTML, you may consider wrapping long lines if it significantly improves readability.</p>\n<p>When line-wrapping, each continuation line should be indented at least 4 additional spaces from the original line.</p>\n</blockquote>\n<p>You've already verified your <a href=\"https://validator.w3.org/\" rel=\"nofollow noreferrer\">validator</a> doesn't have a problem with it either, so, go for it. In hindsight, if the validator would've had problems with it, it would've been time for a better validator.</p>\n<p>Better readability => better maintainability => less bugs and less development time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T10:24:40.007",
"Id": "239500",
"ParentId": "239498",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239500",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T08:59:30.453",
"Id": "239498",
"Score": "0",
"Tags": [
"html"
],
"Title": "Is it ok to break long html elements down into multiple lines?"
}
|
239498
|
<p>This is code for finding if inequality <span class="math-container">\$abc > 2(\text{area of triangle})\$</span>
where <span class="math-container">\$a\$</span>, <span class="math-container">\$b\$</span> and <span class="math-container">\$c\$</span> are the sides of any triangle.</p>
<p>The below, and <a href="https://repl.it/repls/TubbyRoundDeal" rel="nofollow noreferrer">repl</a>, code work as intended. However they take a long time. Can the performance be improved without reducing <code>max_tries</code>? </p>
<pre><code>import random
import math
hn=100000000
num=0
max_tries=10000000
tries = 0
while tries != max_tries:
a= random.randint(1,hn)
b= random.randint(1,hn)
c= random.randint(1,hn)
if a+b>c and c+b>a and a+c>b :
s=(a+b+c)/2
tries= tries +1
k =math.sqrt(s*(s-a)*(s-b)*(s-c))
if a*b*c> 2*k:
num= num+1
print(num/max_tries)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:30:42.237",
"Id": "469752",
"Score": "2",
"body": "Can you flesh out the description on what this does. I've read your post but you've mostly just complained about speed without explaining what you're tying to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:34:45.183",
"Id": "469755",
"Score": "2",
"body": "Also, out of curiosity, did you ever find an example where it is not true or do you expect to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:17:32.547",
"Id": "469774",
"Score": "1",
"body": "My expectation what [triangle inequality](https://en.m.wikipedia.org/wiki/List_of_triangle_inequalities) is about is #1 (the `if` condition above) - *abc* does show up in at least one of the [inequalities for triangle area](https://en.m.wikipedia.org/wiki/List_of_triangle_inequalities#Area)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:20:13.860",
"Id": "469776",
"Score": "1",
"body": "It would be interesting to see the impact of replacing just one of the lengths in each iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T15:34:22.790",
"Id": "469789",
"Score": "2",
"body": "Why can the lengths only be integers? If you want integers to prevent problems with floating point rounding, you might try harder to keep `s` and `k` integers too by slightly rewriting the inequality"
}
] |
[
{
"body": "<p>The problem of your code is the way you generate triangles. You just create three <strong>independent</strong> random numbers. In theory, you could always end up rolling numbers that don't end up in a valid triangle and thus your code would not even terminate. That is, because triangle side lengths are <strong>dependent</strong>.</p>\n\n<p>To always create a valid triangle, you can instead roll two angles and one side and then use the <a href=\"https://en.wikipedia.org/wiki/Law_of_sines\" rel=\"nofollow noreferrer\">law of sines</a> to calculate the remaining sides.</p>\n\n<p>The sum of angles in a triangle is 180 degrees (or pi radians). So the first angle <em>alpha</em> is randomly selected between <em>(0, pi)</em>, the second angle <em>beta</em> is then between <em>(0, pi-alpha)</em> and the third angle <em>gamma</em> is gained by simple arithmetics: <em>gamma = pi - alpha - beta</em></p>\n\n<p>Or in code:</p>\n\n<pre><code>alpha = random.uniform(0, math.pi)\nbeta = random.uniform(0, math.pi - alpha)\ngamma = math.pi - alpha - beta\n</code></pre>\n\n<p>If we know two sides and the angle in between, <a href=\"https://www.mathsisfun.com/algebra/trig-area-triangle-without-right-angle.html\" rel=\"nofollow noreferrer\">we can easily calculate the area</a>. Since your inequality uses twice the area, we can drop the factor of <em>0.5</em>.</p>\n\n<pre><code>double_area = side_b * side_c * sin_alpha\n</code></pre>\n\n<p>Some micro-optimisations: math.sin is an expensive function (time-wise), so we save the result in a variable. Same goes for floating point division. Multiplication is faster, so once again, we save the result to use multiplication later on.</p>\n\n<p>Lastly: Since you already know how often you want to execute the loop, you can use a for-loop instead of a while-loop although frankly, I don't know how well this goes in terms of memory consumption.</p>\n\n<pre><code>import math\nimport random\nimport time\n\n\nmax_side_length = 100000000\nn_max_tries = 10000000\nn_successes = 0\n\ntime_start = time.time()\n\nfor k in range(n_max_tries):\n alpha = random.uniform(0, math.pi)\n beta = random.uniform(0, math.pi - alpha)\n gamma = math.pi - alpha - beta\n\n side_a = random.randint(1, max_side_length)\n sin_alpha = math.sin(alpha)\n side_a_over_sin_alpha = side_a / sin_alpha\n\n side_b = side_a_over_sin_alpha * math.sin(beta)\n side_c = side_a_over_sin_alpha * math.sin(gamma)\n\n double_area = side_b * side_c * sin_alpha\n\n if side_a * side_b * side_c > double_area:\n n_successes += 1\n\ntime_end = time.time()\n\nprint(\"successes: \", n_successes, \" / \", n_max_tries, \" (\", n_successes/n_max_tries, \")\")\nprint(\"time: \", time_end-time_start)\n</code></pre>\n\n<p>I didn't do excessive timings because I couldn't be bothered, but this code runs on my machine in about 37.8s, while three runs of your code averaged on 109.8s, resulting in an optimistic speed-up factor of around 3.</p>\n\n<p><strong>Disclaimer:</strong> I can somewhat write in python but I'm probably violating this famous pep-8. Yet, I strongly encourage you to give reasonable names to your variables as it makes the code more easy to understand. Not only for others, but also for yourself, when you look at it 2 weeks later. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:48:40.667",
"Id": "469767",
"Score": "0",
"body": "Thanks it is working much faster"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:34:29.137",
"Id": "469780",
"Score": "0",
"body": "Wouldn't it be easier to say `double_area = side_a**2 * math.sin(alpha) * math.sin(beta) * math.sin(gamma)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-11T05:39:22.447",
"Id": "471339",
"Score": "0",
"body": "Alternative approach to generating a valid length triple from every pair: draw `c` from [abs(a-b), a+b]."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:43:12.490",
"Id": "239507",
"ParentId": "239503",
"Score": "2"
}
},
{
"body": "<p>One way to speed this up is to use a package designed for numerical evaluation, <a href=\"https://numpy.org/\" rel=\"nofollow noreferrer\"><code>numpy</code></a>. It is implemented in C and can take advantage of multiple cores if necessary. The only limitation is that you can only create arrays that fit into memory. At least on my machine (16GB RAM) your current values fit easily, though (if each integer takes 64 bytes, then I could store over 250 million of them).</p>\n\n<p>Another limitation is that you are limited to long long integers (64 bytes on my machine), so you will have to adapt your upper ceiling for the numbers to that. The largest value being produced by this code is <code>s * (s - a) * (s - b) * (s - c)</code>, so this needs to fit even if all of <code>a</code>, <code>b</code> and <code>c</code> are the maximum value. There is a programmatic way to get the size, so we can figure out what it is. Unfortunately, this formula has basically a <span class=\"math-container\">\\$n^4\\$</span> in it, so the maximum value is quite small. On my machine I can generate values of up to just 83748 this way. Although practically this is probably not relevant, since the likelihood that you generate a larger number like that is very small (case in point, I had previsously assumed <code>a * b * c /2</code> would be the largest value, but I still found 100% matching the inequality). The only problem with this is that if you <em>do</em> get a larger value, you get an overflow, the next number after the largest integer is the smallest integer, so you get negative numbers under the square root. But <code>numpy</code> will tell you about that with a warning, if it happens.</p>\n\n<p>Here is a straight-forward implementation of your code using <code>numpy</code>. I did not make any effort to speed it up in addition, the only real difference is the value of <code>limit</code> and that I moved the factor 2 in the inequality to the other side (so I can make the limit a factor two larger).</p>\n\n<pre><code>import numpy as np\n\n#limit = 100000000\nmax_int = np.iinfo(np.longlong).max\nlimit = int((16./3 * max_int) ** (1./4)) + 1 # 83748 with np.int64\nmax_tries = 10000000\n\na, b, c = np.random.randint(1, limit, size=(3, max_tries), dtype=np.longlong)\nmask = (a + b > c) & (a + c > b) & (b + c > a)\na, b, c = a[mask], b[mask], c[mask]\ns = (a + b + c) / 2\nk = np.sqrt(s * (s - a) * (s - b) * (s - c))\ninequality_true = a / 2 * b * c > k\n\nprint(inequality_true.sum() / len(inequality_true))\n</code></pre>\n\n<p>This script runs in about 1.1s on my machine. Your code (with the same limit for the random numbers) takes about 83s.</p>\n\n<hr>\n\n<p>In addition to speeding up your code, you should also try to make it more readable. Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using spaces around the <code>=</code> when doing assignments and around binary operators (like <code>+</code> and <code>*</code>). In addition, try to use clear variable names (<code>hn</code> tells me nothing about what it is for) and put your main calling code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> if you want to be able to import from a script without everything running.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:21:14.383",
"Id": "469777",
"Score": "0",
"body": "I'd be curious about my solution in a numpy approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:38:48.797",
"Id": "469782",
"Score": "0",
"body": "@infinitezero: It takes about 1.6s. Without doing the math for the maximum limit like I did for my script, which would probably speed it up more since the numbers are smaller. Although your script allows larger numbers, since `a * b * c` is the largest number there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T01:51:46.267",
"Id": "469961",
"Score": "1",
"body": "In numpy >= 1.18, `randint()` can take an array as the lower or upper bound. So I think you can do `a, b = np.random.randint(1, limit, size=(2, max_tries), dtype=np.longlong)` and then `c = np.random.randint(abs(a-b+1), a+b, size=max_tries, dtype=np.longlong)`. That way each triple is guaranteed to be the sides of a triangle."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:49:37.810",
"Id": "239509",
"ParentId": "239503",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:20:29.917",
"Id": "239503",
"Score": "1",
"Tags": [
"python",
"performance",
"beginner",
"mathematics"
],
"Title": "Monte-Carlo method to check triangle inequality"
}
|
239503
|
<p>The data are in a file called <code>test.txt</code>, which is available at <a href="https://drive.google.com/file/d/1g0ffvH5oP5C4Cp6ciEp_L1Rst6WeTuYG/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1g0ffvH5oP5C4Cp6ciEp_L1Rst6WeTuYG/view?usp=sharing</a>. There are some odd formatting things about it which I cannot replicate by putting on this website, hence I'm hosting it on my Google Drive. It is just simulated data, so there are no privacy concerns about using it.</p>
<p>I would like to cut down on the computational time of this code in Java.</p>
<pre><code>import java.io.FileInputStream;
import java.lang.Math;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
public class BlockBootstrapTest {
// B(x, i, L) is the subset of x which starts at index i (based on 1-indexing
// as opposed to 0-indexing) and has length L
public static double[] B(double[] x, int i, int L) {
double[] out = new double[L];
for (int j = 0; j < L; j++)
out[j] = x[i - 1 + j];
return out;
}
// Sum of an array
public static double sum(double[] x) {
double s = 0;
for (int i = 0; i < x.length; i++)
s += x[i];
return s;
}
// Mean of an array
public static double mean(double[] x) {
return sum(x)/((double) x.length);
}
// Compute B-bar_i
public static double bMean(double[] x, int i, int L) {
return(mean(B(x, i, L)));
}
// Compute MBB mean
public static double mbbMu(double[] x, int L) {
int n = x.length;
double[] blockAvgs = new double[n - L + 1];
for (int i = 0; i < n - L + 1; i++) {
blockAvgs[i] = bMean(x, i + 1, L);
}
return mean(blockAvgs);
}
// Compute MBB variance
public static double mbbVariance(double[] x, int L, double alpha) {
int n = x.length;
double mbbMean = mbbMu(x, L);
double[] diffs = new double[n - L + 1];
for (int i = 0; i < n - L + 1; i++) {
diffs[i] = Math.pow(L, alpha) * Math.pow(bMean(x, i + 1, L) - mbbMean, 2);
}
// Compute the summation
double varSum = sum(diffs);
double out = varSum / ((double) n - L + 1);
return out;
}
// Compute NBB mean
public static double nbbMu(double[] x, int L) {
int n = x.length;
int b = (int) Math.floor(((double) n) / L);
double[] blockAvgs = new double[b];
for (int i = 0; i < b; i++)
blockAvgs[i] = bMean(x, 1 + ((i + 1) - 1) * L, L);
return mean(blockAvgs);
}
// Compute NBB variance
public static double nbbVariance(double[] x, int L, double alpha) {
int n = x.length;
int b = (int) Math.floor(((double) n) / L);
double nbbMean = nbbMu(x, L);
double[] diffs = new double[b];
for (int i = 0; i < b; i++)
diffs[i] = Math.pow(bMean(x, 1 + ((i + 1) - 1) * L, L) - nbbMean, 2);
double varSum = Math.pow((double) L, alpha) * sum(diffs) / ((double) b);
return varSum;
}
// factorial implementation
public static double factorial(int x) {
double out = 1;
for (int i = 1; i < x + 1; i++)
out *= i;
return out;
}
// Hermite polynomial
public static double H(double x, int p) {
int upperIdx = (int) Math.floor(((double) p) / 2);
double out = 0;
for (int i = 0; i < upperIdx + 1; i++) {
out += Math.pow(-1, i) * Math.pow(x, p - (2 * i)) /
((factorial(i) * factorial(p - (2 * i))) * Math.pow(2, i));
}
out *= factorial(p);
return out;
}
// Row means
public static double[] rowMeans(double[][] x, int nrows, int ncols) {
double[] means = new double[nrows];
for (int i = 0; i < nrows; i++) {
double[] row = new double[ncols];
for (int j = 0; j < ncols; j++)
row[j] = x[i][j];
means[i] = mean(row);
}
return means;
}
public static void main(String[] argv) throws IOException {
FileInputStream fileIn = new FileInputStream("test.txt");
FileOutputStream fileOutMBB = new FileOutputStream("MBB_test.txt");
FileOutputStream fileOutNBB = new FileOutputStream("NBB_test.txt");
FileOutputStream fileOutMean = new FileOutputStream("means_test.txt");
Scanner scnr = new Scanner(fileIn);
PrintWriter outFSMBB = new PrintWriter(fileOutMBB);
PrintWriter outFSNBB = new PrintWriter(fileOutNBB);
PrintWriter outFSmean = new PrintWriter(fileOutMean);
// These variables are taken from the command line, but are inputted here for ease of use.
int rows = 5000;
int cols = 3000;
int minBlockSize = 0;
int maxBlockSize = 2998; // this could potentially be any value < cols
int p = 1;
double alpha = 0.1;
double[][] timeSeries = new double[rows][cols];
// read in the file, and perform the H_p(x) transformation
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
timeSeries[i][j] = H(scnr.nextDouble(), p);
}
scnr.next(); // skip null terminator
}
// block bootstrap variance estimators
double[][] outMBB = new double[rows][maxBlockSize];
double[][] outNBB = new double[rows][maxBlockSize];
// row means
double[] sampleMeans = rowMeans(timeSeries, rows, cols);
for (int i = 0; i < rows; i++) {
outFSmean.print(sampleMeans[i] + " ");
}
outFSmean.println();
outFSmean.close();
for (int j = 0; j < rows; j++) {
double[] row = new double[cols];
for (int k = 0; k < cols; k++)
row[k] = timeSeries[j][k];
for (int m = minBlockSize; m < maxBlockSize; m++) {
outMBB[j][m] = mbbVariance(row, m + 1, alpha);
outNBB[j][m] = nbbVariance(row, m + 1, alpha);
outFSMBB.print(outMBB[j][m] + " ");
outFSNBB.print(outNBB[j][m] + " ");
}
outFSMBB.println();
outFSNBB.println();
}
outFSMBB.close();
outFSNBB.close();
}
}
</code></pre>
<p>Note that <code>p</code> and <code>alpha</code> can take on any values for which <code>((double) p) * alpha < 1</code> is true.</p>
<h1>A very high-level overview of what this code is doing</h1>
<p>This is implementing a procedure known as <a href="https://en.wikipedia.org/wiki/Bootstrapping_(statistics)#Block_bootstrap" rel="nofollow noreferrer">block bootstrapping</a> on Hermite-transformed data, and attempts to find the variance of a sample mean based on such a procedure for a particular type of time-series data. I will not bore you with the mathematical details of this procedure. Assume that the implementation is correct as is.</p>
<p>Depending on how the block bootstrap is executed (in the Wikipedia page linked above, it talks about "simple" and "moving" block bootstrapping), the formula of the variance of a sample mean changes and is executed using <code>mbbVariance</code> and <code>nbbVariance</code>. I need these variance values for various block lengths spit out into text files for each row of data. </p>
<p>It also outputs a third text file with the means for each row of data.</p>
<p>Please note that the Hermite polynomial implementation is based on the probabilists' Hermite polynomials formula at <a href="https://en.wikipedia.org/wiki/Hermite_polynomials#Explicit_expression" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Hermite_polynomials#Explicit_expression</a>.</p>
<h1>What I know about this code:</h1>
<ul>
<li>The <code>mbbVariance</code> and <code>nbbVariance</code> parts are taking the most time out of all other lines of the code. Especially considering the fact that we could potentially be performing these operations 3000 times each per row for 5000 rows, my estimate is that it would take at least 20 hours just to process the loop in which these functions are executed. This is unacceptable, given that I have about 20 files that I will be processing. I know for a fact that this is executing correctly for smaller data sets, but it needs to be scaled up.</li>
<li>There are many layers of functions calling other functions in <code>mbbVariance</code> and <code>nbbVariance</code>. However, removing such function calls didn't cut down on the time it took to execute these functions.</li>
</ul>
<p>I don't know much about data structures and algorithms, so anything from those topics that would be helpful for this problem I would love to know about. I'm also very new to Java.</p>
|
[] |
[
{
"body": "<p>Four things come to mind immediately:</p>\n\n<p>(1) You’re doing a lot of memory allocations.</p>\n\n<p>(2) You’re doing a lot of copying of arrays.</p>\n\n<p>(3) You have some unnecessary calls to pow() (which is very slow).</p>\n\n<p>(4) You’re actually computing a factorial.</p>\n\n<p>I think we can take care of (1) and (2) together. You have a lot of calls to B() that can eliminated if you implement a new version of mean() that works with an array subrange, rather than using bMean() to allocate, copy, and deallocate an array every single time it’s called. (This will also cut down on memory use, and likely do wonders for cache friendliness.)</p>\n\n<p>Perhaps something like this (WARNING: untested code):</p>\n\n<pre><code>public static double sum(double[] x, int i, int L) {\n double s = 0;\n int hi = i + L;\n while (i < hi)\n s += x[i++];\n return s;\n}\n\n// Mean of an array\npublic static double mean(double[] x, int i, int L) {\n return sum(x, i, L)/((double) L);\n}\n</code></pre>\n\n<p>Now all your calls to bMean() become calls to mean(), and will avoid a memory allocation, L copies of doubles, and a memory deallocation. It would be really interesting to track memory usage before and after the change.</p>\n\n<p>Another place where item (2) can be avoided is in rowMeans(). Since you’re accessing the array by columns, there is no need to copy each row. Just use</p>\n\n<pre><code>means[i] = mean(x[i]);\n</code></pre>\n\n<p>For item (3), you can optimize your frequent calls to pow(2, i). If i is always than 64, use</p>\n\n<pre><code>x = 1L << i\n</code></pre>\n\n<p>If i is always less than 32, use</p>\n\n<pre><code>x = 1 << i\n</code></pre>\n\n<p>Otherwise, use a lookup table:</p>\n\n<pre><code>private static double[] pow2 = { 1.0, 2.0, 4.0, 8.0, … }; // up to the size you need\n// later…\nx = pow2[i];\n</code></pre>\n\n<p>If i can be greater than 64, just compute the table once rather than manually.</p>\n\n<p>Finally, item (4) can also be sped up considerably using a lookup table.</p>\n\n<pre><code>private static double[] fact = { 1.0, 1.0, 2.0, 6.0, 24.0, … }; // up to the size you need\n</code></pre>\n\n<p>Again, if you need large factorials and don’t want to compute the table manually, compute the table once up front and then do a lookup.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T16:11:55.783",
"Id": "239515",
"ParentId": "239504",
"Score": "3"
}
},
{
"body": "<p>My review is focused about simplification of your code using java <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/DoubleStream.html\" rel=\"nofollow noreferrer\">DoubleStream</a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/DoubleSummaryStatistics.html\" rel=\"nofollow noreferrer\">DoubleSummaryStatistics</a> classes; I found some repeated operation in your code that can be avoided to slightly increase efficiency.\nYou have the following methods in your code:</p>\n\n<blockquote>\n<pre><code>public static double sum(double[] x) {\n double s = 0;\n for (int i = 0; i < x.length; i++)\n s += x[i];\n return s;\n}\n // Mean of an array\npublic static double mean(double[] x) {\n return sum(x)/((double) x.length);\n}\n</code></pre>\n</blockquote>\n\n<p>These methods can be erased because already included in <code>DoubleStream</code> and <code>DoubleSummaryStatistics</code>. You have the following methods in your code:</p>\n\n<blockquote>\n<pre><code>// Compute B-bar_i\npublic static double bMean(double[] x, int i, int L) {\n return(mean(B(x, i, L)));\n}\n// Compute MBB variance\npublic static double mbbVariance(double[] x, int L, double alpha) {\n int n = x.length;\n double mbbMean = mbbMu(x, L);\n double[] diffs = new double[n - L + 1];\n for (int i = 0; i < n - L + 1; i++) {\n diffs[i] = Math.pow(L, alpha) * Math.pow(bMean(x, i + 1, L) - mbbMean, 2);\n }\n // Compute the summation\n double varSum = sum(diffs);\n double out = varSum / ((double) n - L + 1);\n return out;\n}\n// Compute NBB mean\npublic static double nbbMu(double[] x, int L) {\n int n = x.length;\n int b = (int) Math.floor(((double) n) / L);\n double[] blockAvgs = new double[b];\n for (int i = 0; i < b; i++)\n blockAvgs[i] = bMean(x, 1 + ((i + 1) - 1) * L, L);\n return mean(blockAvgs);\n}\n// Compute NBB variance\npublic static double nbbVariance(double[] x, int L, double alpha) {\n int n = x.length;\n int b = (int) Math.floor(((double) n) / L);\n double nbbMean = nbbMu(x, L);\n double[] diffs = new double[b];\n for (int i = 0; i < b; i++)\n diffs[i] = Math.pow(bMean(x, 1 + ((i + 1) - 1) * L, L) - nbbMean, 2);\n double varSum = Math.pow((double) L, alpha) * sum(diffs) / ((double) b);\n return varSum;\n}\n</code></pre>\n</blockquote>\n\n<p>They can be rewritten in the following way:</p>\n\n<pre><code>// Compute B-bar_i\npublic static double bMean(double[] x, int i, int l) {\n return DoubleStream.of(b(x, i, l)).average().orElse(0);\n}\n\n// Compute MBB mean\npublic static double mbbMu(double[] x, int l) {\n DoubleSummaryStatistics statistics = new DoubleSummaryStatistics();\n\n for (int i = 0; i < x.length - l + 1; i++) {\n statistics.accept(bMean(x, i + 1, l));\n }\n\n return statistics.getAverage();\n}\n\n// Compute MBB variance\npublic static double mbbVariance(double[] x, int L, double alpha) {\n double mbbMean = mbbMu(x, L);\n DoubleSummaryStatistics statistics = new DoubleSummaryStatistics();\n\n for (int i = 0; i < x.length - L + 1; i++) {\n statistics.accept(Math.pow(L, alpha) * Math.pow(bMean(x, i + 1, L) - mbbMean, 2));\n }\n\n return statistics.getAverage();\n}\n\n// Compute NBB mean\npublic static double nbbMu(double[] x, int L) {\n int b = (int) Math.floor(((double) x.length) / L);\n DoubleSummaryStatistics statistics = new DoubleSummaryStatistics();\n\n for (int i = 0; i < b; i++) {\n statistics.accept(bMean(x, 1 + i * L, L)); \n }\n\n return statistics.getAverage();\n}\n\n// Compute NBB variance\npublic static double nbbVariance(double[] x, int L, double alpha) { \n int b = (int) Math.floor(((double) x.length) / L);\n double nbbMean = nbbMu(x, L);\n DoubleSummaryStatistics statistics = new DoubleSummaryStatistics();\n\n for (int i = 0; i < b; i++) {\n statistics.accept(Math.pow(bMean(x, 1 + i * L, L) - nbbMean, 2));\n }\n\n return Math.pow((double) L, alpha) * statistics.getAverage();\n}\n</code></pre>\n\n<p>Another method rewritten using a <code>DoubleStream</code>:</p>\n\n<pre><code>// Row means\npublic static double[] rowMeans(double[][] x, int nrows, int ncols) {\n double[] means = new double[nrows];\n for (int i = 0; i < nrows; i++) {\n double[] row = new double[ncols];\n for (int j = 0; j < ncols; j++)\n row[j] = x[i][j];\n means[i] = DoubleStream.of(row).average().orElse(0);\n }\n return means;\n}\n</code></pre>\n\n<p>In your main code you can calculate one time the <code>factorial</code> of <code>p</code> and pass it for the consecutive calls of your method h, here your version of the method not passing the factorial:</p>\n\n<blockquote>\n<pre><code>// Hermite polynomial\npublic static double H(double x, int p) {\n int upperIdx = (int) Math.floor(((double) p) / 2);\n double out = 0;\n for (int i = 0; i < upperIdx + 1; i++) {\n out += Math.pow(-1, i) * Math.pow(x, p - (2 * i)) / \n ((factorial(i) * factorial(p - (2 * i))) * Math.pow(2, i));\n }\n out *= factorial(p);\n return out;\n}\n</code></pre>\n</blockquote>\n\n<p>I added the new parameter <code>factorialP</code> to this method, probably it will be an increment of performance:</p>\n\n<pre><code>// Hermite polynomial\npublic static double h(double x, int p, int factorialP) {\n final int upperIdx = (int) Math.floor((double)p / 2);\n int out = 0;\n\n for (int i = 0; i < upperIdx + 1; i++) {\n out += Math.pow(-1, i) * Math.pow(x, p) / \n ((factorial(i) * factorial(p)) * Math.pow(2, i));\n p -= 2;\n }\n\n return out * factorialP;\n\n}\n\n//later in your main method\nint factorialP = factorial(p);\nfor (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n timeSeries[i][j] = h(scnr.nextDouble(), p, factorialP);\n }\n scnr.next(); // skip null terminator\n}\n</code></pre>\n\n<p>I think is possible to parallelize operations because you are doing sum of elements and calculating average of them, but I have no further knowledge or experience about this argument to give an answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:18:56.967",
"Id": "239528",
"ParentId": "239504",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T13:00:24.293",
"Id": "239504",
"Score": "4",
"Tags": [
"java",
"statistics"
],
"Title": "Block Bootstrap Estimation using Java"
}
|
239504
|
<p>I've built out a section on a page that contains multiple instances (why I'm using <code>querySelectorAll()</code>) of this Request Brochure form. They are using Campaign Monitor so much of the form code has been removed for this post.</p>
<p><strong>Operation</strong></p>
<ul>
<li>On page load an event handler that calls <code>preventDefault</code> on click events is added to elements with class <em>download</em> to prevent the submit action.</li>
<li>A class of <code>.is-open</code> is added to the <code>.download</code> container. </li>
<li>This triggers a keyframe animation that transitions the height, then the opacity of the forms</li>
<li>The event listener is removed to allow the button to perform it's submit action</li>
</ul>
<p>I did try using the method of setting the button to disabled initially, then removing this attribute onclick but found this meant the hover states would not work. </p>
<p>I'm looking to see if this is the most efficient way of adding, then removing <code>preventDefault</code> once it is no longer required.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const packageCMCont = document.querySelectorAll('.download');
packageCMCont.forEach(function(item) {
function handleClick(e) {
e.preventDefault()
var btn = item.querySelector('.btn');
item.classList.add('is-open');
btn.classList.remove('is-style-outline');
btn.classList.add('is-style-default');
item.removeEventListener('click', handleClick);
}
item.addEventListener('click', handleClick);
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.download {
width: 100%;
max-width: 600px;
margin: 0 auto;
}
.download.is-open .inputs {
display: flex;
height: 100px;
animation: showForms 3s forwards;
}
.inputs {
opacity: 0;
display: none;
flex-direction: column;
height: 0;
overflow: hidden;
}
input {
height: 50px;
}
button {
height: 50px;
width: 100%;
background-color: green;
color: white;
}
button:hover {
background-color: white;
color: green;
}
@keyframes showForms {
0% {
height: 0;
}
50% {
height: 100px;
opacity: 0;
}
100% {
height: 100px;
opacity: 1;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="download">
<form>
<div class="inputs">
<input aria-label="Name" id="fieldName" maxlength="200" name="cm-name" placeholder="Name">
<input autocomplete="Email" aria-label="Email" id="fieldEmail" maxlength="200" required="" type="email" placeholder="Email">
</div>
<div class="button-cont">
<button class="btn" type="submit">Request Brochure</button>
</div>
</form>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p><a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation\" rel=\"nofollow noreferrer\">Event delegation</a> can be used to improve efficiency. Instead of adding a click handler to every single element with the class <em>download</em>, an event handler could be added to the entire document or a sub-element that contains all elements with class <em>download</em>.</p>\n\n<pre><code>document.addEventListener('click', e => {\n let node = e.target;\n do {\n if (node.classList.contains('download') && !node.classList.contains('is-open')) {\n e.preventDefault();\n const btn = node.querySelector('.btn');\n\n btn.classList.remove('is-style-outline');\n btn.classList.add('is-style-default');\n\n node.classList.add('is-open');\n break;\n } \n node = node.parentNode;\n } while (node && node.classList !== undefined);\n});\n</code></pre>\n\n<p>In the example above, the click handler inspects the target element to see if it or a parent node has the class <em>download</em> and if such an element doesn't have class <em>is-open</em> before modifying class names for the elements. </p>\n\n<p>I noticed that I wasn't able to click on the div element with class <em>download</em> without clicking the button, despite the container element having space on the sides of the button, and in the original code the click event is <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture\" rel=\"nofollow noreferrer\">bubbled up</a> from the button to the div. Instead of needing to use the <em>do while</em> loop to go up the DOM chain, the click handler could check to see if the target element has class name <em>btn</em> and in that case if it has an ancestor up three levels that matches the specified class names then modify the class names.</p>\n\n<pre><code>document.addEventListener('click', e => {\n const node = e.target;\n if (node.classList.contains('btn')) {\n if (node.parentNode && node.parentNode.parentNode && node.parentNode.parentNode.parentNode) {\n const ancestorDiv = node.parentNode.parentNode.parentNode;\n if (ancestorDiv.classList && ancestorDiv.classList.contains('download') && !ancestorDiv.classList.contains('is-open')) {\n e.preventDefault();\n\n node.classList.remove('is-style-outline');\n node.classList.add('is-style-default');\n\n ancestorDiv.classList.add('is-open');\n }\n }\n }\n});\n</code></pre>\n\n<p>Because the code above contains multiple 'if' statements that lead to multiple indentation levels, the logic could be switched to return early instead:</p>\n\n<pre><code>document.addEventListener('click', e => {\n const node = e.target;\n if (!node.classList.contains('btn')) {\n return;\n }\n if (!(node.parentNode && node.parentNode.parentNode && node.parentNode.parentNode.parentNode)) {\n return;\n }\n const ancestorDiv = node.parentNode.parentNode.parentNode;\n if (ancestorDiv.classList && ancestorDiv.classList.contains('download') && !ancestorDiv.classList.contains('is-open')) {\n e.preventDefault();\n\n node.classList.remove('is-style-outline');\n node.classList.add('is-style-default');\n\n ancestorDiv.classList.add('is-open');\n }\n});\n</code></pre>\n\n<hr>\n\n<p>I presume the classes <code>is-style-outline</code> and <code>is-style-default</code> are styled by a library (e.g. wordpress) but the styles could be incorporated based on whether the container div (i.e. with class <em>download</em>) contains class <em>is-open</em>, in the same way the inputs are displayed depending on those class names.</p>\n\n<hr>\n\n<p>Indentation in this code is fairly uniform, though one CSS ruleset (i.e. <code>.download.is-open .inputs</code>) contains rules indented by four spaces instead of two</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T22:23:46.443",
"Id": "239588",
"ParentId": "239510",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239588",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:12:27.353",
"Id": "239510",
"Score": "1",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6",
"event-handling"
],
"Title": "Showing form on btn click - preventDefault of submit btn, then remove listener"
}
|
239510
|
<p>I have a <code>RadioStation</code> class file and a view controller where I create two station objects based on this class, one for FM and one for AM. </p>
<p>I created both of these station objects from within the same <code>required init</code> method. I'm not sure this was this the best way to do this, for example can you imagine if you wanted 8 such objects, this would just get very clunky. Is the issue rather that I am creating them in the view controller, and should I have in fact created separate subclass files for each and init them in those?
Or should I have created two separate <code>init</code> methods, one for each new object? </p>
<p>RadioStation Class File: RadioStation.swift</p>
<pre><code>import UIKit
class RadioStation: NSObject {
var name: String
var frequency: Double
override init() { //init class method to set default values.
name = "Default"
frequency = 100
}
static var minAMFFrequency: Double = 520.0
static var maxAMFFrequency: Double = 1610.0
static var minFMFFrequency: Double = 88.3
static var maxFMFFrequency: Double = 107.9
func isBandFM() -> Int {
if frequency >= RadioStation.minFMFFrequency && frequency <= RadioStation.maxAMFFrequency {
return 1 //FM
} else {
return 0 //AM
}
}
}
</code></pre>
<p>View Controller Class</p>
<pre><code>import UIKit
class ViewController: UIViewController {
@IBOutlet weak var stationName: UILabel!
@IBOutlet weak var stationFrequency: UILabel!
@IBOutlet weak var stationBand: UILabel!
var myStation: RadioStation
var myStationAM: RadioStation //second object variable
required init?(coder aDecoder: NSCoder) {
myStation = RadioStation()
myStationAM = RadioStation()
myStation.frequency = 104.7
myStationAM.frequency = 600.2
myStation.name = "FM1"
myStationAM.name = "AM1"
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func buttonClick(_ sender: Any) {
stationName.text = myStation.name //set top left label text to name property of myStation object instance
stationFrequency.text = "\(myStation.frequency)"
if myStation.isBandFM() == 1 {
stationBand.text = "FM'"
} else {
stationBand.text = "AM"
}
}
@IBAction func buttonClickAM(_ sender: Any) {
stationName.text = myStationAM.name
stationFrequency.text = "\(myStationAM.frequency)"
if myStationAM.isBandFM() == 1 {
stationBand.text = "FM"
} else {
stationBand.text = "AM"
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T21:16:17.930",
"Id": "469816",
"Score": "0",
"body": "Can someone tell me why this was downvoted? The code works, and I would like to learn about init methods for more than one object at a time. What did I do wrong?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:29:12.633",
"Id": "469896",
"Score": "2",
"body": "One problem is that (on this site) the *title* should state what your code does in your title, not your main concerns about it, compare [ask]. I would suggest to revise the title accordingly. Make it clear in the question the code works correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:29:18.923",
"Id": "469897",
"Score": "2",
"body": "(Cont.) There is one “Needs details or clarity” vote, so make sure that the code is self-contained, or at least contains sufficient context to understand it. Then you can (in the question, not in the title) describe your concerns about the code and what you would like to be reviewed. Make sure that it is not a “best practices” question as described in [help/dont-ask]."
}
] |
[
{
"body": "<p>A couple of thoughts:</p>\n\n<ol>\n<li><p>You are conceiving the band as being something derived from the frequency. While this may be technically correct, from a user perspective, you generally choose a band and then choose a frequency within that band. So, I might have a model that reflects this:</p>\n\n<pre><code>typealias RadioFrequency = Decimal\n\nenum RadioBand {\n case am\n case fm\n}\n\nextension RadioBand {\n var allowedRange: ClosedRange<RadioFrequency> {\n switch self {\n case .am: return 520.0 ... 1610.0\n case .fm: return 88.3 ... 107.9\n }\n }\n}\n\nstruct RadioStation {\n let name: String\n let band: RadioBand\n let frequency: RadioFrequency\n\n init?(name: String, band: RadioBand, frequency: RadioFrequency) {\n guard band.allowedRange ~= frequency else { return nil }\n\n self.name = name\n self.band = band\n self.frequency = frequency\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>guard let station = RadioStation(name: \"KPCC\", band: .fm, frequency: 89.3) else {\n // handle error here\n\n return\n}\n</code></pre></li>\n<li><p>If you really wanted to compute the band from the frequency, you could do:</p>\n\n<pre><code>enum RadioBand: CaseIterable {\n case am\n case fm\n}\n\nextension RadioBand {\n var allowedRange: ClosedRange<RadioFrequency> {\n switch self {\n case .am: return 520.0 ... 1610.0\n case .fm: return 88.3 ... 107.9\n }\n }\n\n static func band(for frequency: RadioFrequency) -> RadioBand? {\n RadioBand.allCases.first { $0.allowedRange ~= frequency }\n }\n}\n\nstruct RadioStation {\n let name: String\n let frequency: RadioFrequency\n var band: RadioBand? { RadioBand.band(for: frequency) }\n\n init?(name: String, frequency: RadioFrequency) {\n guard RadioBand.band(for: frequency) != nil else { return nil }\n\n self.name = name\n self.frequency = frequency\n }\n}\n</code></pre></li>\n<li><p>Minor details in the above:</p>\n\n<ul>\n<li><p>I wouldn’t generally subclass <code>NSObject</code> unless there was a compelling reason to do so.</p></li>\n<li><p>Whether you make it a <code>class</code> or <code>struct</code> is up to you, but we often we would lean towards value types and immutable properties unless otherwise needed.</p></li>\n<li><p>I’m abstracting the frequency ranges for bands out of the <code>RadioStation</code> type. This is behavior of radio bands, not of individual radio stations, themselves.</p></li>\n<li><p>The radio bands might be better represented as an enumeration rather than an integer that has only two values, either <code>0</code> or <code>1</code>.</p>\n\n<p>In general, if you find yourself inserting comments to explain cryptic values (e.g. where you note that <code>1</code> represents “FM”), that’s a good sign that you should adopt an enumeration, which makes its intent clear. </p></li>\n<li><p>Note, I made <code>RadioFrequency</code> to be <code>Decimal</code>, rather than <code>Double</code>. I did that because you really don’t need floating point math, but rather want to accurately represent decimal numbers.</p>\n\n<p>FWIW, <code>Double</code> can introduce some strange behavior. Let’s say that you started at the lower bound of your AM frequencies and bumped it up by <code>0.1</code> ten times:</p>\n\n<pre><code>var value: Double = 520.0\nfor _ in 0 ..< 10 {\n value += 0.1\n}\n\nprint(value, value == 521.0) // 521.0000000000002 false\n</code></pre>\n\n<p>The result is not 521. But, if you use <code>Decimal</code>, you get the expected behavior:</p>\n\n<pre><code>var value: Decimal = 520.0\nfor _ in 0 ..< 10 {\n value += 0.1\n}\n\nprint(value, value == 521.0) // 521 true\n</code></pre>\n\n<p>See <a href=\"https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html\" rel=\"noreferrer\">What Every Computer Scientist Should Know About Floating-Point Arithmetic</a>.</p></li>\n<li><p>I’d make the initializer failable in case the band didn’t match the frequency (or the band couldn’t be inferred from the supplied frequency).</p></li>\n<li><p>I would not be inclined to have the <code>RadioStation</code> to have default values. That’s not a concept that makes sense. Sure, if you wanted your radio to default to a particular station, then fine, it would do that. But that’s not <code>RadioStation</code> behavior, but rather behavior of the radio.</p></li>\n</ul></li>\n<li><p>You said:</p>\n\n<blockquote>\n <p>... imagine if you wanted 8 such objects, this would just get very clunky.</p>\n</blockquote>\n\n<p>If you had many, you might use collections. For example:</p>\n\n<pre><code>let stations: [RadioStation]\n</code></pre>\n\n<p>Or you might wrap it in a custom type that indicated the functional intent. For example, let’s imagine that your radio had programmable presets, then the model might be:</p>\n\n<pre><code>struct RadioPresets {\n var stations: [RadioStation]\n}\n</code></pre>\n\n<p>It just depends upon what these various stations are for. But don’t shy away from simpler fundamental object types just because you might need multiple ones. If the concept of a single radio station makes sense (which it does, IMHO), then stick with a simple radio station object, and compose it into more complex objects/models as needed later.</p>\n\n<p>But, as a generally programming principle, we generally prefer simple, cohesive types and compose complex objects from these simple objects (e.g. a collection of 8 radio stations).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T20:24:38.473",
"Id": "469938",
"Score": "0",
"body": "Thank you again Rob, it's a lot to parse and will do so thoroughly, plus learn these new concepts."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T18:19:36.237",
"Id": "239572",
"ParentId": "239519",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "239572",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T18:18:51.343",
"Id": "239519",
"Score": "1",
"Tags": [
"object-oriented",
"swift",
"ios"
],
"Title": "Initializing more than one instance object at a time in init method"
}
|
239519
|
<p>I've decided to implement a simple case of the <a href="https://en.wikipedia.org/wiki/Observer_pattern" rel="nofollow noreferrer">Observer pattern</a>. I've gone about this considering you can only register 1 single observer in the Observable, instead of allowing multiple ones. </p>
<p>I would really like feedback about what'd be the proper way to return the listener in the <code>run</code> method while still yielding values, if possible i'd like to allow some sort of <a href="https://www.tutorialspoint.com/Explain-Python-class-method-chaining" rel="nofollow noreferrer">method chaining</a></p>
<p>Overall I would like some criticism about this whole design and of course, anything else is on the table will be appreciated.</p>
<p>Code:</p>
<pre><code>import time
class Observer:
def __init__(self):
self.lines = []
self.execution_time = None
def on_process(self, value):
line = f"<< processed: {value} >>"
self.lines.append(line)
return line
def on_done(self, value):
self.execution_time = value
class Observable:
def __init__(self):
self.listener = None
def register_listener(self, listener):
self.listener = listener
return self
def run(self, iterable):
s = time.time()
for v in iterable:
yield self.listener.on_process(v)
self.listener.on_done(time.time() - s)
if __name__ == '__main__':
obj = Observable().register_listener(Observer())
for x in obj.run(range(10)):
print(x)
listener = obj.listener
print("Number of lines:", len(listener.lines))
print("Execution time:", listener.execution_time)
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>You haven't implemented the observer pattern as your <strong>subject</strong>, <code>Observable</code>, doesn't contain a list of observers.</p>\n\n<p>Whilst this may seem like some small petty point it is <a href=\"https://en.wikipedia.org/wiki/Observer_pattern#What_problems_can_the_Observer_design_pattern_solve?\" rel=\"nofollow noreferrer\">the core problem that the pattern hopes to solve</a>.</p></li>\n<li><p>You have failed to make the subject relay to its observers. As you have moved the code, <code>run</code>, that should be in the observer into the subject.</p>\n\n<p>This makes the observer interface neigh on useless, because if you want to change this functionality then you're screwed.</p></li>\n</ul>\n\n<p>An example of the observer pattern is in Python's <code>logging</code> library.\nIn this you have events like a <code>logger.info(message)</code>.\nThe <code>logger</code>, the <strong>subject</strong>, goes on to call the underlying <a href=\"https://docs.python.org/3/library/logging.html#handler-objects\" rel=\"nofollow noreferrer\">handlers</a>, <strong>observers</strong>, with the event.\nThis causes the handler to handle the event how it's been designed to.</p>\n\n<p>It's common to have a <a href=\"https://docs.python.org/3/library/logging.handlers.html#streamhandler\" rel=\"nofollow noreferrer\"><code>StreamHandler</code></a> and sometimes a <a href=\"https://docs.python.org/3/library/logging.handlers.html#filehandler\" rel=\"nofollow noreferrer\"><code>FileHandler</code></a>.\nThe former that just <code>print</code>s the message, and the latter that writes the message to a file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:05:42.350",
"Id": "469825",
"Score": "0",
"body": "@BPL Yes exactly that. Yes this would be called an [iterative review](https://codereview.meta.stackexchange.com/q/1763). We have some rules around them, but in short _do not edit the above question_, post a new question. Also, to be clear, I am in no way obligated to help you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T21:02:22.200",
"Id": "239523",
"ParentId": "239520",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239523",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T19:04:28.620",
"Id": "239520",
"Score": "1",
"Tags": [
"python",
"design-patterns",
"generator",
"observer-pattern"
],
"Title": "Using generators on Observable class"
}
|
239520
|
<p>I am dealing with a large amount of XML files which I obtained from here <a href="https://clinicaltrials.gov/ct2/resources/download#DownloadAllData" rel="nofollow noreferrer">https://clinicaltrials.gov/ct2/resources/download#DownloadAllData</a>. The download yields around 300.000 XML files of similar structure which I eventually want to load into a single dataframe / csv. The code gives the result that I want: Each row is a single XML while columns are the categories/variable names coming from the XML X-Paths. The rows are filled with the text of each XML tag.</p>
<p>So far this is my code:</p>
<pre><code>#Import packages.
import pandas as pd
from lxml import etree
import os
from os import listdir
from os.path import isfile, join
from tqdm import tqdm
from functools import partial
from pprint import pprint
#Set options for displaying results
pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', None)
def run(file, content):
data = etree.parse(file)
#get all paths from the XML
get_path = lambda x: data.getpath(x)
paths = list(map(get_path, data.getroot().getiterator()))
content = [
data.getroot().xpath(path)
for path in paths
]
get_text = lambda x: x.text
content = [list(map(get_text, i)) for i in content]
dictionary = dict(zip(paths, content))
df = pd.DataFrame([dictionary])
global df_final
df_final = df_final.append(df)
def write_csv(df_name, csv):
df_name.to_csv(csv, sep=";")
#RUN
mypath = '/Users/marcelwieting/Documents/AllPublicXML'
folder_all = os.listdir(mypath)
for folder in tqdm(folder_all):
df_final = pd.DataFrame()
mypath2 = mypath + "/" + folder
if os.path.isdir(mypath2):
file = [f for f in listdir(mypath2) if isfile(join(mypath2, f))]
output = "./Output/" + folder + ".csv"
for x in tqdm(file):
dir = mypath2 + "/" + x
df_name = x.split(".", 1)[0]
run(dir,df_name)
write_csv(df_final, output)
</code></pre>
<p>I am an absolute Python newbie and this code is the result of some painful mix and match from various forum entries and tutorials. It runs through but given the size of the data sources, it takes really long. Presumably, because I have many iterations in my code which are certainly avoidable. (is there some vector based solution maybe, rather than iterating?) It would be very nice if I could get some feedback on how to improve speed and maybe even some general remarks on how to structure this code better. I know it is not good, but it's all I could pull off for now. :)
Cheers!</p>
<p>One sample XML file here:</p>
<pre><code><clinical_study>
<!--
This xml conforms to an XML Schema at:
https://clinicaltrials.gov/ct2/html/images/info/public.xsd
-->
<required_header>
<download_date>
ClinicalTrials.gov processed this data on March 20, 2020
</download_date>
<link_text>Link to the current ClinicalTrials.gov record.</link_text>
<url>https://clinicaltrials.gov/show/NCT03261284</url>
</required_header>
<id_info>
<org_study_id>2017-P-032</org_study_id>
<nct_id>NCT03261284</nct_id>
</id_info>
<brief_title>
D-dimer to Guide Anticoagulation Therapy in Patients With Atrial Fibrillation
</brief_title>
<acronym>DATA-AF</acronym>
<official_title>
D-dimer to Determine Intensity of Anticoagulation to Reduce Clinical Outcomes in Patients With Atrial Fibrillation
</official_title>
<sponsors>
<lead_sponsor>
<agency>Wuhan Asia Heart Hospital</agency>
<agency_class>Other</agency_class>
</lead_sponsor>
</sponsors>
<source>Wuhan Asia Heart Hospital</source>
<oversight_info>
<has_dmc>Yes</has_dmc>
<is_fda_regulated_drug>No</is_fda_regulated_drug>
<is_fda_regulated_device>No</is_fda_regulated_device>
</oversight_info>
<brief_summary>
<textblock>
This was a prospective, three arms, randomized controlled study.
</textblock>
</brief_summary>
<detailed_description>
<textblock>
D-dimer testing is performed in AF Patients receiving warfarin therapy (target INR:1.5-2.5) in Wuhan Asia Heart Hospital. Patients with elevated d-dimer levels (>0.5ug/ml FEU) were SCREENED AND RANDOMIZED to three groups at a ratio of 1:1:1. First, NOAC group,the anticoagulant was switched to Dabigatran (110mg,bid) when elevated d-dimer level was detected during warfarin therapy.Second,Higher-INR group, INR was adjusted to higher level (INR:2.0-3.0) when elevated d-dimer level was detected during warfarin therapy. Third, control group, patients with elevated d-dimer levels have no change in warfarin therapy. Warfarin is monitored once a month by INR ,and dabigatran dose not need monitor. All patients were followed up for 24 months until the occurrence of endpoints, including bleeding events, thrombotic events and all-cause deaths.
</textblock>
</detailed_description>
<overall_status>Enrolling by invitation</overall_status>
<start_date type="Anticipated">March 1, 2019</start_date>
<completion_date type="Anticipated">May 30, 2020</completion_date>
<primary_completion_date type="Anticipated">February 28, 2020</primary_completion_date>
<phase>N/A</phase>
<study_type>Interventional</study_type>
<has_expanded_access>No</has_expanded_access>
<study_design_info>
<allocation>Randomized</allocation>
<intervention_model>Parallel Assignment</intervention_model>
<primary_purpose>Treatment</primary_purpose>
<masking>None (Open Label)</masking>
</study_design_info>
<primary_outcome>
<measure>Thrombotic events</measure>
<time_frame>24 months</time_frame>
<description>
Stroke, DVT, PE, Peripheral arterial embolism, ACS etc.
</description>
</primary_outcome>
<primary_outcome>
<measure>hemorrhagic events</measure>
<time_frame>24 months</time_frame>
<description>cerebral hemorrhage,Gastrointestinal bleeding etc.</description>
</primary_outcome>
<secondary_outcome>
<measure>all-cause deaths</measure>
<time_frame>24 months</time_frame>
</secondary_outcome>
<number_of_arms>3</number_of_arms>
<enrollment type="Anticipated">600</enrollment>
<condition>Atrial Fibrillation</condition>
<condition>Thrombosis</condition>
<condition>Hemorrhage</condition>
<condition>Anticoagulant Adverse Reaction</condition>
<arm_group>
<arm_group_label>DOAC group</arm_group_label>
<arm_group_type>Experimental</arm_group_type>
<description>
Patients with elevated d-dimer levels was switched to DOAC (dabigatran 150mg, bid).
</description>
</arm_group>
<arm_group>
<arm_group_label>Higher-INR group</arm_group_label>
<arm_group_type>Experimental</arm_group_type>
<description>
Patients' target INR was adjusted from 1.5-2.5 to 2.0-3.0 by adding warfarin dose.
</description>
</arm_group>
<arm_group>
<arm_group_label>Control group</arm_group_label>
<arm_group_type>No Intervention</arm_group_type>
<description>
Patients continue previous strategy without change.
</description>
</arm_group>
<intervention>
<intervention_type>Drug</intervention_type>
<intervention_name>Dabigatran Etexilate 150 MG [Pradaxa]</intervention_name>
<description>Dabigatran Etexilate 150mg,bid</description>
<arm_group_label>DOAC group</arm_group_label>
<other_name>Pradaxa</other_name>
</intervention>
<intervention>
<intervention_type>Drug</intervention_type>
<intervention_name>Warfarin Pill</intervention_name>
<description>Add warfarin dose according to INR values.</description>
<arm_group_label>Higher-INR group</arm_group_label>
</intervention>
<eligibility>
<criteria>
<textblock>
Inclusion Criteria: - Patients with non-valvular atrial fibrillation - Receiving warfarin therapy Exclusion Criteria: - Patients who had suffered from recent (within 3 months) myocardial infarction, ischemic stroke, deep vein thrombosis, cerebral hemorrhages, or other serious diseases. - Those who had difficulty in compliance or were unavailable for follow-up.
</textblock>
</criteria>
<gender>All</gender>
<minimum_age>18 Years</minimum_age>
<maximum_age>75 Years</maximum_age>
<healthy_volunteers>No</healthy_volunteers>
</eligibility>
<overall_official>
<last_name>Zhenlu ZHANG, MD,PhD</last_name>
<role>Study Director</role>
<affiliation>Wuhan Asia Heart Hospital</affiliation>
</overall_official>
<location>
<facility>
<name>Zhang litao</name>
<address>
<city>Wuhan</city>
<state>Hubei</state>
<zip>430022</zip>
<country>China</country>
</address>
</facility>
</location>
<location_countries>
<country>China</country>
</location_countries>
<verification_date>March 2019</verification_date>
<study_first_submitted>August 22, 2017</study_first_submitted>
<study_first_submitted_qc>August 23, 2017</study_first_submitted_qc>
<study_first_posted type="Actual">August 24, 2017</study_first_posted>
<last_update_submitted>March 6, 2019</last_update_submitted>
<last_update_submitted_qc>March 6, 2019</last_update_submitted_qc>
<last_update_posted type="Actual">March 7, 2019</last_update_posted>
<responsible_party>
<responsible_party_type>Sponsor</responsible_party_type>
</responsible_party>
<keyword>D-dimer</keyword>
<keyword>Nonvalvular atrial fibrillation</keyword>
<keyword>Direct thrombin inhibitor</keyword>
<keyword>INR</keyword>
<condition_browse>
<!--
CAUTION: The following MeSH terms are assigned with an imperfect algorithm
-->
<mesh_term>Atrial Fibrillation</mesh_term>
<mesh_term>Thrombosis</mesh_term>
<mesh_term>Hemorrhage</mesh_term>
</condition_browse>
<intervention_browse>
<!--
CAUTION: The following MeSH terms are assigned with an imperfect algorithm
-->
<mesh_term>Warfarin</mesh_term>
<mesh_term>Dabigatran</mesh_term>
<mesh_term>Fibrin fragment D</mesh_term>
</intervention_browse>
<!--
Results have not yet been posted for this study
-->
</clinical_study>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T20:29:39.200",
"Id": "469939",
"Score": "1",
"body": "The answer for fast parsing of large XML files might help: https://stackoverflow.com/questions/324214/what-is-the-fastest-way-to-parse-large-xml-docs-in-python ... the code looks simpler than yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T23:07:59.370",
"Id": "469950",
"Score": "1",
"body": "How do you plan to handle duplicate xml paths? The sample data has more than one `/arm_group/arm_group_label`, and `/keyword`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T23:27:37.437",
"Id": "469951",
"Score": "0",
"body": "This ```get_path = lambda x: data.getpath(x)\n paths = list(map(get_path, data.getroot().getiterator()))```\n automatically creates ```/arm_group/arm_group_label[0]``` and ```/arm_group/arm_group_label[1]```. So x-paths are unique."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T22:18:40.140",
"Id": "470029",
"Score": "0",
"body": "Can you explain the directory structure you're working with? I don't understand the purpose of some of the code in the `for folder in tqdm(folder_all):` loop. It might also be useful to have an example of the output in the post itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T22:37:52.377",
"Id": "470031",
"Score": "0",
"body": "Scratch that, I think having the output is crucial, I'm struggling to follow much of the XPath/parsing section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:57:07.777",
"Id": "470083",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T21:19:24.017",
"Id": "470161",
"Score": "0",
"body": "Understood, thanks for the help and cleaning up my post!"
}
] |
[
{
"body": "<p>Seems like it might be a good use for parallizing with the <code>multiprocessing</code> library. Something like this (untested):</p>\n\n<pre><code>from multiprocessing import Pool\n\n# your other code goes here\n\nmypath = '/Users/marcelwieting/Documents/AllPublicXML'\nfolder_all = os.listdir(mypath)\n\ndef process_folder(folder):\n df_final = pd.DataFrame()\n mypath2 = mypath + \"/\" + folder\n if os.path.isdir(mypath2):\n file = [f for f in listdir(mypath2) if isfile(join(mypath2, f))]\n output = \"./Output/\" + folder + \".csv\"\n for x in tqdm(file):\n dir = mypath2 + \"/\" + x\n df_name = x.split(\".\", 1)[0]\n run(dir,df_name)\n\n write_csv(df_final, output)\n\nif __name__ == \"__main__\":\n with Pool() as p:\n print(p.imap_unordered(process_folder, folder_all))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T00:33:44.100",
"Id": "239594",
"ParentId": "239521",
"Score": "3"
}
},
{
"body": "<p>Avoid doing explicit appends in your for loop and use dictionary (or list) comprehension instead; this makes it run more than 3x faster on my machine.</p>\n\n<p>That is, do something like</p>\n\n<pre><code>def run(file, content):\n data = etree.parse(file)\n\n get_path = lambda x: data.getpath(x)\n paths = list(map(get_path, data.getroot().getiterator()))\n\n content = [\n data.getroot().xpath(path)\n for path in paths\n ]\n\n get_text = lambda x: x.text\n content = [list(map(get_text, i)) for i in content]\n\n bundle = dict(zip(paths, content))\n\n df = pd.DataFrame([bundle])\n global df_final\n df_final = df_final.append(df)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T17:55:36.237",
"Id": "470147",
"Score": "1",
"body": "Note that my answer (earlier just a comment) was essentially integrated into the original question by the OP so it can look a little strange."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-04T18:29:05.050",
"Id": "470621",
"Score": "1",
"body": "check out my answer for another 15x improvement ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T17:54:35.107",
"Id": "239675",
"ParentId": "239521",
"Score": "3"
}
},
{
"body": "<p><strong>TLDR</strong>: it can be done much more quickly and much more concisely, in <strong>28 minutes</strong> end-to-end, and in <strong>12 minutes</strong> when all XML are already on disk. The key trick: using the <strong>long</strong> rather than <strong>wide</strong> format for each data frame.</p>\n\n<p>There are two parts to your code: style and performance. Let me post my approach and comment on why I coded it like this.</p>\n\n<p>For imports, I separate Python standard libraries and user-installed libraries, and put them both in alphabetical order. This makes your code more readable.</p>\n\n<pre><code>import os\nimport zipfile\n\nimport click\nfrom lxml import etree\nimport pandas as pd\nimport requests\n</code></pre>\n\n<p>You didn't post it, so I had to write my own code to download and unzip all the CDC XML files:</p>\n\n<pre><code>def download_data(url, file):\n response = requests.get(url, stream=True)\n assert response.status_code == 200\n with open(file, 'wb') as dst:\n for chunk in response.iter_content(chunk_size=4096):\n dst.write(chunk)\n\ndef unzip_data(file, path):\n with zipfile.ZipFile(file) as src:\n src.extractall(path)\n\nurl = 'https://clinicaltrials.gov/AllPublicXML.zip'\nfile = url.split('/')[-1]\npath = file.split('.')[0]\n\ndownload_data(url, file) \nunzip_data(file, path)\n</code></pre>\n\n<p>Note that I didn't write out my full path for my working directory, this is all implicitly handled relative to the working directory from where you run your code (yeah, explicit is better than implicit, but in this case I ignore the Zen of Python).</p>\n\n<p>Next, there is the issue of parsing a single XML file. Your approach used two iterations over the parse tree, and some unnecessary lambdas stored in variables (why not do it in place?). It is possible to iterate just once over the parse tree, and extract both the xpath and the text. Furthermore, it will turn out that storing this in <strong>long format</strong> as a 3-column data frame with a variable number of rows will gain an order of magnitude when concatenating these data frames later on. </p>\n\n<pre><code>def parse_xml(file):\n # The CDC XML files are named NCTyyyyxxxx, this extracts the 8 yyyyxxxx digits\n id = int(os.path.splitext(os.path.basename(file))[0][-8:])\n tree = etree.parse(file)\n return pd.DataFrame(\n data=[\n (id, tree.getpath(elem), elem.text)\n for elem in tree.iter()\n ],\n columns=['id', 'key', 'value']\n )\n</code></pre>\n\n<p>Note that there is no longer a need to have an intermediate dict. The code above just parses the tree into a list of tuples and initializes a data frame with it.</p>\n\n<p>Next, the iteration over the directory tree is most conveniently done using the standard library, in particular <code>os.walk</code>. Note that in your code, you not only had to manually check for directory and files, but you also manually combined directory names, file names and extensions rather than with the standard <code>os.path.join</code> (which would have made it platform independent).</p>\n\n<pre><code>xml_files = [\n os.path.join(dirpath, file)\n for dirpath, _, filenames in os.walk(path)\n for file in filenames\n if file.endswith('.xml')\n]\n</code></pre>\n\n<p>The code above stores the 335K XML file paths in a list (takes less than 1 second).</p>\n\n<p>Finally, combining the above code is simply a loop over the files, parsing each file and concatenating the results. I use the progressbar to see how fast it will be, but in this case the time is a mere <strong>12 minutes</strong>.</p>\n\n<pre><code>with click.progressbar(xml_files) as bar:\n df = pd.concat((\n parse_xml(f)\n for f in bar\n ))\ndf.to_csv('output.csv')\n</code></pre>\n\n<p>Inspecting this data frame shows that it has almost 100M rows and 3 columns. In contrast, the wide format would have had 335K rows but 730K columns. This is the reason that this code ran so slow: concatenating / appending all these differently laid-out data frames requires an inordinate amount of data copying to align it in the final data frame. In contrast, the long format just appends 3 known columns. </p>\n\n<p>Total file on disk is 11 Gb.</p>\n\n<p><strong>EDIT</strong>: in the end I didn't manage to run your posted code because of memory overflow (335K rows x 730K columns will do that unless you have a Tb of RAM). Note that I didn't use a global variable to which I <code>append()</code> each parsed XML file. The Pandas docs state that <code>pd.concat()</code> should be more performant. It was for my approach: the progress bar indicated that appending to an initially empty data frame would increase the total time to over <strong>2 hours</strong>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-04T17:11:36.837",
"Id": "239932",
"ParentId": "239521",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239932",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T19:38:07.747",
"Id": "239521",
"Score": "9",
"Tags": [
"python",
"performance",
"parsing",
"csv",
"xml"
],
"Title": "Performance - Read large amount of XMLs and load into single csv"
}
|
239521
|
<p>So I wrote this a while ago and yesterday I was going through it and trying to remember every line of code and how it works.
Well, the program simulates a online bank account as well as an ATM. You register your account, you are able to withdraw, deposit, and transfer money. There is a limit to the amount you can transfer and withdraw in a day, there is a limit number for attempts, if you exceed it you will be locked out of the account for 24 hours, you can see all the transactions you've made, and there is a log for the admin, and all of that is saved to file.</p>
<p>Anyway, it is a pretty long program (thus the feeling that the design is wrong), <strong>what I am asking is not to go by line by line and review it, just to check out how the program works and review its design and give some feedback.</strong> However, if you want to review the code itself or if you something that is not right I would appreciate your feedback on that.</p>
<p>Paths.h</p>
<pre><code>#ifndef PATHS_H_INCLUDED
#define PATHS_H_INCLUDED
class Paths
{
public:
static const std::string BASE_PATH;
static const std::string USER_PATH;
static const std::string ADMIN_PATH;
static const std::string USER_INFO;
static const std::string USER_TRANSACTION;
static const std::string ADMIN_BACKUP;
static const std::string ADMIN_LOCKED_ACCOUNTS;
static const std::string ADMIN_LOG;
static const std::string ADMIN_WITHDRAWAL_DATE;
static const std::string ADMIN_WITHDRAWAL_VAL;
static const std::string ADMIN_TRANSFER_DATE;
static const std::string ADMIN_TRANSFER_VAL;
};
#endif // PATHS_H_INCLUDED
</code></pre>
<p>Paths.cpp</p>
<pre><code>#include <iostream>
#include "Paths.h"
using namespace std;
const string Paths::BASE_PATH = "C:\\ProgramData\\BankAcount";
const string Paths::USER_PATH = BASE_PATH + "\\User";
const string Paths::ADMIN_PATH = BASE_PATH + "\\Administrator";
const string Paths::USER_INFO = USER_PATH + "\\Info\\";
const string Paths::USER_TRANSACTION = USER_PATH + "\\Transactions\\";
const string Paths::ADMIN_BACKUP = ADMIN_PATH + "\\Backup\\";
const string Paths::ADMIN_LOCKED_ACCOUNTS = ADMIN_PATH + "\\LockedAccounts\\";
const string Paths::ADMIN_LOG = ADMIN_PATH + "\\Log\\";
const string Paths::ADMIN_TRANSFER_DATE = ADMIN_PATH + "\\Limits\\Transfer\\Dates\\";
const string Paths::ADMIN_TRANSFER_VAL = ADMIN_PATH + "\\Limits\\Transfer\\Values\\";
const string Paths::ADMIN_WITHDRAWAL_DATE = ADMIN_PATH + "\\Limits\\Withdrawal\\Dates\\";
const string Paths::ADMIN_WITHDRAWAL_VAL = ADMIN_PATH + "\\Limits\\Withdrawal\\Values\\";
</code></pre>
<p>classAccount.h</p>
<pre><code>#ifndef CLASSACCOUNT_H_INCLUDED
#define CLASSACCOUNT_H_INCLUDE
class Account
{
protected:
std::string name;
std::string new_name;
long long int balance;
std::string account_num;
std::string file_path;
std::string pin, new_pin;
char buffer[256];
void createFolder() const;
void withdrawal();
void deposit ();
void viewBalance() const;
void transfer();
void logTransactions(const std::string& log_account_num, const std::string& transaction_type, const int& amount) const;
void transactions(const std::string& account_num) const;
void log( bool note ) const;
void logInsideAccount(const std::string& in_account) const;
void withdrawalLimit(int withdrawalAmount);
void transferLImit (int transferAmount);
void createLimitFiles();
void dayShiftCheck();
void deleteFile(std::string file_to_delete);
void settings();
void changePin();
void pinChanged();
void changeName();
void nameChanged();
void clearTransactions();
void transactionsCleared();
// int numberOfTransactions = 0;
void lockAccount();
void lockAccountCheck();
void signUp();
void signIn();
void myAccount(std::ifstream* fileStream);
void signOut ();
void parseAccountInfo(const char* buffer, std::string& assigned_name, std::string& assigned_account_num, long long int& assigned_Balance, std::string& assigned_pin) const;
void backupAccountFile(const std::string& file) const;
void backupTransactionFile(const std::string& file) const;
std::string accountExistenceCheckSignIn(std::string& account_num);
std::string accountExistenceCheckSignUp(std::string& account_num) ;
std::string accountExistenceCheckTransfer(std::string& account_num) ;
public:
void mainMenu();
};
#endif
</code></pre>
<p>classAccount.cpp</p>
<pre><code>#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <stdlib.h>
#include <conio.h>
#include <direct.h>
#include <windows.h>
// #include <algorithm>
// #include <list>
#include <sys/types.h>
#include <sys/stat.h>
#include "classAccount.h"
#include "Paths.h" // a class where constant strings, that contains entire paths to where file containing the necessary info, will be managed
using namespace std;
// a function that creates the directories where the account files will be storaged
// it checks wether the necessary folders are already created before creating the folders
void Account::createFolder() const
{
class stat info; // used when checking the existence of the folder
if(stat(Paths::BASE_PATH.c_str(), &info) != 0) // I could ommit this path and it still would be created in the next lines but I chose to write
system(("mkdir " + Paths::BASE_PATH).c_str()); // it so the code can be slightly more readable, at least in my opinion
if(stat(Paths::USER_PATH.c_str(), &info) != 0)
system(("mkdir " + Paths::USER_PATH).c_str() );
if(stat(Paths::USER_INFO.c_str(), &info) != 0)
system(("mkdir " + Paths::USER_INFO).c_str() );
if(stat(Paths::USER_TRANSACTION.c_str(), &info) != 0)
system(("mkdir " + Paths::USER_TRANSACTION).c_str() );
if(stat(Paths::ADMIN_PATH.c_str(), &info) != 0) // I could ommit this path and it still would be created in the next lines but I chose to write
system(("mkdir " + Paths::ADMIN_PATH).c_str() ); // so the code can be slightly more readable, at least in my opinion
if(stat(Paths::ADMIN_BACKUP.c_str(), &info) != 0)
system(("mkdir " + Paths::ADMIN_BACKUP).c_str() );
if(stat(Paths::ADMIN_LOCKED_ACCOUNTS.c_str(), &info) != 0)
system(("mkdir " + Paths::ADMIN_LOCKED_ACCOUNTS).c_str() );
if(stat(Paths::ADMIN_LOG.c_str(), &info) != 0)
system(("mkdir " + Paths::ADMIN_LOG).c_str() );
// paths to where the dates and values information will be saved for withdrawal and transfer limits purposes
if(stat(Paths::ADMIN_WITHDRAWAL_DATE.c_str(), &info) != 0)
system(("mkdir " + Paths::ADMIN_WITHDRAWAL_DATE).c_str() );
if(stat(Paths::ADMIN_WITHDRAWAL_VAL.c_str(), &info) != 0)
system(("mkdir " + Paths::ADMIN_WITHDRAWAL_VAL).c_str() );
if(stat(Paths::ADMIN_TRANSFER_DATE.c_str(), &info) != 0)
system(("mkdir " + Paths::ADMIN_TRANSFER_DATE).c_str() );
if(stat(Paths::ADMIN_TRANSFER_VAL.c_str(), &info) != 0)
system(("mkdir " + Paths::ADMIN_TRANSFER_VAL).c_str() );
}
void Account::deleteFile(std::string file_to_delete)
{
// convert string to const char* so it can be used in file_path for deletion
/*
const char* deleteFile = sfile_path.data();
const char* deleteFile = sfile_path.c_str();
const char* delete_file = &file_to_delete[0];
*/
remove(file_to_delete.c_str());
}
// display the simple menu at the beginning
void Account::mainMenu()
{
system("cls");
createFolder();
// mkdir("D:\Bank Account");
account_num.clear();
pin.clear();
char option;
cout << "\n\n\n\n\n\n \t\t\t\t\t" << "1 -> Sign In" << endl;
cout << " \t\t\t\t\t" << "2 -> Sign Up" << endl << endl;
cout << " \t\t\t\t\t" << " -> ";
option = _getch();
while (option != '1' && option != '2' && option != 27)
{
option = _getch();
}
switch (option)
{
case '1':
system("cls");
signIn();
break;
case '2':
system("cls");
signUp();
break;
case '0':
cout << "\nProcess returned 0" << endl << "Press enter key to continue";
cin.get();
exit(0);
break;
case 27:
cout << "\nProcess returned 0" << endl << "Press enter key to continue";
cin.get();
exit(0);
break;
default:
mainMenu();
break;
}
}
// a function to lock the account that had 3 failed attempts on a password input
void Account::lockAccount()
{
string sfile_path = Paths::ADMIN_LOCKED_ACCOUNTS + account_num;
time_t now = time(nullptr);
string time_now = ctime(&now); // takes the system times into a string, showing the lock time
tm* lock_time = localtime(&now);
ofstream lock (sfile_path); // create the file that contains the time of the lock
lock << lock_time->tm_mday << " " << lock_time->tm_hour << " " << lock_time->tm_min;
lock.close();
}
// a function that everytime a user goes to sign in it checks if the account is locked or not
void Account::lockAccountCheck()
{
string sfile_path = Paths::ADMIN_LOCKED_ACCOUNTS + account_num;
ifstream file_in (sfile_path);
// checks for the existence of a file that contains the time of the lock, if the file doesn't exist it returns meaning that
// the account is not locked
if ( ! file_in.good() )
{
return;
}
time_t now = time(nullptr);
string time_now = ctime(&now);
tm* lock_time = localtime(&now);
char bufferLine[256];
// integers that hold the dates values
int filelock_timeDay;
int filelock_timeHour;
int filelock_timeMinute;
int lock_timeDay = lock_time->tm_mday;
int lock_timeHour = lock_time->tm_hour;
int lock_timeMinute = lock_time->tm_min;
// it gets the information of the time from the lock account file and hold it in char
file_in.getline(bufferLine, 256);
istringstream lockFile (bufferLine); // it parses the contents of the file
// it assigns each date value to the respective variable
lockFile >> filelock_timeDay;
lockFile >> filelock_timeHour;
lockFile >> filelock_timeMinute;
// count the days, hours and minutes to check if the time of the lock has passed
// it compares the time of the system against the lock time
int count_day = lock_timeDay - filelock_timeDay;
int count_hour = lock_timeHour - filelock_timeHour;
int count_minute = lock_timeMinute - filelock_timeMinute;
file_in.close();
if ( count_day == 0 )
{
cout << endl << endl << "Your Account Has Been Locked Since " << filelock_timeDay << " - " << 1 + lock_time->tm_mon
<< " - " << 1900 + lock_time->tm_year << " | " << filelock_timeHour << ":" << filelock_timeMinute << endl << endl;
cout << "Locking Period: 24 Hours" ;
cout << endl<< endl << "Press enter key to continue";
char ch;
ch = _getch();
while (ch != 13)
{
ch = _getch();
}
mainMenu();
}
else if (count_day > 0 && count_hour < 0 )
{
cout << endl << endl << "Your Account Has Been Locked Since " << filelock_timeDay << " - " << 1 + lock_time->tm_mon
<< " - " << 1900 + lock_time->tm_year << " | " << filelock_timeHour << ":" << filelock_timeMinute << endl << endl;
cout << "Locking Period: 24 Hours" ;
cout << endl<< endl << "Press enter key to continue";
char ch;
ch = _getch();
while (ch != 13)
{
ch = _getch();
}
mainMenu();
}
/*
else if (count_day > 0 && filelock_timeHour < lock_timeHour)
{
}
*/
else if (count_day > 0 && count_hour >= 0 && lock_timeHour == filelock_timeHour && count_minute < 0 )
{
cout << endl << endl << "Your Account has Been Locked Since " << filelock_timeDay << " - " << 1 + lock_time->tm_mon
<< " - " << 1900 + lock_time->tm_year << " | " << filelock_timeHour << ":" << filelock_timeMinute << endl << endl;
cout << "Locking Period: 24 Hours" ;
cout << endl<< endl << "Press enter jey to continue";
char ch;
ch = _getch();
while (ch != 13)
{
ch = _getch();
}
mainMenu();
}
deleteFile(sfile_path); // the file that contains the locking info will be deleted after it is known that it has passed 24hours after the lock
}
// a function that creates a file that contains log information
void Account::log(bool note ) const // the bool note is a bool that logs wether the account was locked because of too many failed password attempts
{
time_t now = time(nullptr);
// string time_now = ctime(&now);
tm* log_time = localtime(&now);
int log_day, log_month, log_year;
string sLog_day, sLog_month, sLog_year;
log_day = log_time->tm_mday;
log_month = 1 + log_time->tm_mon;
log_year = 1900 + log_time->tm_year;
// the dates obtained and held in integer variables will be coverted to string so they can be added to the file path
sLog_day = to_string(log_day);
sLog_month = to_string(log_month);
sLog_year = to_string(log_year);
string sfile_path = Paths::ADMIN_LOG + sLog_day + " - " + sLog_month + " - " + sLog_year;
ifstream file_in(sfile_path);
string existent_content;
char c;
while (file_in.good() && ! file_in.eof())
{
c = file_in.get();
existent_content.push_back(c);
}
ofstream log(sfile_path);
log << existent_content << endl << endl;
log << "-----------------------------------------------------------------------------------" << endl << endl;
log << "Account Number: " << account_num << " | " << "Name: " << name << endl;
log << "Sign In " << " at " << log_time->tm_hour << ":" << log_time->tm_min << ":" << log_time->tm_sec;
//log << "Sign In " << " at " << __DATE__;
// if the note is true it logs in the file that the account was blocked for 24 hours and informing the time of the occured
if (note == true)
{
log << endl << "Account Locked For 24 Hours Started At " << log_time->tm_hour << ":" << log_time->tm_min << ":" << log_time->tm_sec;
}
log.close();
}
// a function that creates a file that logs every activity inside an account
void Account::logInsideAccount(const string& inAccount_activity) const // the string will take the type of activity made
{
time_t now = time(nullptr);
// string time_now = ctime(&now);
tm* log_time = localtime(&now);
int log_day, log_month, log_year;
string sLog_day, sLog_month, sLog_year;
log_day = log_time->tm_mday;
log_month = 1 + log_time->tm_mon;
log_year = 1900 + log_time->tm_year;
sLog_day = to_string(log_day);
sLog_month = to_string(log_month);
sLog_year = to_string(log_year);
string sfile_path = Paths::ADMIN_LOG + sLog_day + " - " + sLog_month + " - " + sLog_year;
ifstream file_in(sfile_path);
string existent_content;
char c;
// while the log file is ok and hasn't reached the end it will keep copying the content to the string existent_content
while (file_in.good() && ! file_in.eof())
{
c = file_in.get();
existent_content.push_back(c);
}
ofstream log(sfile_path);
log << existent_content << endl;
log << " - " << inAccount_activity << " at " << log_time->tm_hour << ":" << log_time->tm_min << ":" << log_time->tm_sec ;
// log << " - " << inAccount_activity << " at " << __TIME__ ;
log.close(); // closes the file after use
}
// log every transaction
void Account::logTransactions(const string& log_account_num, const string& transaction_type, const int& amount) const
{
time_t now = time(nullptr);
char* time_now = ctime(&now);
string sfile_path = Paths::USER_TRANSACTION + log_account_num;
ifstream file_in(sfile_path); // it enters the file
string existent_content;
char c;
// copies the exitent content in the transaction file to a string
while (file_in.good() && ! file_in.eof())
{
c = file_in.get();
existent_content.push_back(c);
}
file_in.close(); // closes the file after use
/* should've used ios::app for appending thus eliminating the need to write the previous
code to save the existing content of the file */
ofstream fileOut (sfile_path); // creates the file with the same name and path of the previous file, thus overwriting
/* Desnecessary */
fileOut << existent_content << endl << endl; // it writes the already logged transactions to the file and below it writes the recent transaction to the file
/* Desnecessary */
fileOut << "-> " << time_now;// << endl ;
fileOut << "[ " << transaction_type << " ] -> ";
fileOut << "Amount: " << amount;
fileOut.close(); // closes the file after use
backupTransactionFile(log_account_num);
}
void Account::parseAccountInfo(const char* buffer, string& assigned_name, string& assigned_account_num,
long long int& assigned_balance, string& assigned_pin) const
{
// associate an istrstream object with the accountut
// character string
istringstream account(buffer);
account >> assigned_name;
// now the account number
account >> assigned_account_num;
// and the balance
account >> assigned_balance;
account >> assigned_pin;
}
// a function that creates a backup file of the account file and of the transaction
void Account::backupAccountFile(const string& file) const
{
string sfile_path = Paths::USER_INFO + file; // original file path
string source(sfile_path);
string target = Paths::ADMIN_BACKUP + file; // backup file path
ifstream input (source.c_str(), ios_base::in | ios_base::binary);
ofstream output (target.c_str(), ios_base::out | ios_base::binary | ios_base::trunc);
if (input.good() && output.good())
{
while( ! input.eof() && input.good())
{
char buffer[4096];
input.read(buffer, 4096);
output.write(buffer, input.gcount());
}
}
}
void Account::backupTransactionFile(const string& file) const
{
string sfile_path = Paths::USER_TRANSACTION + file;
string source(sfile_path);
string target = Paths::ADMIN_BACKUP + file + "-trans" ;
ifstream input (source.c_str(), ios_base::in | ios_base::binary);
ofstream output (target.c_str(), ios_base::in | ios_base::binary | ios_base::trunc);
if (input.good() && output.good())
{
while ( ! input.eof() && input.good())
{
char buffer[4096];
input.read(buffer, 4096);
output.write(buffer, input.gcount());
}
}
}
// function that checks wether the file exists or not when the user is signing in
string Account::accountExistenceCheckSignIn(string& account_num) // the string takes the account number input by the user
{
string sfile_path = Paths::USER_INFO + account_num;
char ch_num;
int num_length = 1;
ifstream file_stream(sfile_path);
// a condition that checks wether the file exists or not, if it is good it means that the file exists thus the account too
if (file_stream.good())
{
return sfile_path;
}
account_num.clear();
while (true)
{
cout << endl << endl << "Account Doesn't Exist!!" << endl;
cout << endl << "Enter Your Bank Account Number: ";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
cout << "\b \b";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_num != 13)
{
if (account_num.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_num == 8)
{
if ( ! account_num.empty())
{
-- num_length;
account_num.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and account_num will be take the character input by the user
// only numbers are accepted
else if (num_length <= 16 && isdigit(ch_num))
{
if (account_num.empty())
cout << "\b \b";
account_num.push_back(ch_num);
cout << ch_num;
++num_length;
}
else if ( account_num.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
{
cout << " \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
}
// when the user learns that the account doesnt exist he or she has the optionion of entering '0' and go back to the main menu
if (account_num[0] == '0' && account_num.size() == 1)
{
mainMenu();
}
sfile_path = Paths::USER_INFO + account_num;
ifstream file_stream (sfile_path);
// the user will keep being noticed that the account doesnt exist until he or she either inputs a valid account number or '0'
if (file_stream.good())
{
break;
}
account_num.clear();
num_length = 1;
}
return sfile_path; // the function will return the path of the acoount file
}
// function that checks wether the file exists or not when the user is signing up
string Account::accountExistenceCheckSignUp(string& account_num)
{
string sfile_path = Paths::USER_INFO + account_num;
char ch_num;
int num_length = 1;
ifstream file_stream(sfile_path);
// a condition that checks wether the file exists or not, if it doesnt exit it breaks out the loop meaning that the account
// doesnt exist so it is safe to create an account with that number
if ( ! file_stream.good())
{
return sfile_path;;
}
account_num.clear();
while (true)
{
cout << endl << endl << "Account Already Exists!!" << endl;
cout << "Account Number: ";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
cout << "\b \b";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_num != 13)
{
if (account_num.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_num == 8)
{
if ( ! account_num.empty())
{
-- num_length;
account_num.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and account_num will be take the character input by the user
// only numbers are accepted
else if (num_length <= 16 && isdigit(ch_num))
{
if (account_num.empty())
cout << "\b \b";
account_num.push_back(ch_num);
cout << ch_num;
++num_length;
}
else if ( account_num.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
{
cout << " \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
}
// when the user learns that the account doesnt exist he or she has the optionion of entering '0' and go back to the main menu
if (account_num[0] == '0' && account_num.size() == 1)
{
mainMenu();
}
sfile_path = Paths::USER_INFO + account_num;
ifstream file_stream (sfile_path);
// the user will keep being noticed that the account doesnt exist until he or she either inputs a valid account number or '0'
if ( ! file_stream.good())
{
break;
}
account_num.clear();
num_length = 1;
}
cout << endl;
return sfile_path;
}
// a function that checks for the existence of a file that is aimed to be transfered an amount
string Account::accountExistenceCheckTransfer(string& transfer_account_number)
{
string sfile_path = Paths::USER_INFO + transfer_account_number;
char ch_num;
int num_length = 1;
ifstream file_stream(sfile_path);
if (file_stream.good())
{
return sfile_path;
}
while (true)
{
transfer_account_number.clear();
num_length = 1;
cout << endl << endl << "Account Doesn't Exist!!" << endl;
cout << setw(10) << "To Account Number: ";
ch_num = _getch();
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
while (ch_num == 13 && num_length <= 16)
{
if (transfer_account_number.empty())
cout << "\b \b";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_num != 13)
{
if (transfer_account_number.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_num == 8)
{
if ( ! transfer_account_number.empty())
{
-- num_length;
transfer_account_number.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and transfer_account_number will be take the character input by the user
// only numbers are accepted
else if (num_length <= 16 && isdigit(ch_num))
{
if (transfer_account_number.empty())
cout << "\b \b";
transfer_account_number.push_back(ch_num);
cout << ch_num;
++num_length;
}
else if ( transfer_account_number.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
while (ch_num == 13 && num_length <= 16)
{
if (transfer_account_number.empty())
{
cout << " \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
}
}
while (transfer_account_number == account_num)
{
transfer_account_number.clear();
num_length = 1;
cout << endl << endl << "Can't Transfer Money To Your Own Account!" << endl;
cout << setw(10) << "To Account Number: ";
ch_num = _getch();
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
while (ch_num == 13 && num_length <= 16)
{
if (transfer_account_number.empty())
cout << "\b \b";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_num != 13)
{
if (transfer_account_number.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_num == 8)
{
if ( ! transfer_account_number.empty())
{
-- num_length;
transfer_account_number.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and transfer_account_number will be take the character input by the user
// only numbers are accepted
else if (num_length <= 16 && isdigit(ch_num))
{
if (transfer_account_number.empty())
cout << "\b \b";
transfer_account_number.push_back(ch_num);
cout << ch_num;
++num_length;
}
else if ( transfer_account_number.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
while (ch_num == 13 && num_length <= 16)
{
if (transfer_account_number.empty())
{
cout << " \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
ifstream file (file_path);
myAccount(&file);
}
}
}
}
sfile_path = Paths::USER_INFO + transfer_account_number;
ifstream file_stream (sfile_path);
if (file_stream.good())
{
break;
}
}
return sfile_path;
}
// create a set of files that will contain days and amounts of withdrawal and transfer thta helps ensuring the limit for withdrawal and transfer
void Account::createLimitFiles()
{
// a file path to where the file that will contain the current day will be saved
string datefile_path = Paths::ADMIN_WITHDRAWAL_DATE + account_num;
ofstream date_file (datefile_path); // it is to check the current day to ensure the amount of the withdrawal in one day won't be exceeded
time_t now = time(nullptr);
tm* day_check = localtime(&now);
date_file << day_check->tm_mday;
date_file.close();
// a file path to where the file that will contain theamount of withdrawal in one day will be saved
string valuefile_path = Paths::ADMIN_WITHDRAWAL_VAL + account_num;
ofstream valueFile (valuefile_path);
valueFile << 0; // the initial amount is 0
valueFile.close();
// a file path to where the file that will contain the current day will be saved
string datefile_pathTransfer = Paths::ADMIN_TRANSFER_DATE + account_num;
ofstream dateFileTransfer (datefile_pathTransfer); // it is to check the current day to ensure the amount of the withdrawal in one day won't be exceeded
dateFileTransfer << day_check->tm_mday;
dateFileTransfer.close();
// a file path to where the file that will contain theamount of withdrawal in one day will be saved
string valuefile_pathTransfer = Paths::ADMIN_TRANSFER_VAL + account_num;
ofstream valueFileTransfer (valuefile_pathTransfer);
valueFileTransfer << 0; // the initial amount is 0
valueFileTransfer.close();
}
// function that gets the user through the 'sign up' steps
void Account::signUp()
{
// cin.get(); // dont know why but it seems like when it enters the functions signIn and signUp it comes with an ENTER already pressed
balance = 0; // balance is set to zero because when the user creates a new account his ir her balance will be zero
string sname;
// int arrow = 224;
// char chName;
// bool check = false;
system("cls");
cout << "\t\t\t Sign Up" << endl << endl;
cout << "Name: ";
getline(cin, sname);
if (sname == "0")
{
mainMenu();
}
while (sname.empty())
{
system("cls");
cout << "\t\t\t Sign Up" << endl << endl;
cout << "Name: ";
getline(cin, sname);
if (sname == "0")
{
mainMenu();
}
}
for (unsigned int i = 0; i < sname.size(); ++i)
{
if (( ! isalpha(sname[i]) && ! isspace(sname[i]) ) || isspace(sname[0]))
{
cout << endl << "Invalid Name \n Re-enter: ";
getline(cin, sname);
if (sname == "0")
{
mainMenu();
}
while (sname.empty())
{
cout << endl << "Can't Be Empty \n Re-enter: ";
getline(cin, sname);
if (sname == "0")
{
mainMenu();
}
}
i = -1;
}
}
system("cls");
char ch_num;
int num_length = 1;
cout << "\t\t\t Sign Up" << endl << endl;
cout << "Name: " << sname;
cout << endl << endl << "Account Number: ";
ch_num = getch();
if (ch_num == 27)
{
mainMenu();
}
// in case the user presses enter right away
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
cout << "\b \b";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_num != 13)
{
if (account_num.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_num == 8)
{
if ( ! account_num.empty())
{
-- num_length;
account_num.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and account_num will be take the character input by the user
// only numbers are accepted
else if (num_length <= 16 && isdigit(ch_num))
{
if (account_num.empty())
cout << "\b \b";
account_num.push_back(ch_num);
cout << ch_num;
++num_length;
}
else if ( account_num.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
{
cout << " \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
}
// after the account number has been input this will call the function that checks wether the ccount number already exists or not
file_path = accountExistenceCheckSignUp(account_num);
system("cls");
cout << "\t\t\t Sign Up" << endl << endl;
cout << "Name: " << sname << endl << endl;
cout << "Account Number: " << account_num << endl << endl;
char ch_pin;
int pin_length = 1; // it counts how many characters the user has input into the pin, it is initialized to 1 in case the user hits the backspace
cout << "Pin: ";
ch_pin = getch();
while (ch_pin == 13 && pin_length <= 4)
{
if (pin.empty())
cout << "\b \b";
ch_pin = getch();
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_pin != 13)
{
if (pin.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_pin == 8)
{
if ( ! pin.empty())
{
-- pin_length;
pin.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and pin_check will be take the character input by the user
// only numbers are accepted
else if (pin_length <= 4 && isdigit(ch_pin))
{
if (pin.empty())
cout << "\b \b";
pin.push_back(ch_pin);
cout << ch_pin;
++pin_length;
}
else if ( pin.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_pin = getch();
while (ch_pin == 13 && pin_length <= 4)
{
if (pin.empty())
{
cout << " \b";
}
ch_pin = getch();
}
}
// it creates a file that will contain all the account information
ofstream file(file_path);
int temp_iterator = 0; // a temporary int variable to ensure that after a space is deleted the letter next will be uppercased and not lowercased
// this for condition ensures the names will begin with an uppercase letter and there will be no space between
for (unsigned int i = 0; i < sname.size(); i++)
{
if (! isupper(sname[0]))
sname[0] = toupper(sname[0]);
if (isspace(sname[i]))
{
sname.erase(i, i - (i - 1));
sname[i] = toupper(sname[i]);
temp_iterator = i;
i += 1; // Be FCKNG CAREFUL, I HAD =+ WRITTEN
}
if( isupper(sname[i]) && toupper(sname[0]))
{
sname[i] = tolower(sname[i]);
sname[temp_iterator] = toupper(sname[temp_iterator]);
}
}
// it will write the account needed information to the recently created file
file << sname << " " << account_num << " " << " " << balance << " " << pin;
file.close();
backupAccountFile(file_path);
system("cls");
cout << "\a \nAccount Successfully Created!!!";
Sleep(1000);
system("cls");
createLimitFiles();
ifstream file_stream(file_path); // it enters the just created account file so the user can directly sign in after sign up
myAccount(&file_stream);
}
// function that gets the user through the 'sign in' steps
void Account::signIn()
{
cout << "\t\t\t Sign In" << endl << endl;
// cin.get(); // dont know why but it seems like when it enters the functions signIn and signUp it comes with an ENTER already pressed
char ch_num;
int num_length = 1;
cout << "Enter Your Bank Account Number: ";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
// in case the user user presses enter right away
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
cout << "\b \b";
ch_num = getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_num != 13)
{
if (account_num.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_num == 8)
{
if ( ! account_num.empty())
{
-- num_length;
account_num.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and account_num will be take the character input by the user
// only numbers are accepted
else if (num_length <= 16 && isdigit(ch_num))
{
if (account_num.empty())
cout << "\b \b";
account_num.push_back(ch_num);
cout << ch_num;
++num_length;
}
else if ( account_num.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
while (ch_num == 13 && num_length <= 16)
{
if (account_num.empty())
{
cout << " \b";
}
ch_num = _getch();
// if the user wishes to go back to the menu he/she presses esc
if (ch_num == 27)
{
mainMenu();
}
}
}
// it checks for the existence of the account
file_path = accountExistenceCheckSignIn(account_num);
// it checks if the account is locked
lockAccountCheck();
ifstream file_stream(file_path);
file_stream.getline(buffer, 256);
parseAccountInfo(buffer, name, account_num, balance, pin);
// char* sParseName = new char[100];
// sParseName = parseName;
// decohereLetter(sParseName);
file_stream.close();
system("cls");
cout << "\t\t\t My Account" << endl << endl;
cout << "Welcome " << name << endl << endl;
char ch_pin;
int pin_length = 1; // it counts how many characters the user has input into the pin, it is initialized to 1 in case the user hits the backspace
string pin_check;
cout << "Pin: ";
ch_pin = getch();
while (ch_pin == 13 && pin_length <= 4)
{
if (pin_check.empty())
cout << "\b \b";
ch_pin = getch();
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_pin != 13)
{
if (pin_check.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_pin == 8)
{
if ( ! pin_check.empty())
{
-- pin_length;
pin_check.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and pin_check will be take the character input by the user
// only numbers are accepted
else if (pin_length <= 4 && isdigit(ch_pin))
{
if (pin_check.empty())
cout << "\b \b";
pin_check.push_back(ch_pin);
cout << "*";
++pin_length;
}
else if ( pin_check.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_pin = _getch();
while (ch_pin == 13 && pin_length <= 4)
{
if (pin_check.empty())
{
cout << " \b";
}
ch_pin = _getch();
}
}
int pin_checkCount = 1;
bool note = false;
// if the pin input is wrong the pin_check will be cleared
if (pin_check != pin)
{
pin_check.clear();
}
// and the pin lenght will be reset to 1
pin_length = 1;
while (pin_check != pin)
{
// if the pin input is wrong the pin_check will be cleared
if (pin_check != pin)
{
pin_check.clear();
}
// and the pin lenght will be reset to 1
pin_length = 1;
system("cls");
cout << "\t\t\t My Account" << endl << endl;
cout << "Welcome " << name << endl << endl;
// it counts how many passwords input attempts the user has tried, when it equal 3 the account is locked for 24 hours
if (pin_checkCount == 3)
{
cout << endl << "3 Attempts Failed!!" << endl;
cout << "Your Account Has Been Locked For the Next 24 Hours" << endl;
cout << endl << "Press enter key to continue";
note = true; //the note is set to true to log the fact the account got locked
log(note);
lockAccount();
char ch = _getch();
while(ch != 13)
{
ch = _getch();
}
mainMenu();
}
cout << "Wrong Pin!!" << endl;
cout << "Pin: ";
ch_pin = _getch();
while (ch_pin == 13 && pin_length < 5)
{
if (pin_check.empty())
{
cout << "\b \b";
}
ch_pin = _getch();
}
// while the user doesnt hit enter, 13 is the ASCII code for enter
while (ch_pin != 13)
{
if (pin_check.empty())
{
cout << " \b";
}
// when the user hits backspace, 8 s the ASCII code for backspace
if (ch_pin == 8)
{
// if the pin_check isn't empty the pin lenght will decreased amd pin characters too
if ( ! pin_check.empty())
{
-- pin_length;
pin_check.pop_back();
}
cout << "\b \b";
}
// if the pin lenght is equal or below 4 asterisk will be displayed to mask the pin and pin_check will be take the character input by the user
// only numbers are accepted
else if (pin_length <= 4 && isdigit(ch_pin))
{
if (pin_check.empty())
cout << "\b \b";
pin_check.push_back(ch_pin);
cout << "*";
++pin_length;
}
else if ( pin_check.empty()) // when the user clear the input this condition won't allow the cursor to improper forward move
{
cout << "\b \b";
}
ch_pin = _getch();
while (ch_pin == 13 && pin_length <= 4)
{
if (pin_check.empty())
cout << " \b";
ch_pin = _getch();
}
}
++pin_checkCount;
}
pin_check.clear(); // the pin_check will be cleared in case another log in is made
log(note); // it will log the time of the 'sign in'
myAccount(&file_stream); // once the user is signed into his or her account the function 'myAccount' will be called
}
// function that lets the user navigate into his or her account
void Account::myAccount(ifstream* file_stream)
{
system("cls");
while (true)
{
char option;
backupAccountFile(account_num);
file_stream->getline(buffer, 256);
parseAccountInfo(buffer, name, account_num, balance, pin);
file_stream->close();
cout << endl << "Account: " << name << endl << endl;
cout << setw(10) << "1 -> Balance";
cout << setw(22) << "2 -> Withdrawal" << endl << endl;
cout << setw(10) << "3 -> Deposit";
cout << setw(20) << "4 -> Transfer" << endl << endl;
cout << setw(10) << "5 -> Transactions";
cout << setw(16) << "6 -> Settings " << endl << endl;
cout << setw(10) << "0 -> Sign Out" << endl << endl;
cout << setw(17) << "-> ";
option = _getch();
while (option != '0' && option != '1' && option != '2' && option != '3' && option != '4' && option != '5' && option != '6')
{
option = _getch();
}
switch(option)
{
case '1':
logInsideAccount("View Balance");
viewBalance();
break;
case '2':
logInsideAccount("Withdrawal");
withdrawal();
break;
case '3':
logInsideAccount("Deposit");
deposit();
break;
case '4':
logInsideAccount("Transfer");
transfer();
break;
case '5':
// it logs the activity (View Transaction) made in the account
logInsideAccount("View Transactions");
transactions(account_num);
break;
case '6':
logInsideAccount("Enter Settings");
settings();
break;
case '0':
signOut();
default:
myAccount(file_stream);
}
}
}
void Account::viewBalance() const
{
system("cls");
cout << endl << "Account: " << name << endl << endl;
cout << "Balance: " << balance << endl << endl;
cout << "******** Click Enter To Return ********";
char ch;
ch = _getch();
while (ch != 13)
{
ch = _getch();
}
system("cls");
}
void Account::withdrawal()
{
system("cls");
string sAmount;
long double amount;
cout << "\t\t\t\t Withdrawal" << endl;
cout << endl << "Account: " << name << endl << endl;
cout << endl << " Amount Of Withdrawal: ";
getline(cin, sAmount);
for (unsigned int i = 0; i < sAmount.size(); ++i)
{
if (! isdigit(sAmount[i]))
{
cout << endl << "Invalid Amount!! \nAmount: ";
getline(cin, sAmount);
i = -1;
}
}
amount = atof(sAmount.c_str()); // it coverts the string to a float number
while (amount > balance)
{
cout << endl << "Insufficient Balance!!";
cout << endl << " Amount Of Withdrawal: ";
getline(cin, sAmount);
for (unsigned int i = 0; i < sAmount.size(); ++i)
{
if (! isdigit(sAmount[i]))
{
cout << endl << "Invalid Amount!! \n Amount Of Withdrawal: ";
getline(cin, sAmount);
i = -1;
}
}
/*
amount = strtod(sAmount.c_str(), nullptr);
amount = atof(sAmount.c_str());
*/
amount = stof(sAmount); // converting string to int
}
system("cls");
char option;
if (amount != 0)
{
cout << endl << "Account: " << name << endl << endl;
cout << "Withdrawal Amount: " << amount << endl << endl;
cout << setw(18) << "Confirm" << endl << endl;
cout << setw(10) << "1 -> Yes" << setw(20) << "Other -> No" << endl << endl;
cout << setw(15) << "-> ";
option = _getch();
switch (option)
{
case '1':
withdrawalLimit(amount);
balance -= amount;
logTransactions(account_num, "Withdrawal", amount);
break;
default:
withdrawal();
break;
}
ofstream drawFile (file_path);
drawFile << name << " " << account_num << " " << " " << balance << " " << pin; // updates the information in the account file
drawFile.close();
}
system("cls");
}
void Account::withdrawalLimit(int withdrawalAmount)
{
dayShiftCheck();
string sfile_path = Paths::ADMIN_WITHDRAWAL_VAL + account_num;
char buffer [256];
int amountDayDrawal;
ifstream file (sfile_path);
file.getline(buffer, 256);
istringstream amountFile (buffer);
amountFile >> amountDayDrawal;
file.close();
int amount_limit = amountDayDrawal + withdrawalAmount;
ofstream day_amount_file (sfile_path);
if ( amount_limit > 20000)
{
system("cls");
cout << "\a \n\n\n\n\n\n \t" << "Exceeded The Withdrawal Amount Limit For The Day" << endl << "\t" << "Withdrawal Amount Limit -> 20000" << endl;
Sleep(2000);
day_amount_file << amountDayDrawal;
day_amount_file.close();
ifstream file_stream (file_path);
myAccount(&file_stream);
}
else
{
day_amount_file << amount_limit;
day_amount_file.close();
}
}
// not complete
</code></pre>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <windows.h>
#include "classAccount.h"
using namespace std;
int main()
{
cout << "\n\n\n\n\n\n \t\t\t\t\t" << "Helder Batalha" << endl;
Sleep(500);
system("cls");
Account acc;
acc.mainMenu();
return 0;
}
</code></pre>
<p>The file classAccount.cpp is not complete as it contains about 3000 lines of codes. So <a href="https://drive.google.com/open?id=1jPeNgBBqNY0fQ0s2pLNTFAIja8GfSqKJ" rel="nofollow noreferrer">here is the file classAccount.cpp</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T00:03:36.370",
"Id": "469835",
"Score": "1",
"body": "In order to design review your code design, you would need to present us with a code design. This is code. Code which you have admitted is confusing. My review is that you should watch [this Kate Gregory talk](https://www.youtube.com/watch?v=n0Ak6xtVXno), at the very least because she's delightful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:48:19.110",
"Id": "469842",
"Score": "7",
"body": "Your title should state what the code does, not your concerns about it. See [ask]."
}
] |
[
{
"body": "<p>1) The strings (BASE_PATH, USER_PATH, etc) shouldn't be hardcoded. It is fine to have program defaults but they should be configurable via some configuration file and/or commandline.</p>\n\n<p>2) There is a lot of repetition in cade, say, when you ensure that all directories exist. This is because all string are seperate variables. It'd be better if they were organized in a vector/array of strings. And use an enum to indicate which entry signifies what.</p>\n\n<p>3) Avoid using non portable system calls. Use portable thirdparty free-open source libraries instead. For creating directories use <code>std::filesystem</code> (or <code>boost::filesystem</code> if C++17 is out of scope). Furthermore, <code>std::string</code> isn't quite good representation for filesystem path - better use a dedicated class. Also filesystem delimiter \"\\\" doesn't work on all platforms (e.g., linux) use \"/\" instead.</p>\n\n<p>4) Don't <code>using namespace std;</code> in headers and avoid in general. Want to shorten <code>cout</code> or <code>string</code> - write <code>using std::cout;</code> and <code>using std::string;</code> so you pull only what you need and not the whole namespace which might accidentally break some code.</p>\n\n<p>5) You should have a separate abstract class that manages user input - whatever is the source of said input. <code>getch</code> isn't a good choice. Nowadays frequently one writes core dll on C++ and interface on C# or whatever language is best for the platform. That's being said, given code can be easily fully implemented on the said languages.</p>\n\n<p>Edit: About requested example for (5).</p>\n\n<p>Generally designing API/interface is a complex topic and you should seek some tutorials and guides online. But I can show something simple.</p>\n\n<p>Imagine you have an external class <code>Controller</code> whose purpose is to process users input and issue requests to the Account class or whatever. The <code>Controller</code> could be cmd-based interface much like you have implemented, a good looking webpage that forwards its data to your Account class, or some sort of socket data interpreter that receives request from some server or whatever. </p>\n\n<p>To encompass all of these one should address <code>Controller</code> as an abstract interface class. The only question is what is its interface and how to work with it.</p>\n\n<p>Basic method (easiest to implement considering current code)</p>\n\n<pre><code>enum class ERequest\n{\n DO_STUFF_A,\n DO_STUFF_B,\n EXIT\n}\nclass IController\n{\n public:\n virtual ~IController() = default;\n virtual ERequest GetRequest() = 0;\n virtual void GetDataForA(...) = 0;\n virtual void SetOutputForA(...) = 0;\n virtual void GetDataForB(...) = 0;\n virtual void SetOutputForB(...) = 0;\n}\n</code></pre>\n\n<p>And in the code you simply write simple function deals with the controller</p>\n\n<pre><code>IController& rController =...;\nwhile(true)\n{\n ERequest rq = rController.GetRequest();\n switch(rq)\n {\n case ERequest::DO_STUFF_A:\n rController.GetDataForA(...);\n // process the request\n rController.SetOutputForA(...);\n break;\n\n case ERequest::DO_STUFF_B:\n rController.GetDataForB(...);\n // process the request\n rController.SetOutputForB(...);\n break;\n\n case ERequest::EXIT:\n return;\n }\n}\n</code></pre>\n\n<p>It is far from perfect and this type of interface is still very limiting but it already allows one to better organize code and prepare for future development and various possible interfaces.</p>\n\n<p>And there are other design options:</p>\n\n<p>I. Instead of making abstract interface for controller, make an interface for Account class that should be exposed to controller and simply supply it to the controller designer.</p>\n\n<p>This method is good as long as all methods require a small amount of time for processing - and are function like. But it will cause problems if some methods take a while for processing.</p>\n\n<p>Also it is harder to implement as it requires to make the exported methods to be extra safe. And you need to consider various situations like: \"what if it methods are called simultaneously? Is my class thread safe?\"</p>\n\n<p>II. Make dual interface. Same as (1) but also account class receives a callback class instance from the controller. This way one can utilize parallelism and asynchronous methods. Nobody wants their interface to be laggy and unresponsive. So each call controller schedules a query, while some worker threads process them and send output via the callback class.</p>\n\n<p>Furthermore, one can run some background analysis and send valuable info to the interface without any query requests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T08:56:12.897",
"Id": "469856",
"Score": "0",
"body": "How would I go about the topic 5 and have a separate abstract class that manages user input. I can't think of a way to do that, I guess I haven't seen something similar, any example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T09:16:34.467",
"Id": "469858",
"Score": "0",
"body": "@HBayalha hmm... perhaps it is better to give this class an external interface to pass to the the API - so API wouldn't be able to call sensitive functions yet be very flexible... But it is also possible with just an abstract API. Dumb example: abstract interface with two function - `receiveNextOrder()` that returns some enum order and extra data needed to execute the order; and function `sendStatus(...)` that reports information to the API. Simply make a procedure that waits for the next order and executes it, and reports result - whereas order can be like \"getinfo\" or \"savedata\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T09:29:01.423",
"Id": "469859",
"Score": "0",
"body": "Could you edit your answer and give a very basic code of this just so I can an idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T23:32:14.417",
"Id": "469952",
"Score": "0",
"body": "@HBatalha I wrote a basic example - as well as provided some ideas for other better but more complex design choices. Check it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T10:23:24.910",
"Id": "469977",
"Score": "0",
"body": "thanks, I will have to google a bit to find more examples of this design though so I can try to implement in my current code, as I never used something similar."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:30:16.947",
"Id": "239538",
"ParentId": "239522",
"Score": "4"
}
},
{
"body": "<p>Even Windows uses '/' as a path separator nowadays. </p>\n\n<pre><code>const string Paths::BASE_PATH = \"C:\\\\ProgramData\\\\BankAcount\";\n</code></pre>\n\n<p>The last time you needed to use '\\' as a path separator was 15 years ago.</p>\n\n<pre><code>const string Paths::BASE_PATH = \"C:/ProgramData/BankAcount\";\n</code></pre>\n\n<p>If you really want to us the '\\' then use the RAW character strings.</p>\n\n<pre><code>const string Paths::BASE_PATH = R\"(C:\\ProgramData\\BankAcount)\";\n</code></pre>\n\n<hr>\n\n<p>Member variables should always be private.</p>\n\n<pre><code>class Account\n{\nprotected:\n std::string name;\n std::string new_name;\n long long int balance;\n std::string account_num;\n std::string file_path;\n\n std::string pin, new_pin;\n\n char buffer[256];\n\n // STUFF\n};\n</code></pre>\n\n<p>Do you trust a stranger that derived his class from your class to main the invariants of the class?</p>\n\n<p>Members should be private and then you provide methods to mutate the state in a way that is logically consistent.</p>\n\n<hr>\n\n<p>OK. Have not read the whole class. But is this a string?</p>\n\n<pre><code> char buffer[256];\n</code></pre>\n\n<hr>\n\n<p>All these methods on a class call <code>Account</code>.</p>\n\n<p>A lot of methods don't seem to have anything to do with an account!</p>\n\n<pre><code>// Not sure what this is to do with an account?\nvoid createFolder() const;\nvoid createLimitFiles();\nvoid deleteFile(std::string file_to_delete);\nvoid settings();\nvoid mainMenu();\n</code></pre>\n\n<hr>\n\n<p>The logging functions don't look like they belong in the account. But rather something that the account would use.</p>\n\n<pre><code>void logTransactions(const std::string& log_account_num, const std::string& transaction_type, const int& amount) const;\nvoid log( bool note ) const;\nvoid logInsideAccount(const std::string& in_account) const;\n</code></pre>\n\n<p>Do you call a method to withdraw information. Then call the logging functions to record that? When you withdraw someting from the account should the account not simply tell the logger about the action so it can be logged.</p>\n\n<p>If that is the case then you need to pass a logging object to the account (probably in the constructor).</p>\n\n<hr>\n\n<p>Modern Time formatting works with time and stream:</p>\n\n<pre><code>time_t now = time(nullptr);\nstring time_now = ctime(&now);\ntm* lock_time = localtime(&now);\n\n\nlock << lock_time->tm_mday << \" \" << lock_time->tm_hour << \" \" << lock_time->tm_min;\n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>auto now = std::chrono::system_clock::now();\nlock << std::format(\"%e %I %M\", now);\n</code></pre>\n\n<hr>\n\n<p>This is very verbose:</p>\n\n<pre><code>if ( ! file_in.good() )\n{\n return;\n}\n</code></pre>\n\n<p>A stream when used in a boolean context (like an if statement) will automatically convert itself to a bool based on its state (by calling <code>good()</code>).</p>\n\n<pre><code>if (!file_in) {\n return;\n}\n</code></pre>\n\n<hr>\n\n<p>You are assuming that a line is less than 256 characters long.</p>\n\n<pre><code>char bufferLine[256];\nfile_in.getline(bufferLine, 256);\n</code></pre>\n\n<p>It may be true now. But in the future when your class is modified do you trust the next person to read all the code and make sure it conforms to all your current standards? If this is a limit you want the next programmer to inforce you should put it as a constant that is named in the class.</p>\n\n<p>But alternatively I would use a resizable string so it can read any size of line.</p>\n\n<pre><code>std::string line;\nif (std::getline(file_in, line)) {\n // Correctly read a line of text from `file_in`\n}\n</code></pre>\n\n<hr>\n\n<p>This is broken.</p>\n\n<pre><code>while (file_in.good() && ! file_in.eof())\n{\n c = file_in.get();\n existent_content.push_back(c);\n}\n</code></pre>\n\n<p>The situation. You have one character left in the stream and the file is good. The above condition is good and you enter the loop.</p>\n\n<p>You will read the last character. The state of the stream is still good and the EOF will NOT be set. This is because the EOF flag is not set until you read past the end of file. So you enter the loop again. But this time when you try and read a character it fails (and sets the EOF flag). But you still unconditionally add it to <code>existent_content</code>.</p>\n\n<p>You can write it like this but you need to test that the read worked:</p>\n\n<pre><code>while (file_in.good() && ! file_in.eof()) {\n int c;\n if ((c = file_in.get()) != EOF) {\n existent_content.push_back(c);\n }\n}\n</code></pre>\n\n<p>But this is still considered bad practice. You shoudl loop on a read working.</p>\n\n<pre><code>int c;\nwhile ((c = file_in.get()) != EOF) {\n existent_content.push_back(c);\n}\n</code></pre>\n\n<hr>\n\n<p>======</p>\n\n<h2>Logging</h2>\n\n<p>I would set up logging so that each action does its own logging. To do this it needs a logging object that knows what to do with the message. If you define your logging object as a class you can define different styles of logging.</p>\n\n<pre><code>class SimpleMessageLogger\n{\n public:\n virtual ~SimpleMessageLogger() {}\n virtual void log(std::string const& message) = 0;\n};\n\nclass SimpleMessageLoggerTOStdErr: public SimpleMessageLogger\n{\n public:\n virtual void log(std::string const& message) override\n {\n std::cerr << time(nullptr) << \": \" << message << \"\\n\";\n }\n}\n\nclass SimpleMessageLoggerTOSystem: public SimpleMessageLogger\n{\n public:\n virtual void log(std::string const& message) override\n {\n // Call system logger\n }\n}\n</code></pre>\n\n<p>Then your account needs to be set up to use a logger:</p>\n\n<pre><code>class Account\n{\n SimpleMessageLogger& logger;\n int balance;\n\n public:\n Account(SimpleMessageLogger& logger)\n : logger(logger)\n , balance(0)\n {}\n\n void withdraw(int amount) {\n if (balance < amount) {\n logger.log(\"OverDrawn. We make money by charging fees\");\n }\n balance -= amount;\n std::stringstream message;\n message << \"Withdrawal: From account 1123 Amount: \" << amount << \" New Balance: \" << balance;\n logger.log(message.str());\n }\n}\n\nint main()\n{\n std::unique_ptr<SimpleMessageLogger> logger;\n // Decide what type of logger you want.\n logger = new SimpleMessageLoggerTOStdErr;\n\n Account. myAccount(*logger);\n\n myAccount.withdraw(1'000'000);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:12:47.807",
"Id": "469845",
"Score": "0",
"body": "Nitpick: \"Member variables should always be private.\" isn't true in all cases! :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:15:41.220",
"Id": "469848",
"Score": "1",
"body": "@L.F. All rules have exceptions. People who are inexperienced follow all the rules. As you gain experience you learn when the rules can be bent and when they can be broken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:23:23.617",
"Id": "469849",
"Score": "0",
"body": "Fair enough ... I was thinking along the lines of aggregates, so I took it to mean more like \"prefer private member variables to protected ones\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T09:05:18.500",
"Id": "469857",
"Score": "0",
"body": "@MartinYork Thanks, I have taken into account all of your reviews and changed things accordingly except for one. Are you saying that I have to create a class only for logging? If so, could you edit your answer and give me some example with code on how I would do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T20:31:18.683",
"Id": "469940",
"Score": "0",
"body": "@HBatalha Yes and done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T10:16:44.760",
"Id": "469976",
"Score": "0",
"body": "@MartinYork wow thanks, didn't know you should have a class that is only responsible for one thing, in this case for logging. So when exactly do we need to create a class?? I will google it but you are more than welcome to give me your insight... again thanks."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:41:22.923",
"Id": "239540",
"ParentId": "239522",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T20:10:12.020",
"Id": "239522",
"Score": "0",
"Tags": [
"c++",
"object-oriented",
"design-patterns"
],
"Title": "What's wrong with this design in C++?"
}
|
239522
|
<p>I just started programming a week ago. Online tutorials aren't my thing, so I decided to just start projects and learn what I need for the project.</p>
<p>My first project is a guess the number game. The user is asked to guess a number between 0 and 20. If the user's guess is too high, they will be told it's high and likewise if it's too low. This will go on until the user guesses correctly.</p>
<pre><code>
print("Enter a random number between 0 and 20")
userInput = int(input())
random_number= random.randint(0,20)
def random_num_checker(num,guess):
if num== guess:
print('CORRECT')
else:
while guess != num:
if guess > 20:
print('I said between 0 and 20')
if guess < num:
print('too small')
elif guess > num:
print('too big')
guess=int(input())
print('CORRECT')
random_num_checker(random_number,userInput)
</code></pre>
|
[] |
[
{
"body": "<p>First off, some minor nitpicks on style.</p>\n\n<ul>\n<li>In Python, variables are usually given names <code>like_this</code> rather than <code>likeThis</code> - most of your names are fine, but <code>userInput</code> should probably be <code>user_input</code> instead.</li>\n<li>You usually want a space on each side of operators, <code>guess = int(input())</code> is more pleasant to look at than <code>guess=int(input())</code></li>\n</ul>\n\n<p>Second, your program's behaviour is different from what I'd expect in some subtle ways.</p>\n\n<ul>\n<li>If I enter a number above 20, I get both a reminder that \"[you] said between 0 and 20\" and a message that says my guess is \"too big\". While both are <em>accurate</em>, only the first is really necessary.</li>\n<li>If I enter a negative number, I'm <em>not</em> reminded that my guess must be between 0 and 20, I'm just told that my guess is too low. Again, that is <em>true</em>, but since you already have a message that says my guess is outside the acceptable range, I'd expect to see that message instead.</li>\n<li>If I enter something that isn't a number at all, the program crashes entirely. I would've expected you to catch the <code>ValueError</code> thrown by the <code>guess = int(input())</code> line and give me a cheeky error message instead.</li>\n</ul>\n\n<p>Third, structure.</p>\n\n<ul>\n<li>Why is the <code>if num == guess</code> there? The program seems to behave exactly the same if that function begins with the <code>while ...</code> line, and the code feels a bit cleaner.</li>\n<li><code>random_num_checker</code> is reponsible for asking the player for numbers until they guess the right one. Why, then, does it not also prompt for the first guess, but rather expect that one to be passed as an argument? It feels weird.</li>\n<li>Constants should preferably be defined in one place only, in case you want to change them. I'd have liked to see the lowest and highest possible guesses be defined as constants. It's not a huge deal in a small program like this, but it's generally good practice.</li>\n<li>On a related note, taking the minimumand maximum allowed guesses as parameters would make the <code>random_num_checker</code> function more flexible.</li>\n</ul>\n\n<p>Based on this, I'd write something kind of like this:</p>\n\n<pre><code>MIN_GUESS = 0\nMAX_GUESS = 20\n\ndef random_num_checker(goal, min_guess, max_guess):\n # Some sanity checks, in case someone wants to use this function for their own game\n if type(goal) is not int:\n raise TypeError(f'Goal must be an int, was {type(goal)}')\n elif goal < min_guess or goal > max_guess:\n raise ValueError(f'Goal must be within the allowed guessing range ({min_guess}-{max_guess}), was {goal}')\n\n print(f'Enter a number between {min_guess} and {max_guess}')\n guess = None\n while guess != goal:\n try:\n guess = int(input())\n\n if guess > max_guess or guess < min_guess:\n print(f'I said between {min_guess} and {max_guess}')\n elif guess > goal:\n print('Too high')\n elif guess < goal:\n print('Too low')\n except ValueError:\n print('That doesn\\'t look like a number to me')\n guess = None\n\n print(\"CORRECT\")\n\n\nrandom_number = random.randint(MIN_GUESS, MAX_GUESS)\nrandom_num_checker(random_number, MIN_GUESS, MAX_GUESS)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T20:01:27.727",
"Id": "469934",
"Score": "0",
"body": "Is it necessary to check if \"goal\" is an int since it's an int generated by Python?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T06:31:59.590",
"Id": "470072",
"Score": "0",
"body": "Sara explained in a comment that the purpose of this check was so that the function could potentially be used elsewhere. You know you aren’t going to feed it a string today, but you might do it accidentally later. Or somebody else might. It’s just insurance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T23:50:07.080",
"Id": "239533",
"ParentId": "239524",
"Score": "4"
}
},
{
"body": "<p>To add to @Sara J's answer, in Python, it's generally a good practice to wrap your main code (so the last two lines) in a <code>if __name__ == '__main__':</code> statement so your script can be either:</p>\n\n<ul>\n<li>Directly run</li>\n<li>Imported and its functions used as the dev that imported it pleases.</li>\n</ul>\n\n<p><a href=\"https://stackoverflow.com/a/419185/1524913\">https://stackoverflow.com/a/419185/1524913</a></p>\n\n<p>Also, contrary to a lot of other programming languages, Python insist on the <code>if it quacks, it's a duck</code> way of handling things:</p>\n\n<p>Usually, in Python, when possible, you don't check data first. You just run the code and wrap it in a <code>try ... except</code> block. If it works (quack) you don't need to type-check, etc. So, eg, you'd do:</p>\n\n<pre><code>try:\n userInput = int(input(f\"Enter a number between {MIN_NUMBER} and {MAX_NUMBER}: \")\nexcept ValueError:\n print(\"Please enter a valid number!\")\n</code></pre>\n\n<p>So, all in all:</p>\n\n<pre><code>MIN_GUESS = 0\nMAX_GUESS = 20\n\ndef random_num_checker(goal, min_guess, max_guess):\n if goal < min_guess or goal > max_guess:\n raise ValueError(\"Goal is outside the min/max bounds\")\n\n print(f'Enter a number between {min_guess} and {max_guess}')\n\n guess = None\n while guess != goal:\n try:\n # Could also (re-)ask every time instead of only once at the beginning\n guess = int(input())\n except ValueError: # Only try to catch what's needed\n print('That doesn\\'t look like a number to me')\n continue\n\n if min_guess < guess < max_guess:\n if guess > goal:\n print('Too high')\n elif guess < goal:\n print('Too low')\n else:\n print(f'I said between {min_guess} and {max_guess}')\n\n print(\"CORRECT\")\n\nif __name__ == '__main__':\n goal = random.randint(MIN_GUESS, MAX_GUESS)\n random_num_checker(goal, MIN_GUESS, MAX_GUESS)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:34:24.227",
"Id": "469839",
"Score": "0",
"body": "Personally, I'd expect calls like `random_num_checker(0.5, 0, 1)` to throw an exception, since the user will never be able to successfully guess anything but a whole number since their input will be converted to an int. But I agree that checking if `type(goal) is int` isn't very pythonic, and checking if `goal % 1 == 0` might be better here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:42:37.700",
"Id": "469905",
"Score": "0",
"body": "@SaraJ oooh that was on `goal`... gotchu. I'm not sure what would be the most pythonic way to do that then. "
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:00:25.357",
"Id": "239537",
"ParentId": "239524",
"Score": "3"
}
},
{
"body": "<p>Aside from the notes already given, here are two big ideas to think about:</p>\n\n<h2>Don't repeat yourself (DRY)</h2>\n\n<p>This is something you'll hear repeated a lot in discussions of code. Any time you see the same \"magic values\" repeated more than one place (e.g. 0 and 20), or you see two lines of code that do exactly the same thing for exactly the same reason (e.g. your <code>input()</code> statements or the multiple <code>CORRECT</code> checks) it's a clue that you have an opportunity to share some code.</p>\n\n<p>In the case of the magic numbers, one solution is to define them as constants at the top of the file. The approach I'd prefer, personally, would be to make them parameters -- rather than hardcoding <code>0</code> and <code>20</code>, have your function(s) take a <code>range</code> as a parameter.</p>\n\n<p>In the case of the multiple \"CORRECT\" checks, this is just a matter of restructuring the loop a little.</p>\n\n<h2>Have each function do one thing well</h2>\n\n<p>This is significantly more subjective, but in looking at your function, I see two very separable things it's doing within its single main loop -- prompting the user for valid input, and giving them feedback on their guess. If you have one piece of code that just has to get the input without having to worry about the game loop, and you have another that handles the game loop without having to worry about whether the input is valid, then both of them can be simpler.</p>\n\n<p>When you start doing larger projects, breaking logic apart into simple functions makes it easier to test the individual units of your code independently.</p>\n\n<p>I messed around with the code for a bit using those two principles and came up with this:</p>\n\n<pre><code>import random\n\ndef describe_range(numbers: range) -> str:\n \"\"\"Nice English-language description of a range.\"\"\"\n return f\"between {numbers[0]} and {numbers[-1]}\"\n\ndef input_number(numbers: range) -> int:\n \"\"\"\n Prompt the user for a number within the range,\n retrying on invalid input.\n \"\"\"\n while True:\n try:\n number = int(input())\n if not number in numbers:\n raise ValueError(f\"The number needs to be {describe_range(numbers)}\")\n return number\n except ValueError as e:\n print(e)\n\ndef guess_number(numbers: range) -> None:\n \"\"\"\n Play a guessing game with the user within a range of numbers.\n Tell them whether their guess is too big or too small. \n They win when they get it right!\n \"\"\"\n print(\"Enter a random number\", describe_range(numbers))\n answer = random.choice(numbers)\n while True:\n guess = input_number(numbers)\n if guess > answer:\n print(\"too big\")\n elif guess < answer:\n print(\"too small\")\n else:\n print(\"CORRECT\")\n break\n\nif __name__ == \"__main__\":\n guess_number(range(21))\n</code></pre>\n\n<p>Note that I'm using Python 3's type annotations to say what type of argument each function takes and what it returns -- this is really handy because you can use the <code>mypy</code> tool to automatically check your code for errors (for example if you say a function returns an <code>int</code> and there's a line in that function that returns a <code>str</code>, <code>mypy</code> will throw an error), and therefore you don't need to worry as much about your code getting the wrong type at runtime. The type annotations also serve as documentation for your functions so that human readers can easily see what sorts of values they should expect the code to be working with.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:41:34.263",
"Id": "239545",
"ParentId": "239524",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T21:37:06.127",
"Id": "239524",
"Score": "7",
"Tags": [
"python",
"performance",
"beginner",
"game",
"random"
],
"Title": "I made a guess the number game in Python"
}
|
239524
|
<p>I am trying to migrate from <a href="https://www.npmjs.com/package/request" rel="nofollow noreferrer">request</a> to <a href="https://www.npmjs.com/package/axios" rel="nofollow noreferrer">axios</a>, since request has been deprecated.</p>
<p>Suppose that the URL '<a href="https://www.example.com" rel="nofollow noreferrer">https://www.example.com</a>' receives a post request with formdata that contains login information, and also suppose that I need to maintain the current session across multiple requests (for that I need a cookieJar).</p>
<p>Using axios I need cookieJar support from an external library therefore I use <a href="https://www.npmjs.com/package/axios-cookiejar-support" rel="nofollow noreferrer">axios-cookiejar</a>. Also, to send formdata using axios I have to use the external library <a href="https://www.npmjs.com/package/form-data" rel="nofollow noreferrer">form-data</a>, and I also have to set the headers manually since axios doesn't do that for me.</p>
<p>I have the following code, which uses axios that does just that:</p>
<pre><code>axios = require('axios')
FormData = require('form-data')
axiosCookieJarSupport = require('axios-cookiejar-support').default
tough = require('tough-cookie')
axiosCookieJarSupport(axios)
cookieJar = new tough.CookieJar()
form = new FormData()
form.append('email', 'example@gmail.com')
form.append('password', '1234')
axios({
method: 'post',
url: 'https://www.example.com',
data: form,
headers: {'Content-Type': `multipart/form-data; boundary=${form._boundary}` },
jar: cookieJar,
withCredentials: true
}).then(function (response) {
console.log(response['data'])
})
</code></pre>
<p>Using request this becomes much simpler:</p>
<pre><code>request = require('request')
requestCookieJar = request.jar()
request.post({
url: 'https://www.example.com',
method: 'POST',
jar: requestCookieJar,
formData: {
'email': 'example@gmail.com',
'password': '1234'
}
}, function(error, response, body) {
console.log(body)
})
</code></pre>
<p>As you can see the request API is much more elegant. Is there a way to use axios more elegantly or is there a different elegant API, which isn't deprecated, that I could use to support my needs stated at the beginning of this question?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:20:12.907",
"Id": "469828",
"Score": "1",
"body": "You should be wrapping the thing you use to make requests, so you can make any API you like. Incidentally had you wrapped request in the first place, your migration would be trivial."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T23:52:52.933",
"Id": "469834",
"Score": "0",
"body": "Good point, thanks"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:13:59.153",
"Id": "239526",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"axios"
],
"Title": "Maintaining current session across multiple requests"
}
|
239526
|
<p>I have an application developed in ASP.NET Core C#, where according to a configuration it must replace certain urls of a text when an http request is made and the text must be returned as soon as possible in response, the text can change on each request. </p>
<p>At this moment the code I have is working well, but I would like you to help me check the code to improve the speed of replacement of the urls.</p>
<pre><code>string r = contenidoRespuesta; //contenidoRespuesta can be html, json or javascript content
string dominio="example.com";
int puertoHttp=81,puertoHttps=444;
foreach (var p in grupo.Paginas.Where(p => p.Proxy))
{
Uri uri = new Uri(p.URL);
string pattern1 = string.Format("(?<=https://){0}(:(443)(?!\\d+))?(?!:)", uri.Host);//generates a regular expression to replace urls that start with "https"
string pattern2 = string.Format("(?<=http://){0}(:(80)(?!\\d+))?(?!:)", uri.Host);//generates a regular expression to replace urls that start with "http"
string pattern3 = string.Format("(?<!%2F|\\.|http(s)?(://)){0}(:((80)|(443))(?!\\d+))?(?!:)", uri.Host);//generates a regular expression to replace urls that start with "//"
r = Regex.Replace(r, pattern1,uri.Host.Replace(".", string.Empty) + "." +dominio + ":" + puertoHttps, RegexOptions.IgnoreCase);// replace https://www.page.com for https://wwwpagecom.example.com
r = Regex.Replace(r, pattern2,uri.Host.Replace(".", string.Empty) + "." + dominio + ":" + puertoHttp, RegexOptions.IgnoreCase);// replace http://www.page.com for http://wwwpagecom.example.com
r = Regex.Replace(r, pattern3, uri.Host.Replace(".", string.Empty) + "." + dominio + ":" +(esquema == "https"? puertoHttps.ToString(): puertoHttp.ToString()));// replace //www.page.com for https://wwwpagecom.example.com
}
return r;//return the responsd with new urls
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:47:01.357",
"Id": "469829",
"Score": "0",
"body": "Could you please provide the configuration requirements ?, and is this for a web api application ? is the current method is executed from an api request ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T23:06:47.253",
"Id": "469830",
"Score": "0",
"body": "Yes it is a web application and the method is executed every time the client makes a request. In each request the application consults information from another page (according to the subdomain) and replaces the previously configured urls, so that new requests continue to be made to the same server, it works as a web proxy. _contenidoRespuesta_ is the response from the website in which I should replace the urls"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T23:22:27.370",
"Id": "469831",
"Score": "0",
"body": "So basically you're routing the web requests from current server to another server. Is that true? If true, why you didn't use Routing ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T23:23:30.283",
"Id": "469832",
"Score": "0",
"body": "See this https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-3.1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T23:41:07.517",
"Id": "469833",
"Score": "0",
"body": "It is not done by routing because the number of pages to be used depends on each client and can change at any time, in addition to doing some additional operations and this allows me to have it centralized. Now, what I want to improve (the method) is not in the requests, it is when processing the response, I need to replace the urls as quickly as possible,so that the response time is not affected."
}
] |
[
{
"body": "<p>Since you just getting the host url, remove the dots, then append it as a subdomain to the given domain with the approprate protocols (Https or Http). You can do this : </p>\n\n<pre><code>public IEnumerable<string> GetRoutedUrls(IEnumerable<string> urls, string domain, int httpPort, int httpsPort)\n{\n if(urls == null) { throw new ArgumentNullException(nameof(urls)); }\n\n if (string.IsNullOrEmpty(domain)) { throw new ArgumentNullException(nameof(domain)); }\n\n foreach (var url in urls)\n {\n if (string.IsNullOrEmpty(url)) { yield return null; }\n\n if(Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri uri))\n {\n yield return uri.Scheme == \"https\" ? $\"https://{uri.Host.Replace(\".\", string.Empty)}.{domain}:{httpsPort}\" : $\"http://{uri.Host.Replace(\".\", string.Empty)}.{domain}:{httpPort}\";\n }\n }\n}\n</code></pre>\n\n<p>usage : </p>\n\n<pre><code>var urls = GetRoutedUrls(grupo.Paginas.Where(p => p.Proxy).Select(x=> x.URL), \"example.com\", 81, 444)\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>After clarifying things, I think you don't need Regex since you're replacing an exact match of urls. Regex would be more useful if you want to search for unknown inputs.</p>\n\n<p>To give you an example of that, if we want to get every single url in the response we can use</p>\n\n<pre><code>Regex.Matches(response, @\"(https?://)(.*)(\\d)\", RegexOptions.IgnoreCase)\n</code></pre>\n\n<p>This would get every single url that has specified a port (e.g. <code>https://example.com:443</code>). Then, we can do stuff on them. </p>\n\n<p>In your method, is different a bit. You already have defined the urls, and you want to check for these urls in your response, if they exist, you want to change them by appending them as subdomain to the given domain, and giving them a new port as well. </p>\n\n<p>Unless if there is any special cases that is not covered or mentioned in your post (which forced you to use Regex in first place), I think it would be a straight forward approach if we just use <code>string.Replace</code> directly. </p>\n\n<pre><code>public string ReplaceResponseUrls(IEnumerable<string> urls, string response, string domain, int httpPort, int httpsPort)\n{\n if (urls == null) { throw new ArgumentNullException(nameof(urls)); }\n\n if (string.IsNullOrEmpty(response)) { throw new ArgumentNullException(nameof(response)); }\n\n if (string.IsNullOrEmpty(domain)) { throw new ArgumentNullException(nameof(domain)); }\n\n var responseStringBuilder = new StringBuilder(response);\n\n foreach (var url in urls)\n {\n if (string.IsNullOrEmpty(url)) { continue; } // skip to the next url\n\n if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out Uri uri))\n {\n responseStringBuilder.Replace(\n $\"{uri.Scheme}://{uri.Host}:{uri.Port}\", // old url\n $\"{uri.Scheme}://{uri.Host.Replace(\".\", string.Empty)}.{domain}:{(uri.Scheme == \"https\" ? httpsPort : httpPort)}\" // new url\n );\n }\n }\n\n return responseStringBuilder.ToString();\n}\n</code></pre>\n\n<p>Try this approach first, do some tests on it, and let me know if you need any help with it. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:06:09.953",
"Id": "469837",
"Score": "0",
"body": "Thank you very much for your collaboration, but if you check my code, the variable \"r\" originally has a text and that text (html or json) is what I return after I replace the urls. Your code could be used to generate the replacement patterns, but it does not include the third pattern that is with when the url does not have the established scheme, in the form \"//www.example.com\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:12:20.360",
"Id": "469838",
"Score": "0",
"body": "I wrote some comments in my code for you to understand better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:45:30.570",
"Id": "469841",
"Score": "0",
"body": "@German just a question before I update it, is it mandatory to have an exact match of `uri.Host`? or do you intend to search for all urls in the response and replace them all ? The only reason that cam up to my head for that is the response may have some other urls that are not related to the context, and you only want to replace specific urls and ignore the rest. Is that what you're trying to do ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:50:35.617",
"Id": "469843",
"Score": "0",
"body": "Yeah that's right. I just need to replace the urls that match **\"uri.Host\"**, the rest should be ignored."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:15:19.947",
"Id": "469847",
"Score": "0",
"body": "@German check out the update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:27:20.073",
"Id": "469892",
"Score": "0",
"body": "The main reason why I didn't use `uri.Scheme` and `uri.Port` in my code is because in the http response I must make sure to replace all possible schemas: **\"https\"**, **\"http\"** or **\"//\"**. Also, it is possible that some urls have the port or not, which is why I used Regex. your code will only replace the exact urls in the current schema and port, but it will not replace the other schemas or when the port is not in the url."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T00:41:58.437",
"Id": "239536",
"ParentId": "239527",
"Score": "1"
}
},
{
"body": "<p>It seems changing the regex is not solution, my suggestions:</p>\n\n<ul>\n<li>get rid of the <code>r</code> variable, it is swelling the memory and makes slow the response time(of course, if value of the parameter <code>contenidoRespuesta</code> is not needed anymore).</li>\n<li>we don't know the content of <code>html</code>/<code>json</code>/<code>js</code>, so next cases indicate assumptions.</li>\n<li>i wondering in your <code>contenidoRespuesta</code> variable can matches with different regex patterns on the same data? if it is not or even there exists the posibility, i suggest you to use if statement seperately to reducing the response time.</li>\n<li>if always one regex match exists, you can use if/else statement to reducing much more the response time.</li>\n<li>i did some tests with lack of mock data which shows performance of if statement. <a href=\"https://dotnetfiddle.net/ooLrYH\" rel=\"nofollow noreferrer\">https://dotnetfiddle.net/ooLrYH</a></li>\n</ul>\n\n<pre class=\"lang-c# prettyprint-override\"><code> //string r = contenidoRespuesta; //decrease the responsee time after RegexReplace succeed\n string dominio = \"example.com\";\n int puertoHttp = 81, puertoHttps = 444;\n foreach (var p in grupo.Paginas.Where(p => p.Proxy))\n {\n Uri uri = new Uri(p.URL);\n string pattern1 = string.Format(\"(?<=https://){0}(:(443)(?!\\\\d+))?(?!:)\", uri.Host); //changing to static method with Regex.Replace may good\n string pattern2 = string.Format(\"(?<=http://){0}(:(80)(?!\\\\d+))?(?!:)\", uri.Host); //changing to static method with Regex.Replace may good\n string pattern3 = string.Format(\"(?<!%2F|\\\\.|http(s)?(://)){0}(:((80)|(443))(?!\\\\d+))?(?!:)\", uri.Host); //changing to static method with Regex.Replace may good\n\n\n //if (new Regex(pattern1).Match(contenidoRespuesta).Success)//positive effects a bit\n contenidoRespuesta= Regex.Replace(contenidoRespuesta, pattern1, uri.Host.Replace(\".\", string.Empty) + \".\" + dominio + \":\" + puertoHttps, RegexOptions.IgnoreCase);// replace https://www.page.com for https://wwwpagecom.example.com\n //if (new Regex(pattern2).Match(contenidoRespuesta).Success)//positive effects a bit\n contenidoRespuesta= Regex.Replace(contenidoRespuesta, pattern2, uri.Host.Replace(\".\", string.Empty) + \".\" + dominio + \":\" + puertoHttp, RegexOptions.IgnoreCase);// replace http://www.page.com for http://wwwpagecom.example.com\n // if (new Regex(pattern3).Match(contenidoRespuesta).Success)//positive effects a bit\n contenidoRespuesta= Regex.Replace(contenidoRespuesta, pattern3, uri.Host.Replace(\".\", string.Empty) + \".\" + dominio + \":\" + (esquema == \"https\" ? puertoHttps.ToString() : puertoHttp.ToString()));// replace //www.page.com for https://wwwpagecom.example.com\n }\nreturn contenidoRespuesta;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-18T21:10:09.353",
"Id": "472325",
"Score": "0",
"body": "The `Regex.Replace` method internally executes the `Regex.Match` method before replacing any text, therefore it is unnecessary to use the `if` statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-18T22:20:38.087",
"Id": "472328",
"Score": "0",
"body": "that is wrong Regex.Replace `returns whole data `even result `false` so moving values from somewhere to another place means extra `work` so performance will be affected. if condition checks then returns `true/false` you should do some tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-18T22:33:17.473",
"Id": "472332",
"Score": "0",
"body": "Remember that `string` is a reference type, therefore when executing the `Replace` method and there are no matches it returns the same reference, values are not being moved to another place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-18T23:51:10.313",
"Id": "472339",
"Score": "0",
"body": "i noticed but it's rerecence will change when you modified the `r`,so they will not have same reference. check with `Object.ReferenceEquals(r, contenidoRespuesta);` before `return r;` so it still swelling the memory and it says performance decreasing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-19T00:08:28.110",
"Id": "472340",
"Score": "0",
"body": "It is correct and that is the reason for my question, how to improve that ?, I have not found another way to do it, when executing the `Replace` method, if there is a match, it will return a new reference, but otherwise it will return the same reference, so it is unnecessary to use the `if` statement before `Replace` since internally it executes the `Match` method."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-17T09:26:08.597",
"Id": "240678",
"ParentId": "239527",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:14:21.887",
"Id": "239527",
"Score": "2",
"Tags": [
"c#",
"asp.net-core"
],
"Title": "Best way to replace Urls in .Net application"
}
|
239527
|
<p>Its been a while since I have written PHP or HTML for a project, so I could use some thoughts on improving the code below. I wrote all of this going off of old knowledge, so I imagine its really sloppy and can be written a lot cleaner. All of the code below works. Here is the link to the project on <a href="https://github.com/Zacke-Dev/pipeline" rel="nofollow noreferrer">GitHub</a></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width-device-width, initial-scale=1"/>
<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="css/mystyle.css"/>
<title>Loan Pipeline</title>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container-fluid">
<h2 class="text-primary">Loan Pipeline &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </h2>
<input type="text" id="myInput" onKeyUp="searchNames()" placeholder="Search by Lender or Processor..." title="Type in a name"> &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;
<?php
include_once "conn.php";
$queryRob = mysqli_query($conn, "SELECT pipeid, lender, SUM(loanamount) AS loanTotal FROM user WHERE lender='Rob'");
$queryAmy = mysqli_query($conn, "SELECT pipeid, lender, SUM(loanamount) AS loanTotal FROM user WHERE lender='Amy'");
$queryCassie = mysqli_query($conn, "SELECT pipeid, lender, SUM(loanamount) AS loanTotal FROM user WHERE lender='Cassie'");
$queryLiz = mysqli_query($conn, "SELECT pipeid, lender, SUM(loanamount) AS loanTotal FROM user WHERE lender='Liz'");
$queryNancy = mysqli_query($conn, "SELECT pipeid, lender, SUM(loanamount) AS loanTotal FROM user WHERE lender='Nancy'");
while($fetch = mysqli_fetch_array($queryRob)){
$robTotal = "$".number_format($fetch['loanTotal'], 2);
}
while($fetch = mysqli_fetch_array($queryAmy)){
$amyTotal = "$".number_format($fetch['loanTotal'], 2);
}
while($fetch = mysqli_fetch_array($queryCassie)){
$cassieTotal = "$".number_format($fetch['loanTotal'], 2);
}
while($fetch = mysqli_fetch_array($queryLiz)){
$lizTotal = "$".number_format($fetch['loanTotal'], 2);
}
while($fetch = mysqli_fetch_array($queryNancy)){
$nancyTotal = "$".number_format($fetch['loanTotal'], 2);
}
?>
<h5 class="text-primary">Amy: <?php echo $amyTotal;?></h5> &nbsp;&nbsp;&nbsp;&nbsp;
<h5 class="text-primary">Cassie: <?php echo $cassieTotal;?></h5> &nbsp;&nbsp;&nbsp;&nbsp;
<h5 class="text-primary">Liz: <?php echo $lizTotal;?></h5> &nbsp;&nbsp;&nbsp;&nbsp;
<h5 class="text-primary">Nancy: <?php echo $nancyTotal;?></h5> &nbsp;&nbsp;&nbsp;&nbsp;
<h5 class="text-primary">Rob: <?php echo $robTotal;?></h5>
</div>
</nav>
<div class="col-md-3"></div>
<div class="col-md-6 well">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#form_modal"><span class="glyphicon glyphicon-plus"></span> Add New Loan</button>
<br /><br />
<table class="table table-bordered" id="allLoans">
<thead class="alert-success">
<tr>
<th>Additional Info</th>
<th>Loan Number</th>
<th>Customer Name</th>
<th>Processor</th>
<th>Lender</th>
<th>Title Company</th>
<th>Contract Price</th>
<th>Loan Amount</th>
<th>Closing Date</th>
<th>Closing Time</th>
<th>Product</th>
<th>Rate</th>
</tr>
</thead>
<tbody style="background-color:#fff;">
<?php
require "conn.php";
$query = mysqli_query($conn, "SELECT * FROM user ORDER BY customername");
while($fetch = mysqli_fetch_array($query))
{
if(is_null($fetch['closingdate'])) {
$closingDate = '';
} else {
$closingDate = date("m/d/Y", strtotime($fetch['closingdate']));
}
if(is_null($fetch['closingtime'])) {
$closingTime = '';
} else {
$closingTime = date("h:i A", strtotime($fetch['closingtime']));
}
if(is_null($fetch['contractprice'])) {
$contractPrice = '';
} else {
$contractPrice = "$".number_format($fetch['contractprice'], 2);
}
if(is_null($fetch['loanamount'])) {
$loanAmount = '';
} else {
$loanAmount = "$".number_format($fetch['loanamount'], 2);
}
$closingConf = $fetch['confirmed'];
if($closingConf == 0) {
$style = 'style="background-color:white;"';
} elseif($closingConf == 1) {
$style = 'style="background-color:rgba(91,244,91,1.00);"';
}
?>
<tr>
<td><button class="btn btn-warning" data-toggle="modal" type="button" data-target="#update_modal<?php echo $fetch['pipeid'];?>"><span class="glyphicon glyphicon-edit"></span> Info</button></td>
<td><?php echo $fetch['loannumber'];?></td>
<td><?php echo $fetch['customername'];?></td>
<td><?php echo $fetch['processor'];?></td>
<td><?php echo $fetch['lender'];?></td>
<td><?php echo $fetch['titleco'];?></td>
<td><?php echo $contractPrice;?></td>
<td><?php echo $loanAmount;?></td>
<td <?php echo $style;?>><?php echo $closingDate;?></td>
<td <?php echo $style;?>><?php echo $closingTime;?></td>
<td><?php echo $fetch['product'];?></td>
<td><?php echo $fetch['notes'];?></td>
</tr>
<?php
include "update_user.php";
}
?>
</tbody>
</table>
</div>
<div class="footer">
<p>&copy; <?php echo date("Y");?> Foresight Bank All Rights Reserved<br><br>
Created by <a href="mailto:ZackE@Foresight.bank">Zack Elcombe</a>
</p>
</div>
<div class="modal fade" id="form_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="save_user.php">
<div class="modal-header">
<h3 class="modal-title">Add Loan Info</h3>
</div>
<div class="modal-body">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="form-group1">
<label >* Required Field</label>
</div>
<div class="form-group">
<label>Loan Number</label>
<input type="text" name="loannumber" class="form-control"/>
</div>
<div class="form-group">
<label>Customer Name *</label>
<input type="text" name="customername" class="form-control" required="required" />
</div>
<div class="form-group">
<label>Processor</label>
<input type="text" name="processor" class="form-control"/>
</div>
<div class="form-group">
<label>Lender *</label>
<input type="text" name="lender" class="form-control" required="required"/>
</div>
<div class="form-group">
<label>Title Company</label>
<input type="text" name="titleco" class="form-control"/>
</div>
<div class="form-group">
<label>Contract Price</label>
<input type="text" name="contractprice" class="form-control"/>
</div>
<div class="form-group">
<label>Loan Amount</label>
<input type="text" name="loanamount" class="form-control"/>
</div>
<div class="form-group">
<label>Closing Date</label>
<input type="date" name="closingdate" class="form-control"/> <br>
<input type="checkbox" name="clsdateconfirmed" class="forme-control"/>
<label>Closing Date Confirmed</label>
</div>
<div class="form-group">
<label>Closing Time</label>
<input type="time" name="closingtime" class="form-control"/>
</div>
<div class="form-group">
<label>Interest Rate</label>
<input type="text" name="interestrate" class="form-control"/>
</div>
<div class="form-group">
<label>Product</label>
<input type="text" name="product" class="form-control"/>
</div>
<div class="form-group">
<label>App Docs Signed?</label>
<input type="text" name="appdocs" class="form-control"/>
</div>
<div class="form-group">
<label>Approval Required?</label>
<input type="text" name="approval" class="form-control"/>
</div>
<div class="form-group">
<label>Appraisal Ordered?</label>
<input type="text" name="appraisal" placeholder="Yes/No" class="form-control"/>
</div>
<div class="form-group">
<label>Closing Location</label>
<input type="text" name="closingloc" class="form-control"/>
</div>
<div class="form-group">
<label>Purchase Agreement</label>
<input type="text" name="purchagreement" class="form-control"/>
</div>
<div class="form-group">
<label>Rate Quote</label>
<input type="text" name="ratequote" class="form-control"/>
</div>
<div class="form-group">
<label>Risk Rating</label>
<input type="text" name="riskrating" class="form-control"/>
</div>
<div class="form-group">
<label>Title Ordered</label>
<input type="text" name="titleordered" class="form-control" placeholder="Yes/No"/>
</div>
</div>
</div>
<div style="clear:both;"></div>
<div class="modal-footer">
<button name="save" class="btn btn-primary"><span class="glyphicon glyphicon-save"></span> Save</button>
<button class="btn btn-danger" type="button" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Close</button>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
function searchNames() {
var input, filter, table, tr, td, i, td2, txtValue, txtValue2;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("allLoans");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[3];
td2 = tr[i].getElementsByTagName("td")[4];
if (td || td2) {
txtValue = td.textContent || td.innerText;
txtValue2 = td2.textContent || td2.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1 || txtValue2.toUpperCase().indexOf(filter) > -1 ) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</body>
</html><span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I dont have time for a full review. But at least one small point:</p>\n\n<p>Dont mix PHP And HTML. Dont mix data loading And logic with the way data Is displayed. That alone Will make Things much cleaner.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T05:49:07.770",
"Id": "239548",
"ParentId": "239530",
"Score": "2"
}
},
{
"body": "<p>It looks like much of the logic is hardcoded -- until that changes, you don't necessarily need to use a prepared statement and bind parameters.</p>\n\n<p>I do recommend that you minimize trips to the database by writing a single query which groups on <code>lender</code> and/or <code>pipeid</code> (assuming pipieid and lender are directly related to each other).</p>\n\n<p>In simplest terms, you can start with a basic query like this:</p>\n\n<pre><code>SELECT\n lender,\n SUM(loanamount) AS loansum\nFROM user\nWHERE lender IN ('Rob', 'Amy', 'Cassie' 'Liz', 'Nancy')\nGROUP BY lender;\n</code></pre>\n\n<p>The <code>user</code> table (probably better-named as <code>lender</code>) seems like an inappropriate place to store multiple rows of loan details. I get the impression that the user table has become the catch-all for lots of data that should be stored separately in a <code>loan</code> table -- this way an individual <code>lender</code> is never represented more than once in the <code>lender</code> table and can be freely represented a multitude of times in the <code>loan</code> table -- this would be where SUMming should take place.</p>\n\n<p>Then leveraging the result set makes producing your content much more elegant (D.R.Y.), not to mention completely controlled by the query at a single point in your script.</p>\n\n<pre><code>$result = mysqli_query($conn, $query);\nforeach ($result as $row) { ?>\n <h5 class=\"text-primary\">\n <?php echo $row['lender'] , \": $\" , number_format($row['loansum'], 2); ?>\n </h5>\n<?php }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T22:30:17.133",
"Id": "239589",
"ParentId": "239530",
"Score": "2"
}
},
{
"body": "<p>Aside from what the other two answers mention:</p>\n\n<ul>\n<li>You have several simular repeating code blocks (such as the <code>if(is_null($fetch[...</code> blocks) that could be shortend/optimizied by using functions</li>\n<li>Don't create spacing with chains of <code>&nbsp;</code> and/or <code><br></code>s. That is what margins and paddings in CSS are for.</li>\n<li>Don't use <code>style</code> attributes. Put all styles into an separate CSS file.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-29T13:29:39.340",
"Id": "241427",
"ParentId": "239530",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:25:01.937",
"Id": "239530",
"Score": "4",
"Tags": [
"php",
"html"
],
"Title": "PHP/HTML Table and Modal Forms that display information"
}
|
239530
|
<p>I am using Python 3.8 with ArcGIS Pro 2.5. This code creates a joined table where I match values for plant greenness in the current month with rainfall X number of months into the past. Each loop iterates through about 600 files (the number of files in ws1 and ws2). The code works perfectly but slowly, taking approximately four hours to run. For my work (a grad student in plant biology) I will need to run this code multiple times. </p>
<p>I am interested in executing the first loop in parallel, however, I've been stumped about how to do so. Any advice about how to optimize this code to run in parallel (using the multiprocessing or other package) would be appreciated. I am using an 8-core 16-thread CPU.</p>
<p><strong>Here is what the code does:</strong></p>
<p>The code first iterates through ws1, which contains tables of plant greenness. The date is isolated from the file name, and then I create a new variable X months before this date. The second loop iterates through ws2, which contains tables of precipitation. Similarly, I isolate the date from the filename, and then create a new variable X months into the past. The final loop iterates through ws2 again and finds the historic filename that matches the one created in the second loop.</p>
<p>r from the first loop is associated with plant greenness at the current month, r2 is associated with precipitation at the current month, while r3 from the last loop is associated with historic precipitation. When the dates from all three loops match then I do the add join.</p>
<pre><code>import arcpy, os, glob, datetime
arcpy.env.addOutputsToMap = 0
from datetime import datetime
ws1=glob.glob(r'D:\GIS_Files\NEW_LA_FULL_SERIES\ALL_DATA_2000_2020\CITY_POLYs\*.shp')
ws2 = glob.glob(r'D:\GIS_Files\NEW_LA_FULL_SERIES\ALL_DATA_2000_2020\PRECIP_preprocessed_2000_2020\CITY_ZONAL_TABLES\*.dbf')
for r in ws1:
basename_BOUND = os.path.basename(r)[35:41]
basename_BOUND1=str(basename_BOUND)
D_POLY=datetime.strptime(basename_BOUND1,'%Y%m').date()
from datetime import datetime
import dateutil.relativedelta
EARLIER_POLY=D_POLY-dateutil.relativedelta.relativedelta(months=2)
STR_PREV_POLY="{:%Y%m}".format(EARLIER_POLY)
print(STR_PREV_POLY)
for r2 in ws2:
basename_ZONAL=os.path.basename(r2)[12:18]
basename_ZONAL1=str(basename_ZONAL)
D_PRECIP= datetime.strptime(basename_ZONAL1,'%Y%m').date()
from datetime import datetime
import dateutil.relativedelta
EARLIER_PRECIP=D_PRECIP-dateutil.relativedelta.relativedelta(months=2)
STR_PREV_PRECIP="{:%Y%m}".format(EARLIER_PRECIP)
for r3 in ws2:
basename_FINAL=os.path.basename(r3)[12:18]
print(basename_FINAL)
if STR_PREV_POLY==STR_PREV_PRECIP:
if STR_PREV_PRECIP==basename_FINAL:
result = arcpy.JoinField_management(in_data=r, in_field="GEO_id",join_table=r3, join_field="GEO_id", fields=["MEAN","STD"])[0]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T05:59:05.850",
"Id": "469850",
"Score": "0",
"body": "Welcome to CodeReview@SE. Can you provide a handful of lines each from input files in your question, and hyperlinks to as much sample input as you see fit? I see surprises coming up."
}
] |
[
{
"body": "<p>You should do a maintainability pass before you start optimizing. In that spirit:</p>\n\n<h2>Imports</h2>\n\n<pre><code>from datetime import datetime\nimport dateutil.relativedelta\n</code></pre>\n\n<p>should be at the top of the file, and should not be repeated. Also, this:</p>\n\n<pre><code>arcpy.env.addOutputsToMap = 0\n</code></pre>\n\n<p>should be moved past the imports section.</p>\n\n<h2>Pathlib</h2>\n\n<p>These:</p>\n\n<pre><code>ws1=glob.glob(r'D:\\GIS_Files\\NEW_LA_FULL_SERIES\\ALL_DATA_2000_2020\\CITY_POLYs\\*.shp')\nws2 = glob.glob(r'D:\\GIS_Files\\NEW_LA_FULL_SERIES\\ALL_DATA_2000_2020\\PRECIP_preprocessed_2000_2020\\CITY_ZONAL_TABLES\\*.dbf')\n</code></pre>\n\n<p>should get a little love from <code>pathlib</code>:</p>\n\n<p>Factor out the common directory -</p>\n\n<pre><code>data_dir = Path(r'D:\\GIS_Files\\NEW_LA_FULL_SERIES\\ALL_DATA_2000_2020')\nws1 = (data_dir / 'CITY_POLYs').glob('*.shp')\nws2 = (data_dir / 'PRECIP_preprocessed_2000_2020' / 'CITY_ZONAL_TABLES').glob('*.dbf')\n</code></pre>\n\n<h2>Hard-coded string slices</h2>\n\n<p>These:</p>\n\n<pre><code>[35:41]\n[12:18]\n</code></pre>\n\n<p>are a nightmare. I don't know what they're actually selecting, but I can nearly guarantee that there's a better way. It seems like a slice out of a path, and paths are structured - you should not have to do indexing like this.</p>\n\n<h2>Nomenclature</h2>\n\n<p>You, currently, understand what these variables mean:</p>\n\n<pre><code>ws1\nws2\nr\nr2\nr3\nresult\n</code></pre>\n\n<p>But no one else does, and you might not in six months. Do yourself a favour and give these meaningful names.</p>\n\n<h2>Logical combination</h2>\n\n<pre><code> if STR_PREV_POLY==STR_PREV_PRECIP:\n if STR_PREV_PRECIP==basename_FINAL:\n</code></pre>\n\n<p>should simply be</p>\n\n<pre><code>if STR_PREV_POLY == basename_FINAL:\n</code></pre>\n\n<p>That intermediate variable has no effect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:10:17.447",
"Id": "239543",
"ParentId": "239535",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T00:23:28.537",
"Id": "239535",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"iteration",
"multiprocessing",
"arcpy"
],
"Title": "Join ArcGIS tables in Python of plant greenness in response to prior month's rainfall"
}
|
239535
|
<p>Python script that can download images and videos of the user, like Gallery with photos or videos. It saves the data in the folder.</p>
<h1>How it works:</h1>
<ul>
<li><p>Log in in instragram using selenium and navigate to the profile</p>
</li>
<li><p>Check the availability of Instagram profile if it's private or existing</p>
</li>
<li><p>Gathering urls from images or videos</p>
</li>
<li><p>Using threads and multiprocessing improve execution speed</p>
</li>
</ul>
<p>My code:</p>
<pre><code>from pathlib import Path
import requests
import time
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from multiprocessing.dummy import Pool
import urllib.parse
import re
from concurrent.futures import ThreadPoolExecutor
from typing import *
chromedriver_path = None
class PrivateException(Exception):
pass
class InstagramPV:
def __init__(self, username: str, password: str, folder: Path, search_name: str):
"""
:param username: username
:param password: password
:param folder: folder name
:param search_name: the name what will search
"""
self.username = username
self.password = password
self.folder = folder
self.http_base = requests.Session()
self._search_name = search_name
self.links: List[str] = []
self.pictures: List[str] = []
self.videos: List[str] = []
self.url: str = 'https://www.instagram.com/{name}/'
self.posts: int = 0
if chromedriver_path is not None:
self.driver = webdriver.Chrome(chromedriver_path)
else:
self.driver = webdriver.Chrome()
@property
def name(self) -> str:
"""
To avoid any errors, with regex find the url and taking the name <search_name>
:return: The name of the Profile
"""
find_name = ''.join(re.findall(r'(?P<url>https?://[^\s]+)', self._search_name))
if find_name.startswith('https'):
self._search_name = urllib.parse.urlparse(find_name).path.split('/')[1]
return self._search_name
else:
return self._search_name
def __enter__(self):
return self
def check_availability(self) -> None:
"""
Checking Status code, Taking number of posts, Privacy and followed by viewer
Raise Error if the Profile is private and not following by viewer
:return: None
"""
search = self.http_base.get(self.url.format(name=self.name), params={'__a': 1})
search.raise_for_status()
load_and_check = search.json()
self.posts = load_and_check.get('graphql').get('user').get('edge_owner_to_timeline_media').get('count')
privacy = load_and_check.get('graphql').get('user').get('is_private')
followed_by_viewer = load_and_check.get('graphql').get('user').get('followed_by_viewer')
if privacy and not followed_by_viewer:
raise PrivateException('[!] Account is private')
def control(self) -> None:
"""
Create the folder name
"""
self.folder.mkdir(exist_ok=True)
def login(self) -> None:
"""Login To Instagram"""
self.driver.get('https://www.instagram.com/accounts/login')
WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'form')))
self.driver.find_element_by_name('username').send_keys(self.username)
self.driver.find_element_by_name('password').send_keys(self.password)
submit = self.driver.find_element_by_tag_name('form')
submit.submit()
"""Check For Invalid Credentials"""
try:
var_error = self.driver.find_element_by_class_name('eiCW-').text
raise ValueError('[!] Invalid Credentials')
except NoSuchElementException:
pass
try:
"""Close Notifications"""
notifications = WebDriverWait(self.driver, 20).until(
EC.presence_of_element_located((By.XPATH, '//button[text()="Not Now"]')))
notifications.click()
except NoSuchElementException:
pass
"""Taking cookies"""
cookies = {
cookie['name']: cookie['value']
for cookie in self.driver.get_cookies()
}
self.http_base.cookies.update(cookies)
"""Check for availability"""
self.check_availability()
self.driver.get(self.url.format(name=self.name))
return self.scroll_down()
def get_href(self) -> None:
elements = self.driver.find_elements_by_xpath('//a[@href]')
for elem in elements:
urls = elem.get_attribute('href')
if 'p' in urls.split('/'):
self.links.append(urls)
def scroll_down(self) -> None:
"""Taking hrefs while scrolling down"""
while len(list(set(self.links))) < self.posts:
self.get_href()
time.sleep(1)
self.driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
time.sleep(1)
return self.submit_links()
def submit_links(self) -> None:
"""Gathering Images and Videos and pass to function <fetch_url> Using ThreadPoolExecutor"""
self.control()
links = list(set(self.links))
print('[!] Ready for video - images'.title())
print(f'[*] extracting {len(links)} posts , please wait...'.title())
new_links = [urllib.parse.urljoin(link, '?__a=1') for link in links]
with ThreadPoolExecutor(max_workers=8) as executor:
[executor.submit(self.fetch_url, link) for link in new_links]
def fetch_url(self, url: str) -> None:
"""
This function extracts images and videos
:param url: Taking the url
:return None
"""
logging_page_id = self.http_base.get(url.split()[0]).json()
try:
"""Taking Gallery Photos or Videos"""
for log_pages in logging_page_id['graphql']['shortcode_media']['edge_sidecar_to_children']['edges']:
video = log_pages['node']['is_video']
if video:
video_url = log_pages['node']['video_url']
self.videos.append(video_url)
else:
image = log_pages['node']['display_url']
self.pictures.append(image)
except KeyError:
"""Unique photo or Video"""
image = logging_page_id['graphql']['shortcode_media']['display_url']
self.pictures.append(image)
if logging_page_id['graphql']['shortcode_media']['is_video']:
videos = logging_page_id['graphql']['shortcode_media']['video_url']
self.videos.append(videos)
def download_video(self, new_videos: Tuple[int, str]) -> None:
"""
Saving the video content
:param new_videos: Tuple[int,str]
:return: None
"""
number = new_videos[0]
link = new_videos[1]
with open(self.folder / f'Video{number}.mp4', 'wb') as f:
content_of_video = InstagramPV.content_of_url(self.http_base.get(link))
f.write(content_of_video)
def images_download(self, new_pictures: Tuple[int, str]) -> None:
"""
Saving the picture content
:param new_pictures: Tuple[int, str]
:return: None
"""
number = new_pictures[0]
link = new_pictures[1]
with open(self.folder / f'Image{number}.jpg', 'wb') as f:
content_of_picture = InstagramPV.content_of_url(self.http_base.get(link))
f.write(content_of_picture)
def downloading_video_images(self) -> None:
"""Using multiprocessing for Saving Images and Videos"""
print('[*] ready for saving images and videos!'.title())
picture_data = enumerate(list(set(self.pictures)))
video_data = enumerate(list(set(self.videos)))
pool = Pool(8)
pool.map(self.images_download, picture_data)
pool.map(self.download_video, video_data)
print('[+] Done')
def __exit__(self, exc_type, exc_val, exc_tb):
self.http_base.close()
self.driver.close()
@staticmethod
def content_of_url(req: [requests.sessions.Session, requests.models.Response]) -> bytes:
"""
:param req: requests.sessions.Session, requests.models.Response
:return: Content of Url
"""
return req.content
def main():
USERNAME = ''
PASSWORD = ''
NAME = ''
FOLDER = Path('')
with InstagramPV(USERNAME, PASSWORD, FOLDER, NAME) as pv:
pv.login()
pv.downloading_video_images()
if __name__ == '__main__':
main()
</code></pre>
<p>My previous comparative review tag:
<a href="https://codereview.stackexchange.com/questions/239074/instagram-bot-selenium-web-scraping">Instagram Bot, selenium, web scraping</a></p>
|
[] |
[
{
"body": "<h2>Duplicated statements in an if-block</h2>\n\n<pre><code> if find_name.startswith('https'):\n self._search_name = urllib.parse.urlparse(find_name).path.split('/')[1]\n return self._search_name\n else:\n return self._search_name\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code> if find_name.startswith('https'):\n self._search_name = urllib.parse.urlparse(find_name).path.split('/')[1]\n return self._search_name\n</code></pre>\n\n<h2>Type hint difference</h2>\n\n<p>You say this has no return:</p>\n\n<pre><code>def login(self) -> None:\n</code></pre>\n\n<p>But then you do one anyway?</p>\n\n<pre><code> return self.scroll_down()\n</code></pre>\n\n<p>This is repeated in <code>scroll_down()</code> itself.</p>\n\n<h2>List comprehensions as loops</h2>\n\n<p>I find this:</p>\n\n<pre><code> with ThreadPoolExecutor(max_workers=8) as executor:\n [executor.submit(self.fetch_url, link) for link in new_links]\n</code></pre>\n\n<p>to be unnecessary. It's more legible to have a simple <code>for</code>-loop than to construct a list and throw it away.</p>\n\n<h2>Method order</h2>\n\n<p>For sane legibility, it's better to put <code>__exit__</code> directly after <code>__enter__</code> in the class.</p>\n\n<h2><code>content_of_url</code></h2>\n\n<p>This method:</p>\n\n<pre><code>@staticmethod\ndef content_of_url(req: [requests.sessions.Session, requests.models.Response]) -> bytes:\n \"\"\"\n :param req: requests.sessions.Session, requests.models.Response\n :return: Content of Url\n \"\"\"\n return req.content\n</code></pre>\n\n<p>doesn't do anything useful enough to deserve being a dedicated method. Even if it did, the type hint for <code>req</code> seems wrong; it should just be a <code>Response</code>. I'm not sure why the <code>Session</code> is mentioned.</p>\n\n<h2>Local variables</h2>\n\n<pre><code>USERNAME = ''\nPASSWORD = ''\nNAME = ''\nFOLDER = Path('')\n</code></pre>\n\n<p>should be lowercase, now that they're in function scope.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T15:36:00.537",
"Id": "469877",
"Score": "0",
"body": "Thanks!! About the type hints, should just get rid of _return_ or it's returning something that i didnt notice? Also, in The content_of_url, if i dont mention the _Session_ is raising me a warning. Should i put it in the class too or to do something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T15:46:07.543",
"Id": "469879",
"Score": "0",
"body": "_ should just get rid of return_ - yes, since the bottom of that stack does not return anything. _if i dont mention the Session is raising me a warning_ - what warning?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:10:56.993",
"Id": "469886",
"Score": "0",
"body": "Strange. It was raising me a warning at _self.http_base.get(link)_ but now nothing. I dont understand. Its ok now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T02:00:17.180",
"Id": "470181",
"Score": "0",
"body": "Should i post my next question ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T02:33:33.757",
"Id": "470188",
"Score": "0",
"body": "Since you've accepted an answer on this one, I would say yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-04T20:16:38.940",
"Id": "470624",
"Score": "0",
"body": "Finally my new [questtion](https://codereview.stackexchange.com/questions/239940/instagram-scraping-posts-using-selenium) :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T03:56:56.237",
"Id": "239542",
"ParentId": "239539",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T01:40:48.993",
"Id": "239539",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"web-scraping",
"selenium"
],
"Title": "Instagram Scraping Using Selenium"
}
|
239539
|
<p>I am creating web page in which I get user location and store it in an <code>input</code> field of a form using <code>javascript</code>.
But perfomance is slow.Review my code and provide a better way.</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 LocArrayForPerfomance = [];
LocArrayForPerfomance["longitude"]=document.getElementById("longitude");
LocArrayForPerfomance["latitude"]=document.getElementById("latitude");
function main_get_location() {
var checkbox = document.getElementById("location_checkbox");
var loc_text=document.getElementById("loc_text");
function clearBox()
{
checkbox.checked=false;
document.getElementById("latitude").value="";
document.getElementById("longitude").value="";
}
function getLocation() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(savePosition, showError);
}
else
{
loc_text.innerHTML = "Geolocation is not supported by this browser.You can't post.Use a device or browser which supports geolocation.";
clearBox();
}
}
function savePosition(position) {
LocArrayForPerfomance["latitude"].setAttribute("value",position.coords.latitude)
LocArrayForPerfomance["longitude"].setAttribute("value",position.coords.longitude)
checkbox.checked=true;
}
function showError(error) {
clearBox();
switch(error.code) {
case error.PERMISSION_DENIED:
loc_text.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
loc_text.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
loc_text.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
loc_text.innerHTML = "An unknown error occurred."
break;
}
}
getLocation();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Create a post</title>
</head>
<body>
<form autocomplete="off" method="post" enctype="multipart/form-data">
<br>
<input type="text" name="latitude" id="latitude">
<input type="text" name="longitude" id="longitude">
<label for="location_checkbox">Add location:</label>
<input type="checkbox" id="location_checkbox" onclick="main_get_location()" required>
<br>
<input type="submit" value="share location!" id="loc_submit">
</form>
<p id="loc_text" color="red"></p>
</body>
</html></code></pre>
</div>
</div>
Sometimes when submit is clicked,location is not sent to the server (even though checkbox is checked,documentGetElementByID() is slow).I read somewhere,using arrays will improve perfomance.Still it is slow.Should I use a delay function??</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T06:16:43.770",
"Id": "469851",
"Score": "3",
"body": "Welcome to CodeReview@SE. `Sometimes … location is not sent to the server` How did you establish this? For the \"fate\" of this question, it may be helpful too to revisit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) and improve, e.g., spacing following punctuation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T06:12:06.280",
"Id": "470494",
"Score": "0",
"body": "If the code doesn't work yet, it's not ready for review. I'm not sure how you think a delay function will improve performance either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-04T14:34:44.070",
"Id": "470616",
"Score": "0",
"body": "It works.But slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T20:32:21.053",
"Id": "470862",
"Score": "0",
"body": "Please can you add a description on what this code hopes to achieve."
}
] |
[
{
"body": "<p>You should prepare everything (find elements, etc) you can as soon as you can (on document load, assuming the elements Are not added dynamically). Dont wait for user action.</p>\n\n<p>Also dont load current location upon checking the checkbox. Load it upon form submit, prevent default submit action And only send to server after location Is obtained. Maybe display some load progress bar to the user meanwhile...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T05:44:44.310",
"Id": "239547",
"ParentId": "239546",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "239547",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T05:23:58.293",
"Id": "239546",
"Score": "-2",
"Tags": [
"javascript",
"html",
"location-services"
],
"Title": "javascript-Location access in a web page"
}
|
239546
|
<p>I followed a video on YouTube to create a custom user model, this is my attempt:</p>
<pre class="lang-py prettyprint-override"><code># Django Imports
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models
# The Custom (UserManager) Class
class UserManager(BaseUserManager):
# Defining A Function That Will Be Used To Create New Users
def create_user(self, email, username, f_name, l_name, password = None):
if not email:
raise ValueError('Users Must Have An E-Mail Address')
if not username:
raise ValueError('Users Must Have A Username')
# Creating An Object Of The Type (User)
user = self.model(
user_email = self.normalize_email(email),
user_name = username,
first_name = f_name,
last_name = l_name
)
# Setting The Password For The User Object We Created Above
user.set_password(password)
# Saving The User To The Database
user.save(using = self._db)
# Returning The (user) Instance To Where The Function Was Called
return user
# Defining A Function That Will Be Used To Create Superusers (Admins)
def create_superuser(self, email, username, f_name, l_name, password):
# Creating An Instance Of Type (User)
user = self.create_user(
user_email = self.normalize_email(email),
user_name = username,
password = password,
first_name = f_name,
last_name = l_name
)
# Setting The User We Created Above As An Administrator
user.is_admin = True
user.is_staff = True
user.is_superuser = True
# Saving The User To The Database
user.save(using = self._db)
# Returning The (user) Instance To Where The Function Was Called
return user
# The Custom (User) Class
class User(AbstractBaseUser):
# The Data (Columns) For Each User
user_email = models.EmailField(max_length = 120, unique = True)
user_name = models.CharField(max_length = 40, unique = True)
first_name = models.CharField(max_length = 60)
last_name = models.CharField(max_length = 60)
date_joined = models.DateTimeField(auto_now_add = True)
last_login = models.DateTimeField(auto_now = True)
is_admin = models.BooleanField(default = False)
is_active = models.BooleanField(default = True)
is_staff = models.BooleanField(default = False)
is_superuser = models.BooleanField(default = False)
# The Data (Column) That Is Going To Be Used As A Login Identifier
USERNAME_FIELD = 'user_email'
REQUIRED_FIELDS = ['user_name', 'first_name', 'last_name']
# Defining How The Output Of An Object Of The (User) Class Will Look Like
def __str__(self):
return f'{self.user_email} - ({self.user_name})'
# Defining A Function That Will Check Whether A User Is Admin Or Not
def has_perm(self, perm, obj = None):
return self.is_admin
# Defining A Function That Will Check Whether A User Is Admin In The Current App Or Not
def has_module_perms(self, app_label):
return True
</code></pre>
<p>I know the way I comment stuff is incorrect, I am going to leave this habit as I don't need to write comments everywhere, instead focus on code clarity, so other than my bad commenting style, is this approach to creating custom users in Django correct? </p>
<p>P.S: I use PostgreSQL as my Database</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T12:08:39.777",
"Id": "469868",
"Score": "0",
"body": "What exactly do you mean _\"I know the way I comment stuff is incorrect,\"_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T12:31:35.530",
"Id": "469870",
"Score": "0",
"body": "The way I write comments everywhere is not considered a good thing."
}
] |
[
{
"body": "<h1>Spacing</h1>\n\n<p>At first glance, it looks like you're creating a bunch of variables instead of creating an object and passing default parameters. You should reduce all this extra spacing to make it clear what you're doing. Have a look:</p>\n\n<pre><code>user = self.model(\n user_email=self.normalize_email(email),\n user_name=username,\n first_name=f_name,\n last_name=l_name\n)\n</code></pre>\n\n<p>This goes for both of the places where you do this.</p>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> there should only be one space before and after the <code>=</code> operator. The issue with how you're creating variables is that all that spaces requires the reader to keep they're gaze straight and follow the line to make sure they know what is being assigned to what. Here's an example in your code:</p>\n\n<pre><code>user_email = models.EmailField(max_length = 120, unique = True)\nuser_name = models.CharField(max_length = 40, unique = True)\nfirst_name = models.CharField(max_length = 60)\nlast_name = models.CharField(max_length = 60)\ndate_joined = models.DateTimeField(auto_now_add = True)\nlast_login = models.DateTimeField(auto_now = True)\nis_admin = models.BooleanField(default = False)\nis_active = models.BooleanField(default = True)\nis_staff = models.BooleanField(default = False)\nis_superuser = models.BooleanField(default = False)\n</code></pre>\n\n<p>All this spacing really isn't necessary.</p>\n\n<p>Parameter spacing is also an issue in your code. Contrary to the suggestions above, there should be <em>no</em> spaces when passing default parameters. Have a look:</p>\n\n<pre><code>user_email = models.EmailField(max_length=120, unique=True)\ndef has_perm(self, perm, obj=None):\nuser.save(using=self._db)\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>You can use type hints to display what types of parameters are accepted and what types are returned by a function. Have a look:</p>\n\n<pre><code>def create_superuser(\n self,\n email: str,\n username: str,\n f_name: str,\n l_name: str, \n password: str\n) -> User:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T05:32:11.503",
"Id": "239639",
"ParentId": "239553",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239639",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T10:25:00.847",
"Id": "239553",
"Score": "2",
"Tags": [
"python",
"django",
"postgresql"
],
"Title": "My Django custom user model"
}
|
239553
|
<p>After just learning a bit of Python I tried coding something myself. I attempted to do a game of Blackjack, which is far from perfect, and still doesn't have some rules a real game has (in my game an ace is always 11 points, whereas in reality it can also be counted as 1 point). </p>
<p>There is however an issue that I'm having, simply because I don't understand it: I would like pack some of my code in methods and call them, but I'm having an issue with some variables. I use j as a variable for the card that would be on top of the deck. By default it is set to 4, because after the starting hands have been dealt the top card of the deck is the fourth one. Each time the player is dealt an additional card j is increased by 1. When the user finishes playing and it's the dealers turn I want to keep the current value of j and not revert to j being 4. How do I need to restructure my code in order to keep the changes that have been made to j in the while loop, if I put that loop into its own method? Is there a way I can "extract" a value of a variable from another method?</p>
<p>Additionally I want to develop good habits right from the start and tried using the best practices I know of, like using formatted Strings or using <code>j += 1</code>instead of <code>j = j + 1</code>. Are there any bad practices in my code, where can I improve? Here's the game in its current state, it seems to be working correctly, as I haven't found a way to break it. (A minor flaw is that you have to press "Y" or "y" for another card, but instead of having to press "n" or "N" for no more cards you can press anything)</p>
<pre><code>import random
# the player plays first
# dealer goes second
# dealer hits on 16 and stands on 17
deck_of_cards = ["Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"]
cards = {
"Two": 2,
"Three": 3,
"Four": 4,
"Five": 5,
"Six": 6,
"Seven": 7,
"Eight": 8,
"Nine": 9,
"Ten": 10,
"Jack": 10,
"Queen": 10,
"King": 10,
"Ace": 11,
}
def drawing_a_card(card_num):
i = card_num - 1
drawn_card = deck_of_cards[i]
return drawn_card
random.shuffle(deck_of_cards)
players_first_card = drawing_a_card(card_num=1)
players_second_card = drawing_a_card(card_num=3)
dealers_first_card = drawing_a_card(card_num=2)
players_total = cards[players_first_card] + cards[players_second_card]
print(f"Your first card: {players_first_card}")
print(f"Your second card: {players_second_card}")
print(f"Dealer's first card: {dealers_first_card}")
decision = input(f"You are standing at {players_total}, would you like another card? (Y/N) ")
if players_total == 21 :
print(f"You hit 21! That's Blackjack, you win!")
j = 4
while decision.lower() == "y":
if decision.lower() == "y":
players_next_card = drawing_a_card(card_num=j)
print(f"Your card: {players_next_card}")
players_total += cards[players_next_card]
j += 1
if players_total > 21:
print(f"That's a Bust! Your total was {players_total}")
break
elif players_total == 21:
print(f"You hit 21! That's Blackjack, you win!")
break
else:
decision = input(f"You are now standing at {players_total}, would you like another card? (Y/N) ")
k = j+1
if players_total < 21:
print("The Dealer will now take his turn...")
dealers_second_card = drawing_a_card(card_num=k)
k += 1
print(f"Dealer's cards are {dealers_first_card} and {dealers_second_card}")
dealers_total = cards[dealers_first_card] + cards[dealers_second_card]
if dealers_total == 21:
print(f"The Dealer hit 21! That's Blackjack, the Dealer wins!")
while dealers_total <= 16:
print(f"Dealer's total is {dealers_total}, he'll take another card.")
dealers_next_card = drawing_a_card(card_num=k)
print(f"The Dealer's card: {dealers_next_card}")
dealers_total += cards[dealers_next_card]
k += 1
if dealers_total == 21:
print(f"The Dealer hit 21! That's Blackjack, the Dealer wins!")
elif dealers_total > 21:
print(f"The Dealers total is {dealers_total}, he has bust and you win!")
if dealers_total >= 17:
print(f"The Dealer stands at {dealers_total}")
if dealers_total < players_total:
print(f"Your total is {players_total}, which is higher than the Dealer's {dealers_total}, you win!")
elif dealers_total == players_total:
print(f"You and the Dealer are both standing at {dealers_total}, it's a draw!")
elif dealers_total > players_total:
print(f"The Dealer beats your {players_total} with his {dealers_total}, you lose!")
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T14:54:58.873",
"Id": "469875",
"Score": "2",
"body": "Please use a descriptive title. Read [How to ask](https://codereview.stackexchange.com/help/how-to-ask) to find out how to do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:23:35.873",
"Id": "469891",
"Score": "1",
"body": "A good title might be \"A very simple Black Jack game in python\". If the code is not working properly, you should try stackoverflow.com, code review is for code that is working as expected. Code review guide lines can be found at https://codereview.stackexchange.com/help/asking. Stackoverflow guidelines can be found at https://stackoverflow.com/help/asking."
}
] |
[
{
"body": "<blockquote>\n <p>Is there a way I can \"extract\" a value of a variable from another method?</p>\n</blockquote>\n\n<p>A method can return a value, so you can assign the variable you need the value of to the call of this method. You just need to think about what j actually represents and what the action that is iterating j meaningfully is. In this case it's pretty clear; you are having player A draw a set of cards from the deck and then player B draw a set of cards from the deck. So you could have a method like PlayHand() where you have a player A play their hand according to the logic you have articulated while returning the value you need for player B. Think about what \"PlayHand\" says in actual language and then what of your code accomplishes that task.</p>\n\n<p>There is more to say but I will have to get to it later. Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T20:19:00.547",
"Id": "470023",
"Score": "0",
"body": "I meant it like this: Let's say I make a method called UsersTurn where the User takes his turn and j represents the number of cards that have already been drawn/the number of the card that is on top so j=4 means the fourth card is on top. Lets say I return players_total or which card was drawn or something else. Is there a way to get to j if I return something else?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T13:00:41.247",
"Id": "239556",
"ParentId": "239555",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T12:30:25.637",
"Id": "239555",
"Score": "0",
"Tags": [
"python",
"beginner",
"random",
"playing-cards"
],
"Title": "My first code - looking for feedback on best practices and things I should avoid doing in the future"
}
|
239555
|
<p>I have a PHP CodeIgniter website that collects volunteer registrations. One thing I have noticed is that the controllers are getting really big. The controllers have many methods, and each method is fairly long. I believe this could be a code smell, and I would like some help and advice on how to refactor the code.</p>
<p>The website is in production and too big to post all the code. I will pick a sample page to post here so you can get an idea. I'm looking for broad feedback on how to improve the organization of the code. For example:</p>
<ul>
<li>Idea 1 - Should I move some of this code to a new layer between the controller and the model? I've seen this recommended in some places. I believe it's called a domain layer.</li>
<li>Idea 2 - Should I break this entire method (and other big methods) off into their own classes? Since I'm using CodeIgniter, I guess these would be library classes?</li>
<li>Idea 3 - Should I make more use of private methods within the giant controller class? Won't shrink the size of the controller, but might make some of the code more readable. Or maybe not, since I'd be scrolling all over the page to find code, instead of just reading it linearly.</li>
<li>Idea 4 - Should I try to move more code into the models? My models are a similar size to the controllers.</li>
<li>Idea 5 - The code works and I (the only developer) can read it just fine. Should I just leave it alone? YAGNI? Keep complexity down?</li>
<li>I have a lot of controller methods that start out with form validation code. What is the best way to handle that?</li>
<li>Bonus question: What are good ways to test a <strong><em>website</em></strong>? I currently use iMacros browser plugin and run scripts that simulate typing, mouse clicks, submitting forms, clicking links, etc. I have heard of unit testing but am not sure where to start with that. Is it worth it to write a bunch of unit tests?</li>
<li>Other ideas/feedback?</li>
</ul>
<h2>Screenshot</h2>
<p><a href="https://i.stack.imgur.com/WgOrW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WgOrW.png" alt="screenshot of website"></a></p>
<h2>Code</h2>
<pre><code>public function edit_group($group_id_and_text = NULL)
{
$this->data = set_page_title('Edit Group', $this->data);
$this->data = $this->_get_group_data_or_throw_error_page($group_id_and_text, $this->data, '/managers/edit_group/');
$this->data['list_of_shifts'] = $this->shift_model->get_race_shifts_with_enrolled_plus_groups_fields($this->data['race']['race_id']);
$this->data['list_of_group_shifts'] = $this->group_shift_model->get_group_shifts_for_group($this->data['group']['group_id']);
// output format is $shift_id => $number_promised
$this->data['list_of_group_shifts_as_list'] = $this->group_shift_model->get_group_shifts_as_list($this->data['group']['group_id'], $this->data['race']['race_id']);
$this->data['list_of_shifts_to_highlight'] = highlight_shifts_that_need_more_groups($this->data['list_of_shifts']);
$this->data['list_of_volunteers_with_shifts'] = $this->volunteer_shift_model->get_volunteers_by_race_and_group($this->data['race']['race_id'], $this->data['group']['group_id']);
$this->data['list_of_volunteers_without_shifts'] = $this->volunteer_shift_model->get_volunteers_with_no_shifts_filter_by_group($this->data['race']['race_id'], $this->data['group']['group_id']);
$this->data['list_of_volunteers'] = array_merge($this->data['list_of_volunteers_with_shifts'], $this->data['list_of_volunteers_without_shifts']);
$this->form_validation->set_rules('group_name', 'Group Name', 'trim|required|max_length[200]');
$this->form_validation->set_rules('shift_id[]', 'Volunteer Shift', 'trim|valid_volunteer_group_shift_for_admin[' . $this->data['race']['race_id'] . ']');
$this->form_validation->set_rules('group_notes', 'Group Notes', 'trim|max_length[1000]');
$this->form_validation->set_rules('group_send_reminder_emails', 'Reminder Emails', 'trim|required|in_list[0,1]');
$this->form_validation->set_rules('fix_shifts', 'Fix Volunteer Shifts', 'trim|in_list[1]');
$this->form_validation->set_rules('email_group_leader', 'Email Group Leader', 'trim|in_list[1]');
$this->form_validation->set_rules('delete_group', 'Delete Group', 'trim|in_list[1]');
$this->form_validation->set_rules('delete_group_members', 'Delete Group Members', 'trim|in_list[1]');
$this->form_validation->set_rules('group_firm', 'Mark As Firm', 'trim|in_list[1]');
// Note: SQL WHERE is case insensitive, which is good in this case
$this->data['group_for_duplicate_check'] = $this->group_model->get_group_by_race_and_group_name(
$this->data['race']['race_id'],
$this->input->post('group_name')
);
if ($this->form_validation->run() === FALSE)
{
load_page_with_event_nav('managers/edit_group', $this->data);
}
elseif ( $this->data['group_for_duplicate_check'] && $this->data['group_for_duplicate_check']['group_id'] != $this->data['group']['group_id'] )
{
add_message('error', 'A group with this name already exists. <a href="/managers/edit_group/' . $this->data['group_for_duplicate_check']['group_uri'] . '">Click here</a> to view and edit the existing group.');
load_page_with_event_nav('managers/edit_group', $this->data);
}
else
{
$group_leader_volunteer_id = $this->data['group']['group_leader_volunteer_id'];
// Putting delete_group_members before delete_group so that the soft deleted volunteers keep their group_id. Will be helpful if I have to undo the soft delete.
if ( $this->input->post('delete_group_members') )
{
$volunteer_ids = $this->data['list_of_volunteers'];
if ( $volunteer_ids ) {
$volunteer_ids = sql_make_list_from_sql_result_array($volunteer_ids, 'volunteer_id');
$volunteer_ids = mv_eliminate_duplicates($volunteer_ids);
$this->volunteer_model->soft_delete_volunteer($volunteer_ids);
add_message('success', '"' . html_escape($this->data['group']['group_name']) . '"\'s group members were successfully deleted from the group AND the volunteer database.');
}
}
if ( $this->input->post('delete_group') )
{
$this->group_model->soft_delete_groups($this->data['group']['group_id']);
// If group_leader_volunteer_id got deleted because the volunteer got soft deleted, AND the group is getting deleted, restore the group_leader_volunteer_id so that email_list can display deleted group leaders.
$this->group_model->set_group_leader($this->data['group']['group_id'], $group_leader_volunteer_id);
add_message('success', '"' . html_escape($this->data['group']['group_name']) . '" was successfully deleted.');
}
else
{
$this->group_model->edit_group($this->data);
// refresh some variables needed down here
$this->data['group'] = $this->group_model->get_group_by_id($this->data['group']['group_id']);
$this->data['volunteer'] = $this->volunteer_model->get_volunteer_by_id($this->data['group']['group_leader_volunteer_id']);
$this->data['list_of_group_shifts'] = $this->group_shift_model->get_group_shifts_for_group($this->data['group']['group_id']);
$shifts_to_compare = $this->data['list_of_group_shifts_as_list'];
/*
PHP's array compare is extremely loose.
1) It compares array contents, not references.
2) It compares across types. For example, 0 and '0' are seen as the same thing.
3) The order of the array keys doesn't matter, so we don't need to sort them.
*/
if ( $this->input->post('shift_id') != $shifts_to_compare )
{
$this->group_shift_model->hard_delete_groups_shifts($this->data['group']['group_id']);
foreach ( $_POST['shift_id'] as $shift_id => $value )
{
if ( $value != 0 )
{
$this->group_shift_model->add_shift(
$this->data['group']['group_id'],
$shift_id,
$value,
$this->data
);
}
}
}
// refresh again
$this->data['list_of_group_shifts'] = $this->group_shift_model->get_group_shifts_for_group($this->data['group']['group_id']);
$list_of_group_shifts = sql_make_list_from_sql_result_array($this->data['list_of_group_shifts'], 'shift_id');
// Make sure the group leader is enrolled in all the group's shifts. This is important so that the group leader receives the volunteer instructions for each of this group's shifts.
if ( $this->data['volunteer'] )
{
foreach ( $list_of_group_shifts as $key => $shift_id )
{
$shift = $this->volunteer_shift_model->get_shift_by_volunteer_id_and_shift_id($this->data['volunteer']['volunteer_id'], $shift_id);
if ( ! $shift )
{
$this->volunteer_shift_model->add_shift(
$this->data['volunteer']['volunteer_id'],
$shift_id,
$this->data['auth']['manager']['manager_id']
);
}
}
}
add_message('success', '"<a href="/managers/edit_group/' . $this->data['group']['group_uri'] . '">' . html_escape($this->data['group']['group_name']) . '</a>" was successfully edited.');
if ( $this->input->post('fix_shifts') == 1 )
{
// ****** FIX_SHIFTS_REMOVE ******
foreach ( $this->data['list_of_volunteers_with_shifts'] as $key => $volunteer_shift )
{
if ( !in_array($volunteer_shift['shift_id'], $list_of_group_shifts) )
{
$this->volunteer_shift_model->hard_delete_one_volunteer_one_shift($volunteer_shift['volunteer_id'], $volunteer_shift['shift_id']);
}
}
// ****** FIX_SHIFTS_ADD ******
$this->data['list_of_volunteers_not_joined_with_volunteer_shifts'] = $this->volunteer_model->get_volunteers_by_race_and_group($this->data['race']['race_id'], $this->data['group']['group_id']);
$this->data['list_of_volunteer_shifts_for_this_race'] = $this->volunteer_shift_model->get_volunteers_by_race_order_by_name($this->data['race']['race_id']);
foreach ( $this->data['list_of_volunteers_not_joined_with_volunteer_shifts'] as $key => $volunteer )
{
foreach ( $list_of_group_shifts as $key => $shift_id )
{
$shift_already_exists = sql_search_result_array_contains_key1_value1_key2_value2(
$this->data['list_of_volunteer_shifts_for_this_race'],
'volunteer_id',
$volunteer['volunteer_id'],
'shift_id',
$shift_id
);
if ( ! $shift_already_exists )
{
$this->volunteer_shift_model->add_shift(
$volunteer['volunteer_id'],
$shift_id,
$this->data['auth']['manager']['manager_id']
);
}
}
}
$this->group_shift_model->fix_more_enrolled_vols_than_estimated_vols($this->data['group']['group_id']);
}
if ( $this->input->post('email_group_leader') == 1 )
{
// return true for non-NULL, non-zero
if ( $this->data['group']['group_leader_volunteer_id'] )
{
$this->data['list_of_this_groups_shifts'] = $this->shift_model->get_group_shifts($this->data['group']['group_id']);
send_group_confirmation_email($this->data, $this->data['volunteer']['volunteer_email']);
add_message('success', 'Also, we e-mailed the group leader a group confirmation e-mail.');
}
else
{
add_message('error', 'You requested that we send a confirmation e-mail, but we were unable to because a volunteer group leader was not provided.');
}
}
}
$this->shift_model->recalculate_shift_stats($this->data['race']['race_id']);
redirect_and_die('/managers/group_report/' . $this->data['race']['race_uri']);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T20:06:06.743",
"Id": "470441",
"Score": "1",
"body": "in idea 3, you are making wrong assumption that you will have to scroll a lot. No, you will actually read it much easier. Put validation into own method, then you read the code And see: here Is validation taking place. Ok now you either think you are not interested in validation piece of code so you continue reading the very next line. Or you Are interested in validation, So you jump to that method and all you see now is validation which is all you care of."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T20:10:00.227",
"Id": "470443",
"Score": "0",
"body": "Ideas 1 and 2 are basically the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T02:18:31.907",
"Id": "470478",
"Score": "0",
"body": "@slepic All these years I didn't know about \"Go To Definition\" command in IDE. F12 in VS Code. That will make jumping around big classes much easier. Thank you for pointing it out."
}
] |
[
{
"body": "<p>There are a lot of possibilities laid out here, but I think I would lean towards:</p>\n\n<blockquote>\n <p>Idea 3 - Should I make more use of private methods within the giant controller class? Won't shrink the size of the controller, but might make some of the code more readable. Or maybe not, since I'd be scrolling all over the page to find code, instead of just reading it linearly.</p>\n</blockquote>\n\n<p>I would recommend taking this approach. Looking at the sample controller method I would separate chunks into separate methods, or consider making separate controllers that would have unique methods (part of Idea 2 I guess). Ask yourself what the chunks are doing - e.g.</p>\n\n<ul>\n<li>setting data</li>\n<li>setting form validation rules</li>\n<li>loading page with event nav and/or adding error/success message</li>\n</ul>\n\n<p>Having smaller, more atomic methods should allow for better unit testing. This is congruent with the <a href=\"https://deviq.com/single-responsibility-principle/\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. Like I mentioned in <a href=\"https://codereview.stackexchange.com/a/203576/120114\">my review of your chess code</a> it is wise to limit methods to 15-20\n lines. \nIn <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about limiting the indentation level to one per method and avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>). </p>\n\n<p>I'm not very familiar with CodeIgniter but see the documentation for CI4 contains a section <a href=\"https://codeigniter4.github.io/userguide/testing/feature.html\" rel=\"nofollow noreferrer\">HTTP Feature Testing</a>. I'd recommend reading through that page - hopefully something there will be useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T02:25:12.077",
"Id": "470482",
"Score": "1",
"body": "Thank you very much for your comment Sam. I actually remember this video from your PHP chess code review, and I used it and your other tips to refactor a lot of my PHP chess program. I gave the video another watch start to finish today and I refreshed myself on many of the concepts. That converting \"else\" into \"returns\" idea is excellent, as is keeping indentation down."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T02:27:01.800",
"Id": "470484",
"Score": "1",
"body": "I am still on CI3. Exciting to see CI4 (released in Feb 2020) has some testing features built in. Of course, the core problem with testing a website is how inter-connected everything on a website is. Most PHP controller methods on my website rely heavily on reading and writing the SQL database. And also the HTML needs testing, too. Unit testing is a no brainer with something like a ChessBoard class that doesn't touch a database, but is much harder for a website that is constantly touching the SQL database."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T21:55:33.603",
"Id": "239769",
"ParentId": "239558",
"Score": "2"
}
},
{
"body": "<p>Somebody on another website posted a good idea and I want to share it. They suggested that I make each webpage its own class. Then any private methods that support that webpage are grouped together in the same file, and other webpages and private methods get their own files and aren't cluttering things up.</p>\n\n<p>I could use folders to keep similar pages grouped together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T02:21:44.387",
"Id": "239845",
"ParentId": "239558",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "239769",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T13:45:17.327",
"Id": "239558",
"Score": "3",
"Tags": [
"php",
"mvc",
"codeigniter"
],
"Title": "PHP Edit Volunteer Group Form"
}
|
239558
|
<p>I wrote a program to insert a checksum into a Game Boy cartridge. Here is a <a href="https://gbdev.gg8.se/wiki/articles/The_Cartridge_Header" rel="noreferrer">spec of the cartridge header</a>, but I'll include the relevant information here, as well.</p>
<p>The header checksum is defined as the sum of the bitwise-NOT of the 52nd through the 76th bytes of the file, inclusive.</p>
<p>The global checksum is defined as the sum of all the bytes in the file except for the bytes of the global checksum itself.</p>
<p>This program requires placeholder zero bytes for these checksums. If the placeholder bytes are not zero, the program errors.</p>
<p>Here's the program:</p>
<pre><code>#include <errno.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
// Insert various checksums into a Game Boy cartridge file.
// Gives an error if the checksums are present prior to checksumming.
#define HEADER_DATA \
/* nop; jmp $150 */ \
"\x00\xc3\x50\x01" \
/* Nintendo logo */ \
"\xce\xed\x66\x66\xcc\x0d\x00\x0b\x03\x73\x00\x83\x00\x0c\x00\x0d" \
"\x00\x08\x11\x1f\x88\x89\x00\x0e\xdc\xcc\x6e\xe6\xdd\xdd\xd9\x99" \
"\xbb\xbb\x67\x63\x6e\x0e\xec\xcc\xdd\xdc\x99\x9f\xbb\xb9\x33\x3e"
enum cartridge_header_section_sizes
{
// oversimplification, but the extra data is not needed
ENTRY = 0x0,
MISC = ENTRY + 0x34,
HEADER_CHECKSUM = MISC + 0x19,
GLOBAL_CHECKSUM = HEADER_CHECKSUM + 0x01,
};
// checksum functions save and restore file position
static unsigned char header_checksum(FILE *const fp, size_t nbytes)
{
fpos_t pos;
unsigned char result;
if(fgetpos(fp, &pos) == -1)
return -1;
for( result = 0; nbytes--; )
{
int c = fgetc(fp);
if(c == -1)
return -1;
result += (unsigned char)~(unsigned char)c;
}
if(fsetpos(fp, &pos) == -1)
return -1;
return result;
}
static unsigned short global_checksum(FILE *const fp, size_t nbytes)
{
fpos_t pos;
unsigned short result;
if(fgetpos(fp, &pos) == -1)
return -1;
for( result = 0; nbytes--; )
{
int c = fgetc(fp);
if(c == -1)
return -1;
result += (unsigned char)c;
}
if(fsetpos(fp, &pos) == -1)
return -1;
return result;
}
int main(const int argc, const char *const *const argv)
{
if(argc != 2)
{
printf("Usage: %s gb-file\n", argv[0]);
goto fail;
}
FILE *const fp = fopen(argv[1], "r+b");
if(fp == NULL)
{
perror(argv[1]);
goto fail;
}
// -1 for the trailing null byte
unsigned char header[sizeof(HEADER_DATA) - 1];
if(fread(header, 1, sizeof(header), fp) != sizeof(header))
{
fputs("Short file: header read failed\n", stderr);
goto fail;
}
if(memcmp(header, HEADER_DATA, sizeof(header)) != 0)
{
fputs("Invalid header!\n"
"Make sure that your header contains nop; jp $150 "
"and the official Nintendo logo before running again.\n",
stderr);
goto fail;
}
errno = 0;
unsigned char hchk = header_checksum(fp, HEADER_CHECKSUM - MISC);
if(hchk == (unsigned char)-1 && errno)
{
perror("header checksum");
goto fail;
}
#ifndef NDEBUG
printf("%hx\n", hchk);
#endif
if(fseek(fp, HEADER_CHECKSUM, SEEK_SET) == -1)
{
perror("fseek");
goto fail;
}
// sanity checking
if(fgetc(fp))
{
fputs("Header checksum already in place!\n"
"Did you run the program twice?\n", stderr);
goto fail;
}
// rewind to previous position if successful
if(fseek(fp, -1, SEEK_CUR) == -1)
{
perror("fseek");
goto fail;
}
if(fwrite(&hchk, 1, sizeof(hchk), fp) != sizeof(hchk))
{
fputs("Insertion of header checksum failed.\n", stderr);
goto fail;
}
if(fseek(fp, 0, SEEK_END) == -1)
{
perror("fseek");
goto fail;
}
long size = ftell(fp);
if(size == -1)
{
perror("ftell");
goto fail;
}
if(fseek(fp, 0, SEEK_SET) == -1)
{
perror("fseek");
goto fail;
}
// eh, why not?
errno = 0;
unsigned short gchk = global_checksum(fp, (size_t)size);
if(gchk == (unsigned short)-1 && errno)
{
perror("global checksum");
goto fail;
}
#ifndef NDEBUG
printf("%hx\n", gchk);
#endif
unsigned char gchk_arr[2] = { gchk >> 8, gchk & 0xff };
if(fseek(fp, GLOBAL_CHECKSUM, SEEK_SET) == -1)
{
perror("fseek");
goto fail;
}
// more sanity checking
int c1 = fgetc(fp);
int c2 = fgetc(fp);
if(c1 || c2)
{
fputs("Global checksum already in place!\n"
"Did you run the program twice?\n", stderr);
goto fail;
}
if(fseek(fp, -2, SEEK_CUR) == -1)
{
perror("fseek");
goto fail;
}
if(fwrite(gchk_arr, 1, sizeof(gchk_arr), fp) != sizeof(gchk_arr))
{
perror("fwrite");
goto fail;
}
fflush(fp);
fclose(fp);
return EXIT_SUCCESS;
fail:
if(fp)
fclose(fp);
return EXIT_FAILURE;
}
</code></pre>
<p>What I'm looking for:</p>
<ul>
<li>Is there any way to simplify this? It seems that I read, seek, and re-read the file many times, and I repeat code a lot.</li>
<li>Are my variable, structure, and function names self-explanatory? Do the comments help improve the readability of the program?</li>
<li>Are there any edge-cases that I might've missed when testing this?</li>
<li>Any other general advice.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:09:58.617",
"Id": "469885",
"Score": "0",
"body": "Why C89? Is this being compiled for a specific platform that has a terrible compiler?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:14:25.197",
"Id": "469888",
"Score": "1",
"body": "Distant back-compatibility comes at a cost (not naming any names, but Intel). There's some syntactical sugar you're missing out on that helps with maintainability. If you have a specific application in mind that requires C89, fine; but it doesn't seem like that's the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:16:54.590",
"Id": "469889",
"Score": "0",
"body": "@Reinderien Yeah. I deleted my comment. I also began to think about why I am only using C89. I think it's because of Windows."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:19:30.830",
"Id": "469890",
"Score": "1",
"body": "@Reinderien C99 now. Sweet syntatic sugar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T23:34:00.523",
"Id": "469953",
"Score": "0",
"body": "S.S. Anne, \"only using C89. I think it's because of Windows\" --> Widows does not restrict C to C89. I am running C11 on a Windows machine. The restriction you may see comes from Visual Studio, not the OS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T23:41:52.453",
"Id": "469954",
"Score": "0",
"body": "@chux Yes, I was mainly concerned about VS."
}
] |
[
{
"body": "<h2>Error printing</h2>\n\n<p>You do the right thing in some cases:</p>\n\n<pre><code>if(fseek(fp, -2, SEEK_CUR) == -1)\n perror(\"fseek\");\n</code></pre>\n\n<p>but not others:</p>\n\n<pre><code>if(fgetpos(fp, &pos) == -1)\n return -1;\n</code></pre>\n\n<p>Also, that particular check does not adhere to the <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/fgetpos.html\" rel=\"nofollow noreferrer\">specification</a>, which says:</p>\n\n<blockquote>\n <p>Upon successful completion, fgetpos() shall return 0; otherwise, it shall return a non-zero value and set errno to indicate the error.</p>\n</blockquote>\n\n<h2>C89/C99</h2>\n\n<p>We've been over this a little bit in the comments, but unless there is a specific target you have in mind that requires C89, it's best to go with something more modern. I generally use C18 but C99 is also a safe bet.</p>\n\n<p>Among other things, this will buy you the ability to declare and initialize variables much closer to where you actually use them in the code, something that I find helps with legibility and maintainability.</p>\n\n<h2>Enum offsets</h2>\n\n<p>This isn't a critique, but a compliment: I had forgotten (or maybe never knew?) that enum values can be computed against each other, like</p>\n\n<pre><code>MISC = ENTRY + 0x34,\n</code></pre>\n\n<p>That's really cool. Keep doing that.</p>\n\n<h2>Double-cast</h2>\n\n<pre><code>(unsigned char)~(unsigned char)c;\n</code></pre>\n\n<p>The rightmost cast is not necessary. Whereas inversion does change the type of a term to <code>int</code> (TIL), it is safe to do the inversion on the character directly, and then cast it after.</p>\n\n<h2>Gotos</h2>\n\n<p>Sometimes I find that there's actually a valid application of <code>goto</code>; I have a few toes outside of the never-<code>goto</code> camp. But I don't think that's the case here. Your use of <code>goto</code> can be easily avoided by factoring out a function that does early-<code>return</code> on failure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:27:28.393",
"Id": "469893",
"Score": "0",
"body": "Darn `man`-page says *\"Upon successful completion, fgetpos(), fseek(), fsetpos() return 0, and ftell() returns the current offset. Otherwise, -1 is returned and errno is set to indicate the error.\"*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:28:51.677",
"Id": "469895",
"Score": "1",
"body": "Interesting - it could be that the man page is about a more specific implementation (GNU C?), in which case, believe the man page over the spec."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:29:51.513",
"Id": "469898",
"Score": "3",
"body": "`!= 0` still works so I'll go with that. I've found that the man-pages don't always match the spec."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:40:01.803",
"Id": "469903",
"Score": "0",
"body": "The double cast is necessary: https://tio.run/##jVFLDoIwEN33FBNc2CbqAUTdegkTQtoKjTgltPiJ0atjESFUILGLTt5vMp3yZcJ5Vc0U8qwUEjbGCqVX6Y6QmZBHhRLsPZeRsQW9MTiQaC9RFopTBxcOgzs8jYs1BHUJWq5EoxKUohU93LlMqgvr1E8dZlvZJzqfwlp09zDZSH3YeTKNidPqMsx9RQ97yX4cpnuMNvL9br1xmTVjnlBfMWCEuEHhHCukF60EI4/2ncBhC/N4HpIPk5fW0O5jOGPhCE29nbMJ1@s/249rNPWsqjc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:48:56.480",
"Id": "469906",
"Score": "0",
"body": "Isn't bitwise-NOT on a signed type implementation-defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:48:57.027",
"Id": "469907",
"Score": "0",
"body": "Yeah, so I got that wrong. The double cast is _not_ necessary, but the single cast needs to be done on the _right_. Edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:53:32.990",
"Id": "469908",
"Score": "0",
"body": "The left cast might still not be necessary, though, due to implicit conversion to `unsigned char`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:56:28.057",
"Id": "469910",
"Score": "0",
"body": "I meant left. And yes, implicit conversion is possible. As to implementation-defined: https://stackoverflow.com/a/11644797/313768 seems to explain it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:06:41.843",
"Id": "469914",
"Score": "0",
"body": "I think I'll just use the alternative `result = result - c - 1;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:08:54.943",
"Id": "469917",
"Score": "0",
"body": "The problem is that signed representation is itself implementation-specific. The moment you go from \"a signed integer\" to \"a bit representation upon which XOR can operate\", an implicit conversion happens, and that conversion may use one of several different signed formats."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:10:19.397",
"Id": "469919",
"Score": "0",
"body": "But it's guaranteed that the result of `fgetc` can be represented if it is cast back to `unsigned char` (and I already check for `-1`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T00:37:25.423",
"Id": "469957",
"Score": "1",
"body": "A thought on C89 reviews: Not only has C been updated 20+ years ago, the what is proper for C89 gets fuzzier each year as the few compilers still adhering to that have added _some_ of C99, etc. Also those who truly know C89 are fewer and have more cobwebs to sift to that - ahem romantic - era."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:25:21.023",
"Id": "239564",
"ParentId": "239560",
"Score": "6"
}
},
{
"body": "<p><strong>Wrong compare</strong></p>\n\n<p><code>fgetc()</code> returns an <code>int</code> with the value of <code>EOF</code> or something in the <code>unsigned char</code> range. Although <code>EOF</code> is commonly -1, it is not specified as so.</p>\n\n<pre><code> int c = fgetc(fp);\n // if(c == -1)\n if(c == EOF)\n</code></pre>\n\n<p><strong>Useless cast</strong></p>\n\n<p>The 2nd cast is not needed as <code>c</code> is in the <code>unsigned char</code> range so there is no value change. Before the <code>~</code> is applied, the <code>(unsigned char)c</code> is converted to <code>int</code>. No value nor type change --> cast not needed.</p>\n\n<pre><code>// result += (unsigned char)~(unsigned char)c;\nresult += (unsigned char)~c;\n</code></pre>\n\n<p>The first cast not needed either <em>there</em>. <code>result += (unsigned char)~c;</code> is same as <code>result = result + (unsigned char)~c;</code>. Both <code>result</code> and <code>(unsigned char)~c</code> are promoted to <code>int</code> before the addition. The cast in <code>(unsigned char)~c</code> does not affect the end result.</p>\n\n<p>A cast is useful just before the assignment to quiet <code>int</code> to <code>unsigned char</code> warnings. Suggest the following:</p>\n\n<pre><code>// result += (unsigned char)~c;\nresult = (unsigned char) (result + ~c);\n</code></pre>\n\n<p><strong>Clarity</strong></p>\n\n<p>Alternative that, IMO, is more clear.</p>\n\n<pre><code>// hchk == (unsigned char)-1\nhchk == UCHAR_MAX\n</code></pre>\n\n<p><strong>Strange format specifier choice</strong></p>\n\n<p>Unclear why code uses <code>\"%hx\"</code>. Usually that is for <code>unsigned short</code>.</p>\n\n<pre><code> unsigned char hchk;\n ...\n// printf(\"%hx\\n\", hchk);\nprintf(\"%hhx\\n\", hchk);\n// or\nprintf(\"%x\\n\", hchk); // the hh is not truly needed, but it does add some clarity\n</code></pre>\n\n<p><strong>Wrong error test</strong></p>\n\n<p>\"on failure, the fgetpos function returns nonzero\"</p>\n\n<pre><code>// if(fgetpos(fp, &pos) == -1)\nif(fgetpos(fp, &pos))\n</code></pre>\n\n<p>Note: good use of <code>fsetpos(), fgetpos()</code>, versus <code>fseek(), ftell()</code>. Unclear why code uses <code>fseek()</code> elsewhere.</p>\n\n<p><strong>Performance</strong></p>\n\n<p><code>header_checksum()</code> calls <code>fgetc()</code> to perform a checksum. There is non-trivial overhead per call. Consider re-write with a block of memory, say 256 or 4096, and <code>fread()</code>.</p>\n\n<p>The back and forth of reading <em>Global checksum</em> looks easy to do in one pass.</p>\n\n<p><strong><code>main()</code> has too many details</strong></p>\n\n<p>I'd recommend making more helper functions.</p>\n\n<p><strong>Minor</strong></p>\n\n<p><code>(size_t)size</code> relies on <code>SIZE_MAX >= LONG_MAX</code>. Common, but not certain. File sizes are not limited to <code>SIZE_MAX</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T01:11:51.253",
"Id": "469960",
"Score": "0",
"body": "If I tried to print a `size_t` constant such as `SIZE_MAX` using `%zu`, would I have to cast it to `size_t`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T04:05:28.997",
"Id": "469966",
"Score": "0",
"body": "@S.S.Anne `z` was introduced in C99. Whenever printing some unsigned value lacking a matching print specifiers, a simple solution is to cast to widest type. In C89 that is `unsigned long` or `printf(\"%lu\\n\", (unsigned long) nbytes);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T14:43:11.370",
"Id": "469987",
"Score": "0",
"body": "I've given up on C89 since I have no reason whatsoever for using it. I was thinking about checking the size of the file against `SIZE_MAX` to see if it's safe to cast before doing so, and I wanted to print an error with the value of `SIZE_MAX` if it's too big. However, I think it might be possible that the constant might not have the same type as `size_t`, so I wanted to be sure that I'm using the correct type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T15:18:19.557",
"Id": "469990",
"Score": "0",
"body": "In terms of a _Game Boy cartridge_, I doubt any practical concerns about file size. In general, a test of `(unsigned long) nbytes > SIZE_MAX` is prudent. The cast is to quiet a potential warning about signed/unsigned compare without changing values. Further, a subtle issue occurs when the file is larger than `LONG_MAX`. To handle that, code needs to find the file length in another way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T13:12:33.913",
"Id": "470220",
"Score": "0",
"body": "`result + ~c` This is fishy code, please note that `c` is `int` and the `~` almost certainly turns it into a negative number. Doing arithmetic on that is risky, in theory it would become something like `0 + INT_MIN` when `c` is zero."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T14:43:27.677",
"Id": "470223",
"Score": "0",
"body": "@Lundin Disagree with your concern, yet on review, the entire checksum can simplify to `for( result = 0; nbytes--; ) { int c = fgetc(fp); ... result += c; } ... return ~result;`. The `~` only needed at the end."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T00:18:17.100",
"Id": "239593",
"ParentId": "239560",
"Score": "4"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Fix the bug</h2>\n\n<p>The program starts reading the header as though the file pointer were already pointing to location 0x100. That's an error because in all of the Gameboy files I've ever seen, the first 0x100 bytes are present and needed for calculating the checksum.</p>\n\n<h2>Use a <code>struct</code> where appropriate</h2>\n\n<p>This code could be made much simpler just by using a <code>struct</code> to represent the header. I'd use this:</p>\n\n<pre><code>struct CartridgeHeader {\n uint8_t filler[0x100];\n uint8_t entry[4];\n uint8_t logo[0x30];\n uint8_t title[0x10];\n uint8_t licensee[2];\n uint8_t SGB;\n uint8_t cart_type;\n uint8_t ROM_size;\n uint8_t RAM_size;\n uint8_t dest_code;\n uint8_t old_licensee_code;\n uint8_t mask_ROM_version;\n uint8_t header_checksum;\n uint8_t checksum_hi;\n uint8_t checksum_lo;\n};\n</code></pre>\n\n<p>We can ignore most of these for the purposes of this program, but it only takes a minute to create the whole thing and parts of it might be useful for other purposes.</p>\n\n<p>As noted in some of the comments, this assumes that the structure is not padded and that is not guaranteed by the standard. Many compilers include something like <a href=\"https://www.google.com/search?client=firefox-b-1-d&q=pragma+packed\" rel=\"nofollow noreferrer\"><code>#pragma pack</code></a>. If yours does, use it. Also, if your compiler supports C11, add this line to assure (at compile time) that the <code>struct</code> is what it needs to be:</p>\n\n<pre><code>static_assert(sizeof(struct CartridgeHeader) == 0x150, \n \"Code relies on struct having no padding\");\n</code></pre>\n\n<h2>Be efficient in file I/O</h2>\n\n<p>Instead of jumping around back and forth in the file, I'd suggest that a much cleaner approach would be to simply read the file once and then make a single write to update the file if needed.</p>\n\n<h2>Understand the header specification</h2>\n\n<p>The header specification says that the offset <em>usually</em> contains \"NOP; JP 0150h\" but not always. For that reason, it's not technically correct to check for those specific instructions there. The only thing the Gameboy checks for is the logo portion.</p>\n\n<h2>Avoid <code>goto fail</code></h2>\n\n<p>While it may seem appealing, the <code>goto fail</code> as a technique is hazardous especially, as in this program, if you don't always use <code>{}</code> with <code>if</code> and <code>for</code>. It's difficult to make sure it is done correctly and easy to make a catastrophic error that makes international news as with <a href=\"https://www.synopsys.com/blogs/software-security/understanding-apple-goto-fail-vulnerability-2/\" rel=\"nofollow noreferrer\">Apple's infamous <code>goto fail</code> error</a>. That's not something you want to be known for!</p>\n\n<h2>Avoid <code>#define</code> if you can</h2>\n\n<p>The problem with using a <code>#define</code> for data is that there is no type and therefore no type checking. Instead, you can better accomplish what you need with something like this:</p>\n\n<pre><code>static const uint8_t logo[] = {\n/* Nintendo logo */ \\\n 0xce,0xed,0x66,0x66,0xcc,0x0d,0x00,0x0b,0x03,0x73,0x00,0x83,0x00,0x0c,0x00,0x0d, \n 0x00,0x08,0x11,0x1f,0x88,0x89,0x00,0x0e,0xdc,0xcc,0x6e,0xe6,0xdd,0xdd,0xd9,0x99,\n 0xbb,0xbb,0x67,0x63,0x6e,0x0e,0xec,0xcc,0xdd,0xdc,0x99,0x9f,0xbb,0xb9,0x33,0x3e\n};\n</code></pre>\n\n<h2>Separate I/O from calculations where practical</h2>\n\n<p>If, as suggested above, we already have a <code>struct</code>, it would make sense to do the calculations on it in memory rather than as the values are being read. Here's one way to implement such a function:</p>\n\n<pre><code>static uint8_t cart_header_checksum(const struct CartridgeHeader *ch) {\n uint8_t sum = 0;\n for (uint8_t *ptr = (uint8_t *)&ch->title; ptr != &ch->header_checksum; ++ptr) {\n sum += ~*ptr;\n }\n return sum;\n}\n</code></pre>\n\n<h2>Think about more informative error return values</h2>\n\n<p>Most modern operating systems employ the use of an error value that can be returned from <code>main</code>. I'd suggest that instead of just pass/fail it might be useful if the program returned an error code suggesting what the problem was. It might look like this as an <code>enum</code>:</p>\n\n<pre><code>enum error_code { ERROR_NONE, ERROR_READ, ERROR_LOGO, ERROR_WRITE };\n</code></pre>\n\n<h2>Think of the user</h2>\n\n<p>Rather than exiting the program with an error, I think it would be more useful to a user if the program simply told me that the checksums were correct already (if they are). If they're not, one might also want to know what values were originally and what the corrected values are. There's no need for the values to be required to be zero.</p>\n\n<h2>Putting it all together</h2>\n\n<p>Here's an alternative version that uses all of these ideas:</p>\n\n<pre><code>#include <assert.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdbool.h>\n\nstruct CartridgeHeader {\n uint8_t filler[0x100];\n uint8_t entry[4];\n uint8_t logo[0x30];\n uint8_t title[0x10];\n uint8_t licensee[2];\n uint8_t SGB;\n uint8_t cart_type;\n uint8_t ROM_size;\n uint8_t RAM_size;\n uint8_t dest_code;\n uint8_t old_licensee_code;\n uint8_t mask_ROM_version;\n uint8_t header_checksum;\n uint8_t checksum_hi;\n uint8_t checksum_lo;\n};\n\nstatic_assert(sizeof(struct CartridgeHeader) == 0x150, \"Code relies on struct having no padding\");\n\n\nstatic uint8_t cart_header_checksum(const struct CartridgeHeader *ch) {\n uint8_t sum = 0;\n for (uint8_t *ptr = (uint8_t *)&ch->title; ptr != &ch->header_checksum; ++ptr) {\n sum += ~*ptr;\n }\n return sum;\n}\n\nstatic bool cart_check_logo(const struct CartridgeHeader *ch) {\n static const uint8_t logo[] = {\n /* Nintendo logo */ \\\n 0xce,0xed,0x66,0x66,0xcc,0x0d,0x00,0x0b,0x03,0x73,0x00,0x83,0x00,0x0c,0x00,0x0d, \n 0x00,0x08,0x11,0x1f,0x88,0x89,0x00,0x0e,0xdc,0xcc,0x6e,0xe6,0xdd,0xdd,0xd9,0x99,\n 0xbb,0xbb,0x67,0x63,0x6e,0x0e,0xec,0xcc,0xdd,0xdc,0x99,0x9f,0xbb,0xb9,0x33,0x3e\n };\n return memcmp(&ch->logo, logo, sizeof(logo)) == 0;\n}\n\nenum error_code { ERROR_NONE, ERROR_READ, ERROR_LOGO, ERROR_WRITE };\n\nint main(const int argc, const char *const *const argv)\n{\n if(argc != 2)\n {\n printf(\"Usage: %s gb-file\\n\", argv[0]);\n return ERROR_READ;\n }\n\n FILE *const fp = fopen(argv[1], \"r+b\");\n if(fp == NULL)\n {\n perror(argv[1]);\n return ERROR_READ;\n }\n\n struct CartridgeHeader header;\n if (fread(&header, 1, sizeof(header), fp) != sizeof(header)) {\n puts(\"Short file: header read failed\");\n fclose(fp);\n return ERROR_READ;\n }\n if (!cart_check_logo(&header)) {\n puts(\"Logo verification failed; is this a valid file?\");\n fclose(fp);\n return ERROR_LOGO;\n }\n\n // calculate header checksum\n uint8_t mysum = cart_header_checksum(&header);\n\n // calculate global checksum\n uint16_t global_sum = mysum;\n // first over part we alredy read\n for (uint8_t *ptr = (uint8_t *)&header; ptr != &header.header_checksum; ++ptr) {\n global_sum += *ptr;\n }\n // then continue with rest of file\n for (int ch = fgetc(fp); ch != EOF; ch = fgetc(fp)) {\n global_sum += ch;\n }\n\n if (mysum == header.header_checksum && global_sum == header.checksum_hi * 256 + header.checksum_lo) {\n puts(\"Cartridge already has valid checksums: nothing to do\");\n } else {\n printf(\"calculated header checksum = %2.2x\\n\", mysum);\n printf(\"file header checksum = %2.2x\\n\", header.header_checksum);\n printf(\"calculated global sum = %4.4x\\n\", global_sum);\n printf(\"file global sum = %2.2x%2.2x\\n\", header.checksum_hi, header.checksum_lo);\n puts(\"Updating checksums\");\n header.header_checksum = mysum;\n header.checksum_hi = global_sum >> 8;\n header.checksum_lo = global_sum && 0xff;\n if (fseek(fp, 0L, SEEK_SET) || fwrite(&header, 1, sizeof(header), fp) != sizeof(header)) {\n perror(\"Unable to write to file\");\n return ERROR_WRITE;\n }\n }\n fclose(fp);\n return ERROR_NONE;\n}\n</code></pre>\n\n<h2>A few more notes</h2>\n\n<p>The code above reads most of the file using <code>fgetc</code> character at a time. While this may seem slow, modern operating systems typically use buffering and so this is not as slow as it might first seem. Another note is the code above does not attempt to distinguish between <code>EOF</code> and an actual file read error. This might happen, if, for example, the file is on removeable media and gets ejected during the process. This would lead to a failure of the <code>fseek</code> which is the next operation and so while the error message might be a bit misleading, it seemed to me not worth the bother to do anything differently. Such error checking could be added with a call to <code>ferror</code> if desired.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T17:10:57.937",
"Id": "470139",
"Score": "0",
"body": "*\"The program starts reading the header as though the file pointer were already pointing to location 0x100. That's an error because in all of the Gameboy files I've ever seen, the first 0x100 bytes are present and needed for calculating the checksum.\"* Yes, they are. I've fixed that by now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T17:18:44.350",
"Id": "470141",
"Score": "0",
"body": "That `struct` would be hard to read to if structure elements are not stored sequentially in memory (which they're not guaranteed to be)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T17:24:08.703",
"Id": "470143",
"Score": "0",
"body": "It's true that it's not guaranteed by the C standard that items are stored sequentially in memory. While many compilers support something like [`#pragma pack`](https://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/Structure_002dPacking-Pragmas.html) it's not portable by definition. One could also write a custom reader or simply declare it as an 0x150 byte array of `uint8_t` (and use custom access methods) for guaranteed portability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T17:27:44.600",
"Id": "470145",
"Score": "0",
"body": "In the time since I posted the question I changed the program so it reads the whole file in and only writes the three checksum bytes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T17:29:20.497",
"Id": "470146",
"Score": "1",
"body": "Yes, that's another perfectly valid way to do it. Using that method, one could even calculate both the header checksum and the global checksum in the same pass."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T13:36:56.547",
"Id": "470221",
"Score": "0",
"body": "\"Use a struct where appropriate\" This is not an obvious case for struct at all, it may introduce padding and will certainly make the code non-portable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T13:43:20.203",
"Id": "470222",
"Score": "0",
"body": "I've added a `static_assert` (which was introduced with C11) to address that concern."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T16:43:49.643",
"Id": "239673",
"ParentId": "239560",
"Score": "4"
}
},
{
"body": "<p>In addition to remarks by previous reviews:</p>\n\n<ul>\n<li><p>This is wrong:</p>\n\n<pre><code>int main(const int argc, const char *const *const argv)\n</code></pre>\n\n<p>The form of main() is for the <em>compiler</em> to decide, not the programmer. This form is not at all compatible with standard C <code>int main(int argc, char *argv[])</code>. So unless your compiler docs specifically tell you that your custom form of main() is ok, you are invoking undefined behavior.</p></li>\n<li><p>Regarding the <code>#define HEADER_DATA</code>, you have a subtle but severe bug, namely that each line introduces a null terminator <code>\\x00</code> since the data is string literals. This may screw up all CRC calculations and <code>memcmp</code> calls, if you don't take it in account. Wiser to roll with <code>static const uint8_t</code> as advised in another review.</p>\n\n<p>If you can compile as standard C, use lots of <code>_Static_assert</code>. For example your enum could end with a dummy entry <code>END</code> and that one should be the same as the size of the data, or otherwise your constants are corrupt somewhere.</p></li>\n<li><p><code>for( result = 0; nbytes--; )</code> should be <code>for(result = 0; nbytes>0; nbytes--)</code> or you will get very strange results when passing <code>nbytes == 0</code> to the function.</p></li>\n<li><p>The <code>result += (unsigned char)~(unsigned char)c;</code> is code smell and the other reviews didn't get this quite right. This is what actually happens:</p>\n\n<ul>\n<li><code>(unsigned char)c</code> you explicitly convert from <code>int</code> to <code>unsigned char</code>.</li>\n<li><code>~</code> the compiler spots this operator and immediately and silently integer promotes back to <code>int</code>.</li>\n<li>The result of <code>~</code> is of type <code>int</code> and very likely a negative number.</li>\n<li>Casting to <code>unsigned char</code> again means that you parse out one byte from this negative number in an implementation-defined way. In practice, this will probably work just fine on most systems.</li>\n<li><code>result += op</code> is equivalent to <code>result = result + op</code> except <code>result</code> is only evaluated once (which doesn't matter here). Since both operands of <code>+</code> are small integer types, the result of <code>+</code> is <code>int</code>, but it can't be negative. You then lvalue convert this temporary <code>int</code> back into <code>unsigned char</code> upon assignment.</li>\n</ul>\n\n<p>Summary: way too much implicit crap going on here! C is dangerously subtle, particularly when it comes to the <code>~ << >></code> operators. There is no bug here, but this code is brittle. For rugged code with a minimum of implicit conversions, I would change this to: </p>\n\n<p><code>result += ~(unsigned int)c;</code> or if you prefer <code>result += ~(uint32_t)c;</code>.</p>\n\n<p>This contains 2 silent promotions, <code>result</code> up to <code>unsigned int</code> and then the result of that back to <code>unsigned char</code>. All operands remain unsigned types, so it is harmless. More importantly, this should be fail-safe on traditional simple 8 bit checksums that rely on 8 bit unsigned wrap-around.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T15:46:41.340",
"Id": "470227",
"Score": "0",
"body": "Each line does *not* introduce a null character. Only the last one does, since they are concatenated. This is handled where noted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T15:50:08.453",
"Id": "470228",
"Score": "0",
"body": "`for( result = 0; nbytes--; )` will handle `nbytes == 0`. It's a post-increment, so it breaks from the loop without doing anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T15:57:55.033",
"Id": "470229",
"Score": "0",
"body": "I would change it to `result = result - c - 1;`, which I've already done."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T13:35:20.707",
"Id": "239698",
"ParentId": "239560",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "239593",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T14:54:02.343",
"Id": "239560",
"Score": "8",
"Tags": [
"c",
"checksum",
"c99"
],
"Title": "Checksum a Game Boy cartridge"
}
|
239560
|
<p>I am trying to work through this challenge, I have come up with a solution but however I look at the problem statement and the examples provided I cant help but come to the conclusion that the "example 3" and "test case 2" as explained in the problem statement are wrong.</p>
<p>I would appreciate it if someone could review my solution and the problem statement and provide any feedback.</p>
<blockquote>
<p><strong>problem statement:</strong></p>
<p>You are working on developing a movie with Amazon Video that consists
of a series of shots: short pieces of video from a particular camera
angle. You want to devise an application to easily group identical
shots in a video into scenes (a sequence of shots). Shots are
identical when they are labeled with the same letter, and everything
in between identical shots is considered part of same scene. There is
already an algorithm that breaks the video up into shots and labels
them.</p>
<p>Write a function which will partition a sequence of shot labels into
minimal subsequences so that a shot label only appears in a single
subsequence. The output should be the length of each subsequence.</p>
<p>Input The input to the function/method consists of an argument -
inputList, a list of characters representing the sequence of shots.</p>
<p>Output Return a list of integers representing the length of each
scene, in the order in which it appears in the given sequence of
shots.</p>
<p><code>Examples Example 1: Input inputList = [a, b, c]</code></p>
<p><code>Output [1, 1, 1]</code></p>
<p>Explanation: Because there are no recurring shots, all shots can be in
the minimal length 1 subsequence.</p>
<p><code>Example 2: Input inputList = [a, b, c, a]</code></p>
<p><code>Output [4]</code></p>
<p>Explanation: Because ‘a’ appears more than once, everything between
the first and last appearance of ‘a’ must be in the same list.</p>
<p><code>Example 3: Input: inputList = [a, b, a, b, c, b, a, c, a, d, e, f, e,
g, d, e, h, i, j, h, k, l, i, j]</code></p>
<p><code>Output: [9, 7, 8]</code></p>
<p><code>Testcase 1: Input: [a, b, c, d, a, e, f, g, h, i, j, e]</code></p>
<p><code>Expected Return Value: 5 7</code></p>
<p><code>Testcase 2: Input: [z, z, c, b, z, c, h, f, i, h, i]</code></p>
<p><code>Expected Return Value: 6 5</code></p>
</blockquote>
<p>my solution and test cases:</p>
<pre><code>using System.Collections.Generic;
using Xunit;
namespace LengthEachSceneChallenge
{
public class Task
{
public List<int> lengthEachScene(List<char> inputList)
{
var counts = new List<int>();
for (int i = 0; i < inputList.Count; i++)
{
var item = inputList[i];
var lastIndex = inputList.LastIndexOf(item);
if (i == lastIndex)
{
counts.Add(1);
}
else
{
counts.Add(i == 0 ? lastIndex + 1 : lastIndex - i + 1);
i = lastIndex;
}
}
return counts;
}
[Fact]
public void Example1()
{
var data = new List<char>() { 'a', 'b', 'c' };
Assert.Equal(new List<int>() { 1, 1, 1 }, lengthEachScene(data));
}
[Fact]
public void Example2()
{
var data = new List<char>() { 'a', 'b', 'c', 'a' };
Assert.Equal(new List<int>() { 4 }, lengthEachScene(data));
}
[Fact]
public void Example3()
{
var data = new List<char>() { 'a', 'b', 'a', 'b', 'c', 'b', 'a', 'c', 'a', 'd', 'e', 'f', 'e', 'g', 'd', 'e', 'h', 'i', 'j', 'h', 'k', 'l', 'i', 'j' };
Assert.Equal(new List<int>() { 9, 7, 8 }, lengthEachScene(data));
}
[Fact]
public void TestCase1()
{
var data = new List<char>() { 'a', 'b', 'c', 'd', 'a', 'e', 'f', 'g', 'h', 'i', 'j', 'e' };
Assert.Equal(new List<int>() { 5, 7 }, lengthEachScene(data));
}
[Fact]
public void TestCase2()
{
var data = new List<char>() { 'z', 'z', 'c', 'b', 'z', 'c', 'h', 'f', 'i', 'h', 'i' };
Assert.Equal(new List<int>() { 6, 5 }, lengthEachScene(data));
}
}
</code></pre>
<p>}</p>
<p>count Length of each sequence of chars according to start and end characters</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-07T12:12:59.283",
"Id": "470935",
"Score": "0",
"body": "At first I thought I agreed that the test cases were wrong. Then I realized that in Example #3, the 7 comes from this sub-sequence: `d, e, f, e, g, d, e`. In Test Case #2, the 6 comes form this sub-sequence: `z, z, c, b, z, c,`"
}
] |
[
{
"body": "<p>I agree that the question takes a little time to understand. Once I understood it, I felt compelled to code a solution, which is below.</p>\n\n<p>The solution you built gets the length between each letter, but the question is more nuanced. The formal logic is in the code, but in plain English: A scene only ends when all of the shots it contains are done.</p>\n\n<p>On a related note, I would consider your solution to be a \"procedural\" approach to solving the problem. </p>\n\n<p>As an object-oriented language, C# lends itself to the \"object-oriented\" approach, which to me means modeling the domain with classes. In this case, a <code>Movie</code> class and a <code>Scene</code> class. I initially thought there would be a <code>Shot</code> class, but in this example shots are reduced to character labels, so it was unnecessary. </p>\n\n<p>Of course a real solution would definitely contain a <code>Shot</code> class, perhaps with additional properties like <code>Camera</code>, <code>Lighting</code>, and <code>Description</code>.</p>\n\n<p>Here is the output:<br>\n<a href=\"https://i.stack.imgur.com/xKRrg.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xKRrg.jpg\" alt=\"output\"></a></p>\n\n<p>Here is the sample code:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class App_MovieScenes\n{\n public void Run()\n {\n var shotList = new char[] { 'a', 'b', 'a', 'b', 'c', 'b', 'a', 'c', 'a', 'd', 'e', 'f', 'e', 'g', 'd', 'e', 'h', 'i', 'j', 'h', 'k', 'l', 'i', 'j' };\n var movie = new Movie(shotList);\n movie.ToScenes();\n movie.Output();\n } \n}\n\npublic class Movie\n{\n private char[] shotList;\n\n public List<Scene> Scenes { get; private set; }\n\n public Movie(char[] shotList) => this.shotList = shotList ?? new char[1];\n\n public void ToScenes()\n {\n var all = new string(shotList);\n var groups = new List<List<char>>();\n var group = new List<char>();\n var index = 0;\n\n all.ToList().ForEach(c =>\n {\n var remaining = all.Substring(index++);\n var groupIsEmpty = !group.Any();\n var anyInGroupHasMore = group.Any(g => remaining.Contains(g));\n\n if (groupIsEmpty || !anyInGroupHasMore)\n {\n ///start a new group\n group = new List<char>();\n group.Add(c);\n groups.Add(group);\n }\n else\n {\n ///add to current group\n group.Add(c);\n }\n });\n\n Scenes = groups.Select(g => new Scene(g)).ToList();\n }\n\n public void Output() => Console.WriteLine(ToString());\n\n public override string ToString() => string.Join(\"\\n\", Scenes.Select(s => s.ToShotList()));\n}\n\npublic class Scene\n{\n public List<char> Shots { get; private set; }\n public int Length => Shots.Count;\n\n public Scene(List<char> shots) => Shots = shots;\n\n public string ToShotList() => $\"{Length}\\t{string.Join(\", \", Shots)}\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-07T13:50:14.657",
"Id": "240099",
"ParentId": "239561",
"Score": "2"
}
},
{
"body": "<p>This should work... Just tried upon your code @Xerxes...\nExplanation : Thing which was missing in ur code was handling the cross sequence like ' a b a b d '... Here abab is single shot but urs consider it 2 independent shots.... </p>\n\n<pre><code>public List<Integer> lengthEachScene(List<Character> inputList)\n {\n List<Integer> counts = new ArrayList<>();\n for (int i = 0; i < inputList.size(); i++)\n {\n Character item = inputList.get(i);\n Integer lastIndex = inputList.lastIndexOf(item);\n\n if (i == lastIndex)\n {\n counts.add(1);\n }\n else if (inputList.size() == lastIndex - 1 )\n {\n counts.add(1);\n break;\n }\n\n else\n {\n int temp = i;\n i++;\n while (i < lastIndex){\n Character character = inputList.get(i);\n if(character == item){\n i++;\n continue;\n }\n if(inputList.lastIndexOf(character)> lastIndex){\n lastIndex = inputList.lastIndexOf(character);\n }\n i++;\n }\n counts.add(lastIndex - temp + 1);\n i = lastIndex + 1;\n }\n }\n return counts;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T14:13:07.627",
"Id": "476724",
"Score": "1",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T13:18:04.563",
"Id": "242897",
"ParentId": "239561",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "240099",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T15:39:29.830",
"Id": "239561",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Group chars in an array if they have the same start and end elements"
}
|
239561
|
<p>I use the following code to add tree item to vscode extension, Im getting the data and build the tree according to the entries I got, the code works.
As I new to typescript I appreciate your feedback's, if the code looks good let me know either :) thanks</p>
<pre><code>
export class TaskTreeDataProvider implements vscode.TreeDataProvider<TreeItem> {
private _onDidChangeTreeData: vscode.EventEmitter<TreeItem | null> = new vscode.EventEmitter<TreeItem | null>();
readonly onDidChangeTreeData: vscode.Event<TreeItem | null> = this
._onDidChangeTreeData.event;
private eeake: Promise<TreeItem[]> | undefined = undefined;
private autoRefresh: boolean = true;
constructor(private context: vscode.ExtensionContext) {
this.autoRefresh = vscode.workspace
.getConfiguration(“sView")
.get("autorefresh");
let filePath = this.fileName;
let fileWatcher = vscode.workspace.createFileSystemWatcher(filePath);
fileWatcher.onDidChange(() => (this.eeake = this.getChildren()), this.refresh());
}
refresh(): void {
this._onDidChangeTreeData.fire();
}
public async getChildren(task?: TreeItem): Promise<TreeItem[]> {
let tasks = await vscode.tasks
.fetchTasks({ type: “run” })
.then(function (value) {
return value;
});
let entry: TreeItem[] = [];
if (tasks.length !== 0) {
for (var i = 0; i < tasks.length; i++) {
entry[i] = new TreeItem(
tasks[i].definition.type,
tasks[i].name,
{
command: “sView.executeTask",
title: "Execute",
arguments: [tasks[i]]
}
);
}
}
return entry;
}
getTreeItem(task: TreeItem): vscode.TreeItem {
return task;
}
}
class TreeItem extends vscode.TreeItem {
type: string;
constructor(
type: string,
label: string,
collapsibleState: vscode.TreeItemCollapsibleState,
command?: vscode.Command
) {
super(label, collapsibleState);
this.type = type;
this.command = command;
this.iconPath = getIcon();
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-13T07:34:21.490",
"Id": "471599",
"Score": "0",
"body": "Why use `let` when you are not changing the variable. Every linter will tell you that."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T15:44:11.750",
"Id": "239562",
"Score": "1",
"Tags": [
"javascript",
"asynchronous",
"typescript",
"async-await"
],
"Title": "create vscode tree item extesion"
}
|
239562
|
<p>I am relatively new so any help would in improving this and future codes. The code involves basic file management for two different files, one for buses and another for the employees and I am not very experienced with file managing so expect some beginner errors and mistakes</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SIZE 100
int provbid;
int proveid;
int login();
void menu2();
void menu3();
void bus_mgm();
void emp_mgm();
typedef struct bus_data
{
int busid;
float distrav;
}bus;
typedef struct emp_data
{
int empid;
float hrswrkd;
}emp;
void addb(int*,bus[]);
void adde(int*,emp[]);
void viewb(int*,bus[]);
void viewe(int*,emp[]);
void updateb(int*,bus[]);
void updatee(int*,emp[]);
void deleteb(int*,bus[]);
void deletee(int*,emp[]);
int searchb(int,bus[]);
int searche(int,emp[]);
void readfileb(int*,bus[]);
void readfile(int*,emp[]);
void writefileb(int,bus[]);
void writefilee(int,emp[]);
int main(){
int option1;
int p = 0;
p = login();
if (p==1){
printf("\n-*-*-*-*-* Welcome to 'Company Manager' user *-*-*-*-*\n");
}
else{
return 0;
}
system("pause");
system("cls");
printf("\n\nPlease slect an option:\n");
printf("1 Bus managment menu\n");
printf("2 Employee managment menu\n");
printf("3 Exit\n");
scanf("%d", &option1);
while (option1 != 3){
switch(option1){
case 1:
menu2();
break;
case 2:
menu3();
break;
default:
{
if (option1 != 3){
printf("\nOption is not supported.");
}
}
system("pause");
printf("Please slect an option:\n");
printf("1 Bus managment menu\n");
printf("2 Employee managment menu\n");
printf("3 Exit\n");
scanf("%d", &option1);
}
system("pause");
}
return 0;
}
int login(){
int pwd = 12345678;
int count = 0;
int pw;
printf("Welcome to 'comapnay manager' login screen\n");
while (count != 5){
printf("Please enter password. \n");
scanf("%d",&pw);
if (pw == pwd){
printf("Password accepted");
return 1;
}
else{
printf("\n Wrong Password, try again.\n");
}
count++;
printf("You have done %d chances out of 5\n", count);
}
return 0;
}
void menu2(){
int choice;
int bl = 0;
bus bslist[SIZE];
readfileb(&bl, bslist);
system("pause");
system("cls");
printf("Welcome to the bus menu.\n\n");
printf("Please select an option:\n\n1: Add bus information\n2: View bus information\n3: Update bus information\n4: Delete bus information\n5: Return to login menu\n6: to exit the prgram\n");
scanf("%d",&choice);
while (choice != 6){
switch (choice){
case 1:
addb(&bl, bslist);
break;
case 2:
viewb(&bl, bslist);
break;
case 3:
updateb(&bl, bslist);
break;
case 4:
deleteb(&bl, bslist);
break;
case 5:
main();
break;
default:
if (choice != 6){
printf("you have not selected a proper option\n");
}
else{
goto end;
}
}
system("pause");
system("cls");
printf("Please select an option:\n\n1: Add bus information\n2: View bus information\n3: Update bus information\n4: Delete bus information\n5: Return to login menu\n6: Exit\n ");
scanf("%d",&choice);
}
end:
exit(0);
}
void menu3(){
int choice;
int el = 0;
emp eplist[SIZE];
system("pause");
system("cls");
printf("Welcome to the Employee menu menu.\n\n");
printf("Please select an option:\n\n1: Add Employee information\n2: View Employee information\n3: Update Employee information\n4: Delete Employee information\n5: Return to login menu\n6: Exit\n");
scanf("%d", &choice);
while (choice != 6){
switch (choice){
case 1:
adde(&el, eplist);
break;
case 2:
viewe(&el, eplist);
break;
case 3:
updatee(&el, eplist);
break;
case 4:
deletee(&el, eplist);
break;
case 5:
main();
break;
default:
if (choice != 6){
printf("you have not selected a proper option\n");
}
else{
goto end;
}
}
system("pause");
printf("Please select an option:\n1: Add Employee information\n2: View Employee information\n3: Update Employee information\n4: Delete Employee information\n5: Return to login menu\n6: Exit\n");
scanf("%d", &choice);
}
end:
exit(0);
}
void addb(int *loc ,bus list[]){
printf("Add bus information");
int n = searchb( *loc, list);
if (n != -1){
printf("This ID is already being used.");
}
else
{
list[*loc].busid = provbid;
fflush(stdin);
printf("Please enter the total distance traveled, the number you have given will be accepted as km: ");
scanf("%f", &list[*loc].distrav);
*loc = *loc + 1;
}
}
void adde(int*loc ,emp list[]){
printf("Add Employee information\n");
int n = searche( *loc, list);
if (n != -1){
printf("This ID is already being used.");
}
else
{
list[*loc].empid = proveid;
fflush(stdin);
printf("Please enter the total hours worked: ");
scanf("%f", &list[*loc].hrswrkd);
*loc = *loc + 1;
}
}
void viewb(int *loc ,bus list[]){
int meh;
printf("Showing information of all buses.\n");
for(meh = 0; meh < *loc; meh++)
{
printf("Bus ID is: %d\n", list[meh].busid);
printf("Distance traveled is: %.1f km\n", list[meh].distrav);
}
}
void viewe(int *loc,emp list[]){
int meh;
printf("Showing information of all Employess.\n");
for(meh = 0; meh < *loc; meh++)
{
printf("Employee ID is: %d\n", list[meh].empid);
printf("Hours worked are: %.1f hours\n", list[meh].hrswrkd);
}
}
void updateb(int *loc,bus list[]){
int tempbid;
printf("Update bus information");
tempbid = searchb(*loc, list);
if( tempbid== -1)
{
printf("This ID does not exist.\n");
}
else
{
printf("Enter new distanced traveled: ");
scanf("%f", &list[tempbid].distrav);
printf("Distance traveled has been updated. \a");
}
}
void updatee(int *loc ,emp list[]){
int tempeid;
printf("Update employee information");
tempeid = searche(*loc, list);
if( tempeid== -1)
{
printf("This ID does not exist.\n");
}
else
{
printf("Enter new hours worked: ");
scanf("%f", &list[tempeid].hrswrkd);
printf("Hours worked has been updated. \a");
}
}
void deleteb(int *loc, bus list[]){
int tempbid, meh;
printf("Delete bus info");
tempbid = searchb(*loc, list);
if(tempbid == -1)
{
printf("This ID does not exist.\n");
}
else
{
for(meh = tempbid; meh < *loc; meh++)
{
list[meh].busid = list[meh + 1].busid;
list[meh].distrav = list[meh + 1].distrav;
}
*loc = *loc - 1;
printf("Bus ID %d has been deleted.\n", tempbid);
}
}
void deletee(int *loc,emp list[]){
int tempeid, meh;
printf("Delete employee info");
tempeid = searche(*loc, list);
if(tempeid == -1)
{
printf("This ID does not exist.\n");
}
else
{
for(meh = tempeid; meh < *loc; meh++)
{
list[meh].empid = list[meh + 1].empid;
list[meh].hrswrkd = list[meh + 1].hrswrkd;
}
*loc = *loc - 1;
printf("Employee ID %d has been deleted.\n", tempeid);
}
}
int searchb(int loc, bus list[]){
int meh;
printf("Enter bus ID: ");
scanf("%d", &provbid);
for(meh=0; meh<loc; meh++){
if(list[meh].busid == provbid)
return meh;
}
return -1;
}
int searche(int loc ,emp list[]){
int meh;
printf("Enter employee ID: ");
scanf("%d", &proveid);
for(meh=0; meh<loc; meh++){
if(list[meh].empid == proveid)
return meh;
}
return -1;
}
void readfileb(int *loc, bus list[]){
FILE *bd;
bd = fopen("Bus Data.txt", "r");
if(bd != NULL)
{
while(!feof(bd))
{
fscanf(bd, "%d %f ", &list[*loc].busid, &list[*loc].distrav);
*loc = *loc + 1;
}
}
fclose(bd);
}
void readfile(int *loc, emp list[]){
FILE *ed;
ed = fopen("Employee Data.txt", "r");
if(loc != NULL)
{
while(!feof(ed))
{
fscanf(ed, "%d %f ", &list[*loc].empid, &list[*loc].hrswrkd);
*loc = *loc + 1;
}
}
fclose(ed);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:28:28.167",
"Id": "469894",
"Score": "0",
"body": "The title has been changed to better follow the code review guideline at https://codereview.stackexchange.com/help/asking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:32:25.413",
"Id": "469900",
"Score": "1",
"body": "_expect some problems_ is unfortunately not specific enough for us. Does the code work as it should?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T18:54:18.517",
"Id": "469927",
"Score": "1",
"body": "(To determine whether or not code works as specified, a *specification* would be invaluable.)"
}
] |
[
{
"body": "<p>the posted code is ignoring the returned values from <code>scanf()</code> <code>fscanf()</code>, and <code>system()</code> </p>\n\n<p>Critical success/fail information is contained in those returned values, so the code should be checking those returned values</p>\n\n<p>Please read <a href=\"https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong\">why while(!feof(ed)) is always wrong</a></p>\n\n<p>suggest replacing:</p>\n\n<pre><code>while(!feof(ed))\n {\n fscanf(ed, \"%d %f \", &list[*loc].empid, &list[*loc].hrswrkd);\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>while( fscanf(ed, \"%d %f \", &list[*loc].empid, &list[*loc].hrswrkd) == 2 ) {\n</code></pre>\n\n<p>Much better to use the returned value from <code>fscanf()</code> to control the loop</p>\n\n<p>regarding:</p>\n\n<pre><code>ed = fopen(\"Employee Data.txt\", \"r\");\nif(loc != NULL)\n</code></pre>\n\n<p>What about when the call to <code>fopen()</code> fails?</p>\n\n<p>in function: <code>menu2()</code> the call to <code>readfile()</code> should contain a parameter that indicates the max number of 'slots' that can be filled, so the array of <code>structs bus bslist[SIZE];</code> is not overflowed. </p>\n\n<p>regarding:</p>\n\n<pre><code>else{\n goto end;\n</code></pre>\n\n<p>a <code>goto</code> is (almost) always a bad idea. Suggest fixing the code logic so no <code>goto</code> is needed</p>\n\n<p>Please do not use for indenting as everyone's editor can be set for different tab widths. Strongly suggest using 4 spaces where there are current characters</p>\n\n<p>regarding:</p>\n\n<pre><code>system(\"pause\");\nsystem(\"cls\");\n</code></pre>\n\n<p>the shell commands: <code>pause</code> and <code>cls</code> are not portable. so if you want this code to run on anything but Windows, please use more generic methods</p>\n\n<p>regarding:</p>\n\n<pre><code>case 5:\n main();\n break; \n</code></pre>\n\n<p>DO NOT call the function: <code>main()</code> rather use some kind of looping construct</p>\n\n<p>regarding:</p>\n\n<pre><code>end:\n exit(0);\n</code></pre>\n\n<p>do you really want to exit the whole program?</p>\n\n<p>regarding:</p>\n\n<pre><code>fflush(stdin);\n</code></pre>\n\n<p>The function: <code>fflush()</code> is for output streams, not input streams. The C standard specifically states using <code>fflush()</code> on a input stream is undefined behavior. Some compilers, like <code>visual c</code> allow it, but such deviations from the C standard should not be used. Suggest:</p>\n\n<pre><code>int ch;\nwhile( (ch = getchar()) != EOF && ch != '\\n' ){;}\n</code></pre>\n\n<p>regarding:</p>\n\n<pre><code> printf(\"Welcome to the Employee menu menu.\\n\\n\");\n printf(\"Please select an option:\\n\\n1: Add Employee information\\n2: View Employee information\\n3: Update Employee information\\n4: Delete Employee information\\n5: Return to login menu\\n6: Exit\\n\");\n</code></pre>\n\n<p>it is best to honor the right margin, amongst other reasons, so the code can easily be printed.</p>\n\n<p>Suggest:</p>\n\n<pre><code>printf(\"Welcome to the Employee menu.\\n\\n\");\nprintf(\"Please select an option:\\n\\n\"\n \"1: Add Employee information\\n\"\n \"2: View Employee information\\n\"\n \"3: Update Employee information\\n\"\n \"4: Delete Employee information\\n\"\n \"5: Return to login menu\\n\"\n \"6: Exit\\n\");\n</code></pre>\n\n<p>which makes it much more readable and does honor the right margin</p>\n\n<p>For ease of readability and understanding: </p>\n\n<ol>\n<li>follow the axiom: <em>only one statement per line and (at most) one variable declaration per statement.</em> </li>\n<li>separate code blocks: <code>for</code> <code>if</code> <code>else</code> <code>while</code> <code>do...while``switch</code> <code>case</code> <code>default</code> via a single blank line. </li>\n<li>separate functions by 2 or 3 blank lines (be consistent)</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:28:21.353",
"Id": "239580",
"ParentId": "239563",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:17:24.787",
"Id": "239563",
"Score": "-2",
"Tags": [
"c"
],
"Title": "Data management for buses and and employees"
}
|
239563
|
<p>A friend gave me the following riddle:</p>
<blockquote>
<p>Given n people with n distinct names, you place n names tags on a round table with n seats. If the n people now sit at those seats randomly such that exactly one person sits correctly (in the seat with the correct name tag with their name one it), can we rotate the table such that (at least) two people sit correctly?</p>
</blockquote>
<p>For odd n this is false, which you can see by considering by placing the name tags 1, ..., n in order and seating the people as 1, n, n - 1, ... 2. I haven't been able that this true for even n so I wanted to try out small even n with a python script.</p>
<p>I wrote the following code. Unfortunately, it is very slow (n = 10 takes about 25 seconds, but n = 12 takes nearly 11 minutes!) so I am searching for libraries which can speed up the things I implemented from scratch or maybe a method which speeds things up.</p>
<p>I have 4 methods:</p>
<ol>
<li><code>perms(n)</code>, which gives me all permutations of 0, ..., n- 1 which have one fixed point,</li>
<li><code>fixtest(L,m)</code>, which tests if the permutation L has m fixed points,</li>
<li><code>rot(L)</code>, which rotates the permutation L, i.e. [1,2,3] becomes [2,3,1] and</li>
<li><code>test(n)</code> which, for a given n generates all permutations of 0, ..., n- 1 which have one fixed point with <code>perms(n)</code> and then for each one, performs all rotations and for every rotation checks the number of fixed points and writes them in a list <code>C</code>. If <code>C</code> only contains ones, we have found a counterexample to the riddle above.</li>
</ol>
<p>My code looks like this</p>
<pre><code>from itertools import permutations
from collections import deque
# find all permutations of [n] with 1 fixed point
def perms(n):
P = (perm for perm in permutations(range(n)))
D = [] # D will contain the 'right' permutations (those with one fixed point)
for perm in P: # count fixed points (counter c)
c = 0
for idx, k in enumerate(perm):
if idx == k:
c +=1
if c == 1:
D.append(perm)
return D
# tests if a sequence L has m fixed points
def fixtest(L,m):
L = list(L)
c = 0
for idx, k in enumerate(L):
if idx == k:
c +=1
if c == m:
return True
else:
return False
# rotates the list L
def rot(L):
L = deque(L)
a = L.pop()
L.appendleft(a)
return list(L)
def test(n):
for f in perms(n):
k = 0
C = []
f_real = list(f)
while k < n - 1:
f = rot(f)
C.append(fixtest(f,1))
k +=1
if all(x == True for x in C):
return n, 'Counterexample found:', f_real
return n, 'no counterexamples found'
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T17:07:18.810",
"Id": "470003",
"Score": "0",
"body": "So you have to rotate a permutation n times?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T18:48:12.560",
"Id": "470012",
"Score": "0",
"body": "@DaniMesejo To find a counterexample, we need to find a permutation such that after every rotation there's only one fixed point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T18:49:51.787",
"Id": "470013",
"Score": "0",
"body": "Yep, that is correct but isn't the rotation another permutation? That you could have check already?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T18:55:56.073",
"Id": "470014",
"Score": "0",
"body": "@DaniMesejo Yes. I haven't found a good way to eliminate them, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T19:08:34.720",
"Id": "470015",
"Score": "0",
"body": "Are you sure that this is the right solution, what would change from 8 to 10 for example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T19:13:36.233",
"Id": "470017",
"Score": "3",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/106084/discussion-between-viktor-glombik-and-dani-mesejo)."
}
] |
[
{
"body": "<p>You're checking <em>way</em> too much in your program. In your test function, the <code>all</code> is going through <em>every single element</em> in the list and checking if it's <code>True</code>. What you should do is do the check yourself, and return on the very first instance of a <code>False</code> value. With the other optimizations made, this speed up runtime from 18 seconds to about four seconds.</p>\n\n<p>You can do the same check above in the <code>fixtest</code> function. Simply return on the very first time that the value is above the <code>points</code> parameter passed. This reduces the amount of iterations needed. Let's say <code>points</code> was 1, as you wrote. At the end of the loop, after checking <em>a lot</em> of permutations, the if statement check is now <code>if 1 == 1467811728:</code>, or some arbitrarily large number. With returning on the first instance of it being <em>above</em> the <code>points</code> parameter, it's a lot faster.</p>\n\n<p>You shouldn't need to convert the list to a <code>deque</code> to just shift the list. Use list slicing, it's better. You also pass a list as an argument to a function, then convert that list to a list, even when you just passed one! This unnecessary converting can slow down your program.</p>\n\n<p>Also, use better variable names and type hinting. Makes your program a lot clearer and easier to understand.</p>\n\n<p>At the end of the day, for <code>n=10</code> the program takes about four seconds to run, give or take a few hundred milliseconds.</p>\n\n<pre><code>from itertools import permutations\nfrom typing import List, Tuple, Union\n\ndef perms(number_of_permutations: int):\n \"\"\"\n Returns a list of all permutations of `n` with one fixed point.\n \"\"\"\n P = (perm for perm in permutations(range(number_of_permutations)))\n return [\n perm for perm in P if sum(1 if idx == k else 0 for idx, k in enumerate(perm)) == 1\n ]\n\ndef fixtest(sequence: List[int], points: int) -> bool:\n \"\"\"\n Tests if a sequence has `points` fixed points.\n \"\"\"\n count = 0\n for index, value in enumerate(sequence):\n if index == value:\n count += 1\n if count > points:\n return False\n return True\n\ndef rotate(sequence: List[int]) -> List[int]:\n \"\"\"\n Rotates the sequence by one position\n \"\"\"\n return sequence[-1:] + sequence[:-1]\n\ndef test(number: int) -> Union[Tuple[int, str], Tuple[int, str, List[int]]]:\n \"\"\"\n Run numerous tests for this code.\n \"\"\"\n for f in perms(number):\n C = []\n for _ in range(number - 1):\n f = rotate(f)\n C.append(fixtest(f, 1))\n for value in C:\n if not value:\n return number, 'no counterexamples found'\n return number, 'Counterexample found:', f\n\n# [START] 21.5174s\n# [END] 4.6866s\n</code></pre>\n\n<p><strong>Edit</strong>: That <code>Union</code> type hint may look confusing, so let me clear that up. It's essentially saying that the function will either return a tuple of an int and a string, or a tuple of an int, a string, and a list of integers. It depends on what the outcome of the tests are.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T04:08:17.717",
"Id": "470751",
"Score": "0",
"body": "I believe your indentation is wrong as it will only test 1 permutation as written"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T11:46:23.857",
"Id": "470783",
"Score": "0",
"body": "you can replace `1 if idx == k else 0 ` with a simple `idx==k`. `True` counts as 1, `False` as 0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T11:47:31.723",
"Id": "470784",
"Score": "0",
"body": "No need to make the arguments of `rotate` into `List`. This also works for `tuple`s, or any contained which you can slice on index"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-05T20:28:24.813",
"Id": "240004",
"ParentId": "239566",
"Score": "1"
}
},
{
"body": "<p>The next big improvement is also an algorithmic one. Rather than rotating a permutation <code>n</code> times, to check for fixed points, we can instead look the distribution of <code>(index-value) % n</code>. If two different elements of the permutation have the same value <code>x</code> for this, it means that rotating by <code>x</code> will produce 2 fixed points. This means that for each permutation, rather than doing <code>n</code> rotations (<code>O(n^2)</code>), we can instead hash all values of this quantity, and check for colsions (<code>O(n)</code>). </p>\n\n<p>The result is </p>\n\n<pre><code>def rotfixtest(sequence: List[int], points: int):\n \"\"\"\n Tests if a sequence has `points` fixed points.\n \"\"\"\n n = len(sequence)\n offsets = Counter()\n for index, value in enumerate(sequence):\n offsets[(index - value) % n] += 1\n most_common = offsets.most_common(1)\n if most_common[0][1] >= points:\n return False\n return most_common[0][0]\n\ndef test(number: int) -> Union[Tuple[int, str], Tuple[int, str, List[int]]]:\n \"\"\"\n Run numerous tests for this code.\n \"\"\"\n for f in perms(number):\n rotations = rotfixtest(f, 2)\n if rotations:\n return number, 'Counterexample found:', f, rotations\n return number, 'no counterexamples found'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T04:10:12.860",
"Id": "240022",
"ParentId": "239566",
"Score": "1"
}
},
{
"body": "<p>Your major issue here is the algorithm, in which the number of operations grows as the factorial as <code>n</code>. To avoid this you will, I believe, need to go inside the loops that generate permutations. </p>\n\n<p>First, I'd like to restate the problem as: if n individuals are seated around a table and then rearranged randomly, is it possible to move them in such a way that everybody moves a different number of places? The number of places moved is counted clockwise, from 0 to <code>n-1</code>. </p>\n\n<p>This is equivalent to your problem, because if any two are moved displaced the same number of places, they can be rotated back to their original places.</p>\n\n<p>This means that we are looking for solutions in which each displacement 0 to <code>n-1</code> is used once and only once. For any solution, we can generate another <code>n-1</code> solutions by rotations: if there is a solution in which place 1 does not move, we can re-label to get a solution in which 0 does not move. It follows that it is enough to look only at the cases in which position 0 has 0 displacement.</p>\n\n<p>The next step is to observe that if we select 0 for position 0, the normal set of permutations as n-1 options for place 1, namely 1 to <code>n-1</code>, but in this problem we have only <code>n-2</code> options, 2 to <code>n-1</code>. Then when we make a selection for position 1, it will generally rule out two choices for position 2, so we only have <code>n-4</code> options left to try for position 2. This starts to look like a problem with <strong>only</strong> the <code>n/2</code> factorial options to search through. </p>\n\n<p>The following code will loop through this algorithm recursively. The timing is 68 seconds for n=14, 0.083 seconds for n=10 (compared with 27 seconds for n=10 using your algorithm).</p>\n\n<p>(Edited to take into account feedback below -- but the algorithm is unchanged).</p>\n\n<pre><code>def options(ring_length,options_used):\n \"\"\"The options functions computes the available options at the \n next position in a ring of length *ring_length* given places \n taken specified in *options_used*, taking into account \n that no index should be reused and no displacement should \n be reused.\n \"\"\"\n\n l1 = len(options_used)\n\n displacements_used = [ ( options_used[i] - i ) % ring_length for i in range(l1) ]\n\n options_next = [i for i in range(ring_length) if (i not in options_used) and ( (i - l1) % ring_length not in displacements_used)]\n\n return options_next\n\ndef _recurse(ring_length,options_used,result_set):\n \"\"\"\n ring_length: length of ring (number of elements)\n options_used: options which have been set for some of \n the places: this is a list of length 1 up to ring_length - 1\n specifying the elements which have been set so far;\n result_set: a set which is used to accumulate permutations \n which match the imposed constraint.\n \"\"\"\n\n for i in options(ring_length,options_used):\n if len(options_used) == ring_length-1:\n result_set.add( tuple( options_used + [i,] ) )\n else:\n _recurse(ring_length,options_used + [i,],result_set)\n\ndef testn(ring_length,result_set):\n \"\"\"Search for permutations of a ring of length *ring_length* with \n the constraint that all displacements should be different.\n \"\"\"\n _recurse(ring_length,[0,],result_set)\n\n\nif __name__ == \"__main__\":\n import sys\n ring_length = int( sys.argv[1] )\n result_set = set()\n testn(ring_length,result_set)\n\n count = len( result_set )\n print( \"%s: %s,:: %s\" % (ring_length, count, count*ring_length) )\n</code></pre>\n\n<p>To verify that the code is doing the same as your algorithm, I have tweaked your code to count the solutions, rather than stopping at the first, and verified that the results are the same up to <code>n=12</code>. The results are zero for even numbers and the following for odd numbers (extended up to <code>n=15</code>):</p>\n\n<pre><code>n # solutions\n3 3\n5 15\n7 133\n9 2025\n11 37851\n13 1030367\n15 36362925\n</code></pre>\n\n<p>I've checked even numbers up to <code>n=14</code>: still no solutions. Despite these algorithmic improvements, checking <code>n=16</code> would take several hours on my laptop. The cost is growing roughly as the factorial of <code>n/2</code>, which is a lot slower than <code>n</code> factorial, but still fast. I suspect that the efficiency of the <code>options</code> function could be improved, but it would be nice to know if there is a mathematical solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T14:28:38.513",
"Id": "470795",
"Score": "0",
"body": "no need for the ´Callback´. you can do `results = set(); testn(k, result.__add__)`, or make the purpose even clearer by just passing the `result` set along as argument"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T14:31:02.387",
"Id": "470797",
"Score": "0",
"body": "I have also difficulty following your algorithm. The obscure variable names don't really help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T16:56:51.550",
"Id": "470835",
"Score": "0",
"body": "Fair comment. I was so pleased to get the algorithm working that I failed to tidy up the code. I've created clearer variable names and removed the callback function, as you suggested, and also simplified the logical structure of the `options` function. This doesn't change the timing of the script."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T07:08:31.913",
"Id": "240033",
"ParentId": "239566",
"Score": "1"
}
},
{
"body": "<h1>Doc-string</h1>\n\n<p>You can add a docstring to the method using the convention of PEP-257 so IDE's etc can parse it and show it when looking at the method.</p>\n\n<h1>typing</h1>\n\n<p>By adding type annotations you can make it more clear to the user of the function what input the methods require and what to expect as answers, serving as extra documentation. It also allows static analysers like <code>mypy</code> to discover bugs.</p>\n\n<h1>generator</h1>\n\n<p>Instead of returning a list, you can have the permutation generate yield the correct permutations one by one</p>\n\n<h1>reduce the number of permutations</h1>\n\n<p>If any permutation where 1 person sits on the correct chair is ok, why not pick one where person 0 sits on the correct chair. This reduces the number of permutations to check <code>n</code> times</p>\n\n<pre><code>import itertools\nimport typing\ndef perms_gen(n: int) -> typing.Iterator[typing.Sequence[int]]:\n \"\"\"Yields the permutations where only the first person sits on his own seat.\"\"\"\n for perm in itertools.permutations(range(1, n)):\n if any(i == j for i,j in enumerate(perm, 1)):\n continue\n yield (0,) + perm\n</code></pre>\n\n<p>This is a generator function which yields a new permutation each time another function (<code>next</code>, <code>for-loop</code>, ..) asks for it,instead of all generating them in one go. This way, only those permutations that are needed are generated, and they occupy less memory. I you want a list of all permutations, you have to explicitly ask for it by <code>list(perms_gen(10))</code></p>\n\n<h1><code>rotate</code></h1>\n\n<p>Rotating a list can be done by splice indexing. No need to call a <code>deque</code>. If you want to use a <code>deque</code>, then use its <a href=\"https://docs.python.org/3/library/collections.html#collections.deque.rotate\" rel=\"nofollow noreferrer\"><code>rotate</code></a> method, instead of popping and appending yourself</p>\n\n<p>Saving the 3 letters to type is also not useful.</p>\n\n<pre><code>def rotate(\n seq: typing.Sequence[typing.Any], n: int\n) -> typing.Sequence[typing.Any]:\n \"\"\"Rotates `seq` `n` places.\"\"\"\n n %= len(seq)\n return seq[n:] + seq[:n]\n</code></pre>\n\n<p>The in-place modulo is to make sure <code>n</code> is in the range <code>[0, len(seq))</code></p>\n\n<h1>Testing further rotations</h1>\n\n<p>To see whether there is a rotation which allows more than 1 person in his or her seat, you can also count for each person how much spaces they need to go to their correct seat. If more than 1 person needs the same number of rotations, you have a match. To check whether there is no rotation of a permutation so 2 people sit in their correct seat, you can use this set comprehension <code>{(i - j) % n for i, j in enumerate(permutation)}</code> and test whether its length is <code>n</code></p>\n\n<h1>return values</h1>\n\n<p>When there is no response, I would either raise an exception or a sentinel value. You do approximately the same, by your <code>return n, 'Counterexample found:', f_real</code> in case of success and in case of failure <code>return n, 'no counterexamples found'</code>. But using a string as sentinel value means the users of this function needs a complicated test, further complicated by the face that the lengths of the return tuples are different, so you can not use tuple unpacking.</p>\n\n<p>Returning <code>n</code> has no use, since the user called the method with n as an argument. If he wants to produce a message with <code>n</code> included, he doesn't need to get it returned here.</p>\n\n<p>As sentinel for failure I would return None or raise an exception.</p>\n\n<h1>putting it together:</h1>\n\n<pre><code>def main(n: int) -> typing.Optional[typing.Tuple[int, ...]]:\n \"\"\"Tests whether there is a permutation so not more than 1 person\n return to their original seat when rotated.\n\n returns a counter example when found, or None.\n \"\"\"\n for permutation in perms_gen(n):\n if len({(i - j) % n for i, j in enumerate(permutation)}) == n:\n return permutation\n</code></pre>\n\n<p>This either returns a tuple with an example, or <code>None</code> is implicitly returned when all permutations are tested.</p>\n\n<h1>timings</h1>\n\n<p>On my machine, for n == 10 this takes about 700ms compared to 30s for your original</p>\n\n<h1>Keeping it as a generator</h1>\n\n<p>If you rewrite it a bit, you can keep the <code>rotations_to_place</code> as a generator, only calculating as needed, and yielding the correct permutations</p>\n\n<pre><code>def main_generator(n: int) -> typing.Iterator[typing.Tuple[int, ...]]:\n \"\"\"Yields all complying permutations.\"\"\"\n permutations = perms_gen(n)\n for permutation in perms_gen(n):\n if len({(i - j) % n for i, j in enumerate(permutation)}) == n:\n yield permutation\n</code></pre>\n\n<p>If you want to test if there is a permutation, you can do <code>any(main(n))</code>. If you want all permutations, you can do <code>list(main(n))</code></p>\n\n<p>For 9:</p>\n\n<pre><code>results = list(main_generator(9))\n</code></pre>\n\n<blockquote>\n<pre><code>[(0, 2, 1, 6, 8, 7, 3, 5, 4),\n (0, 2, 1, 6, 8, 7, 4, 3, 5),\n (0, 2, 1, 7, 6, 8, 3, 5, 4),\n (0, 2, 1, 7, 6, 8, 4, 3, 5),\n ...\n (0, 8, 6, 5, 3, 2, 7, 1, 4),\n (0, 8, 7, 4, 6, 2, 5, 1, 3),\n (0, 8, 7, 5, 3, 6, 1, 4, 2),\n (0, 8, 7, 6, 5, 4, 3, 2, 1)]\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T16:53:21.940",
"Id": "470833",
"Score": "0",
"body": "Since I don't know generators and `typing` it wil take time for me to understand this. But thanks for your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T19:42:38.247",
"Id": "470848",
"Score": "0",
"body": "seems like I misunderstood the original question. I corrected my algorithm."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T10:31:05.050",
"Id": "240042",
"ParentId": "239566",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T16:46:13.743",
"Id": "239566",
"Score": "5",
"Tags": [
"python",
"performance",
"beginner",
"python-3.x",
"combinatorics"
],
"Title": "Check whether a permutation with one fixed point can be rotated into one with two fixed points"
}
|
239566
|
<p>I'd like you to take a look at those extension functions I made in kotlinjs (version 1.3.61):</p>
<pre><code>inline fun <reified E : Element> Element.queryHtmlSelectorOrNull(selectors: String): E? {
return this.querySelector(selectors = selectors) as E?
}
inline fun <reified E : Element> Element.queryHtmlSelector(selectors: String): E {
return this.queryHtmlSelectorOrNull(selectors = selectors)
?: error("couldn't find element by selectors '$selectors'")
}
</code></pre>
<p>Now let me elaborate. I was using classic javascript <a href="https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom/-document/query-selector.html" rel="nofollow noreferrer">querySelector</a>. This signature:</p>
<pre><code>fun querySelector(selectors: String): Element?
</code></pre>
<p>Has some downsides/qualities:</p>
<ul>
<li>It is optional.</li>
<li><p>When I force cast to for example <code>HTMLDivElement</code> and result is actually null, I get <code>NullPointerException</code> with no additional information/error message. Example:</p>
<pre><code>document.querySelector(".something-non-existent") as HTMLDivElement //throws
</code></pre></li>
<li><p>I have to explicitly cast my query to specific element I want (example <code>HTMLDivElement?</code> or <code>HTMLDivElement</code>).</p></li>
</ul>
<p>My functions fix some of the issues, but create new issues:</p>
<ul>
<li><p>You can explicitly select what type you need or compiler can guess it based on variable type.</p>
<p>Example:</p>
<pre><code>document.queryHtmlSelector<HTMLDivElement>(".something")
</code></pre>
<p>or</p>
<pre><code>val element: HTMLDivElement = document.queryHtmlSelector(".something")
</code></pre></li>
</ul>
<p>The downside is that this doesn't work (need to set type explicitly):</p>
<pre><code>val element = document.queryHtmlSelector(".something")
</code></pre>
<p>I would be cool somehow to "default" base type to <code>Element</code> if none is specified, but can't think of way to do that.</p>
<p>I'd like something that can pretty much replace original function and just add benefits of stronger typing and nicer error message. Any hints on how to improve this are greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:32:07.863",
"Id": "469922",
"Score": "0",
"body": "Which Kotlin version are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:46:26.393",
"Id": "469924",
"Score": "0",
"body": "Currently `1.3.61`, but targeting latest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T14:44:32.087",
"Id": "470121",
"Score": "0",
"body": "The usage of `reified`, do you have that to get any potential ClassCastExceptions earlier, or any other reason?"
}
] |
[
{
"body": "<p><em>\"Would be cool somehow, to \"default\" base type to Element if none is specified, but can't think of way to do that.\"</em> Indeed it is not possible to do that, at least not with the same method. An option could be to have a separate method for that. <code>document.queryHtmlSelectorRaw</code> ? Or wait, actually... That leaves you back to what you were starting with, <code>Element.querySelector</code>.</p>\n\n<blockquote>\n <p>I'd like something, that can pretty much replace original function and just add benefits of stronger typing and nicer error message. Any hints on how to improve this are greatly appreciated.</p>\n</blockquote>\n\n<p>Given those requirements, I'd say that the current methods is about as good as you're gonna get. You have the stronger typing (but you will have to specify it). You have the better error message if it's null.</p>\n\n<p>The only things that I would consider are:</p>\n\n<ul>\n<li>Get rid of <code>reified</code>, I'm not convinced that you need it.</li>\n<li>Change method names, <code>queryHtmlSelector</code> can easily be confused with the built in <code>querySelector</code>. May I recommend just the name <code>selector</code> or <code>select</code>?</li>\n<li>Improve the error message even further, such as <code>No element found using selector '$selector' on $this</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T14:55:06.370",
"Id": "239663",
"ParentId": "239567",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:17:42.973",
"Id": "239567",
"Score": "2",
"Tags": [
"kotlin"
],
"Title": "Make querySelector in kotlin-js more convenient and type-safe"
}
|
239567
|
<p>So I attempted to write <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">Conway's game of life</a> on an Arduino and display using the FastLED library. I use a custom bitset class to manage the game board state. I'm looking for feedback on performance, and general code style towards embedded systems.</p>
<p>I should note that my led strip is a little bit weird see diagram below to show how 4 rows work in it, and 4 columns. It kind of snakes back and forth, with zero being in the top right. My actual grid has 8 columns on it, and can be daisy chained to get more rows.</p>
<pre><code>+----+----+----+----+
| 3 | 2 | 1 | 0 |
+----+----+----+----+
| 4 | 5 | 6 | 7 |
+----+----+----+----+
| 11 | 10 | 9 | 8 |
+----+----+----+----+
| 12 | 13 | 14 | 15 |
+----+----+----+----+
</code></pre>
<pre><code>/**
Game of Life with LEDS and variable HUE
Assumes a square grid of leds on a 8x8 led matrix.
Controlled with WS2812B led controller.
*/
#include <FastLED.h>
/**
* How long should each frame be displayed roughly
*/
#define FRAME_TIME 500
/**
* Should we draw the red border. If so we reduce the playfield by one on each side.
* Undefine this if we should not draw it
*/
#define DRAW_BORDER
//#undef DRAW_BORDER
/**
* The width of the grid
*/
#define WIDTH 8
/**
* The height of the grid
*/
#define HEIGHT 32
/**
* The initial number of live cells in the grid. They are randomly placed.
*/
#define NUMBER_OF_INITIAL_LIVE_CELLS 16
/**
* WS2812B Data pin
*/
#define DATA_PIN 3
/*
* Computed Values based on above constants
*/
#ifdef DRAW_BORDER
// We provide a spot for the border to go.
#define GRID_X_START 1
#define GRID_X_END (WIDTH - 1)
#define GRID_Y_START 1
#define GRID_Y_END (HEIGHT - 1)
#else
#define GRID_X_START 0
#define GRID_X_END WIDTH
#define GRID_Y_START 0
#define GRID_Y_END HEIGHT
#endif // DRAW_BORDER
#define NUM_LEDS (WIDTH * HEIGHT)
/**************************************************
* Begin Main Code Below
**************************************************/
int computeBitNumber(byte x, byte y) {
return y * WIDTH + x;
}
template<size_t N>
class MyBitset {
public:
MyBitset& operator=(const MyBitset& b) {
memcpy(this->data, b.data, N/8);
}
void setBit(size_t idx, byte val) {
size_t idx2 = idx / 8;
int bit2 = idx % 8;
bitWrite(data[idx2], bit2, val);
}
void zeroArray() {
memset(data, 0, N/8);
}
byte getBit(size_t idx) const {
size_t idx2 = idx / 8;
return bitRead(data[idx2], idx % 8);
}
private:
byte data[N/8];
};
const CRGB BORDER_COLOR = CRGB(255, 25, 25);
const CRGB WAS_LIVE_COLOR = CHSV(115, 82, 60);
const CRGB LIVE_COLOR = CHSV(115, 82, 100);
const CRGB LIVE_AND_WAS_COLOR = CHSV(115, 82, 140);
CRGB leds[NUM_LEDS];
MyBitset<NUM_LEDS> current, prev;
CRGB& getLed(byte x, byte y) {
int xOffset = y & 1 ? (WIDTH - 1) - x : x;
return leds[y * WIDTH + xOffset];
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
FastLED.setBrightness(100);
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
// Randomize the initial grid everytime on start up
setupBorder();
generateRandomGame();
prev = current;
FastLED.show();
}
void loop() {
int startTime = millis();
setupBorder();
current.zeroArray();
for (int x = GRID_X_START; x < GRID_X_END; ++x) {
for (int y = GRID_Y_START; y < GRID_Y_END; ++y) {
int count = countNeighbors(x, y);
int index = computeBitNumber(x, y);
CRGB& targetLed = getLed(x, y);
if (count == 2 || count == 3) {
current.setBit(index, 1);
targetLed = prev.getBit(index) ? LIVE_AND_WAS_COLOR : LIVE_COLOR;
} else {
current.setBit(index, 0);
targetLed = prev.getBit(index) ? WAS_LIVE_COLOR : CRGB::Black;
}
}
}
prev = current;
int finishTime = millis();
Serial.println(finishTime - startTime);
FastLED.show();
FastLED.delay(FRAME_TIME - (finishTime - startTime));
}
int countNeighbors(byte xCenter, byte yCenter) {
int sum = 0;
for (int x = xCenter - 1; x < xCenter + 2; ++x) {
for (int y = yCenter - 1; y < yCenter + 2; ++y) {
if (x >= GRID_X_END || x < GRID_X_START || y < GRID_Y_START || y >= GRID_Y_END)
continue;
sum += prev.getBit(computeBitNumber(x,y));
}
}
return sum - prev.getBit(computeBitNumber(xCenter, yCenter));
}
/**
* Clears the LED array to black using memset.
*/
void setupBorder() {
memset(leds, 0, sizeof(leds));
#ifdef DRAW_BORDER
for (int i = 0; i < WIDTH; ++i) {
getLed(i, 0) = BORDER_COLOR;
getLed(i, GRID_Y_END) = BORDER_COLOR;
}
for (int i = GRID_Y_START; i < HEIGHT; ++i) {
getLed(0, i) = BORDER_COLOR;
getLed(GRID_X_END, i) = BORDER_COLOR;
}
#endif // DRAW_BORDER
}
void generateRandomGame() {
for (int i = 0; i < NUMBER_OF_INITIAL_LIVE_CELLS; ++i) {
int x, y, v;
do {
x = random(GRID_X_START, GRID_X_END);
y = random(GRID_Y_START, GRID_Y_END);
v = computeBitNumber(x, y);
} while(current.getBit(v) > 0);
current.setBit(v, 1);
getLed(x, y) = LIVE_COLOR;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First, given that this is C++, it's surprising that you're still using C-style <code>#define</code>s when you could be using <code>constexpr</code> variables, e.g.</p>\n\n<pre><code>/**\n * WS2812B Data pin\n */\n#define DATA_PIN 3\n</code></pre>\n\n<p>could have been done in one line as</p>\n\n<pre><code>constexpr int ws2812b_data_pin = 3;\n</code></pre>\n\n<hr>\n\n<p>One place it does still make sense to use <code>#define</code>s is when you have things that could conceivably be configured at build time. For example,</p>\n\n<pre><code>/**\n * Should we draw the red border. If so we reduce the playfield by one on each side.\n * Undefine this if we should not draw it\n */\n#define DRAW_BORDER\n//#undef DRAW_BORDER\n</code></pre>\n\n<p>seems like a reasonable use of the preprocessor. However, it would be much more conventional, and useful, if you permitted the build system to control the border via <code>-DDRAW_BORDER=1</code> and <code>-DDRAW_BORDER=0</code>, rather than <code>-DDRAW_BORDER</code> and <code>-UDRAW_BORDER</code>. That is, the traditional way to write a macro like this is:</p>\n\n<pre><code>// Should we draw the red border?\n// Default to \"yes\", but let the build system override it with -DDRAW_BORDER=0.\n#ifndef DRAW_BORDER\n #define DRAW_BORDER 1\n#endif\n\n#if DRAW_BORDER\n constexpr int grid_x_start = ...\n#endif\n</code></pre>\n\n<hr>\n\n<pre><code> MyBitset& operator=(const MyBitset& b) {\n memcpy(this->data, b.data, N/8);\n }\n</code></pre>\n\n<p>C++20 deprecated providing a user-defined <code>operator=</code> without a user-declared copy constructor. If you provide one, you should provide all three of the \"Rule of Three\" operations. Fortunately, in this case, you don't need a customized <code>operator=</code> at all. Just eliminate these three useless lines of code.</p>\n\n<p>Also, it should have been <em>four</em> useless lines of code! Did you not receive a warning from your compiler about the missing <code>return *this</code>?</p>\n\n<hr>\n\n<p>You never define the identifier <code>byte</code>, which makes me a little nervous. Is it just a typedef for <code>unsigned char</code>?</p>\n\n<hr>\n\n<pre><code>const CRGB WAS_LIVE_COLOR = CHSV(115, 82, 60);\nconst CRGB LIVE_COLOR = CHSV(115, 82, 100);\nconst CRGB LIVE_AND_WAS_COLOR = CHSV(115, 82, 140);\n</code></pre>\n\n<p>You forgot <code>THE_WAS_AND_THE_LIVE_TOKYO_DRIFT</code>...</p>\n\n<p>IIUC, these constants are meant to be the colors of cells that were \"live in the previous generation but not now,\" \"live in this generation but not the previous one,\" and \"live in both.\" For some reason you provide constants for these three, but then hard-code the fourth option (\"live in neither generation\") as <code>CRGB::Black</code>. I would much prefer to see this as a pure function of the two inputs:</p>\n\n<pre><code>static CRGB computeCellColor(bool prev, bool curr) {\n switch (2*prev + 1*curr) {\n case 0: return CRGB::Black;\n case 1: return CHSV(115, 82, 100);\n case 2: return CHSV(115, 82, 60);\n case 3: return CHSV(115, 82, 140);\n }\n __builtin_unreachable();\n}\n</code></pre>\n\n<p>Then you can write your main loop more simply:</p>\n\n<pre><code> for (int x = GRID_X_START; x < GRID_X_END; ++x) {\n for (int y = GRID_Y_START; y < GRID_Y_END; ++y) {\n int index = computeBitNumber(x, y);\n bool isLive = computeLiveness(x, y);\n bool wasLive = prev.getBit(index);\n\n current.setBit(index, isLive);\n getLed(x, y) = computeCellColor(wasLive, isLive);\n }\n }\n</code></pre>\n\n<p>I replaced your <code>countNeighbors</code> function with a <code>computeLiveness</code> function that does exactly what you need it to do — no more. Our main loop <em>does not care</em> about the exact number of neighbors involved; all it wants to know is a single bit of information. So that's all it should be asking for.</p>\n\n<p>It is <em>almost</em> correct to say <code>leds[index] = computeCellColor(...)</code> instead of having to do that weird \"assign to the result of a function call\" thing. I would suggest looking for a way to eliminate the \"assign to function call.\" For example,</p>\n\n<pre><code>setLed(x, y, computeCellColor(wasLive, isLive));\n</code></pre>\n\n<p>or</p>\n\n<pre><code>leds[computeLedIndex(x, y)] = computeCellColor(wasLive, isLive);\n</code></pre>\n\n<hr>\n\n<pre><code>/**\n * Clears the LED array to black using memset.\n */\nvoid setupBorder() {\n memset(leds, 0, sizeof(leds));\n}\n</code></pre>\n\n<p>I can write that code in half the number of lines:</p>\n\n<pre><code>void clearLedsToBlack() {\n memset(leds, 0, sizeof(leds));\n}\n</code></pre>\n\n<p>Also, I don't even see why you're clearing the LEDs to black on each iteration through the loop. Don't you end up overwriting all of the LEDs' values in the main loop anyway? And who says <code>0</code> means \"black\"? Elsewhere, when you want to set an LED to black, you use the symbolic constant <code>CRGB::Black</code>. You should try to be consistent — if you <em>know</em> black is <code>0</code>, then just say <code>0</code>, and if you don't know it, then don't write <code>setupBorders</code> to rely on it.</p>\n\n<p>C++ does also allow you to assert that black is <code>0</code> at compile-time:</p>\n\n<pre><code>static_assert(CRGB::Black == 0);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T10:30:45.273",
"Id": "469978",
"Score": "0",
"body": "\"C++20 deprecated providing a user-defined operator= without a user-declared copy constructor\" really? Which paper did that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T13:50:55.603",
"Id": "469985",
"Score": "0",
"body": "@L.F.: I stand corrected! The deprecation happened in [depr.impldec](http://eel.is/c++draft/depr.impldec), which has been around [**since C++11**](https://timsong-cpp.github.io/cppwp/n3337/depr.impldec), not since C++20 as I had said. I just recently became aware of the deprecation, but now I can't figure out what changed to _make_ me aware of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T00:27:50.517",
"Id": "470033",
"Score": "0",
"body": "Oh, that's right. C++11 made user-defined move operations disable auto-generation of copy operations and destructor, but copy operations weren't made to do so for compatibility. So they deprecated it instead. Now I'm wondering how I forgot that ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T18:16:12.863",
"Id": "239571",
"ParentId": "239568",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239571",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:35:51.877",
"Id": "239568",
"Score": "2",
"Tags": [
"c++",
"game-of-life",
"arduino"
],
"Title": "Arduino Conways Game of Life using FastLED"
}
|
239568
|
<p>I'm trying to preprocess a large text document. I've written a text normalization function which takes a disproprtionate amount of time and memory. How can I format the function to lower these two?</p>
<p>The time result below was for this example.</p>
<pre><code>t = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst."
</code></pre>
<p>This is the script. </p>
<pre><code>import time
import string
import nltk
import numpy as np
# text preprocessing module, use boolean flags to customize function
def normalize_text(text, lowercase=True, punctuation=True):
# Step 1: Tokenize
output = nltk.word_tokenize(text)
# Step 2: Convert to lowercase (optional)
if lowercase:
output = [word.lower() for word in output]
# Step 3: Remove punctuation:
if punctuation:
output = [str(token).translate(str.maketrans('', '', string.punctuation)) for token in output]
output = [token for token in output if token != '']
return(output)
</code></pre>
<p>Removing all filters and the corresponding if-statements sped up processing by a mere 0.7%.</p>
<pre><code>def normalize_text2(text):
# Step 1: Tokenize
output = nltk.word_tokenize(text)
# Step 2: Convert to lowercase (optional)
output = [word.lower() for word in output]
# Step 3: Remove punctuation:
output = [str(token).translate(str.maketrans('', '', string.punctuation)) for token in output]
output = [token for token in output if token != '']
return(output)
</code></pre>
<p>Here is the bagged comparison.</p>
<pre><code>times1 = []
for i in range(1000):
start = time.time()
tokens = normalize_text(t)
end = time.time()
times1.append(end - start)
time1 = np.mean(times1)
print(time1)
times2 = []
for i in range(1000):
start = time.time()
tokens = normalize_text2(t)
end = time.time()
times2.append(end - start)
time2 = np.mean(times2)
print(time2)
print(time2/time1)
</code></pre>
<p>Here are the results:</p>
<pre><code>0.0021646411418914796
0.0021491129398345946
0.9928264312470212
</code></pre>
<p>Any advice on how to improve further? For example, how could I reduce the number of different list comprehensions, so that the same sequence of text does not need to crunched anew this many times?</p>
|
[] |
[
{
"body": "<p>You can save a little bit of time by not re-running <code>str.maketrans</code> for each token, since it's always going to produce the same result:</p>\n\n<pre><code>import nltk\nfrom statistics import mean\nimport string\nimport time\nfrom typing import List\n\n\ndef normalize_text3(text: str) -> List[str]:\n output: List[str] = []\n punctuation_filter = str.maketrans('', '', string.punctuation)\n for token in nltk.word_tokenize(text):\n token = token.translate(punctuation_filter)\n if not token:\n continue\n output.append(token.lower())\n return output\n</code></pre>\n\n<p>tested with:</p>\n\n<pre><code>for func in [normalize_text, normalize_text2, normalize_text3]:\n times = []\n for _ in range(1000):\n start = time.time()\n tokens = normalize_text(t)\n end = time.time()\n times.append(end - start)\n print(f\"{func.__name__.rjust(15)}: {mean(times)}\")\n</code></pre>\n\n<p>gets me:</p>\n\n<pre><code>dog runs\n normalize_text: 0.003226396322250366\nnormalize_text2: 0.0032752704620361327\nnormalize_text3: 0.0030987038612365725\n</code></pre>\n\n<p>If you want to lower memory consumption, you might consider having this function return a generator rather than a list...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:32:32.963",
"Id": "469930",
"Score": "0",
"body": "How would the code have to be modified to include the generator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:37:57.793",
"Id": "469932",
"Score": "0",
"body": "Your code took the longest on my machine --> normalize_text: 0.0020242140293121338\nnormalize_text2: 0.0019795351028442385\nnormalize_text3: 0.0020566964149475097"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:41:39.047",
"Id": "469933",
"Score": "1",
"body": "My results varied with repeated attempts; my version seemed to be faster about 75% of the time, bu t it's close enough that even with 1000 tries random futzing can make any of them the fastest. To use a generator you'd have to change the entire interface; I'm not sure how you're using this function so that may not be practical."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:24:02.360",
"Id": "239579",
"ParentId": "239569",
"Score": "2"
}
},
{
"body": "<p>A slight change to the answer:</p>\n\n<pre><code>def normalize_text4(text):\n output: List[str] = []\n punctuation_filter = str.maketrans('', '', string.punctuation)\n for token in nltk.word_tokenize(text, preserve_line=True):\n token = token.translate(punctuation_filter)\n if token:\n output.append(token.lower())\n return output\n</code></pre>\n\n<p>Usage with <code>preserve_line=True</code> is a bit faster, and with the punctuation removed, the result is the same as with the default <code>preserve_line=False</code>.\nAs most of the time is spent in <code>word_tokenize</code>, this is the first you want to optimize, though I haven't looked farther than this.</p>\n\n<p>Here is the measurement (same as above):</p>\n\n<pre><code>times = []\nbase = None\nfor fct in (normalize_text, normalize_text2, normalize_text3, normalize_text4):\n for i in range(1000):\n start = time.time()\n tokens = fct(t)\n end = time.time()\n times.append(end - start)\n\n avg = np.mean(times)\n if not base:\n base = avg\n print(f'{fct.__name__:15}: {avg * 1000:4.3} ms, {avg / base * 100:6.4} %')\n</code></pre>\n\n<p>and the results (on my Windows 10 notebook):</p>\n\n<pre><code>normalize_text : 4.88 ms, 100.0 %\nnormalize_text2: 4.86 ms, 99.44 %\nnormalize_text3: 4.64 ms, 94.93 %\nnormalize_text4: 3.85 ms, 78.88 %\n</code></pre>\n\n<p>The results vary, with the percentage somewhere between 74 and 82%, but this is a typical outcome.</p>\n\n<p><strong>EDIT:</strong><br>\nSomething I noticed afterwards, and that I don't have an explanation for: if you run <code>normalize_text4</code> <em>before</em> any of the other scripts (that use <code>preserve_line=False</code>) instead of after them, it is quite a bit faster:</p>\n\n<pre><code>normalize_text4: 1.81 ms, 41.07 %\nnormalize_text : 4.42 ms, 100.0 %\nnormalize_text4: 3.57 ms, 80.76 %\n</code></pre>\n\n<p>(I changed the script to have <code>normalize_text</code> as base like before)<br>\nI would guess that some caching is happening that is counter-productive in this (constructed) case. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T19:02:28.230",
"Id": "239625",
"ParentId": "239569",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239579",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T17:40:25.273",
"Id": "239569",
"Score": "1",
"Tags": [
"python",
"strings"
],
"Title": "increase speed & lower memory consumption of text normalization function"
}
|
239569
|
<p>The N-Queens puzzle can be solved in many ways. One is by a depth-first-search backtracking algorithm.</p>
<p>Below is my generalized version using mutual recursion:</p>
<pre><code>let dfsBacktrack initialValue solved getNextItems =
let rec procCurrent path =
match solved path with
| true -> Some path
| false -> procNext path (getNextItems path)
and procNext path nextItems =
match nextItems with
| [] -> None
| next::tail ->
match procCurrent (next::path) with
| Some solution -> Some solution
| None -> procNext path tail
procCurrent [ initialValue ]
</code></pre>
<p>The main problem with it is that it is not tail recursive so it builds up the stack with the limitations that leads to.</p>
<p>Anyway solving the N-Queens problem with it could look like:</p>
<pre><code>let queensProblem n =
if n < 4 then failwith "n must be greater than or equal to 4"
let solved queens = queens |> List.length = n
let getFields row = [0..n-1] |> List.map (fun col -> col, row)
let isValidField (col, row) (qcol, qrow) =
col <> qcol && row <> qrow // horz and vert
&& abs (col - qcol) <> abs (row - qrow) // diagonals
let reduceByQueen fields queen =
fields
|> List.where (fun pos -> isValidField pos queen)
let getValidFields queens =
let row = queens |> List.head |> (snd)
queens
|> List.fold reduceByQueen (getFields (row + 1))
dfsBacktrack (0, 0) solved getValidFields |> Option.get |> List.rev
</code></pre>
<p>For <code>n < 27</code> it finds a solution fairly quickly.</p>
<p>For <code>n = 8</code> it produces the output: <code>[(0, 0); (4, 1); (7, 2); (5, 3); (2, 4); (6, 5); (1, 6); (3, 7)]</code></p>
<p>The above algorithm can also be used to find a solution for the Knight's Tour-problem:</p>
<pre><code>let knightsTour n =
if n < 5 then failwith "n must be greater than or equal to 5"
let solved positions = positions |> List.length = n*n
let onboard (x, y) = x >= 0 && x < n && y >= 0 && y < n
let offsets = [ (2, 1); (2, -1); (1, 2); (1, -2); (-1, 2); (-1, -2); (-2, 1); (-2, -1) ]
let offset (x, y) (dx, dy) = x + dx, y + dy
let nextPositions path =
let pos = path |> List.head
let rec collect pos path recall =
let posses =
offsets
|> List.map (fun o -> offset pos o)
|> List.where (fun p -> onboard p && not (path |> List.contains p))
// Warnsdorff's rule
match recall with
| true ->
posses
|> List.map (fun pt -> pt, collect pt (pt::path) false |> List.length)
|> List.sortBy (fun (_, count) -> count)
|> List.map (fun (pt, _) -> pt)
| false -> posses
collect pos path true
dfsBacktrack (0, 0) solved nextPositions
</code></pre>
<hr>
<p>Another algorithm for the N-Queens problem is the <a href="https://en.wikipedia.org/wiki/Min-conflicts_algorithm" rel="nofollow noreferrer">Min-conflicts algorithm</a>, which shows to be much more efficient:</p>
<pre><code>let queensProblemByMinConflicts maxIterations n =
if n < 4 then failwith "n must be greater than or equal to 4"
let rand = Random(5)
let initQueens =
Array.init n id
|> Array.map (fun i -> i, (i * 2) % n) // map (fun i -> i, rand.Next() % n) //
let hasConflict (q1c, q1r) (q2c, q2r) = q1c = q2c || q1r = q2r || abs (q1c - q2c) = abs (q1r - q2r)
let getConflicts queen queens =
let conflicts =
queens
|> Array.where (fun q -> q <> queen && hasConflict queen q)
match conflicts with
| [||] -> None
| arr -> Some (arr)
let countConflicts queen queens =
match getConflicts queen queens with
| None -> 0
| Some conflicts -> conflicts |> Array.length
let indicesWithConflicts queens =
queens
|> Array.mapi (fun i q -> (i, q))
|> Array.where (fun (_, q) -> countConflicts q queens > 0)
|> Array.map (fst)
let minimizeConflicts (qc, qr) queens =
[| 0..n-1 |]
|> Array.where (fun r -> r <> qr)
|> Array.map (fun r -> (qc, r))
|> Array.groupBy (fun q -> countConflicts q queens)
|> Array.sortBy (fun (k, _) -> k)
|> Array.head
|> fun (_, qs) -> qs.[rand.Next(0, qs |> Array.length)]
let rec nextState queens iteration =
match indicesWithConflicts queens with
| [||] -> Some queens
| conflicts ->
match iteration with
| _ when iteration = maxIterations -> None
| _ ->
let curQueenIndex = conflicts.[rand.Next(0, conflicts |> Array.length)]
let curQueen = minimizeConflicts queens.[curQueenIndex] queens
queens.[curQueenIndex] <- curQueen
nextState queens (iteration + 1)
nextState initQueens 0
</code></pre>
<p>From an initial full - most likely invalid - configuration of N queens on the board (one queen per column), it recursively chooses randomly a queen with conflicts and positions that in its column on a field with the smallest number of conflicts. If more fields have the same smallest number of conflicts one is randomly chosen among them. In the above algorithm <code>maxIterations</code> makes it possible to return with no valid solution found instead of just continue infinitely. <code>nextState</code> is tail recursive.</p>
<p>With <code>let rand = Random(5)</code> and <code>n = 8</code> the following result is produced:</p>
<pre><code>[|(0, 4); (1, 1); (2, 3); (3, 5); (4, 7); (5, 2); (6, 0); (7, 6)|]
</code></pre>
<hr>
<p>I'm interested in any comment, but improvements of and tips about the use of F# as a language are very welcome.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T18:27:30.687",
"Id": "239574",
"Score": "3",
"Tags": [
"recursion",
"f#",
"depth-first-search",
"backtracking",
"n-queens"
],
"Title": "N-Queens Puzzle"
}
|
239574
|
<p>The natural logarithm can be approximated by the following formula:</p>
<p><span class="math-container">$$ln(x) = 2\sum_{k = 0}^{\infty}\frac{(x-1)^{2k+1}}{(2k+1)(x+1)^{2k+1}}$$</span></p>
<p>I've implemented this formula using Java. Parameter <code>n</code> is the amount of iterations to approximate the natural logarithm.</p>
<pre class="lang-java prettyprint-override"><code> static double lnApproximation(double x, int n) {
double ln = 0;
for (int k = 0; k < n; k++) {
double a = Math.pow(x - 1, 2*k + 1);
double b = 2*k + 1;
double c = Math.pow(x + 1, 2*k+1);
ln += a/(b*c);
}
return 2*ln;
}
</code></pre>
<p>I've noticed that my first version has potential to be optimized as calculated factors are not stored temporarily for the next iteration.</p>
<pre class="lang-java prettyprint-override"><code> /**
* Faster than lnApproximation by factor ~5.
* Still slower than Math.log that is calling the native system method.
*/
static double lnApproximationOptimized(double x, int n) {
double a = x - 1;
double aIteration = Math.pow(x - 1, 2);
double b = 1d;
double bIteration = 2d;
double c = x + 1;
double cIteration = Math.pow(x + 1, 2);
double ln = a/(b*c);
for (int k = 1; k < n; k++) {
a *= aIteration;
b += bIteration;
c *= cIteration;
ln += a/(b*c);
}
return 2*ln;
}
</code></pre>
<p>The optimized version is faster than the first version by the factor ~5. On my machine and the parameters <code>x = 1024</code>, <code>n = 32</code> the first version takes around 50000 ns to finish. The second version takes around 10000 ns to finish the same thing.</p>
<p>I got curious and wonder if there are more micro optimizations possible here?</p>
<hr>
<p><em>Two constraints: First, it has to be Java. Second, it has to be this formula.</em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T18:57:02.983",
"Id": "469928",
"Score": "0",
"body": "Have you measured performance? From one sample, you can't tell that the second algorithm is 5 times faster. You should compare the two curves."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:06:22.300",
"Id": "469929",
"Score": "0",
"body": "@ThomasWeller I've ran each function 10 times and have written down times using `System.nanoTime`. The first version takes on average 50k ns and the second version takes on average 10k. Of course this is far from professional benchmarking but we can say that the optimized function is faster for sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T13:22:28.233",
"Id": "469982",
"Score": "0",
"body": "Have you compared this approximation algorithm with actually invoking the functions? I am worried because the asker at https://stackoverflow.com/questions/45785705/logarithm-in-c-and-assembly benchmarked C++'s `std::log` function and gets, if I calculate correctly, 6ns per logarithm... That makes me assume I do not calculate correctly, but, more importantly, unless I'm off by a factor of ten thousand, it is faster than 10000ns. There's also a random blog article that accuses the `FYL2X` assembly instruction of taking up to 700 cycles, which is definitely much less than 10000 nanoseconds."
}
] |
[
{
"body": "<p>Since it's always <span class=\"math-container\">\\$n^2\\$</span> in the second version, by not using <code>java.lang.Math#pow</code> (<span class=\"math-container\">\\$n * n\\$</span>), you can save computation time. It takes me ±3k nanoseconds instead of the ±20k nanoseconds with the <code>java.lang.Math#pow</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> static double lnApproximationOptimized(double x, int n) {\n double a = x - 1;\n double aIteration = a * a;\n double b = 1d;\n double bIteration = 2d;\n double c = x + 1;\n double cIteration = c * c;\n double ln = a / (b * c);\n\n for (int k = 1; k < n; k++) {\n a *= aIteration;\n b += bIteration;\n c *= cIteration;\n ln += a / (b * c);\n }\n\n return 2 * ln;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T18:54:17.910",
"Id": "239576",
"ParentId": "239575",
"Score": "6"
}
},
{
"body": "<p>To speed it up a fraction more add <code>double dIteration = aIteration/cIteration;</code> and <code>double d = a/c;</code> before the loop. In the loop remove <code>a</code> and <code>c</code> and insert</p>\n\n<pre><code> d*= dIteration;\n ln += d/b;\n</code></pre>\n\n<p>You then have one multiplication, one division and an addition in the loop, cutting out two excess multiplications in your version. </p>\n\n<p>Edit: you can get further optimization (though perhaps outside the scope of your question) if you look at maths of your series. For <code>1/sqrt(10) < x <= sqrt(10)</code> you only need around 20 terms (because the ratio between successive terms is<code>$<0.26</code>). For <code>x</code> outside this range, find an <code>n</code> such th at <code>x_0*10**n = x</code> such that <code>x_0</code> is in this range (by repeated division or multiplication by 10) and use <code>ln(x) = ln(x_0) + n*ln(10)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:00:18.937",
"Id": "239577",
"ParentId": "239575",
"Score": "6"
}
},
{
"body": "<p>After applying the suggestions the function has changed as follows.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> static final double ln2;\n static final int twoExpLimit;\n static final double precision;\n static {\n int k = 0;\n int n = Integer.MAX_VALUE;\n while (n > 1) {\n n /= 2;\n k++;\n }\n twoExpLimit = k;\n // WolframAlpha\n ln2 = 0.693147180559945309417232121458176568075500134360255254120;\n precision = 1.0e-16;\n }\n\n /**\n * No way to optimize that further.\n */\n static double lnApproximationPerfect(double x) {\n int exponent = 1;\n int twoExp = 2;\n while (x > twoExp && exponent < twoExpLimit) {\n twoExp *= 2;\n exponent++;\n }\n x /= twoExp;\n\n double a = x - 1;\n double aIteration = a*a;\n double b = 1d;\n double bIteration = 2d;\n double c = x + 1;\n double cIteration = c*c;\n double d = a/c;\n double dIteration = aIteration/cIteration;\n double iteration = d/b;\n double ln = iteration;\n\n while (iteration < -precision || iteration > precision) {\n b += bIteration;\n d *= dIteration;\n iteration = d/b;\n ln += iteration;\n }\n return 2*ln + exponent*ln2;\n }\n</code></pre>\n\n<p>I've added a nicer way to approach the result by using a while-loop. Another thing I've added is the extraction of <span class=\"math-container\">\\$2^k\\$</span> from <span class=\"math-container\">\\$ln(x)\\$</span>, thus the approximation is simplified to <span class=\"math-container\">\\$ln(\\frac{x}{2^k})+ln(2^k)\\$</span>. This resolved the problem where the previous versions were getting very slow with growing <span class=\"math-container\">\\$x\\$</span>.</p>\n\n<p>I've tested it against <code>Math.log</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> long startTime;\n double testNumber = 3.14;\n double lnNative, lnCustom;\n long nativeTook, customTook;\n\n // Run the methods and print something for initialization.\n Math.log(testNumber - 1);\n lnApproximationPerfect(testNumber - 1);\n System.nanoTime();\n System.out.println(\"Start measurement:\");\n\n {\n startTime = System.nanoTime();\n lnNative = Math.log(testNumber);\n nativeTook = System.nanoTime() - startTime;\n\n startTime = System.nanoTime();\n lnCustom = lnApproximationPerfect(testNumber);\n customTook = System.nanoTime() - startTime;\n }\n\n System.out.println(\"Native: \" + nativeTook);\n System.out.println(\"Custom: \" + customTook);\n System.out.println(\"Native result: \" + lnNative);\n System.out.println(\"Custom result: \" + lnCustom);\n</code></pre>\n\n<p>It's still slower but not by much. I guess you cannot beat handwritten assembly code. ^^</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T18:13:01.020",
"Id": "470009",
"Score": "1",
"body": "Re the code comment *No way to optimize that further.* -- There most certainly is, which is to use a completely different algorithm. The constraint in the question restricts solutions to the given series. Library implementations are not constrained in this way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T21:55:59.210",
"Id": "470027",
"Score": "1",
"body": "If you want no-constraints fast Log approximations, you're going to want to look at getting the FP bit pattern as an integer. The exponent part of the floating point format already uses log2() so you only need a polynomial approximation for log that works over a range like `[0.5, 2)` or `[0.5, 1)` to handle the linear mantissa. My answer on [Efficient implementation of log2(__m256d) in AVX2](https://stackoverflow.com/q/45770089) explains in more detail, with links to fast `float` implementations. The same algorithm that works on every element of a SIMD vector also works scalar if you want."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T20:38:54.680",
"Id": "239584",
"ParentId": "239575",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239577",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T18:29:58.180",
"Id": "239575",
"Score": "8",
"Tags": [
"java",
"performance"
],
"Title": "log_e approximation"
}
|
239575
|
<p>everybody.
It took a tree of squares for my web game. I wrote a preview using Typescript. I would like to hear from you tips on how to improve the code (I just started writing in Typescript). First of all, I would like to improve performance. I have a couple of ideas but I don't know how to implement them:</p>
<ol>
<li>What if you don't keep dots in the tree itself but keep them inside
some array?</li>
<li>Are there more optimal insertion and intersection functions than I
have written</li>
<li>Is it better to write four subnodes directly or leave it as my
array?</li>
</ol>
<p>In my game the dots will move and there will be a lot of them (about 8-10 thousand, I take it it is correct to remove and recreate the tree every time?).</p>
<p>So let's start describing the code. First, there are two small classes for a point and a rectangle:</p>
<pre><code>// represent simple point on canvas
class Point {
x: number;
y: number;
constructor(x, y) {
this.x = x;
this.y = y;
}
move(x , y) {
this.x = x;
this.y = y;
}
}
// represent box (rectangle) on canvas
class Box {
x: number;
y: number;
w: number;
h: number;
constructor(x,y,w,h) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
contain(p: Point): boolean {
return (p.x >= this.x - this.w
&& p.x <= this.x + this.w
&& p.y >= this.y - this.h
&& p.y <= this.y + this.h)
}
}
</code></pre>
<p>Now the largest code fragment responsible for Node's representation</p>
<pre><code>// Maximum number of points after which the Node will be divided
const MAX_ELEMENTS: number = 5;
// Maximum depth of the QuadTree
const MAX_DEEP: number = 9;
// Represents a node in the quadtree
class QuadNode {
x: number;
y: number;
width: number;
height: number;
maxElements: number;
maxDeep: number;
divided: boolean;
// all points in Node
pointList: Point[];
children: QuadNode[];
constructor(x,y, width, height, deep) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.maxElements = MAX_ELEMENTS;
this.maxDeep = 0;
this.divided = false;
}
// Divide node into subnodes
split() {
this.divided = true;
let x = this.x;
let y = this.y;
let subWidth = this.width / 2;
let subHeight = this.height / 2;
let newDeep = this.maxDeep + 1;
this.children.push(new QuadNode(x - subWidth, y - subWidth, subWidth, subHeight, newDeep));
this.children.push(new QuadNode(x - subWidth, y + subWidth, subWidth, subHeight, newDeep));
this.children.push(new QuadNode(x + subWidth, y + subWidth, subWidth, subHeight, newDeep));
this.children.push(new QuadNode(x + subWidth, y - subWidth, subWidth, subHeight, newDeep));
}
// Node contain point? if yes - true
contain(p: Point): boolean {
return (p.x >= this.x - this.width
&& p.x <= this.x + this.width
&& p.y >= this.y - this.height
&& p.y <= this.y + this.height)
}
intersects (b: Box) {
return (b.x - b.w > this.x + this.width
|| b.x + b.w < this.x - this.width
|| b.y - b.h > this.y + this.height
|| b.y + b.h < this.y - this.height)
}
// The function returns an array of points that are contained inside a Box.
range(b: Box, points = []) {
if (!this.intersects(b)) {
return [];
} else {
for (let point of this.pointList) {
if (b.contain(point)) {
points.push(point);
}
}
if (this.divided) {
for (let child of this.children) {
child.range(b, points);
}
}
return points;
}
}
// Insert point into tree
insert(p: Point) {
if (this.divided) {
for (let child of this.children) {
if (child.contain(p)) {
child.insert(p);
}
}
} else {
if (this.maxDeep == MAX_DEEP) {
this.pointList.push(p);
} else {
if (this.pointList.length < this.maxElements) {
this.pointList.push(p);
} else if (this.pointList.length >= this.maxElements) {
this.split();
this.insert(p);
}
}
}
}
}
</code></pre>
<p>And finally, a small piece of code (for better api) representing the trees themselves:</p>
<pre><code>class QuadTree {
rootNode: QuadNode;
constructor(x,y,width,height, ) {
this.rootNode = new QuadNode(x,y,width,height, 0);
}
add(p: Point) {
this.rootNode.insert(p);
}
range(b: Box, points = []) {
this.rootNode.range(b,points);
}
};
</code></pre>
<p>Thank you very much!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:05:49.350",
"Id": "239578",
"Score": "2",
"Tags": [
"javascript",
"typescript",
"collision"
],
"Title": "Typescript QuadTree"
}
|
239578
|
<p>My target website is <a href="https://www.indeed.com/" rel="noreferrer">Indeed</a>. I tried to implement the scraper such that it is convenient for the end user. I am introducing my code in the readme file on my github repo.</p>
<p>I am somewhat a beginner in programming so I am looking for guidance on things such as if the libraries that I used are approriate, the code itself and on generally making the script better.</p>
<p>Link to the <a href="https://github.com/Viktor-stefanov/Jobs-Crawler/blob/master/README.md" rel="noreferrer">README</a> file.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
jobName = input('Enter your desired position: ').replace(' ', '-')
place = input("Enter the location for your desired work(City, state or zip): ")
URL = 'https://www.indeed.com/q-'+jobName+'-l-'+place.replace(' ', '-')+'-jobs.html'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
pages = soup.find(id='searchCountPages')
noPag = pages.text.split('of')[1].strip(' jobs').replace(',', '')
nmoPag = input(f"There are {noPag} number of pages. If you want to scrape all of them write 'Max' else write number of pages you wish to scrape: ")
if nmoPag == 'Max':
nmoPag = noPag
for i in range(0, int(nmoPag)*10, 10):
URL = 'https://www.indeed.com/jobs?q='+jobName+'&l='+place.replace(' ', '+')+'&start='+str(i)
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find(id='resultsCol')
listings = results.find_all('div', class_='result')
for job in listings:
jobT = job.find('a', class_='jobtitle')
jobL = job.find('span', class_='location').text.strip()
jobS = job.find('div', class_='summary').text.strip()
link = jobT['href']
if any(any(subs in s for s in (jobT.text.strip().lower(), jobS.lower())) for subs in (jobName.split('+')[0], jobName[1])):
print('Your job in '+jobL+' as a '+ jobT.text.strip()+
'.\nHere is a quick summary of your job here: '+
jobS+'\nLink for more information and application for the job - https://indeed.com'+link, end='\n\n\n')
</code></pre>
|
[] |
[
{
"body": "<p>What you are doing sounds reasonable overall.</p>\n\n<p>It's good that you are using F-strings:</p>\n\n<pre><code>nmoPag = input(f\"There are {noPag} number of pages. If you want to scrape all of them write 'Max' else write number of pages you wish to scrape: \")\n</code></pre>\n\n<p>But there are many other places where you don't eg:</p>\n\n<pre><code>print('Your job in '+jobL+' as a '+ jobT.text.strip()+\n '.\\nHere is a quick summary of your job here: '+\n jobS+'\\nLink for more information and application for the job - https://indeed.com'+link,\n</code></pre>\n\n<p>So I would upgrade the rest of the code for more consistency and better readability :)</p>\n\n<p><strong>Consistency</strong>: you are mixing lower case and upper case in some variable names eg <code>jobName</code> vs <code>place</code>. Remember that variable names are <strong>case-sensitive</strong> in Python. The practice could be dangerous and confusing. Imagine that you have jobName and jobname, it's two variables that may be assigned different values.</p>\n\n<p>There is <strong>redundancy</strong> in the use of functions, for example this bit of code is repeated twice:</p>\n\n<pre><code>jobT.text.strip()\n</code></pre>\n\n<p>Don't repeat yourself, just assign the result of <code>jobT.text.strip()</code> to a variable once, and reuse it.</p>\n\n<p>More repetition: <code>www.indeed.com</code> is hardcoded 3 times. Define a global variable for the root URL, then add the query string parameters as required.</p>\n\n<p>With the <code>urllib</code> library you could take advantage of the URI-building functions that are available to you. See <a href=\"http://www.compciv.org/guides/python/how-tos/creating-proper-url-query-strings/\" rel=\"nofollow noreferrer\">Creating URL query strings in Python</a>. Tip: if you want to build URIs but don't fire them immediately, you can also use <a href=\"https://requests.kennethreitz.org/en/master/user/advanced/#prepared-requests\" rel=\"nofollow noreferrer\">prepared requests</a>.</p>\n\n<p>Although in the present case, the site does not use classic query string parameters separated with a <code>&</code>. So you can instead use an F-string, again, with sanitized variable values:</p>\n\n<pre><code>url = f\"https://www.indeed.com/q-{jobName}-l-{place}-jobs.html\"\n</code></pre>\n\n<p>Note regarding user input: the most obvious is to check that the input is not empty. Always trim the input too, because some people might copy-paste text with extra tabs or spaces (think Excel). Maybe you could use a regex to replace multiple occurrences of whitespace with a single hyphen.</p>\n\n<p>I would also add more checks to make sure that all the DOM elements you are expecting were found - because a website is subject to change at any time. When that happens, the code must alert you.</p>\n\n<p>Finally, a quality script should have <strong>exception handling</strong> (10 lines of code would suffice). Catch exceptions always and log the full details to a file. This will help you a lot with debugging and troubleshooting.</p>\n\n<p>As your code is on Github, some people might want to use it. If they have problems with it, it would be good if they could attach a log in their bug report, so that you get better insight into the error.</p>\n\n<p>Since you are scraping a website, all sorts of errors will happen often: DNS resolution errors, timeouts, requests denied etc. Your script should handle those errors gracefully.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T20:33:29.140",
"Id": "470158",
"Score": "0",
"body": "I did some tinkering with the code this past hour. New and refined code on my github [repo](https://github.com/Viktor-stefanov/Jobs-Crawler). I would appreciate any subsequent feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T02:21:37.340",
"Id": "239596",
"ParentId": "239581",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239596",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T19:51:18.420",
"Id": "239581",
"Score": "4",
"Tags": [
"python",
"web-scraping"
],
"Title": "Web Scraping with Python"
}
|
239581
|
<p><em>The full repo is <a href="https://github.com/tomhosker/chancery-b" rel="nofollow noreferrer">here</a>, but I'll post the most important extracts below.</em></p>
<h2>Background</h2>
<p>I'm trying to get the hang of <strong>blockchain</strong> and <strong>public key cryptography</strong>, so I thought it would be fun to create a program for drawing up and promulgating government decrees - the government in question being one that I've just made up.</p>
<p>The system is intended to work like this:</p>
<ol>
<li>A government official in possession of the necessary passwords draws up a decree, stamps it with a digital stamp, and then adds it the register.</li>
<li>A private citizen then encounters decrees while going about his business:
<ul>
<li>If he encounters a decree in isolation, he can judge its authenticity using its stamp and the public key.</li>
<li>If he has access to the register, he can check that the government hasn't tried to hide an earlier decree by checking the chain of hashes.</li>
</ul></li>
</ol>
<h2>The Code</h2>
<p>This is the code in which I make and verify my <strong>stamps</strong>, the certificates which authenticate decrees:</p>
<pre class="lang-py prettyprint-override"><code>### This code defines two classes: one of which produces a digital stamp for
### documents issued by the Chancellor of Cyprus, and the other of which
### verfies the same.
# Imports.
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from pathlib import Path
import datetime, getpass, os
# Local constants.
path_to_digistamp = str(Path.home())+"/chancery-b/digistamp/"
path_to_private_key = path_to_digistamp+"stamp_private_key.pem"
path_to_public_key = path_to_digistamp+"stamp_public_key.pem"
public_exponent = 65537
key_size = 2048
encoding = "utf-8"
################
# MAIN CLASSES #
################
# A class which produces a string which testifies as to the authenticity of
# a given document.
class Stamp_Machine:
def __init__(self, data):
if os.path.exists(path_to_private_key) == False:
raise Exception("No private key on disk.")
self.private_key = load_private_key()
self.data = data
# Ronseal.
def make_stamp(self):
data_bytes = bytes(self.data, encoding)
result_bytes = self.private_key.sign(
data_bytes,
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH),
hashes.SHA256())
result = result_bytes.hex()
return result
# A class which allows the user to verify a stamp produced as above.
class Verifier:
def __init__(self, stamp, data):
if isinstance(stamp, str) == False:
raise Exception("")
self.stamp_str = stamp
self.stamp_bytes = bytes.fromhex(stamp)
self.public_key = load_public_key()
self.data = data
# Decide whether the stamp in question is authentic or not.
def verify(self):
data_bytes = bytes(self.data, encoding)
try:
self.public_key.verify(
self.stamp_bytes,
data_bytes,
padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH),
hashes.SHA256())
except InvalidSignature:
return False
else:
return True
####################
# HELPER FUNCTIONS #
####################
# Get a password from the user, and convert it into bytes.
def get_bytes_password():
password = getpass.getpass(prompt="Digistamp password: ")
result = bytes(password, encoding)
return result
# Get a NEW password from the user, and convert it into bytes.
def get_bytes_password_new():
password = getpass.getpass(prompt="Digistamp password: ")
password_ = getpass.getpass(prompt="Confirm password: ")
if password != password_:
raise Exception("Passwords do not match.")
result = bytes(password, encoding)
return result
# Generate a public key from a private key object.
def generate_public_key(private_key):
public_key = private_key.public_key()
pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo)
f = open(path_to_public_key, "wb")
f.write(pem)
f.close()
# Generate a new private and public key.
def generate_keys():
if os.path.exists(path_to_private_key):
raise Exception("Private key file already exists.")
bpw = get_bytes_password_new()
private_key = rsa.generate_private_key(public_exponent=public_exponent,
key_size=key_size,
backend=default_backend())
pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=
serialization.BestAvailableEncryption(bpw))
f = open(path_to_private_key, "wb")
f.write(pem)
f.close()
generate_public_key(private_key)
# Load the private key from its file.
def load_private_key():
bpw = get_bytes_password()
key_file = open(path_to_private_key, "rb")
result = serialization.load_pem_private_key(key_file.read(),
password=bpw,
backend=default_backend())
return result
# Load the public key from its file.
def load_public_key():
key_file = open(path_to_public_key, "rb")
result = serialization.load_pem_public_key(key_file.read(),
backend=default_backend())
return result
###########
# TESTING #
###########
# Run the unit tests.
def test():
stamp = Stamp_Machine("123").make_stamp()
assert(Verifier(stamp, "123").verify())
assert(Verifier(stamp, "abc").verify() == False)
print("Tests passed!")
###################
# RUN AND WRAP UP #
###################
def run():
test()
if __name__ == "__main__":
run()
</code></pre>
<p>This is the code in which a decree-in-the-making is <strong>uploaded</strong> to the register:</p>
<pre><code>### This code defines a class, which uploads a record to the ledger.
# Imports.
import datetime, hashlib, os, sqlite3
# Local imports.
from digistamp.digistamp import Stamp_Machine
import ordinance_inputs
# Constants.
encoding = "utf-8"
##############
# MAIN CLASS #
##############
# The class in question.
class Uploader:
def __init__(self):
self.connection = None
self.c = None
self.block = Block_of_Ledger()
# Ronseal.
def make_connection(self):
self.connection = sqlite3.connect("ledger.db")
self.connection.row_factory = dict_factory
self.c = self.connection.cursor()
# Ronseal.
def close_connection(self):
self.connection.close()
# Add the ordinal and the previous block's hash to the block.
def add_ordinal_and_prev(self):
self.make_connection()
query = "SELECT * FROM Block ORDER BY ordinal DESC;"
self.c.execute(query)
result = self.c.fetchone()
self.close_connection()
if result is None:
self.block.set_ordinal(1)
self.block.set_prev("genesis")
else:
self.block.set_ordinal(result["ordinal"]+1)
self.block.set_prev(result["hash"])
# Add the hash to the present block.
def add_hash(self):
m = hashlib.sha256()
m.update(bytes(self.block.ordinal))
m.update(bytes(self.block.ordinance_type, encoding))
m.update(bytes(self.block.latex, encoding))
m.update(bytes(self.block.year))
m.update(bytes(self.block.month))
m.update(bytes(self.block.day))
if self.block.annexe:
m.update(self.block.annexe)
m.update(bytes(self.block.prev, encoding))
self.block.set_the_hash(m.hexdigest())
# Add a new block to the legder.
def add_new_block(self):
new_block_tuple = (self.block.ordinal, self.block.ordinance_type,
self.block.latex, self.block.year,
self.block.month, self.block.day,
self.block.stamp, self.block.annexe,
self.block.prev, self.block.the_hash)
query = ("INSERT INTO Block (ordinal, ordinanceType, latex, year, "+
" month, day, stamp, annexe, prev, "+
" hash) "+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);")
self.make_connection()
self.c.execute(query, new_block_tuple)
self.connection.commit()
self.close_connection()
# Construct a new block and add it to the chain.
def upload(self):
self.add_ordinal_and_prev()
self.add_hash()
self.add_new_block()
################################
# HELPER CLASSES AND FUNCTIONS #
################################
# A class to hold the properties of a block of the ledger.
class Block_of_Ledger:
def __init__(self):
dt = datetime.datetime.now()
self.ordinal = None
self.ordinance_type = ordinance_inputs.ordinance_type
self.latex = ordinance_inputs.latex
self.year = dt.year
self.month = dt.month
self.day = dt.day
self.annexe = annexe_to_bytes()
self.prev = None
self.the_hash = None
self.stamp = None
# Assign a value to the "ordinal" field of this object.
def set_ordinal(self, ordinal):
self.ordinal = ordinal
# Assign a value to the "prev" field of this object.
def set_prev(self, prev):
self.prev = prev
# Assign a value to the "the_hash" field of this object.
def set_the_hash(self, the_hash):
self.the_hash = the_hash
self.stamp = Stamp_Machine(self.the_hash).make_stamp()
# A function which allows queries to return dictionaries, rather than the
# default tuples.
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
# Convert the annexe folder to a zip, load the bytes thereof into memory,
# and then delete the zip.
def annexe_to_bytes():
if len(os.listdir("annexe/")) == 0:
return None
os.system("zip -r annexe.zip annexe/")
f = open("annexe.zip", "rb")
result = f.read()
f.close()
os.system("rm annexe.zip")
return result
###################
# RUN AND WRAP UP #
###################
def run():
Uploader().upload()
if __name__ == "__main__":
run()
</code></pre>
<p>And this is the code in which decrees are <strong>extracted</strong> from the register and put into something more human-readable, i.e. a PDF:</p>
<pre><code>### This code defines a class which takes a given record in the ledger and
### converts it into a directory.
# Imports.
from uploader import dict_factory
import os, sqlite3, sys
# Local imports.
from digistamp.digistamp import Verifier
# Constants.
month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"]
##############
# MAIN CLASS #
##############
# The class in question.
class Extractor:
def __init__(self, ordinal):
self.ordinal = ordinal
self.block = self.fetch_block()
self.main_tex = self.make_main_tex()
# Fetch the block matching this object's ordinal from the ledger.
def fetch_block(self):
connection = sqlite3.connect("ledger.db")
connection.row_factory = dict_factory
c = connection.cursor()
query = "SELECT * FROM Block WHERE ordinal = ?;"
c.execute(query, (self.ordinal,))
result = c.fetchone()
connection.close()
if result is None:
raise Exception("No block with ordinal "+str(self.ordinal)+
" in the ledger.")
return result
# Get the base for main.tex, given the type of the Ordinance.
def get_base(self):
if self.block["ordinanceType"] == "Decleration":
path_to_base = "latexery/base_decleration.tex"
elif self.block["ordinanceType"] == "Order":
path_to_base = "latexery/base_order.tex"
else:
raise Exception("Invalid ordinanceType: "+
self.block["ordinanceType"])
f = open(path_to_base, "r")
result = f.read()
f.close()
return result
# Make the code for main.tex, which will then be used build our PDF.
def make_main_tex(self):
day_str = str(self.block["day"])
if len(day_str) == 0:
day_str = "0"+day_str
packed_ordinal = str(self.ordinal)
while len(packed_ordinal) < 3:
packed_ordinal = "0"+packed_ordinal
month_str = month_names[self.block["month"]-1]
result = self.get_base()
result = result.replace("#BODY", self.block["latex"])
result = result.replace("#DAY_STR", day_str)
result = result.replace("#MONTH_STR", month_str)
result = result.replace("#YEAR", str(self.block["year"]))
result = result.replace("#PACKED_ORDINAL", packed_ordinal)
result = result.replace("#DIGISTAMP", self.block["stamp"])
return result
# Check that the block isn't a forgery.
def authenticate(self):
self.compare_hashes()
self.verify_stamp()
# Compare the "prev" field of this block with the hash of the previous.
def compare_hashes(self):
if self.ordinal == 1:
if self.block["prev"] != "genesis":
raise Exception("Block with ordinal=1 should be the "+
"genesis block.")
else:
return
prev_ordinal = self.ordinal-1
connection = sqlite3.connect("ledger.db")
c = connection.cursor()
query = "SELECT hash FROM Block WHERE ordinal = ?;"
c.execute(query, (prev_ordinal,))
extract = c.fetchone()
connection.close()
prev_hash = extract["0"]
if prev_hash != self.block["prev"]:
raise Exception("Block with ordinal="+str(self.ordinal)+" is "+
"not authentic: \"prev\" does not match "+
"previous \"hash\".")
# Check that this block's stamp is in order.
def verify_stamp(self):
v = Verifier(self.block["stamp"], self.block["hash"])
if v.verify() == False:
raise Exception("Block with ordinal="+str(self.ordinal)+" is "+
"not authentic: \"prev\" does not match "+
"previous \"hash\".")
# Ronseal.
def write_main_tex(self):
f = open("latexery/main.tex", "w")
f.write(self.main_tex)
f.close()
# Compile the PDF.
def compile_main_tex(self):
script = ("cd latexery/\n"+
"pdflatex main.tex")
os.system(script)
# Create the directory, and copy the PDF into it.
def create_and_copy(self):
script1 = ("cd extracts/\n"+
"mkdir "+str(self.ordinal)+"/")
script2 = "cp latexery/main.pdf extracts/"+str(self.ordinal)+"/"
if os.path.isdir("extracts/"+str(self.ordinal)+"/"):
os.system("rm -r extracts/"+str(self.ordinal)+"/")
os.system(script1)
os.system(script2)
# Write annexe to a file in the directory.
def write_annexe_zip(self):
if self.block["annexe"] is None:
return
f = open("extracts/"+str(self.ordinal)+"/annexe.zip", "wb")
f.write(self.block["annexe"])
f.close()
# Do the thing.
def extract(self):
self.authenticate()
self.write_main_tex()
self.compile_main_tex()
self.create_and_copy()
self.write_annexe_zip()
# Ronseal.
def zip_and_delete(self):
script = ("cd extracts/\n"+
"zip -r ordinance_"+str(self.ordinal)+".zip "+
str(self.ordinal)+"/\n"+
"rm -r "+str(self.ordinal)+"/")
if os.path.exists("extracts/ordinance_"+str(self.ordinal)+".zip"):
os.system("rm extracts/ordinance_"+str(self.ordinal)+".zip")
os.system(script)
###########
# TESTING #
###########
# Run a demonstration.
def demo():
e = Extractor(1)
e.extract()
#e.zip_and_delete()
###################
# RUN AND WRAP UP #
###################
def run():
if len(sys.argv) == 2:
e = Extractor(int(sys.argv[1]))
e.extract()
else:
print("Please run me with exactly one argument, the number of the "+
"Ordinance you wish to extract.")
if __name__ == "__main__":
run()
</code></pre>
<h2>What I'd Like to Know</h2>
<ul>
<li><strong>Am I using blockchain and public key cryptography in a sane fashion?</strong> Or have I misunderstood some of the fundamental concepts involved?</li>
<li><strong>Are there any glaring security issues?</strong> Is there any obvious exploit in which someone could start manufacturing convincing forgeries?</li>
<li>How's my Python?</li>
</ul>
|
[] |
[
{
"body": "<p>Neat question! I'm afraid I ran out of steam before reaching anything too crypto-ish, though. There's a lot of Python to unpack here.</p>\n\n<p>The repeated comment \"Ronseal.\" is <a href=\"https://en.wikipedia.org/wiki/Does_exactly_what_it_says_on_the_tin\" rel=\"nofollow noreferrer\">cute if you know the reference</a> but I guess you know it doesn't help the reader; I'd rather save a line of screen real estate.</p>\n\n<p>Re Python style, I recommend running your code through <code>flake8</code> and fixing everything it complains about (with the possible exception of line-length warnings). It'll rightly complain about commented-out code like</p>\n\n<pre><code>#e.zip_and_delete()\n</code></pre>\n\n<hr>\n\n<pre><code>def write_annexe_zip(self):\n if self.block[\"annexe\"] is None:\n return\n f = open(\"extracts/\"+str(self.ordinal)+\"/annexe.zip\", \"wb\")\n f.write(self.block[\"annexe\"])\n f.close()\n</code></pre>\n\n<p>Either this is another in-joke that I <em>don't</em> get, or you misspelled \"annex.\" (You certainly misspelled \"declaration\" and \"ledger\" at least once each.) I also looked for anywhere you might have explained what an annex[e] actually <em>is</em> in this context, without success.</p>\n\n<p>If <code>f.write</code> throws an exception, then <code>f.close()</code> won't happen and you'll have leaked a file handle. It's always best to use RAII constructions for this kind of thing: i.e.,</p>\n\n<pre><code>def write_annexe_zip(self):\n if self.block[\"annexe\"] is not None:\n with open(\"extracts/%d/annexe.zip\" % self.ordinal, \"wb\") as f:\n f.write(self.block[\"annexe\"])\n</code></pre>\n\n<p>Looks like you haven't learned <code>printf</code> format strings yet. It's a really good investment in your career! Consider:</p>\n\n<pre><code> day_str = str(self.block[\"day\"])\n if len(day_str) == 0: ## I'm guessing this was a typo?!\n day_str = \"0\"+day_str\n packed_ordinal = str(self.ordinal)\n while len(packed_ordinal) < 3:\n packed_ordinal = \"0\"+packed_ordinal\n</code></pre>\n\n<p>versus what you could have written:</p>\n\n<pre><code> day_str = \"%02d\" % self.block[\"day\"]\n packed_ordinal = \"%03d\" % self.ordinal\n</code></pre>\n\n<p>Anything you can do to eliminate <em>mutation</em> (repeated overwriting) of your variables is a good thing for maintainability. In this case it's also shorter and clearer.</p>\n\n<hr>\n\n<pre><code> script1 = (\"cd extracts/\\n\"+\n \"mkdir \"+str(self.ordinal)+\"/\")\n</code></pre>\n\n<p>I'm surprised that <code>os.system()</code> allows you to pass multiple commands separated by newlines. However, here it would be clearer to do it in a single command. There's no reason for you to change working directories before creating the <code>extracts/foo</code> directory.</p>\n\n<pre><code>def create_and_copy(self):\n mypath = \"extracts/%d\" % self.ordinal\n if os.path.isdir(mypath):\n os.system(\"rm -r %s\" % mypath)\n os.system(\"mkdir -p %s\" % mypath)\n os.system(\"cp latexery/main.pdf %s\" % mypath)\n</code></pre>\n\n<hr>\n\n<pre><code>class Stamp_Machine:\n def __init__(self, data):\n if os.path.exists(path_to_private_key) == False:\n raise Exception(\"No private key on disk.\")\n self.private_key = load_private_key()\n self.data = data\n</code></pre>\n\n<ul>\n<li><p>Why is <code>path_to_private_key</code> not a <em>function parameter</em> to <code>load_private_key</code>?</p></li>\n<li><p>Why is <code>load_private_key</code> a free function? Shouldn't it be a private implementation detail (i.e., a member) of the <code>Stamp_Machine</code> class?</p></li>\n<li><p>The construction <code>if f() == False</code> would be better expressed as <code>if not f()</code>.</p></li>\n<li><p>Are you at all concerned that someone might remove the file in between the time you check for its existence and the time you read it? (This is a \"TOCTTOU\" vulnerability.)</p></li>\n<li><p>Are you at all concerned that someone might replace the file with another file, such as a private key under their personal control?</p></li>\n</ul>\n\n<hr>\n\n<pre><code> if isinstance(stamp, str) == False:\n raise Exception(\"\")\n self.stamp_str = stamp\n</code></pre>\n\n<p>This should at <em>least</em> raise <code>RuntimeError(\"expected a string\")</code>. And in reality, you shouldn't manually raise an exception at all; any operation that requires a string will eventually raise <code>TypeError</code>, which is plenty self-descriptive, and if no such operation ever takes place, then maybe you didn't need to raise an exception in the first place.</p>\n\n<p>You never use the member variable <code>self.stamp_str</code>, so you shouldn't be creating it.</p>\n\n<hr>\n\n<p>You repeatedly pass <code>backend=default_backend()</code> to crypto functions. That's redundant; by definition, the backend that will be used by default <em>is</em> the default backend.</p>\n\n<hr>\n\n<pre><code>password = getpass.getpass(prompt=\"Digistamp password: \")\npassword_ = getpass.getpass(prompt=\"Confirm password: \")\nif password != password_:\n raise Exception(\"Passwords do not match.\")\n</code></pre>\n\n<p>This seems to be conflating two different kinds of \"error handling.\" Superficially, this function's job seems to be to interact with the <em>user</em>, present a prompt to the <em>user</em>, and wait for the <em>user</em> to type in their new password. But then when the user makes a typo, you don't ask the <em>user</em> to fix their typo; you raise a programming exception indicating an unexpected failure to be handled by <em>code in your calling routine</em>. What's the calling routine supposed to do about it?</p>\n\n<p>This should just be a loop:</p>\n\n<pre><code>while True:\n password = getpass.getpass(prompt=\"Digistamp password: \")\n password_ = getpass.getpass(prompt=\"Confirm password: \")\n if password == password_:\n break\n print(\"Your two inputs did not match. Please try again.\")\n</code></pre>\n\n<hr>\n\n<pre><code># Add the hash to the present block.\ndef add_hash(self):\n</code></pre>\n\n<p>This function operates only on <code>self.block</code>. Shouldn't it be a member function of <code>Block_of_Ledger</code> instead?</p>\n\n<p>Incidentally, Python style would be CamelCase, e.g. <code>BlockOfLedger</code> or simply <code>LedgerBlock</code>.</p>\n\n<hr>\n\n<p>It is absolutely insane that creating a <code>Block_of_Ledger</code> object in Python — i.e., the single line</p>\n\n<pre><code>foo = Block_of_Ledger()\n</code></pre>\n\n<p>— causes the program to irretrievably delete files from disk. That just shouldn't happen. You should write a conspicuously named function that deletes files, and then use its result as a <em>parameter</em> to the constructor. E.g.:</p>\n\n<pre><code>annex = collect_annex_files(delete_from_disk=True)\nfoo = Block_of_Ledger(annex)\n</code></pre>\n\n<p>Similarly, <code>dt = datetime.datetime.now()</code> should be a parameter to the constructor. Everything you write should be unit-testable, and that means no hard dependencies on external realities like \"time\" or \"disk\" or \"network\" or \"database.\" Look up <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">dependency injection</a> and/or watch <a href=\"https://www.youtube.com/watch?v=u5senBJUkPc\" rel=\"nofollow noreferrer\">this excellent talk on unit-testing</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T15:52:31.317",
"Id": "469995",
"Score": "0",
"body": "Thank you for such a thoughtful and useful review. Inevitably, there are a few suggestions which I've decided **not** to carry out - although I've carried out all the others - and which I detail below..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T15:57:24.617",
"Id": "469996",
"Score": "0",
"body": "1. The spelling ***annexe*** is British English, like *axe* and *programme* (although not even I use the latter). It pains me every time Gmail tries to nudge me into using an American spelling, and this is my way of fighting back!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T16:06:55.703",
"Id": "469997",
"Score": "0",
"body": "2. I'm aware of `printf`-ery. (Would you believe that C was my first language?) And I like what you've done here. However, I'm going to keep things as they are because: (A) in Python, I'll always prefer something *verbose but clear* over something *terse*, and (B) I still have PTSD from my days as a C programmer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T16:10:41.803",
"Id": "469998",
"Score": "0",
"body": "3. So `backend=default_backend()` is redundant? Ah, that'll be why it throws an exception when I remove that snippet!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T16:29:37.327",
"Id": "469999",
"Score": "0",
"body": "4. Yes, the constructor of `Block_of_Ledger` calls a function which deletes a file, but that same function **creates** the file to be deleted only 4 lines up. I really don't find that insane - either absolutely or relatively."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T16:43:27.007",
"Id": "470000",
"Score": "0",
"body": "Thank you again. I've push the revised code to GitHub ([here](https://github.com/tomhosker/chancery-b)). I really want to get someone to look at security side of things. Now that the bulk of the lower-level issues have at least been discussed, what's the best way of achieving this? Should I ask a fresh question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T16:24:36.220",
"Id": "470130",
"Score": "0",
"body": "\"Should I ask a fresh question?\" — Probably yes. CodeReview etiquette forbids updating _this_ question in place; so your options are \"ask a fresh question re the updated code\" or \"go somewhere besides CodeReview\" (but I have no better options to suggest).\nRe 4.: Oops, I misread `zip -r annexe.zip annexe/ ... rm annexe.zip` as `rm -r annexe.zip annexe/`. That's less insane. It would still be good to use the `tempfile` module here, or even better, https://stackoverflow.com/questions/2463770/python-in-memory-zip-library to avoid touching the filesystem at all."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T21:36:45.090",
"Id": "239586",
"ParentId": "239583",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239586",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T20:29:32.583",
"Id": "239583",
"Score": "2",
"Tags": [
"python",
"cryptography",
"blockchain"
],
"Title": "A register of government decrees, authenticated with blockchain and public key cryptography"
}
|
239583
|
<p>I have a list of rule names coming from <em>.xml</em> file. These rule names needs to be validated against rule names in database (<code>Validator.cs)</code>. If valid, then <code>Id</code> of these rule names are used to fetch user data from database (<code>ExportService.cs</code>).</p>
<p>I am using a <code>Dictionary</code> object to save name, Id pair from database - </p>
<p><em>Validator.cs</em></p>
<pre><code>var rulesDictionary = new Dictionary<string, string>();
while (sqlDataReader.Read())
{
string ruleName = sqlDataReader["NAME"].ToString();
string ruleLink = sqlDataReader["LINK"].ToString();
rulesDictionary.Add(ruleName, ruleLink);
}
</code></pre>
<p>The values coming from XML file are validated against this dictionary as -</p>
<p>ExportService.cs</p>
<pre><code>if (DepositRulesDictionary.ContainsKey(xmlRuleName1) == false)
{
//log error
}
</code></pre>
<p>If all the values are valid, then this dictionary is further used to pass 'ruleLink' values in <em>ExportService.cs</em>.</p>
<p>I used Dictionary object in this instance as it returns O(1) result for validating XML file values. </p>
<p>My XML file is not going to be very big, so efficiency is not a major concern right now.</p>
<p>My question is what is more recommended - </p>
<ul>
<li><code>Dictionary<string, string></code> object or </li>
<li><code>List<T></code> where T is having two properties of Name and Link.</li>
</ul>
<p>For scalability and unit-testability?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T19:13:50.110",
"Id": "470018",
"Score": "0",
"body": "Why do you use a ´sqlDataReader´? Please don't write ADO.NET, instead use [Dapper](https://github.com/StackExchange/Dapper). Also, considering you seem to need the value belonging to a key, don't use `ContainsKey` but use `TryGetValue`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T19:14:06.513",
"Id": "470019",
"Score": "0",
"body": "This might be more on-topic over at [SoftwareEngineering](https://SoftwareEngineering.StackExchange.com/), but before posting there please [**follow their tour**](https://SoftwareEngineering.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://SoftwareEngineering.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://SoftwareEngineering.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://SoftwareEngineering.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-09T20:51:08.813",
"Id": "471165",
"Score": "0",
"body": "@BCdotWEB: Dapper is useful, and the OP should certainly consider it. But I wouldn't be so quick to dismiss the use of raw ADO.NET out-of-hand without understanding the broader context of the OP's application. For this case _per se_, Dapper might streamline this into a single line, but I'm not sure it's buying them all that much. Regardless, it's not really relevant either way to the OP's question."
}
] |
[
{
"body": "<p>I think you are too concerned with the implementation right now. </p>\n\n<p>The last part of the question </p>\n\n<blockquote>\n <p>... recommended ... for scalability and unit-testability?</p>\n</blockquote>\n\n<p>is the most important one.</p>\n\n<p>Let's imaging you were to write the test for this feature. You would start off by designing the API that the user of the functionality would ultimately consume. Secondly as far as the tests go ... they could careless how it is implemented 'under the hood' it only cares that it meets the requirements performance just being on possible requirement. Many times asymptotic complexity doesn't even play a critical role unless <code>n</code> is large. Take for example Strassen matrix multiplication it is only practical for larger matrices.</p>\n\n<p>For scalability I'm assuming you mean maintainability and extensibility. The best way to achieve that is to use the <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">dependency inversion principle</a> (DIP) so that you are not depending on either a list or a dict but instead on the correct abstraction.</p>\n\n<p>One possible abstraction is that the rules represent a validation.</p>\n\n<pre><code>interface IValidator<T>\n{\n bool IsValid(T item);\n}\n</code></pre>\n\n<p>Your test would look as follows.</p>\n\n<pre><code>[Test]\nvoid NoRulesEverythingIsFalse()\n{\n var rules = new Rules();\n Assert.False(rules.IsValid(\"\"));\n}\n\n[Test]\nvoid SingleRule()\n{\n var rules = new Rules(new[] \n {\n new LinkedRule(\"abc\", \"Only abc is allowed.\")\n });\n Assert.True(rules.IsValid(\"abc\"));\n Assert.AreEqual(\n rules.GetLinkForRule(\"abc\"),\n \"Only abc is allowed.\");\n Assert.False(rules.IsValid(\"123\"));\n}\n</code></pre>\n\n<p>Now with this you can implement it however you want as long as your test pass. Feel free to add a performance test if it is required.</p>\n\n<pre><code>// LinkedRule.cs\nstruct LinkedRule {\n string Rule { get; set; }\n string Link { get; set; }\n}\n</code></pre>\n\n<pre><code>// Rules.cs\nclass Rules : IValidator<string>\n{\n private Dictionary<string, LinkedRule> RulesToLinks { get; }\n\n public RuleValidator(IEnumerable<LinkedRule> linkedRules)\n {\n RulesToLinks = linkedRules.ToDictionary(\n x => x.Rule);\n }\n\n public bool IsValid(string rule) =>\n RulesToLinks.Keys.Contains(rule);\n\n public string GetLinkForRule(string rule) => RulesToLinks[rule];\n\n // ...\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T23:43:43.067",
"Id": "239592",
"ParentId": "239590",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T22:35:08.340",
"Id": "239590",
"Score": "1",
"Tags": [
"c#",
"hash-map",
"collections"
],
"Title": "Dictionary or custom Collection"
}
|
239590
|
<p>I have this method that attaches the year and year's rowspan for a TD and Quarter and a Quarter's rowspan for the TD.</p>
<p>Year and Quarter are 2 columns in an Angular Material Table which are calculated from an array of objects one of which property of the object is a date string.</p>
<p>Here is a demo for the code: <a href="https://stackblitz.com/edit/angular-ynpmdk" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ynpmdk</a></p>
<blockquote>
<p></p>
</blockquote>
<p><strong>This is my method which works fine, I wanted to review if I can shorten this method, looks very ugly. Open to suggestions.</strong></p>
<pre><code>/**
* Gets the year/quarter span information and filters what data is to be shown in tabs
* @param data launch data all
* @param mode which tab we are on
*/
getGroupData(data: DATA[]) {
data.sort((a:DATA, b:DATA) =>
!a.date ? -1
: !b.date
? -1 : (new Date(a.date).getTime() - new Date(b.date).getTime())
);
let cYear = data[0];
let cQuarter = data[0];
for (let i = 0; i < data.length; i++) {
if (data[i].date) {
const curDate = new Date(data[i].date);
const dateYear = new Date(cYear.date);
const dateQuarter = new Date(cQuarter.date);
// Get Year span and Year values
data[i].year = curDate.getFullYear();
cYear.year = dateYear.getFullYear();
if (cYear.year === data[i].year) {
cYear.yearSpan = (cYear.yearSpan || 0) + 1;
} else {
cYear = data[i];
cYear.yearSpan = 1;
}
// Get Quarter span and Quarter values
data[i].quarter = this.getQuarter(curDate.getMonth());
cQuarter.quarter = this.getQuarter(dateQuarter.getMonth());
if (cQuarter.quarter === data[i].quarter) {
cQuarter.quarterSpan = (cQuarter.quarterSpan || 0) + 1;
} else {
cQuarter = data[i];
cQuarter.quarterSpan = 1;
}
} else {
cYear = cQuarter = data[i];
cYear.yearSpan = cYear.quarterSpan = 1;
cYear.year = cYear.quarter = 'TBD';
if (i === data.length - 1) {
break;
} else {
cYear = cQuarter = data[i + 1];
}
}
}
return data;
}
/**
* Get the quarter info from month index
* @param month month index
*/
private getQuarter(month: number): string {
return `Q${Math.ceil((month + 1) / 3)}`;
}
</code></pre>
<p>A sample data object looks like</p>
<pre><code>{position: 1, name: 'Hydrogen', date: '2016-01-11', symbol: 'H'}
</code></pre>
<p>when the method is invoked the record becomes</p>
<pre><code>{
position: 1,
name: 'Hydrogen',
date: '2016-01-11',
symbol: 'H',
year: 2016,
quarter: 'Q1',
yearSpan: 5, // The other records have 5 entries pertaining to this year
quarterSpan: 2, // The other records have 2 entries pertaining to this quarter of this year
}
</code></pre>
<p>Here is a demo for the code: <a href="https://stackblitz.com/edit/angular-ynpmdk?file=src%2Fapp%2Ftable-basic-example.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-ynpmdk?file=src%2Fapp%2Ftable-basic-example.ts</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T23:31:19.267",
"Id": "239591",
"Score": "2",
"Tags": [
"javascript",
"angular-2+"
],
"Title": "Group data based on dates to populate a Material Angular table with rowspans"
}
|
239591
|
<p>I have written this code as a college assignment fot the famous <a href="https://www.geeksforgeeks.org/job-sequencing-problem/" rel="noreferrer">job sequencing problem</a>. Please tell me any improvements if possible. Oh, for <code>algorithms.h</code> header file, refer <a href="https://github.com/kesarling/cpp-projects/blob/master/algorithms.h" rel="noreferrer">my github repo</a> </p>
<p>The code: </p>
<pre><code>#include "algorithms.h"
struct Job {
int index = 0;
int time_slot = 0;
int profit = 0;
public:
Job() = delete;
explicit Job(int i, int time, int pr) {
index = i;
time_slot = time;
profit = pr;
}
bool operator>=(Job j) {
if ((this->time_slot == j.time_slot && this->profit >= j.profit) || (this->time_slot > j.time_slot)) {
return true;
}
return false;
}
bool operator<=(Job j) {
if ((this->time_slot == j.time_slot && this->profit <= j.profit) || (this->time_slot < j.time_slot)) {
return true;
}
return false;
}
bool operator<(Job j) {
if ((this->time_slot == j.time_slot && this->profit < j.profit) || (this->time_slot < j.time_slot)) {
return true;
}
return false;
}
bool operator>(Job j) {
if ((this->time_slot == j.time_slot && this->profit > j.profit) || (this->time_slot < j.time_slot)) {
return true;
}
return false;
}
bool operator==(Job j) {
if (this->time_slot == j.time_slot) {
return true;
}
return false;
}
friend std::ostream& operator<<(std::ostream& out, Job job) {
out << job.index;
return out;
}
};
int main() {
Job j1(1, 1, 3);
Job j2(2, 3, 5);
Job j3(3, 4, 20);
Job j4(4, 3, 18);
Job j5(5, 2, 1);
Job j6(6, 1, 6);
Job j7(7, 2, 30);
std::vector<Job> vect = { j1,j2,j3,j4,j5,j6,j7 };
vect = Sorter<Job>::mergeSort(vect);
auto order = [&]() {
auto it = vect.begin();
while (it + 1 != vect.end()) {
if (*it == *(it + 1)) {
it = vect.erase(it);
continue;
}
it++;
}
};
order();
std::for_each(vect.begin(), vect.end(), [](Job i) {std::cout << i << " "; });
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T07:06:35.997",
"Id": "469967",
"Score": "1",
"body": "Thank you for accepting my answer 1 minute 4 seconds after I posted it, but you may consider waiting for a couple of days to accept an answer. This gives other reviewers the opportunity to see the question and provide their answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T07:07:38.403",
"Id": "469969",
"Score": "0",
"body": "Okay. Sure :) I will keep this in mind henceforth"
}
] |
[
{
"body": "<p>The <code>Job</code> class has public members, so it's simpler to make it an aggregate:</p>\n\n<pre><code>struct Job {\n int index;\n int time_slot;\n int profit;\n};\n</code></pre>\n\n<p>Then, use <code>std::tie</code> to simplify the comparison operators: (operands to these operators should be marked as <code>const</code>, which you didn't)</p>\n\n<pre><code>bool operator<(const Job& lhs, const Job& rhs)\n{\n return std::tie(lhs.time_slot, lhs.profit) < std::tie(rhs.time_slot, rhs.profit);\n}\n\n// implement other operators in terms of <\n</code></pre>\n\n<p>You <code>==</code> is not consistent with other comparison operators, which is confusing and likely to cause problems.</p>\n\n<p>Also note that <code>if (condition) { return true; } return false;</code> should be changed to <code>return condition;</code> for clarity.</p>\n\n<p>This is convoluted:</p>\n\n<blockquote>\n<pre><code>Job j1(1, 1, 3);\nJob j2(2, 3, 5);\nJob j3(3, 4, 20);\nJob j4(4, 3, 18);\nJob j5(5, 2, 1);\nJob j6(6, 1, 6);\nJob j7(7, 2, 30);\nstd::vector<Job> vect = { j1,j2,j3,j4,j5,j6,j7 };\n</code></pre>\n</blockquote>\n\n<p>It should be simplified to</p>\n\n<pre><code>std::vector<Job> vect {\n {1, 1, 3}, {2, 3, 5}, // ...\n};\n</code></pre>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code>auto order = [&]() {\n auto it = vect.begin();\n while (it + 1 != vect.end()) {\n if (*it == *(it + 1)) {\n it = vect.erase(it);\n continue;\n }\n it++;\n }\n};\norder();\n</code></pre>\n</blockquote>\n\n<p>should be</p>\n\n<pre><code>vect.erase(std::unique(vect.begin(), vect.end()), vect.end());\n</code></pre>\n\n<p>(provided that I understand the code correctly).</p>\n\n<p>And this:</p>\n\n<blockquote>\n<pre><code>std::for_each(vect.begin(), vect.end(), [](Job i) {std::cout << i << \" \"; });\n</code></pre>\n</blockquote>\n\n<p>is a complicated way of writing</p>\n\n<pre><code>for (const auto& job : vect) {\n std::cout << job << ' ';\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>std::copy(vect.begin(), vect.end(),\n std::ostream_iterator<Job>{std::cout, ' '});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T07:07:08.347",
"Id": "469968",
"Score": "0",
"body": "Thanks a lot. Well, I tried the `std::unique` thing looking at the SO questions asked on it. It somehow doesn't work. I mean, it does not do what's expected. The problem is that it is not calling my overloaded operator. How do I go about this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T07:12:13.430",
"Id": "469970",
"Score": "1",
"body": "@cpplover `std::unique` should call the `==` associated with `Job`. It is possible that failing to mark your `operator==` as `const` made `std::unique` unable to pick it up. Anyway, you should not overload `==` just for the purpose of `std::unique` - pass a custom comparator instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T22:21:50.910",
"Id": "470030",
"Score": "1",
"body": "@cpplover std::unique is calling your comparison function, the difference is in how it eliminates duplicates. Your `order()` handles consecutive duplicates by removing the _first_ duplicate, whereas `std::unique` will leave the first, and move any that _follow_ to the end of the list. So, when you use `std::unique` you get the same result in terms of `.time_slot` (1, 2, 3, 4), but the jobs retained are different. (Enhancing the `<<` operator to output the entire Job triple, not just the `.index` makes inspection easier.) You might be able to finesse your behavior with reverse iterators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-05T07:45:30.440",
"Id": "470675",
"Score": "0",
"body": "+1 for \" if (condition) { return true; } return false; should be changed to return condition;\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T07:03:38.343",
"Id": "239600",
"ParentId": "239598",
"Score": "5"
}
},
{
"body": "<ol>\n<li><code>public:</code> is excess in a <code>struct</code>.</li>\n<li>Members directly initialized in ctors are better directly initialized:</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>Job(int index, int time_slot, int profit)\n : index(index), time_slot(time_slot), profit(profit) {}\n</code></pre>\n\n<p>only more complex logic should go in ctor's body, if any.</p>\n\n<ol start=\"3\">\n<li>As a matter of fact,</li>\n</ol>\n\n<pre class=\"lang-cpp prettyprint-override\"><code> if(cond) {\n return true;\n }\n return false;\n</code></pre>\n\n<p>is actually <code>return cond;</code>, indeed.</p>\n\n<ol start=\"4\">\n<li><code>this-></code> simply increases the code size without any additional benefits.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T09:18:32.723",
"Id": "469975",
"Score": "2",
"body": "\"explicit is excess for a ctor of arity greater than one.\" Actually no, `explicit` prevents copy-list-initialization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T04:21:27.697",
"Id": "470065",
"Score": "0",
"body": "@L.F. Thanks, forgot."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T07:59:45.530",
"Id": "239602",
"ParentId": "239598",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239600",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T06:12:23.727",
"Id": "239598",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"vectors"
],
"Title": "A job sequencing solution"
}
|
239598
|
<p>I was working on making a cache in bash and I found <a href="https://codereview.stackexchange.com/questions/170958/memoizing-or-caching-bash-function-results">this link</a> - But this guy is attempting to generate new bash functions by introspecting their source and generating a new one as a cache. This seems to me, way overkill. Here is my implementation and it works just fine:</p>
<pre><code>cache() {
local file
file="/tmp/$(printf "%s" ${@})"
if [[ -f "${file}" && $(($(date +%s) - $(date -r "$file" +%s))) -le 1800 ]]; then
cat "${file}"
else
${1} ${@:2} | tee "${file}"
fi
}
mkurls() {
local url="${1:?You must supply a URL}"
local batchSize=${2:-100}
local repoCount
repoCount=$(curl -fsnL "$url?pagelen=0&page=1" | jq -re .size)
local pages=$(((repoCount / batchSize) + 1))
printf "$url?pagelen=${batchSize}&page=%s\n" $(seq 1 "$pages")
}
bbusers() {
_users() {
mkurls https://api.bitbucket.org/2.0/teams/twengg/members/ |
xargs -n 30 -P 20 curl -fsnL | jq -ser '.[].values[] | "\(.display_name), \(.links.self.href)" ' | sort
}
cache _users $@
}
</code></pre>
<p>and here are the results:</p>
<pre><code>$ time bbusers &> /dev/null
#output
real 0m5.670s
user 0m0.184s
sys 0m0.099s
$ time bbusers &> /dev/null # seconds later
real 0m0.053s
user 0m0.010s
sys 0m0.017s
</code></pre>
<p>As you can see, it's literally 100x faster. If I delete the file behind the cache:</p>
<pre><code>$ rm -fR /tmp/_users
$ time bbusers &> /dev/null
real 0m4.924s
user 0m0.170s
sys 0m0.082s
</code></pre>
<p>It goes right back to normal. So, how can this be improved and what am I missing that warrants such a wildly complicated approach as the other guy has?</p>
|
[] |
[
{
"body": "<p>As the \"guy\" in question, I'm happy to discuss my approach :) feel free also to file issues on <a href=\"https://github.com/dimo414/bash-cache\" rel=\"nofollow noreferrer\">GitHub</a> if you have feedback.</p>\n\n<p>You are certainly correct that <a href=\"https://unix.stackexchange.com/q/125819/19157\">decorating functions</a> as bash-cache does isn't necessary, but the intent is to simplify the development experience - to memoize a function all you have to do is make a call to <code>bc::cache</code>, and bash-cache (generally) handles the rest. No need to keep separate functions in sync or wrestle with naming schemes. Whether that's a feature or overkill is in the eye of the beholder, but I find it very flexible and expressive :)</p>\n\n<p>As you've shown it's not too complicated to implement a reasonable caching mechanism in Bash, but the devil is really in the details. With bash-cache I've addressed a number of very subtle issues that most caching implementations fail to handle, including:</p>\n\n<ul>\n<li>stdout and stderr are both cached and preserved separately (your approach only caches stdout, other approaches merge the two streams with <code>>&</code>)</li>\n<li>the return code of the function is also preserved, few other implementations I've seen do this (correctly)</li>\n<li>avoids a <a href=\"https://stackoverflow.com/a/49552002/113632\">common gotcha</a> with command substitutions (<code>$(...)</code>), which are actually lossy</li>\n<li>stale cache data is regularly cleaned up in the background</li>\n<li>caches are separated by user and <code>chmod</code>-ed to only be readable by that user; a global cache risks leaking sensitive data</li>\n</ul>\n\n<hr>\n\n<p>Since this is CodeReview.SE, some tips on your approach:</p>\n\n<ul>\n<li>Be sure to consistently quote all variables, including arrays like <code>\"$@\"</code>; without quotes Bash will expand variables and arrays with word-splitting, which is rarely desirable and often leads to bugs. In your code it's likely that whitespace arguments will break things. It's a great idea to run any shell code through <a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\">ShellCheck</a> and address the issues it flags.</li>\n<li><code>file=\"/tmp/$(printf \"%s\" ${@})\"</code> is unsafe, as it munges arguments together without a delimiter, e.g. it will treat <code>foo 12 3</code> and <code>foo 1 23</code> as the same set of arguments. It also will fail if any arguments contain invalid filename characters (notably <code>/</code>), which is (part of) why bash-cache hashes the arguments.</li>\n<li>It's probably a good idea to asynchronously delete the cache file when it's too old, instead of making multiple <code>date</code> calls in subshells to determine whether the file is still valid. I'd have to benchmark to be sure but I suspect it will be faster.</li>\n<li><code>${1} ${@:2}</code> isn't necessary, just say <code>\"$@\"</code> (note the quotes)</li>\n<li>Bash doesn't support nested/anonymous functions, so what you're doing in <code>bbusers</code> is actually just re-defining <code>_users</code> in the top-level namespace on every invocation, which isn't necessary or helpful. Just define <code>_users</code> as a normal function and then: <code>bbusers() { cache _users \"$@\"; }</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-14T08:01:34.263",
"Id": "471739",
"Score": "0",
"body": "All very good tips! As for your \"$@\" - I misunderstood what it meant by splitting. My intent is \"give it to me, as is\" so, if someone had `ab \"c e\" d` that is exactly what I wanted passed in. I will address these all. And, if you're interested, I have this in a repo https://github.com/chb0github/bashful - i'd welcome more input"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-14T08:04:54.463",
"Id": "471741",
"Score": "0",
"body": "BTW: I am not sure of the wisdom of caching errors - errors usually respond fast and don't need caching and frequently they are transient (so, you'd want to try again). So, if I run a command with the same args, It would have to know, per function implementation, when to invalidate the cache and not"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-14T08:56:36.557",
"Id": "471747",
"Score": "0",
"body": "You're right that caching errors may not be desirable in certain circumstances, but in the shell many commands use exit codes to communicate more than just errors. For example `grep` returns a non-zero exit code if no match is found. My goal with bash-cache is to provide cached results that are as high-fidelity as possible, and work for all commands, rather than make an opinionated decision about how errors should be handled that may or may not be desirable in certain circumstances. But feel free to file a FR or send a PR if you'd like to have a `bc::cache_success` variant :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-13T21:21:26.740",
"Id": "240461",
"ParentId": "239599",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T06:15:16.163",
"Id": "239599",
"Score": "2",
"Tags": [
"bash",
"cache"
],
"Title": "Comparing two bash caches"
}
|
239599
|
<p>Please check the following the LRU cache implementation.</p>
<p>Thanks for the valuable comments</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
public class LRUCache {
HashMap<Integer, Node> lruHashMap = new HashMap<>();
private final int DEFAULT_CACHE_SIZE =5;
int capacity = 0;
class Node{
int value;
Node prev, next;
public Node(int value, Node prev, Node next){
this.value = value;
this.prev = prev;
this.next = next;
}
public Node(int value){
this.value = value;
this.prev = null; this.next = null;
}
}
Node head;
Node tail;
public void addData(int value){
if(head == null) {
head = new Node(value);
tail = head;
capacity++;
lruHashMap.put(value, head);
return;
}
if( lruHashMap.containsValue(value)) {
// Item already at the linkedList and map
// Delete node first
Node deleteNode = lruHashMap.get(value);
deleteNode.next.prev = deleteNode.prev;
deleteNode.prev.next = deleteNode.next;
deleteNode = null;
}
Node newNode = new Node(value,null,head);
// Add item to head
head.prev = newNode;
head = head.prev;
lruHashMap.put(value,newNode);
++capacity;
checkSize(capacity);
}
private void checkSize(int capacity) {
if(capacity > DEFAULT_CACHE_SIZE) {
// remove last element
removeLast();
}
}
private void removeLast() {
int value = tail.value;
tail = tail.prev;
tail.next = null;
--capacity;
lruHashMap.remove(value);
}
private void getDataOfLRUCache(){
for(Map.Entry<Integer,Node> entry: lruHashMap.entrySet()){
System.out.print (entry.getKey() + " - " );
System.out.println(entry.getValue() );
}
}
public boolean isEmpty() {
return capacity == 0;
}
public static void main(String args[]){
LRUCache lruCache = new LRUCache();
lruCache.addData(5);
lruCache.addData(6);
lruCache.addData(7);
lruCache.addData(8);
lruCache.addData(9);
// lruCache.getDataOfLRUCache();
lruCache.addData(11);
lruCache.addData(12);
lruCache.getDataOfLRUCache();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T10:43:40.427",
"Id": "469979",
"Score": "0",
"body": "You could use a LinkedHashMap is specially useful for implementing an LRUCache, as it maintains a double-linked list for you"
}
] |
[
{
"body": "<p>I have some advices for you.</p>\n\n<ul>\n<li>Add the <code>static</code> keyword to the <code>DEFAULT_CACHE_SIZE</code> variable (<a href=\"https://en.wikipedia.org/wiki/Naming_convention_(programming)#Java\" rel=\"nofollow noreferrer\">all cap snake case</a> = constant).</li>\n</ul>\n\n<h3>Use the size of the map instead of using the <code>capacity</code> variable</h3>\n\n<p>You can use <code>java.util.HashMap#size</code>. In my opinion, it will be less error-prone to do so (If you forget to update it, ect).</p>\n\n<h3>Avoid using <code>C-style</code> array declaration</h3>\n\n<p>In the main method, you declared a <code>C-style</code> array declaration with the <code>args</code> variable.</p>\n\n<p><strong>before</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String args[]\n</code></pre>\n\n<p><strong>after</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String[] args\n</code></pre>\n\n<p>In my opinion, this style is less used and can cause confusion.</p>\n\n<h2>Potential issues</h2>\n\n<h3>Never expose directly Arrays / Collections / Maps to external classes</h3>\n\n<p>In this case, the <code>lruHashMap</code> map is exposed to any other instances, I highly suggest that you put the <code>private</code> keyword to hide the instance. If you don’t do so, any other classes can edit the map directly and your class will lose control over its own data.</p>\n\n<h3>Always compare objects of the same type</h3>\n\n<p>In the method <code>LRUCache#addData</code>, when you are checking if the <code>lruHashMap</code> contains the value, you are comparing <code>java.lang.Integer</code> with <code>Node</code>. You probably wanted to use the <code>java.util.HashMap#containsKey</code> instead.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nif (lruHashMap.containsValue(value)) { // Bug, will always return false\n//[...]\n</code></pre>\n\n<h3>By setting the object null, when coming from a collection, it does not delete it from the collection.</h3>\n\n<p>In this case, in the <code>LRUCache#addData</code> method, you set the object null to delete it ? This will only affect the current reference of the variable <code>deleteNode</code>; not the object in the map.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// Item already at the linkedList and map\n// Delete node first\n\nNode deleteNode = lruHashMap.get(value);\ndeleteNode.next.prev = deleteNode.prev;\ndeleteNode.prev.next = deleteNode.next;\ndeleteNode = null; // Set the `deleteNode` to null\n</code></pre>\n\n<h2>Refactored code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code> public class LRUCache {\n private HashMap<Integer, Node> lruHashMap = new HashMap<>();\n\n private static final int DEFAULT_CACHE_SIZE = 5;\n private Node head;\n private Node tail;\n\n class Node {\n int value;\n Node prev, next;\n\n public Node(int value, Node prev, Node next) {\n this.value = value;\n this.prev = prev;\n this.next = next;\n }\n\n public Node(int value) {\n this.value = value;\n this.prev = null;\n this.next = null;\n }\n }\n\n public void addData(int value) {\n if (head == null) {\n head = new Node(value);\n tail = head;\n lruHashMap.put(value, head);\n return;\n }\n\n if (lruHashMap.containsKey(value)) {\n // Item already at the linkedList and map\n // Delete node first\n\n Node deleteNode = lruHashMap.get(value);\n deleteNode.next.prev = deleteNode.prev;\n deleteNode.prev.next = deleteNode.next;\n // lruHashMap.remove(value); uncomment if you want to remote the item from the map\n }\n\n Node newNode = new Node(value, null, head);\n // Add item to head\n head.prev = newNode;\n head = head.prev;\n\n lruHashMap.put(value, newNode);\n\n checkSize();\n }\n\n private void checkSize() {\n if (lruHashMap.size() > DEFAULT_CACHE_SIZE) {\n // remove last element\n removeLast();\n }\n }\n\n\n private void removeLast() {\n int value = tail.value;\n\n tail = tail.prev;\n tail.next = null;\n\n lruHashMap.remove(value);\n }\n\n private void getDataOfLRUCache() {\n\n for (Map.Entry<Integer, Node> entry : lruHashMap.entrySet()) {\n System.out.print(entry.getKey() + \" - \");\n System.out.println(entry.getValue());\n }\n }\n\n\n public boolean isEmpty() {\n return lruHashMap.isEmpty();\n }\n\n public static void main(String[] args) {\n LRUCache lruCache = new LRUCache();\n\n lruCache.addData(5);\n lruCache.addData(6);\n lruCache.addData(7);\n lruCache.addData(8);\n lruCache.addData(9);\n\n // lruCache.getDataOfLRUCache();\n\n lruCache.addData(11);\n lruCache.addData(12);\n lruCache.getDataOfLRUCache();\n }\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T14:30:46.097",
"Id": "239610",
"ParentId": "239605",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "239610",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T08:44:54.637",
"Id": "239605",
"Score": "2",
"Tags": [
"java",
"cache"
],
"Title": "LRU Cache Example"
}
|
239605
|
<p>I'm a very new Haskell programmer, and I've written the following code for loading TSV files. I think it can be improved, but I'm not sure how.</p>
<ol>
<li>I feel like the giant "do" block in loadData is inelegant, and that there's likely a better way to approach this.</li>
<li>I think I'm trying to avoid the IO monad because I'm not sure how to work with it, but that there's probably a better way to handle mapping <code>parseTSV</code> over the contents of the files.</li>
</ol>
<p>One note: I'm not super concerned about performance - this will run once at the beginning of my program. I want to load in all the files entirely to build a composite data structure from their contents.</p>
<pre><code>module LanguageMachine (loadData) where
import System.Directory (listDirectory)
import Data.List ((\\), elemIndex)
import Data.Maybe (mapMaybe)
parseTsv :: String -> [(String, Int)]
parseTsv contents = mapMaybe parseLine (lines contents)
parseLine :: String -> Maybe (String, Int)
parseLine line =
case elemIndex '\t' line of
Just i ->
let
(word, count) = splitAt i line
in
Just (word, read count :: Int)
Nothing -> Nothing
loadData :: FilePath -> [FilePath] -> IO [(String, [(String, Int)])]
loadData path exclude = do
files <- listDirectory path
let filtered = files \\ exclude
let prefixed = map ((path ++ "/") ++) filtered
contents <- traverse readFile prefixed
let results = map parseTsv contents
return $ zip filtered results
</code></pre>
<p>The files look like this, which are two-value TSV lines of a word and then the number of occurrences of that word:</p>
<pre><code>ARIA 4308
ORE 4208
</code></pre>
<p>Thank you!</p>
|
[] |
[
{
"body": "<p>The <code>loadData</code> function looks just fine to me. I don't see a way it could be any more elegant given what it's doing. I do actually like the way you have separated reading the file and parsing it. That's the way to go. </p>\n\n<p>Your concern about \"avoiding the IO monad\" shouldn't be a concern. On the contrary, that's actually a \"best practice\", known as \"pushing I/O to the boundary\". It means that the majority of your program should be pure, and only a thin shell should deal with external world. This way you can easily test and debug the majority of your program.</p>\n\n<p>The only thing I might do is make the last three lines one expression:</p>\n\n<pre><code>traverse readFile prefixed\n <&> map parseTsv\n <&> zip filtered\n</code></pre>\n\n<p>I find this a bit more readable, but that's just a matter of personal taste.</p>\n\n<hr>\n\n<p>But the <code>parseLine</code> function could sure use some improvement.</p>\n\n<p><strong>First,</strong> the control flow. Look what it's doing: compute a <code>Maybe</code> value, then if it's <code>Just</code>, compute another <code>Maybe</code> value from its contents. That's exactly what \"bind\" does! This means it can be nicely represented as a <code>do</code> block.</p>\n\n<p><strong>Second,</strong> <code>read</code> is a partial function. This means it can fail at runtime if there is a non-number in the file. I understand this probably Should Never Happen™, but you'd be surprised how many things that \"should never happen\" do, in fact, happen all the time. :-)</p>\n\n<p>But since you're already in the <code>Maybe</code> context, it would be easy to use <a href=\"https://www.stackage.org/haddock/lts-15.5/base-4.13.0.0/Text-Read.html#v:readMaybe\" rel=\"nofollow noreferrer\"><code>readMaybe</code></a> instead, and skip the malformed numbers.</p>\n\n<p>Applying both points:</p>\n\n<pre><code>parseLine line = do\n i <- elemIndex '\\t' line\n let (word, strCount) = splitAt i line\n count <- readMaybe strCount\n return (word, count)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T20:44:26.257",
"Id": "470024",
"Score": "0",
"body": "Thank you! The <&> operator is very handy. I'm still getting comfortable thinking in monads, so your feedback is very helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:42:52.797",
"Id": "470079",
"Score": "0",
"body": "Glad I could help!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T15:32:46.423",
"Id": "239615",
"ParentId": "239608",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239615",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T12:06:51.567",
"Id": "239608",
"Score": "4",
"Tags": [
"haskell",
"file-system",
"monads"
],
"Title": "Loading Files from a Directory in Haskell"
}
|
239608
|
<h1>Problem</h1>
<p>A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.</p>
<p>Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].</p>
<p>The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|</p>
<p>In other words, it is the absolute difference between the sum of the first part and the sum of the second part.</p>
<p>For example, consider array A such that:</p>
<pre><code>A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
</code></pre>
<p>We can split this tape in four places:</p>
<pre><code>P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7
</code></pre>
<p>Write a function:</p>
<p>function solution(A);</p>
<p>that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.</p>
<pre><code>For example, given:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
the function should return 1, as explained above.
</code></pre>
<p>Write an efficient algorithm for the following assumptions:</p>
<p>N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−1,000..1,000].</p>
<h1>My solution:</h1>
<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>A = []
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
function solution(A) {
// write your code in JavaScript (Node.js 8.9.4)
if (A.length > 0) {
let defArr = [];
let l = [];
let all = A.reduce((a, b) => {
l.push(a)
return a + b
})
l.forEach((item) => {
defArr.push(Math.abs(all - (item + item)))
})
return Math.min(...defArr)
}
return 0;
}
console.log(solution(A))</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T15:37:19.727",
"Id": "469993",
"Score": "0",
"body": "Will the person that down voted this question please provide a comment explaining why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T16:08:02.040",
"Id": "470129",
"Score": "3",
"body": "I thought this is for code review, and I'm a junior on that field, So I'm looking for the experts reviewing my code."
}
] |
[
{
"body": "<p>Logically, the code looks correct but from performance perspective, there are few things that can be improved. Let's look at the 2 points: </p>\n\n<ul>\n<li><strong>Time Complexity: O(n)</strong> - 1 loop, 1 reduce and 1 Math.min. All run in O(n) time.</li>\n<li><strong>Space Complexity: O(n)</strong> - Two arrays - defArr and l which have size n</li>\n</ul>\n\n<p>There is <code>nothing can be done for time complexity</code> but <code>space complexity can be reduced to constant space</code>. No need to have additional arrays. One can simply loop and store intermediate values in temporary variables.</p>\n\n<p>I have re-written the same. Inside the loop, at each <em>index</em>, the difference is calculated and compared to a <em>min</em> variable. If the new min is lesser than existing one; then update min otherwise do next iteration.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>A = []\nA[0] = 3\nA[1] = 1\nA[2] = 2\nA[3] = 4\nA[4] = 3\n\nfunction solution(A) {\n let sum = A.reduce((total, value) => total + value, 0)\n let min = Number.POSITIVE_INFINITY\n let cumulativeSum = 0\n for (let i = 0; i < A.length - 1; ++i) {\n cumulativeSum = cumulativeSum + A[i]\n sum = sum - A[i]\n diff = Math.abs(sum - cumulativeSum)\n if (diff < min) {\n min = diff\n }\n }\n return min\n}\n\nconsole.log(solution(A))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Hope it helps. Revert for any doubts/clarifications.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-07T21:51:40.910",
"Id": "471005",
"Score": "0",
"body": "Thanks for your clarification."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-04T08:26:51.183",
"Id": "239907",
"ParentId": "239609",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239907",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T13:06:51.457",
"Id": "239609",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "TapeEquilibrium - codility - JavaScript"
}
|
239609
|
<p>I'm trying to come up with a design for a chess engine in Kotlin that hides implementation details, and that ensures that such an implementation cannot accidentally become spaghetti.</p>
<h1>Client side example code</h1>
<p>I envision that a client would access the chess engine with something like:</p>
<pre><code>package chessprototype
import chessprototype.chess.Chess
class ChessClient {
fun hello() {
val searcher = Chess.mateSearcher()
searcher.board = "k1K/2Q w"
val move = searcher.findBestMove()
println("Best move is " + move.toString())
}
}
</code></pre>
<p>To achieve that I created the following.</p>
<h1>Main interface code</h1>
<pre><code>package chessprototype.chess
// Undesired cyclic dependency needed to expose the MateSearcher
import chessprototype.chess.searchers.MateSearcher
/** Understandable interface for the client */
class Chess {
interface Move {
override fun toString(): String
}
data class TextMove(val text: String): Move { override fun toString() = text }
interface Searcher {
var board: String
fun findBestMove(): Move
}
companion object {
fun mateSearcher() = MateSearcher()
}
}
</code></pre>
<p>I've put all interfaces that a client would use in a <em>facade</em>-like <code>Chess</code> object.
And I've put basic access types in there as well, such as <code>TextMove</code></p>
<p>I've put a <em>factory method</em> in the <code>Chess</code> object as well to expose the complicated <code>MateSearcher</code> while hiding its implementation.
I've put it in a <code>companion object</code> so that I can create it without instantiating a <code>Chess</code> class.</p>
<h1>Implementation code</h1>
<pre><code>package chessprototype.chess.searchers
// Undesired cyclic dependency needed for
// - basic types (Move, TextMove)
// - the interface to implement (Searcher)
import chessprototype.chess.Chess
class MateSearcher: Chess.Searcher {
override var board: String = ""
override fun findBestMove(): Chess.Move {
return doComplicatedSearch()
}
// Complicated code that should not be exposed to the client
private fun doComplicatedSearch(): Chess.Move { return Chess.TextMove("Qb7#") }
}
</code></pre>
<p>I've put the implementation in a separate package so that:</p>
<ul>
<li>it cannot accidentally use code that was not explicitly imported first.</li>
<li>it cannot accidentally allow other code to use implementation details.</li>
</ul>
<p>As you can see there is a mutual import that seems undesired to me.</p>
<h1>My challenges</h1>
<ol>
<li>Ensure that the Searcher cannot 'accidentally' start using low level implementations from other parts of the code.</li>
<li>Ensure that the main interface cannot 'accidentally' leak implementation details.</li>
<li>Ensure that the main interface for the client is as clean and simple as possible.</li>
</ol>
<p>My immediate problem: how can I eliminate the cyclic dependency of packages?</p>
<p>And more generally, what would you do differently and why?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T10:22:53.480",
"Id": "470092",
"Score": "1",
"body": "Welcome to Code Review. First of all, I am planning on writing a review for you later today. Secondly, the custom on this site is for titles to include something related to what the code does, otherwise we will end up with too similar titles that aren't very helpful. Therefore I have added the Chess-part of your question again. (Although it's possible that the title can be improved further, I think this is good enough)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T22:19:04.737",
"Id": "470163",
"Score": "0",
"body": "For a guide on how to handle follow-ups, please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T22:30:02.367",
"Id": "470164",
"Score": "0",
"body": "Welcome to Code Review! Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>The cyclic import dependencies can only be removed in one way: By removing one of them. :)</p>\n\n<p>As I see it now, you have:</p>\n\n<ul>\n<li>Client, which needs to create the MateSearcher object, and also know about the API.</li>\n<li>An API</li>\n<li>An implementation class</li>\n</ul>\n\n<p>Naturally, the implementation class - <code>MateSearcher</code> - needs to be aware of the API, so that's not an import that you want to remove.</p>\n\n<p>I'd recommend putting a <code>ChessFactory</code> class (or rather, <code>object</code>) in the same package as the <code>MateSearcher</code>. It can look something like this:</p>\n\n<pre><code>object ChessFactory {\n fun mateSearcher(): Searcher = MateSearcher()\n}\n</code></pre>\n\n<p>Some things to note here:</p>\n\n<ul>\n<li>It's an object, not a class, meaning the method can be called with <code>ChessFactory.mateSearcher()</code> (no need for a companion object)</li>\n<li>The method declares to return a <code>Searcher</code>, it doesn't need to declare that it is a <code>MateSearcher</code> since that will make the client aware about the implementation details.</li>\n</ul>\n\n<p>Now, removing the construction of the <code>MateSearcher</code> leaves your <code>Chess</code> class with... two interfaces and a data class. The <code>Chess</code> class is basically wrapping them, which I personally don't find very useful, but I'll leave that to you to decide whether to keep it or not.</p>\n\n<hr>\n\n<p>Looking a bit closer at what the <code>Chess</code> class contains,</p>\n\n<pre><code>class Chess {\n interface Move {\n override fun toString(): String\n }\n data class TextMove(val text: String): Move { override fun toString() = text }\n interface Searcher {\n var board: String\n fun findBestMove(): Move\n }\n}\n</code></pre>\n\n<p>The <code>Move</code> interfaces specifies that a <code>toString</code> method should exist. Such an interface <em>always</em> exists. It's also not recommended to make your code dependent on the return values of <code>toString</code>. The <code>toString</code> method should be used for only one thing: Printing information to you, the programmer. Its results should not be shown to users of the program and its implementation details should not be important for the application logic. \nIt's currently hard to tell what your <code>Move</code> interface should contain as the only implementation is your <code>TextMove</code> class, which makes me doubt that you need the <code>Move</code> interface at all. What other implementations will you have?</p>\n\n<p>Your generic <code>Move</code> class should possibly have methods like <code>Move.validate(ChessBoard)</code> and <code>Move.perform(ChessBoard)</code>.</p>\n\n<hr>\n\n<p>You have code in your <code>MateSearcher</code> that is commented with <code>Complicated code that should not be exposed to the client</code>. I'd like to make you aware of the fact that that function is marked <code>private</code>, and no function or field marked <code>private</code> will ever be exposed to anything else other than the class itself, no matter if we're implementing an interface or not.</p>\n\n<hr>\n\n<p>The <code>Searcher</code> interface stings a bit to me, especially when looking at your usage of it. Let me ask you this: What if I have a <code>Searcher</code> and call <code>findBestMove()</code> without setting the <code>board</code>? That shouldn't be allowed, right? Why is the board not a parameter to <code>findBestMove()</code>?</p>\n\n<p>Making this change would leave us with:</p>\n\n<pre><code>interface Searcher {\n fun findBestMove(board: String): Move\n}\n</code></pre>\n\n<p>Which could be changed to:</p>\n\n<pre><code>typealias Searcher = (board: String) -> Move\n</code></pre>\n\n<p>Which, in my opinion, is more Kotlinic (like Pythonic but for Kotlin), and it would make it easier to use lambdas or method references for the searcher.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T16:13:21.320",
"Id": "239669",
"ParentId": "239613",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239669",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T15:18:54.183",
"Id": "239613",
"Score": "6",
"Tags": [
"design-patterns",
"kotlin",
"chess"
],
"Title": "Design that avoids undesired dependencies in Kotlin for a chess engine"
}
|
239613
|
<p>I implemented a compiler that compiles a dialect of BASIC known as SimpleBASIC into Simpletron Machine Language to be run by the <a href="https://codereview.stackexchange.com/questions/239425/simpletron-simulator-in-c">Simpletron simulator</a>.</p>
<p>I wrote the manual for the SimpleBASIC compiler in troff, it contains the commands of the SimpleBASIC language and some example programs.</p>
<pre class="lang-none prettyprint-override"><code>simple(6) Games Manual simple(6)
NAME
simple - compiles SimpleBASIC into Simple Machine Language
SYNOPSIS
simple [-O] [-o outfile] infile
DESCRIPTION
simple compiles a source code written in a dialect of BASIC known as
SimpleBASIC into a program in Simple Machine Language (SML) ready to
be run by the Simpletron simulator.
A file containing a SimpleBASIC program is read by the compiler and
converted to SML code. The SML code is output to a file on disk, in
which SML instructions appear one per line. This file is by default
a.out, but can be set by the option -o. The SML file can then be
loaded into the Simpletron simulator.
The options are as follows:
-O Optimize the compilation. Makes the compiler do another pass
to get rid of redundant instructions.
-o outfile
Put executable program into output file outfile.
THE SIMPLEBASIC COMPILATOR
The symbol table
The symbol table is a table that contains each symbol (label or
variable) in the program and its corresponding location in the Sim‐
pletron's memory. For a label, the location is the position in the
Simpletron memory where the SML instruction generated by the Simple‐
BASIC statement begin. For a variable, the location is the position
in the Simpletron memory where the variable is stored.
Each symbol (variable or label) is a single-character identifier.
The SML array
The SML array contains the Simpletron Machine Language (SML) in‐
structions generated by the SimpleBASIC commands. An SML instruc‐
tion is a four-digit integer that comprises two parts: the operation
code (opcode) and the operand.
The opcode is determined by commands in SimpleBASIC. For example,
the SimpleBASIC command input correspond to SML opcode 11 (write).
The operand is a immediate value or a memory location containing the
data on which the operation code performs its task. For example,
the opcode 10 (input) reads a value from keyboard and stores it in
the memory location specified by the operand. The compiler searchs
the symbol table to determine the Simpletron memory location for
each symbol so the corresponding location can be used to complete
the SML instructions.
Generaly, each SimpleBASIC command generates a single SML instruc‐
tion. But compilation of IF...GOTO and LET statements is more com‐
plicated than other statements: they are the only statements that
produce more than one SML instruction.
For an IF...GOTO statement, the compiler produces code to test the
condition and to branch to another line if necessary. The result of
the branch could be an unresolved reference. Each of the relational
and quality operators can be simulated using SML's branch zero and
branch negative instructions (or possibly a combination of both).
For a LET statement, the compiler produces code to evaluate an arbi‐
trarily complex arithmetic expression consisting of integer vari‐
ables and/or constants. When a compiler encounters an expression,
it converts the expression from infix notation to postfix notation,
then evaluates the postfix expression.
The flag array
When a GOTO statement is compiled with an unresolved reference (ie',
it refers to a location in the code that has not been read yet), the
SML instruction must be flagged to indicate that the second pass of
the compiler must complete the instruction. The flags are stored in
an array of type char in which each element is initialized to zero.
If the memory location to which a line number in the Simple program
refers is not yet known (ie', it's not in the symbol table), the
line number is stored in the flag array in the element with the same
subscript as the incomplete instruction. The operand of the incom‐
plete instruction is set to 00 temporarily.
For example, an unconditional branch instruction (making a forward
reference) is left as +5000 until the resolve pass of the compiler.
Memory size
The Simpletron machine contains only 100 locations of memory, and a
SML program loaded into the Simpletron's machine occupies the whole
memory. Both data and instructions are located in memory. The be‐
ginning of the memory is used to store instructions, while the end
of the memory is used to store data. The position of the memory
where the next instruction and data should be placed is determined
by the instruction counter and the the data counter, respectively.
Counters
It's necessary to keep track of the next instruction location in the
SML array because there is not a one-to-one correspondence between
SimpleBASIC statements and SML instructions.
Each time an instruction is produced, the instruction counter is in‐
cremented to the next location in the SML array.
The size of Simpletron's memory could present a problem for Simple
programs with many statements, variables and constants. It's con‐
ceivable that the compiler will run out of memory. To test for this
case, the program contains a data counter to keep track of the loca‐
tion at which the next variable or constant will be stored in the
SML array.
If the value of the instruction counter is larger than the data
counter, the SML array is full. In this case, the compilation
process terminates and the compiler prints an error message indicat‐
ing that it ran out of memory during compilation.
Passes
The compiler performs four passes (five, if optimization is set) to
convert a SimpleBASIC program to SML.
Initialize
The zeroth pass initializates the compilation variables and
arrays. The symbol table, the SML array and the flag array
are allocated and initialized. The compilation counters are
zeroed.
Populate
The first actual pass populate the symbol table with the
variable names and label names from the source code, populate
the SML array with instructions generated by the SimpleBASIC
statements, and flag any instruction that is incomplete and
needs another pass to be fully completed.
Optimization
This pass only occurs if the -O option is used. It walks
through the SML array in order to find sets of redundant in‐
structions and replace them with a single instruction. When‐
ever a redundant set of instructions is found, the locations
in the symbol table and the flags are ajusted to point to the
new instruction.
Resolve
This pass resolves any incomplete instruction. Incomplete
instructions have only the opcode, but does not have a oper‐
and, and are flagged as incomplete by the populate pass.
When an instruction flagged as incomplete is found, this pass
locate the symbol refered to by the flag array and insert the
memory location from the symbol into the instruction with the
unresolved reference.
Assemble
This pass walks through the SML array in order to write the
instructions to a file. This file is ready to be executed by
the Simpletron simulator. By default, this file is created
as a.out, but this can be changed by the -o outfile option.
THE SIMPLEBASIC LANGUAGE
SimpleBASIC is a simple, yet powerful, high level language similar
to early versions of the popular language BASIC.
Each line is a SimpleBASIC statement that consists of a command and
its arguments. Each command begins with one of the following key‐
words.
input
let
print
goto
if
end
Variable and label names are single-letter names. SimpleBASIC does
not allow descriptive variable names, so variables should be ex‐
plained in comments to indicate their use in the program.
SimpleBASIC uses only integer variables. Simple does not have vari‐
able declarations, merely mentioning a variable name in a program
causes the variable to be declared and initialized to zero automati‐
cally.
The syntax of SimpleBASIC does not allow string manipulation. If a
string is encountered in a SimpleBASIC command, the compiler gener‐
ates a syntax error.
SimpleBASIC uses the conditional IF...GOTO statement and the uncon‐
ditional GOTO statement to alter the flow of control during program
execution. If the condition in the IF...GOTO statement is true,
control is transferred to a specific line of the program.
A comment in SimpleBASIC beggins with ; and go through the end of
line.
Labels
A label is any letter followed by a colon. A label can occur before
any SimpleBASIC statement. Labels are used by transfer of control
statements to implement flow of control and loops during process ex‐
ecution.
SimpleBASIC commands
Commands in SimpleBASIC are case insensitive. Both INPUT and input
are the same command.
INPUT A input statement prompts the user to enter an integer and
assign it to a variable. For example, the following state‐
ment reads an integer from the keyboard and stores that inte‐
ger in x.
INPUT x
LET A let statement assign the value of an expression to a vari‐
able. For example, the following statement assign u the
value of 4 * (j - 56). An arbitarily complex expression can
appear to the right of the equal sign. SimpleBASIC evaluates
only integer expressions using the +, -, *, / and % opera‐
tors. These operators have the same precedence as in C.
Parentheses can be used to change the order of evaluation of
an expression.
LET u = 4 * (j - 56)
PRINT A print statement display the value of a previously defined
variable. For example, the following statement display the
value of w.
PRINT w
GOTO A goto statement transfer program control to the statement
after a specified label in the source code. For example, the
following statement transfer control to the statement after
the label a.
GOTO a
IF ... GOTO
A if...goto statement compare two variables and transfer pro‐
gram control to the label specified after GOTO if the condi‐
tion is true; otherwise, continue execution with the next
statement. The following relational and equality operators
are valid in an IF...GOTO statement: <, >, <=, >=, == or !=.
For example, the following statement compare i and z for
equality and transfer program control to label j if they are
equal.
IF i == z GOTO j
end A end statement terminate program execution. For example
END
EXAMPLES
add.basic
The following program reads two integers from the keyboard, stores
the values in variables a and b, and computes and prints their sum
(stored in variable c).
; determine and print the sum of two integers
; input two integers
INPUT a
INPUT b
; add integers and store result in c
LET c = a + b
; print the result
PRINT c
; terminate program execution
END
larger.basic
The following program determines and prints the larger of two inte‐
gers. The integers are input from the keyboard and stored in s and
t. The IF...GOTO statement tests the condition s >= t. If the con‐
dition is true, control is transferred to label a and s is output;
otherwise, t is output and control is transferred to the END state‐
ment in label
; determine the larger of two integers
INPUT s
INPUT t
; test if s >= t
IF s >= t GOTO a
; t is greater than s, so print t
PRINT t
GOTO b
; s is greater than or equal to t, so print s
a:
PRINT s
b:
END
square.basic
SimpleBASIC does not provide a repetition structure (such as C's
for, while or do...while). However, SimpleBASIC can simulate each
of C's repetition structures using the IF...GOTO and GOTO state‐
ments.
The following program uses a sentinel-controlled loop to calculate
the squares of several integers. Each integer is input from the
keyboard and stored in variable j. If the value entered is the sen‐
tinel +0000, control is transfered to END, where the program termi‐
nates. Otherwise, k is assigned the square of j, k is output to the
screen and control is passed to where the next integer is input.
; Calculate the squares of several integers
a:
INPUT j
; set i as the sentinel value
LET i = +0000
; test for sentinel value
IF j == i GOTO b
; calculate square of j and assign result to k
LET k = j * j
PRINT k
; loop to get next j
GOTO a
b:
END
EXIT STATUS
0 Success.
>0 Error occurred.
HISTORY
This version of simple, the SimpleBASIC compiler, is based on the
exercises 12.26~12.28 from the [Build Your Own Compiler] pdf pro‐
vided by Deitel.
The line label system is unique to this implementation, since the
exercise use line number system as the target of GOTO statements.
For more information, see the Wikipedia pages on [Line Number] and
[Line Label].
CAVEATS
This version of simple supports only variables in IF statements. It
does not support expressions or constants in IF statements.
This version of simple only supports single-letter symbols. In a
next version, I will replace the symbol table by a binary search
tree and implement multi-letter symbols.
It also does not support immediate operands for instructions.
SEE ALSO
simpletron(6)
[Build Your Own Compiler]
https://web.archive.org/web/20190819021934/http://www.deitel.com/bookresources/chtp8/CompilerExercises.pdf
[Line number]
https://en.wikipedia.org/wiki/Line_number
[Line label]
https://en.wikipedia.org/wiki/Line_label
[Deitel & Deitel]
C: How to Program (8th edition), Paul Deitel and Harvey Dei‐
tel
simple(6)
</code></pre>
<p>Here is simple.h</p>
<pre><code>#define MEMSIZE 100
#define TOKENSIZE 63
typedef int16_t memtype;
enum tokentype {
COMMENT,
RELATIONAL,
ARITHMETIC,
ASSIGNMENT,
GOTOKEYWRD,
VARIABLE,
EXPRESSION,
LABEL,
NEWLINE,
COMMAND
};
enum operation {
READ = 10,
WRITE = 11,
LOAD = 20,
STORE = 21,
ADD = 30,
SUBTRACT = 31,
DIVIDE = 32,
MULTIPLY = 33,
REMINDER = 34,
ADD_I = 40,
SUBTRACT_I = 41,
DIVIDE_I = 42,
MULTIPLY_I = 43,
REMINDER_I = 44,
BRANCH = 50,
BRANCHNEG = 51,
BRANCHZERO = 52,
HALT = 53
};
struct symbol {
enum {
label,
variable,
none
} type;
size_t location;
};
struct expression {
enum {
symb,
num,
op
} type;
union {
memtype n;
char c;
} u;
struct expression *next;
};
struct compiler {
size_t memsize;
struct symbol *symtable; /* the symbol table */
memtype *sml; /* the sml instructions */
char *flag; /* the flag array */
char *file; /* name of file to be compiled*/
size_t ln; /* current line of file to be compiled */
size_t inscount;
size_t datacount;
};
typedef void (*instruction)(struct compiler *);
</code></pre>
<p>Here is simple.c</p>
<pre><code>#include <err.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include "simple.h"
static char *tokenstring[] = {
[COMMENT] = "comment",
[RELATIONAL] = "relational operator",
[ARITHMETIC] = "arithmetic operator",
[ASSIGNMENT] = "equal sign",
[GOTOKEYWRD] = "goto keyword",
[VARIABLE] = "variable",
[EXPRESSION] = "expression",
[LABEL] = "label",
[NEWLINE] = "newline",
[COMMAND] = "command"
};
/* compilation passes */
static void initialize(struct compiler *, char *);
static void populate(struct compiler *);
static void optimize(struct compiler *);
static void resolve(struct compiler *);
static void assemble(struct compiler, char *);
/* grammatical functions */
static char *gettoken(struct compiler *, enum tokentype, enum tokentype *);
/* functions to generate machine instructions */
static void command_input(struct compiler *);
static void command_let(struct compiler *);
static void command_print(struct compiler *);
static void command_goto(struct compiler *);
static void command_if(struct compiler *);
static void command_end(struct compiler *);
static instruction iscommand(char *);
/* symbol table manipulation functions */
static struct symbol *inserttable(struct compiler *, char, int, size_t);
static struct symbol *searchtable(struct compiler *, char);
/* expression handler functions */
static struct expression *getexpr(struct compiler *, char *s);
static int isoperator(char c);
static void enqueue(struct expression **head, struct expression **tail, struct expression operand);
/* usage */
static void usage(void);
/* simpleBASIC to Simpletron Machine Language compiler */
int
main(int argc, char *argv[])
{
struct compiler comp;
int c;
char *out = "a.out";
bool dooptimize;
dooptimize = false;
while ((c = getopt(argc, argv, "Oo:")) != -1) {
switch (c) {
case 'O':
dooptimize = true;
break;
case 'o':
out = optarg;
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc != 1)
usage();
initialize(&comp, *argv);
populate(&comp);
if (dooptimize)
optimize(&comp);
resolve(&comp);
assemble(comp, out);
return EXIT_SUCCESS;
}
/* initialize symbol table, instruction array, flag array and counters */
static void
initialize(struct compiler *comp, char *filename)
{
static struct symbol symtable['z' - 'A'];
static memtype sml[MEMSIZE];
static char flag[MEMSIZE];
size_t i;
comp->symtable = symtable;
comp->sml = sml;
comp->flag = flag;
comp->memsize = MEMSIZE;
comp->file = filename;
comp->ln = 1;
comp->inscount = 0;
comp->datacount = comp->memsize - 1;
/* initialize arrays */
for (i = 'A'; i < 'z'; i++)
symtable[i - 'A'].type = none;
for (i = 0; i < comp->memsize; i++)
flag[i] = '\0';
}
/* populate symbol table, instruction array, and flag array */
static void
populate(struct compiler *comp)
{
enum tokentype toktype;
char *tok;
/* while there is a command, generate instructions for it */
while ((tok = gettoken(comp, COMMAND, &toktype)) != NULL) {
/* ignore comments */
if (toktype == COMMENT)
continue;
/* if command is a label declaration, put it in symbol table */
if (toktype == LABEL) {
if (searchtable(comp, *tok) != NULL) {
fprintf(stderr, "%s:%lu: error: redeclaration of '%c'\n",
comp->file, comp->ln, *tok);
exit(EXIT_FAILURE);
}
inserttable(comp, *tok, label, comp->inscount);
continue;
}
/* generate instructions for statement */
(*iscommand(tok))(comp);
/* get obligatory newline after statement */
gettoken(comp, NEWLINE, &toktype);
/* if instructions overlap data, compilation run out of memory */
if (comp->inscount > comp->datacount)
errx(1, "compilation ran out of memory");
}
}
/* optimize compilation by getting rid of redundant instructions */
static void
optimize(struct compiler *comp)
{
memtype opcode0, opcode1, opcode2; /* current, next and nextnext opcode */
memtype operand0, operand1; /* current and next operand */
size_t i, j;
for (i = 0; i < comp->inscount; i++) {
opcode0 = comp->sml[i] / comp->memsize;
operand0 = comp->sml[i] % comp->memsize;
opcode1 = comp->sml[i+1] / comp->memsize;
operand1 = comp->sml[i+1] % comp->memsize;
opcode2 = comp->sml[i+2] / comp->memsize;
if (operand0 == operand1 && opcode2 == STORE
&& opcode0 == STORE && opcode1 == LOAD) {
for (j = 0; j < 'z' - 'A'; j++)
if (comp->symtable[j].type == label && comp->symtable[j].location > i)
comp->symtable[j].location -= 2;
for (j = i; j < comp->inscount; j++) {
comp->sml[j] = comp->sml[j + 2];
comp->flag[j] = comp->flag[j + 2];
}
}
}
}
/* resolve memory locations flagged as incomplete */
static void
resolve(struct compiler *comp)
{
struct symbol *sym;
size_t i;
/* traverse flag array looking for flagged memory locations */
for (i = 0; i < comp->memsize; i++) {
if (comp->flag[i] != '\0') {
sym = searchtable(comp, comp->flag[i]);
if (sym == NULL)
errx(1, "failed to find label %c", comp->flag[i]);
if (sym->type != label)
errx(1, "failed to find label %c", comp->flag[i]);
comp->sml[i] += sym->location;
}
}
}
/* write machine code in memory to file */
static void
assemble(struct compiler comp, char *file)
{
FILE *fp;
size_t i;
if ((fp = fopen(file, "w")) == NULL)
err(EXIT_FAILURE, "%s", file);
for (i = 0; i < comp.memsize; i++)
fprintf(fp, "%+05d\n", comp.sml[i]);
if (ferror(fp))
err(1, "%s", file);
fclose(fp);
}
/*
* Get next token from fp, and return a pointer to it (or NULL if EOF is found).
* expected is the type of expected token, *got is the type of got token.
* If expected and *got are different, exit with error, except when expected a
* command and got a label definition.
*/
static char *
gettoken(struct compiler *comp, enum tokentype expected, enum tokentype *got)
{
instruction inst;
static char s[TOKENSIZE];
static FILE *fp = NULL;
int c;
size_t i;
if (fp == NULL) {
fp = fopen(comp->file, "r");
if (fp == NULL)
err(EXIT_FAILURE, "%s", comp->file);
}
/* get blank on the beginning */
while (isblank(c = getc(fp)))
;
i = 0;
/* consider blank lines as remarks */
if (expected == COMMAND && c == '\n') {
s[i] = ';';
s[i++] = '\0';
comp->ln++;
*got = COMMENT;
} else if (expected == EXPRESSION) { /* if expected expression, get remaining of line */
while (c != '\n' && i < TOKENSIZE - 1) {
s[i++] = c;
c = getc(fp);
}
if (c != '\n') {
fprintf(stderr, "%s:%lu: error: expression too long\n", comp->file, comp->ln);
exit(EXIT_FAILURE);
}
ungetc(c, fp);
s[i] = '\0';
*got = EXPRESSION;
} else if (c == '\n') { /* because newline is a token */
s[i++] = c;
s[i] = '\0';
*got = NEWLINE;
} else if (c == ';') { /* comment */
s[i++] = c;
s[i] = '\0';
while (c != '\n')
c = getc(fp);
comp->ln++;
*got = COMMENT;
} else if (c == '=') { /* test if it's = or == */
s[i++] = c;
c = getc(fp);
if (c == '=') {
s[i++] = c;
*got = RELATIONAL;
} else {
ungetc(c, fp);
*got = ASSIGNMENT;
}
s[i] = '\0';
} else if (c == '!') { /* token is != */
s[i++] = c;
c = getc(fp);
if (c != '=') {
fprintf(stderr, "%s:%lu: error: unexpected character '%c'\n",
comp->file, comp->ln, c);
exit(EXIT_FAILURE);
}
s[i++] = c;
s[i] = '\0';
*got = RELATIONAL;
} else if (c == '<' || c == '>') { /* token is <, >, <= or >= */
s[i++] = c;
c = getc(fp);
if (c == '=')
s[i++] = c;
else
ungetc(c, fp);
s[i] = '\0';
*got = RELATIONAL;
} else if (isoperator(c)) { /* token is operator */
s[i++] = c;
s[i] = '\0';
*got = ARITHMETIC;
} else if (isalpha(c)) { /* token is command, variable or label */
do {
s[i++] = c;
c = getc(fp);
} while (isalpha(c) && i < TOKENSIZE - 1);
s[i] = '\0';
if (isalpha(c)) {
fprintf(stderr, "%s:%lu: error: token too long\n", comp->file, comp->ln);
exit(EXIT_FAILURE);
}
if (c == ':') {
*got = LABEL;
while (isblank(c = getc(fp)))
;
if (c != '\n')
ungetc(c, fp);
} else if ((inst = iscommand(s)) != NULL) {
ungetc(c, fp);
if (expected == GOTOKEYWRD && inst == command_goto)
*got = GOTOKEYWRD;
else
*got = COMMAND;
} else {
ungetc(c, fp);
if (expected == LABEL)
*got = LABEL;
else
*got = VARIABLE;
}
} else if (c == EOF) { /* close file after reading it */
fclose(fp);
return NULL;
} else {
fprintf(stderr, "%s:%lu: error: unexpected character '%c'\n", comp->file, comp->ln, c);
exit(EXIT_FAILURE);
}
if (ferror(fp))
err(1, "%s", comp->file);
/* if got a newline, increment line count */
if (*s == '\n')
comp->ln++;
/* test whether you got what you expected (except for labels) */
if (expected != *got) {
if (expected != COMMAND || (*got != LABEL && *got != COMMENT)) {
fprintf(stderr, "%s:%lu: error: %s expected (got %s)\n",
comp->file, comp->ln, tokenstring[expected], tokenstring[*got]);
exit(EXIT_FAILURE);
}
}
return s;
}
/* generate machine instructions for let statement */
static void
command_let(struct compiler *comp)
{
struct symbol *sym;
char *tok;
enum tokentype toktype;
size_t *stack, stacksize;
size_t var, i;
struct expression *expr;
/* get location of variable to be assigned by let statement */
tok = gettoken(comp, VARIABLE, &toktype); /* get variable symbol */
sym = searchtable(comp, *tok); /* search in symbol table*/
if (sym == NULL) /* if not found, insert it*/
sym = inserttable(comp, *tok, variable, comp->datacount--);
var = sym->location;
/* get equal sign */
tok = gettoken(comp, ASSIGNMENT, &toktype);
/* get expression to assign and stack of addresses */
tok = gettoken(comp, EXPRESSION, &toktype);
expr = getexpr(comp, tok);
stacksize = strlen(tok);
stack = calloc(stacksize, sizeof *stack);
/* generate machine instructions */
i = 0;
while (i < stacksize && expr != NULL) {
size_t op1, op2;
struct expression *tmp;
if (expr->type == num) {
comp->sml[comp->datacount] = expr->u.n;
stack[i++] = comp->datacount--;
} else if (expr->type == symb) {
if ((sym = searchtable(comp, expr->u.c)) == NULL) /* if symbol not found, insert it*/
sym = inserttable(comp, expr->u.c, variable, comp->datacount--);
stack[i++] = sym->location;
} else {
if (i < 2) {
fprintf(stderr, "%s:%lu error improper expression '%s'\n",
comp->file, comp->ln, tok);
exit(EXIT_FAILURE);
}
op2 = stack[--i];
op1 = stack[--i];
comp->sml[comp->inscount++] = LOAD * MEMSIZE + op1;
if (expr->u.c == '+')
comp->sml[comp->inscount++] = ADD * MEMSIZE + op2;
if (expr->u.c == '-')
comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op2;
if (expr->u.c == '*')
comp->sml[comp->inscount++] = MULTIPLY * MEMSIZE + op2;
if (expr->u.c == '/')
comp->sml[comp->inscount++] = DIVIDE * MEMSIZE + op2;
if (expr->u.c == '%')
comp->sml[comp->inscount++] = REMINDER * MEMSIZE + op2;
comp->sml[comp->inscount++] = STORE * MEMSIZE + comp->datacount;
stack[i++] = comp->datacount--;
}
tmp = expr;
expr = expr->next;
free(tmp);
}
if (i == 0) {
fprintf(stderr, "%s:%lu error improper expression '%s'\n",
comp->file, i, tok);
exit(EXIT_FAILURE);
}
comp->sml[comp->inscount++] = LOAD * MEMSIZE + stack[--i];
comp->sml[comp->inscount++] = STORE * MEMSIZE + var;
}
/* generate machine instructions for input statement */
static void
command_input(struct compiler *comp)
{
char *tok;
enum tokentype toktype;
struct symbol *sym;
/* get location of variable to be input */
tok = gettoken(comp, VARIABLE, &toktype); /* get variable name */
sym = searchtable(comp, *tok); /* search in symbol table */
if (sym == NULL) /* if not found, insert it*/
sym = inserttable(comp, *tok, variable, comp->datacount--);
/* generate machine instruction */
comp->sml[comp->inscount++] = READ * MEMSIZE + sym->location;
}
/* generate machine instructions for print statement */
static void
command_print(struct compiler *comp)
{
char *tok;
enum tokentype toktype;
struct symbol *sym;
/* get location of variable to print */
tok = gettoken(comp, VARIABLE, &toktype); /* get variable name */
sym = searchtable(comp, *tok); /* search in symbol table */
if (sym == NULL) { /* if not found, it's an error */
fprintf(stderr, "%s:%lu: error: '%c' undeclared\n",
comp->file, comp->ln, *tok);
exit(EXIT_FAILURE);
}
/* generate machine instruction */
comp->sml[comp->inscount++] = WRITE * MEMSIZE + sym->location;
}
/* generate machine instructions for goto statement */
static void
command_goto(struct compiler *comp)
{
char *tok;
enum tokentype toktype;
struct symbol *sym;
size_t labeladdr;
/* get location to go to */
labeladdr = 0;
tok = gettoken(comp, LABEL, &toktype); /* get label name */
sym = searchtable(comp, *tok); /* search in symbol table */
if (sym == NULL) /* if label not found, flag it*/
comp->flag[comp->inscount] = *tok;
else /* if label is found, set it */
labeladdr = sym->location;
/* generate machine instruction */
comp->sml[comp->inscount++] = BRANCH * MEMSIZE + labeladdr;
}
/* generate machine instructions for if statement */
static void
command_if(struct compiler *comp)
{
char *tok;
char relop[3]; /* relational operator */
enum tokentype toktype;
struct symbol *sym;
size_t op1, op2, labeladdr;
/* get location of first variable */
tok = gettoken(comp, VARIABLE, &toktype); /* get variable */
sym = searchtable(comp, *tok); /* search in symbol table */
if (sym == NULL) /* if not found, insert it*/
sym = inserttable(comp, *tok, variable, comp->datacount--);
op1 = sym->location;
/* get relational operator */
tok = gettoken(comp, RELATIONAL, &toktype);
strncpy(relop, tok, 2);
relop[3] = '\0';
/* get location of second variable */
tok = gettoken(comp, VARIABLE, &toktype); /* get variable */
sym = searchtable(comp, *tok); /* search in symbol table */
if (sym == NULL) /* if not found, insert it*/
sym = inserttable(comp, *tok, variable, comp->datacount--);
op2 = sym->location;
/* get obligatory 'goto' keyword */
tok = gettoken(comp, GOTOKEYWRD, &toktype);
/* get address of label to go to */
labeladdr = 0;
tok = gettoken(comp, LABEL, &toktype); /* get label */
sym = searchtable(comp, *tok); /* search in symbol table */
if (sym != NULL) /* if label is found, set it */
labeladdr = sym->location;
/* generate instructions based on branch type */
if (strcmp(relop, "==") == 0) {
comp->sml[comp->inscount++] = LOAD * MEMSIZE + op1;
comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op2;
comp->sml[comp->inscount++] = BRANCHZERO * MEMSIZE + labeladdr;
} else if (strcmp(relop, "!=") == 0) {
comp->sml[comp->inscount++] = LOAD * MEMSIZE + op1;
comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op2;
comp->sml[comp->inscount++] = BRANCHZERO * MEMSIZE + 2;
comp->sml[comp->inscount++] = BRANCH * MEMSIZE + labeladdr;
} else if (strcmp(relop, "<") == 0) {
comp->sml[comp->inscount++] = LOAD * MEMSIZE + op1;
comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op2;
comp->sml[comp->inscount++] = BRANCHNEG * MEMSIZE + labeladdr;
} else if (strcmp(relop, ">") == 0) {
comp->sml[comp->inscount++] = LOAD * MEMSIZE + op2;
comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op1;
comp->sml[comp->inscount++] = BRANCHNEG * MEMSIZE + labeladdr;
} else if (strcmp(relop, "<=") == 0) {
comp->sml[comp->inscount++] = LOAD * MEMSIZE + op1;
comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op2;
comp->sml[comp->inscount++] = BRANCHNEG * MEMSIZE + labeladdr;
comp->sml[comp->inscount++] = BRANCHZERO * MEMSIZE + labeladdr;
} else if (strcmp(relop, ">=") == 0) {
comp->sml[comp->inscount++] = LOAD * MEMSIZE + op2;
comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op1;
comp->sml[comp->inscount++] = BRANCHNEG * MEMSIZE + labeladdr;
comp->sml[comp->inscount++] = BRANCHZERO * MEMSIZE + labeladdr;
} else {
exit(EXIT_FAILURE);
}
/*
* this checking must go after generating the instructions,
* for it needs the variable inscount to be modified.
*/
if (sym == NULL) /* if label not found, flag it */
comp->flag[comp->inscount-1] = *tok;
}
/* generate machine instructions for end statement */
static void
command_end(struct compiler *comp)
{
comp->sml[comp->inscount++] = HALT * MEMSIZE + 0;
}
/* return type of command s */
static instruction
iscommand(char *s)
{
if (strcasecmp(s, "INPUT") == 0)
return command_input;
if (strcasecmp(s, "PRINT") == 0)
return command_print;
if (strcasecmp(s, "LET") == 0)
return command_let;
if (strcasecmp(s, "GOTO") == 0)
return command_goto;
if (strcasecmp(s, "IF") == 0)
return command_if;
if (strcasecmp(s, "END") == 0)
return command_end;
return NULL;
}
/* search for symbol in symbol table */
static struct symbol *
searchtable(struct compiler *comp, char c)
{
if (comp->symtable[c - 'A'].type != none)
return comp->symtable + c - 'A';
return NULL;
}
/* insert symbol in symbol table */
static struct symbol *
inserttable(struct compiler *comp, char c, int type, size_t loc)
{
if (comp->symtable[c - 'A'].type != none)
return NULL;
comp->symtable[c - 'A'].type = type;
comp->symtable[c - 'A'].location = loc;
return comp->symtable + c - 'A';
}
/* Convert infix expression in s into postfix expression in *expr list */
struct expression *
getexpr(struct compiler *comp, char *s)
{
struct expression *head, *tail;
char *stack, *endp;
long n;
int i;
head = tail = NULL;
stack = endp = NULL;
i = 0;
if ((stack = malloc(strlen(s) + 1)) == NULL)
err(1, NULL);
while (*s != '\0') {
while (isspace(*s))
s++;
if (isalpha(*s)) {
enqueue(&head, &tail, (struct expression) {.type = symb, .u.c = *s});
} else if (isdigit(*s) || ((*s == '+' || *s == '-') && isdigit(s[1]))) {
n = strtol(s, &endp, 10);
if (n > INT_MAX || n < INT_MIN || endp == s) {
fprintf(stderr, "%s:%lu: error: integer to big\n",
comp->file, comp->ln);
exit(EXIT_FAILURE);
}
enqueue(&head, &tail, (struct expression) {.type = num, .u.n = n});
} else if (*s == '(') {
stack[i++] = '(';
} else if (*s == ')') {
while (i > 0 && isoperator(stack[i-1])) {
i--;
enqueue(&head, &tail, (struct expression) {.type = op, .u.c = stack[i]});
}
if (i > 0 && stack[i-1] == '(')
i--;
} else if (isoperator(*s)) {
while (i > 0 && isoperator(stack[i-1])
&& isoperator(stack[i-1]) >= isoperator(*s)) {
i--;
enqueue(&head, &tail, (struct expression) {.type = op, .u.c = stack[i]});
}
stack[i++] = *s;
} else {
fprintf(stderr, "%s:%lu: error: unexpected character '%c'\n",
comp->file, comp->ln, *s);
exit(EXIT_FAILURE);
}
s++;
}
while (i > 0 && isoperator(stack[i-1])) {
i--;
enqueue(&head, &tail, (struct expression) {.type = op, .u.c = stack[i]});
}
free(stack);
return head;
}
/* return precedence of operator c, or 0 if it is not an operator */
static int
isoperator(char c)
{
switch (c) {
case '+': case '-':
return 1;
case '/': case '*': case '%':
return 2;
default:
break;
}
return 0;
}
/* enqueue an operand or operator (op) into the expression list */
static void
enqueue(struct expression **head, struct expression **tail, struct expression op)
{
struct expression *p;
if ((p = malloc(sizeof *p)) == NULL)
err(1, NULL);
p->type = op.type;
if (p->type == num)
p->u.n = op.u.n;
else
p->u.c = op.u.c;
p->next = NULL;
if (*head == NULL)
*head = p;
else
(*tail)->next = p;
*tail = p;
}
static void
usage(void)
{
(void) fprintf(stderr, "usage: simple [-O] [-o file.sml] file.simp\n");
exit(EXIT_FAILURE);
}
</code></pre>
<p>Here is a sample program in the SimpleBASIC language, sum.basic, it receives an integer (in the format of a Simpletron instruction) and outputs the sum of each number from 1 to the value entered.</p>
<pre><code>; Sum 1 to x
INPUT x
; check y == x
a: IF y == x GOTO e
; increment y
LET y = y + 1
; ADD y to total
LET t = t + y
; loop y
GOTO a
; output result
e:
PRINT t
END
</code></pre>
<p>The input of a Simpletron program must be a signed four-digit integer, like <code>+0007</code> or <code>-0001</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:13:28.293",
"Id": "470038",
"Score": "0",
"body": "`[COMMENT] = \"comment\"` - what the heck is happening here? Is this some way of specifying the index of assignment for an array initializer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:19:24.537",
"Id": "470039",
"Score": "0",
"body": "`COMMENT` is `0`, it is defined in `enum tokentype`. The array `tokenstring` is initialized with the values in `enum tokentype`. The array is used by the function `gettoken` to generate error strings when the got token is different from the expected token. For example, when the compiler expects a variable name but gets a comment, it prints `\"%s expected (got %s)\", tokenstring[VARIABLE], tokenstring[COMMENT]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:21:01.990",
"Id": "470040",
"Score": "0",
"body": "_The array tokenstring is initialized with the values in enum tokentype_ - right; specifically I'm unfamiliar with the brackets-on-the-LHS syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:24:57.413",
"Id": "470042",
"Score": "1",
"body": "An array can be initialized with the elements 2 and 4 specified as `int my_array[5] = { [2] = 5, [4] = 9 };`. It is equivalent to `int my_array[5] = { 0, 0, 5, 0, 9 };`. That's a C99 thing, I think."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:34:50.863",
"Id": "470044",
"Score": "0",
"body": "Neat :) I don't pretend to know the whole standard; that's useful."
}
] |
[
{
"body": "<h2>C99, assignment-in-conditions</h2>\n\n<p>At the risk of sounding like a broken record - I'll make the same recommendations as in <a href=\"https://codereview.stackexchange.com/questions/239425/simpletron-simulator-in-c\">Simpletron simulator in C</a> . Consider moving your variable declarations closer to where they're used, and expanding out your assignment-in-condition statements.</p>\n\n<p>There's another benefit to C99: this - </p>\n\n<pre><code>comp->symtable = symtable;\ncomp->sml = sml;\ncomp->flag = flag;\ncomp->memsize = MEMSIZE;\ncomp->file = filename;\ncomp->ln = 1;\ncomp->inscount = 0;\ncomp->datacount = comp->memsize - 1;\n</code></pre>\n\n<p>could be converted to a <code>const static</code> structure instance using C99 standard section 6.7.8 Initialization (\"designated initializers\"), like:</p>\n\n<pre><code>const static struct compiler default = {\n .ln = 1,\n // ...\n};\n</code></pre>\n\n<p>and then all of the defaults assigned in a single statement.</p>\n\n<h2>Nasty side-effects</h2>\n\n<p>This:</p>\n\n<pre><code>static struct symbol symtable['z' - 'A'];\nstatic memtype sml[MEMSIZE];\nstatic char flag[MEMSIZE];\n\ncomp->symtable = symtable;\ncomp->sml = sml;\ncomp->flag = flag;\n</code></pre>\n\n<p>is nasty. From the outside it <em>looks</em> like <code>compiler</code> is a re-entrant structure, but in actuality the memory is shared. A naive caller would pass in two different compiler instances, and then be surprised when data leaks from one to the other.</p>\n\n<h2>Surprising function names</h2>\n\n<p>I would assume that this:</p>\n\n<pre><code>iscommand(tok)\n</code></pre>\n\n<p>returns a boolean, but it actually returns a pointer?</p>\n\n<pre><code>(*iscommand(tok))(comp);\n</code></pre>\n\n<p>It should be named something like <code>getinstruction</code>.</p>\n\n<h2>Helper pointers</h2>\n\n<p>This:</p>\n\n<pre><code> opcode0 = comp->sml[i] / comp->memsize;\n operand0 = comp->sml[i] % comp->memsize;\n opcode1 = comp->sml[i+1] / comp->memsize;\n operand1 = comp->sml[i+1] % comp->memsize;\n opcode2 = comp->sml[i+2] / comp->memsize;\n</code></pre>\n\n<p>can be somewhat abbreviated by the creation of a temporary pointer equal to <code>comp->sml + i</code>.</p>\n\n<h2>Switch</h2>\n\n<p>This is the perfect use-case for a <code>switch</code>:</p>\n\n<pre><code> if (expr->u.c == '+')\n comp->sml[comp->inscount++] = ADD * MEMSIZE + op2;\n if (expr->u.c == '-')\n comp->sml[comp->inscount++] = SUBTRACT * MEMSIZE + op2;\n if (expr->u.c == '*')\n comp->sml[comp->inscount++] = MULTIPLY * MEMSIZE + op2;\n if (expr->u.c == '/')\n comp->sml[comp->inscount++] = DIVIDE * MEMSIZE + op2;\n if (expr->u.c == '%')\n comp->sml[comp->inscount++] = REMINDER * MEMSIZE + op2;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:37:04.057",
"Id": "470045",
"Score": "0",
"body": "`iscommand` actually returned int in a previous version. It returned a number representing the command, or zero, if the string is not a command. But then I needed a function that returned a pointer to the function related to a string, then reused `iscommand` for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:49:09.513",
"Id": "470050",
"Score": "0",
"body": "_From the outside it looks like compiler is a re-entrant structure, but in actuality the memory is shared_. Should I define the arrays inside the structure, then? It would be a humongous array, so I should switch the pass-by-value from function `assemble` to a pass-by-reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:49:52.273",
"Id": "470052",
"Score": "1",
"body": "I think your structure can basically remain as-is; just use `malloc` instead of assigning a reference to a static variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T02:25:04.480",
"Id": "470059",
"Score": "0",
"body": "_Consider moving your variable declarations closer to where they're used_. I have adopted a coding style that explicitly specifies to [not mix declaration and code](https://suckless.org/coding_style/) and to put declarations at the beginning of the function. On assignment-in-conditions, I watched out to not use them, but I think there is a few I wrote on automatic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T02:46:05.970",
"Id": "470060",
"Score": "0",
"body": "I agree with Reinderien - that coding style is 40 years obsolete. The original reason (in the 1970s) to put declarations first was to accommodate memory limitations of hardware at that time (e.g. my first computer in 1978 only had 8K of RAM). In more modern renditions of C, the computer accommodates the human instead of the human having to accommodate the machine. Unless you're going to code exclusively for a PDP-8, sticking with that limitation is going to impede your progress to more complex projects."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:32:51.883",
"Id": "239634",
"ParentId": "239616",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "239634",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T15:55:07.087",
"Id": "239616",
"Score": "5",
"Tags": [
"c",
"compiler",
"basic-lang"
],
"Title": "Simple BASIC to Simpletron Machine Language compiler in C"
}
|
239616
|
<p>The following code uses dynamic approach to solve <a href="https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/" rel="noreferrer">0/1 knapsack problem</a>. (I know the maximum <code>profit</code> function I have used is not as good as the one I have defined <a href="https://github.com/kesarling/cpp-projects/blob/master/algorithms.h" rel="noreferrer">here</a> and I still am <a href="https://stackoverflow.com/questions/60917612/how-do-i-sort-the-possibilities-vector-in-0-1-knapsack-problem-using-the-templat">working on that</a> . Are any optimizations possible for the following code?</p>
<pre><code>#include "algorithms.h"
struct Item {
int index = 1;
int profit = 1;
int weight = 1;
Item() = delete;
explicit Item(int i, int _profit, int w) {
index = i;
profit = _profit;
weight = w;
}
bool operator<(const Item& item) {
return this->profit < item.profit;
}
bool operator<=(const Item& item) {
return this->profit <= item.profit;
}
bool operator>(const Item& item) {
return this->profit > item.profit;
}
bool operator>=(const Item& item) {
return this->profit >= item.profit;
}
friend std::ostream& operator<<(std::ostream& out, const Item item) {
out << item.index;
return out;
}
};
long weight(const std::vector<Item>& item_list, const std::vector<int>& item_switch) {
long sum = 0;
for (int i = 0; i < item_switch.size(); i++) {
sum += item_switch[i] * item_list[i].weight;
}
return sum;
}
long profit(const std::vector<Item>& item_list, const std::vector<int>& item_switch) {
long sum = 0;
for (int i = 0; i < item_switch.size(); i++) {
sum += item_switch[i] * item_list[i].profit;
}
return sum;
}
void increment(std::vector<int>& vec) {
auto it_bit = vec.end();
it_bit--;
while (*it_bit == 1) {
*it_bit = 0;
if (it_bit == vec.begin()) {
return;
}
it_bit--;
}
*it_bit = 1;
}
int main() {
long M = 25;
Item i1(1, 10, 9);
Item i2(2, 12, 8);
Item i3(3, 14, 12);
Item i4(4, 16, 14);
std::vector<Item> items = { i1,i2,i3,i4 };
std::vector<int> enable(4,0);
std::vector<std::vector<int>> possible;
for (int i = 1; i <= 16; i++) {
if (weight(items, enable) <= M) {
possible.push_back(enable);
}
increment(enable);
}
long pr = 0;
for (int i = 0; i < possible.size(); i++) {
long temp = profit(items, possible[i]);
if (temp > pr) {
pr = temp;
}
}
std::cout << pr;
return 0;
}
</code></pre>
<p>P.S. I did not implement the nice suggestion <a href="https://codereview.stackexchange.com/a/239600/220833">here</a> regarding creation of objects, as during the assignment submission, I am supposed to make objects at run-time. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:53:47.517",
"Id": "470055",
"Score": "1",
"body": "\"I am supposed to make objects at run-time. \" Hmm ... Does aggregate initialization has anything to do with compile-time/run-time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T05:20:12.543",
"Id": "470066",
"Score": "1",
"body": "Don't take it that way. All I wanted to say was that objects creation has to be done at run time, i.e. I am supposed to do `Item item(...whatever);` then `items.push_back(item);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T05:56:18.230",
"Id": "470070",
"Score": "1",
"body": "Well, all objects that are not created in a compile-time evaluation context are created at run time. The only benefit of creating the item first and then pushing back is slowing the program down by forcing a copy in case the compiler doesn't optimize that out. And aggregate initialization still allows you to do that (with braces instead of parentheses before C++20)."
}
] |
[
{
"body": "<p>Since you declare a three parameter constructor, the default constructor will not be implicitly defined, so it does not need to be explicitly deleted. There's no real harm in providing a default constructor, since you have initializers for all your members. Alternatively, since the only constructor you supply requires three parameters that initialize all three members of your class, you do not need to provide initializers for them (although doing so can lead to fewer problems in the future if this is expanded on).</p>\n\n<p>The comparison operators should a be declared as <code>const</code> functions. The use of <code>this-></code> in them is not necessary.</p>\n\n<p>The output operator should take <code>item</code> as a reference to avoid making a copy.</p>\n\n<p>The <code>weight</code> and <code>profit</code> functions assume that both provided vectors have the same size. The size used to end the loop can be stored in a variable to avoid potentially recomputing it every time.</p>\n\n<p>In <code>increment</code>, predecrement should be used for iterators (<code>--it_bit;</code>) to avoid making an unnecessary copy. Have you considered using reverse iterators here (using <code>vec.rbegin()</code>)?</p>\n\n<p>The last <code>for</code> loop in <code>main</code> can use the range-for-loop (e.g. <code>for (auto p: possible)</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:53:07.033",
"Id": "470054",
"Score": "1",
"body": "Just to clarify: explicit disables copy-list-initialization, such as `Item i = {1, 2, 3};`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T03:55:08.487",
"Id": "470064",
"Score": "1",
"body": "@L.F. Ah, one of those little details in the language I seem to have missed. I updated my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T18:24:20.567",
"Id": "239621",
"ParentId": "239618",
"Score": "9"
}
},
{
"body": "<h1>Loops</h1>\n\n<blockquote>\n<pre><code>for (int i = 0; i < item_switch.size(); i++) {\n</code></pre>\n</blockquote>\n\n<p>Your loops have a common problem: the correct type for traversing a <code>std::vector<T></code> via index is <code>std::vector<T>::size_type</code> (<code>std::size_t</code> is fine too). However, a better solution is to eliminate loops altogether using <a href=\"https://en.cppreference.com/w/cpp/algorithm/inner_product\" rel=\"nofollow noreferrer\"><code>std::inner_product</code></a> (defined in header <a href=\"https://en.cppreference.com/w/cpp/header/numeric\" rel=\"nofollow noreferrer\"><code><numeric></code></a>) and <a href=\"https://en.cppreference.com/w/cpp/utility/functional/plus\" rel=\"nofollow noreferrer\"><code>std::plus</code></a> (defined in header <a href=\"https://en.cppreference.com/w/cpp/header/functional\" rel=\"nofollow noreferrer\"><code><functional></code></a>):</p>\n\n<pre><code>long weight(const std::vector<Item>& item_list, const std::vector<int>& item_switch)\n{\n return std::inner_product(item_list.begin(), item_list.end(),\n item_switch.begin(), item_switch.end(),\n 0L, std::plus{}, [](const Item& item, int switch_) {\n return item.weight * switch_;\n };\n}\n\nlong profit(const std::vector<Item>& item_list, const std::vector<int>& item_switch)\n{\n return std::inner_product(item_list.begin(), item_list.end(),\n item_switch.begin(), item_switch.end(),\n 0L, std::plus{}, [](const Item& item, int switch_) {\n return item.profit * switch_;\n };\n}\n</code></pre>\n\n<p>Or, with <a href=\"https://ericniebler.github.io/range-v3/\" rel=\"nofollow noreferrer\">range-v3</a>:</p>\n\n<pre><code>long weight(const std::vector<Item>& item_list, const std::vector<int>& item_switch)\n{\n return ranges::inner_product(item_list, item_switch, 0L, {}, {}, &Item::weight, {});\n}\n\nlong profit(const std::vector<Item>& item_list, const std::vector<int>& item_switch)\n{\n return ranges::inner_product(item_list, item_switch, 0L, {}, {}, &Item::profit, {});\n}\n</code></pre>\n\n<h1>Enumerating possibilities</h1>\n\n<p><a href=\"https://en.cppreference.com/w/cpp/utility/bitset\" rel=\"nofollow noreferrer\"><code>std::bitset</code></a> (defined in header <a href=\"https://en.cppreference.com/w/cpp/header/bitset\" rel=\"nofollow noreferrer\"></a>) seems more convenient for enumerating possibilities if the number of elements is fixed at compile-time — <code>std::bitset<4>{13}</code> yields <code>1101</code>, for example.</p>\n\n<p>This loop:</p>\n\n<blockquote>\n<pre><code>for (int i = 0; i < possible.size(); i++) {\n long temp = profit(items, possible[i]);\n if (temp > pr) {\n pr = temp;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>should be replaced by <code>std::max_element</code>.</p>\n\n<h1>My version</h1>\n\n<p>Just for fun, I rewrote the program in a functional style using C++20 and range-v3:</p>\n\n<pre><code>#include <array>\n#include <cstddef>\n#include <iostream>\n#include <range/v3/all.hpp>\n\n// for convenience\nconstexpr auto operator\"\"_zu(unsigned long long num) noexcept\n{\n return static_cast<std::size_t>(num);\n}\n\nnamespace views = ranges::views;\n\nusing profit_type = long long;\nusing weight_type = long long;\n\nstruct Item {\n int weight;\n int profit;\n};\n\ntemplate <std::size_t N>\nprofit_type knapsack(const std::array<Item, N>& items, weight_type max_weight)\n{\n return ranges::max(\n views::iota(0ULL, 1ULL << items.size())\n | views::transform([](auto code) { return std::bitset<N>{code}; })\n | views::filter([&](const auto& mask) {\n auto weight = ranges::accumulate(\n views::iota(0_zu, N) | views::filter([&](auto i) { return mask[i]; }),\n weight_type{0}, {}, [&](auto i) { return items[i].weight; }\n );\n return weight <= max_weight;\n })\n | views::transform([&](const auto& mask) {\n return ranges::accumulate(\n views::iota(0_zu, N) | views::filter([&](auto i) { return mask[i]; }),\n profit_type{0}, {}, [&](auto i) { return items[i].profit; }\n );\n })\n );\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>int main()\n{\n std::cout << knapsack(\n std::to_array<Item>({{10, 60}, {20, 100}, {30, 120}}), 50\n );\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>220\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/dCaljg8hIcxMlMIu\" rel=\"nofollow noreferrer\">live demo</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T02:12:32.730",
"Id": "239635",
"ParentId": "239618",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239621",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T17:33:04.377",
"Id": "239618",
"Score": "9",
"Tags": [
"c++",
"vectors",
"knapsack-problem"
],
"Title": "0/1 knapsack algorithm implementation with possibilities vector"
}
|
239618
|
<p>As a hobby I am working on a game engine in order to learn C++ and graphics programming, now I have completed my first iteration of my camera system using OpengGL and GLM. Because I am mostly self taught I am searching for some feedback.</p>
<p>I am mostly searching for feedback regarding the following points:</p>
<ul>
<li>Is the API easy to understand/implement by another user</li>
<li>Are there any obvious mistakes made regarding performance</li>
<li>Are there any missing features you would suspect to be in a camera controller</li>
<li>Is the API consistent regarding code style and practices</li>
</ul>
<p>But of course any other feedback is also much appreciated!</p>
<p><strong>Perspective Camera</strong><br>
Low level, responsible for the projection matrix</p>
<pre><code>// PerspectiveCamera.h
#ifndef CHEETAH_ENGINE_RENDERER_PERSPECTIVECAMERA_H_
#define CHEETAH_ENGINE_RENDERER_PERSPECTIVECAMERA_H_
#include "Core/Core.h"
#include "Events/ApplicationEvents.h"
#include "Camera.h"
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
namespace cheetah
{
struct PerspectiveCameraParams
{
const float radians = 45.0f;
const float zNear = -1.0f;
const float zFar = 1.0f;
const float aspectRatio;
const float zoom;
const glm::vec3 position = glm::vec3(0.0f);
const glm::vec3 rotationAxis = glm::vec3(1.0f);
const float rotationDegrees = 0.0f;
};
class CH_API PerspectiveCamera : public Camera
{
public:
PerspectiveCamera(const PerspectiveCameraParams& params);
inline glm::mat4 getViewProjectionMatrix() const override { return m_viewProjectionMatrix; };
inline glm::mat4 getProjectionMatrix() const override { return m_projectionMatrix; };
inline glm::mat4 getViewMatrix() const override { return m_viewMatrix; };
inline float getZoom() const override { return m_zoom; };
inline float getAspectRatio() const override { return m_aspectRatio; };
void setZoom(const float& zoom) override;
void setAspectRatio(const float& aspectRatio) override;
void setViewMatrix(const glm::mat4& viewMatrix) override;
void recalculateViewProjectionMatrix() override;
private:
float m_aspectRatio;
float m_zoom;
float m_zNear;
float m_zFar;
float m_radians;
glm::mat4 m_projectionMatrix;
glm::mat4 m_viewMatrix;
glm::mat4 m_viewProjectionMatrix;
};
}
#endif // !CHEETAH_ENGINE_RENDERER_PERSPECTIVECAMERA_H_
</code></pre>
<pre><code>// PerspectiveCamera.cpp
#include "PerspectiveCamera.h"
namespace cheetah
{
PerspectiveCamera::PerspectiveCamera(const PerspectiveCameraParams& params)
:
m_projectionMatrix(glm::perspective(glm::radians(params.radians), params.aspectRatio, params.zNear, params.zFar)),
m_viewMatrix(glm::rotate(glm::translate(glm::mat4(1.0f), params.position), params.rotationDegrees, params.rotationAxis)),
m_viewProjectionMatrix(m_projectionMatrix* m_viewMatrix),
m_aspectRatio(params.aspectRatio),
m_zoom(params.zoom),
m_zNear(params.zNear),
m_zFar(params.zFar),
m_radians(params.radians)
{
}
void PerspectiveCamera::setViewMatrix(const glm::mat4& viewMatrix)
{
m_viewMatrix = viewMatrix;
recalculateViewProjectionMatrix();
}
void PerspectiveCamera::setZoom(const float& zoom)
{
m_zoom = zoom;
m_projectionMatrix = glm::perspective(glm::radians(m_radians += m_zoom), m_aspectRatio, m_zNear, m_zFar);
recalculateViewProjectionMatrix();
}
void PerspectiveCamera::setAspectRatio(const float& aspectRatio)
{
m_aspectRatio = aspectRatio;
m_projectionMatrix = glm::perspective(glm::radians(m_radians), aspectRatio, m_zNear, m_zFar);
recalculateViewProjectionMatrix();
}
void PerspectiveCamera::recalculateViewProjectionMatrix()
{
m_viewProjectionMatrix = m_projectionMatrix * m_viewMatrix;
}
}
</code></pre>
<p><strong>CameraController</strong>
Higher level, doesn't care about camera type(ortho or perspective)</p>
<pre><code>// CameraController.h
#ifndef CHEETAH_ENGINE_RENDERER_CAMERACONTROLLER_H_
#define CHEETAH_ENGINE_RENDERER_CAMERACONTROLLER_H_
#include "Core/Core.h"
#include "Camera.h"
#include "OrthoGraphicCamera.h"
#include "PerspectiveCamera.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/glm.hpp>
#include <memory>
namespace cheetah
{
class CH_API CameraController
{
public:
CameraController(const OrthoGraphicCameraParams& params);
CameraController(const PerspectiveCameraParams& params);
// affect ProjectionMatrix
void setZoom(const float& zoom);
void setAspectRatio(const float& width, const float& height);
// affect ViewMatrix
void setPosition(const glm::vec3& position);
void translate(const glm::vec3& position);
void rotate(const float& degrees, const glm::vec3& axis);
inline float getZoom() const { return m_camera->getZoom(); };
inline float getAspectRatio() const { return m_camera->getAspectRatio(); };
inline glm::vec3 getPosition() const { return m_position; };
inline glm::vec3 getRotationAxis() const { return m_rotationAxis; };
inline float getRotationDegrees() const { return m_rotationDegrees; };
inline Camera& getCamera() const { return *m_camera; };
private:
float m_rotationDegrees;
glm::vec3 m_rotationAxis;
glm::vec3 m_position;
std::unique_ptr<Camera> m_camera;
};
}
#endif // !CHEETAH_ENGINE_RENDERER_CAMERACONTROLLER_H_
</code></pre>
<pre><code>// CameraController.cpp
#include "CameraController.h"
namespace cheetah
{
CameraController::CameraController(const OrthoGraphicCameraParams& params)
:
m_camera(std::make_unique<OrthoGraphicCamera>(params)),
m_position(params.position),
m_rotationAxis(params.rotationAxis),
m_rotationDegrees(params.rotationDegrees)
{
}
CameraController::CameraController(const PerspectiveCameraParams& params)
:
m_camera(std::make_unique<PerspectiveCamera>(params)),
m_position(params.position),
m_rotationAxis(params.rotationAxis),
m_rotationDegrees(params.rotationDegrees)
{
}
void CameraController::setZoom(const float& zoom)
{
m_camera->setZoom(zoom);
}
void CameraController::setAspectRatio(const float& width, const float& height)
{
m_camera->setAspectRatio(width / height);
}
void CameraController::setPosition(const glm::vec3& position)
{
m_position = position;
m_camera->setViewMatrix(glm::rotate(glm::translate(glm::mat4(1.0f), position), m_rotationDegrees, m_rotationAxis));
}
void CameraController::translate(const glm::vec3& position)
{
m_position = position;
m_camera->setViewMatrix(glm::translate(m_camera->getViewMatrix(), m_position));
}
void CameraController::rotate(const float& degrees, const glm::vec3& axis)
{
m_rotationDegrees = degrees;
m_rotationAxis = axis;
m_camera->setViewMatrix(glm::rotate(m_camera->getViewMatrix(), degrees, axis));
}
}
</code></pre>
<p><strong>Implementation</strong><br>
Here a possible way of implementing the CameraController</p>
<pre><code>// MainCamera.h
#ifndef GAME_MAINCAMERA_H_
#define GAME_MAINCAMERA_H_
#include "Cheetah.h"
class MainCamera : public cheetah::CameraController
{
public:
MainCamera(const cheetah::PerspectiveCameraParams& params);
void onUpdate(const float& deltaTime);
bool onWindowResize(const cheetah::WindowResizeEvent& event);
private:
void handleKeyInput(const float& deltaTime);
};
#endif // !GAME_MAINCAMERA_H_
</code></pre>
<pre><code>// MainCamera.cpp
#include "MainCamera.h"
using namespace cheetah;
using namespace math;
using namespace input;
MainCamera::MainCamera(const cheetah::PerspectiveCameraParams& params)
: CameraController(params)
{
}
bool MainCamera::onWindowResize(const WindowResizeEvent& event)
{
setAspectRatio((float)event.m_width, (float)event.m_height);
return true;
}
void MainCamera::onUpdate(const float& deltaTime)
{
handleKeyInput(deltaTime);
}
void MainCamera::handleKeyInput(const float& deltaTime)
{
// reset
if (Input::isKeyPressed(keys::R))
{
setPosition(vec3(0.0f, 0.0f, 0.0));
}
// moving
if (Input::isKeyPressed(keys::W))
{
translate(vec3(0.0f, -(0.001f * deltaTime), 0.0f));
}
if (Input::isKeyPressed(keys::A))
{
translate(vec3(-(0.001f * deltaTime), 0.0f, 0.0f));
}
if (Input::isKeyPressed(keys::S))
{
translate(vec3(0.0f, 0.001f * deltaTime, 0.0f));
}
if (Input::isKeyPressed(keys::D))
{
translate(vec3(0.001f * deltaTime, 0.0f, 0.0f));
}
// rotating
if (Input::isKeyPressed(keys::Q))
{
rotate(-(0.001f * deltaTime), vec3(0, 1, 0));
}
if (Input::isKeyPressed(keys::E))
{
rotate(0.001f * deltaTime, vec3(0, 1, 0));
}
if (Input::isKeyPressed(keys::Z))
{
translate(vec3(0.0f, 0.0f, 0.001f * deltaTime));
}
if (Input::isKeyPressed(keys::X))
{
translate(vec3(0.0f, 0.0f, -(0.001f * deltaTime)));
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your header files seem to be including unnecessary things, apparently for convenience. A header should only include the files required for that header to compile. Anything else just adds to the compile overhead for files that include the header but don't need those details.</p>\n\n<p><code>float</code> parameters should be passed to functions by value, not reference. Passing by value will allow them to be passed in registers, while reference needs both a memory location and a register to hold the address.</p>\n\n<p>You don't need to use the <code>inline</code> keyword when defining a member function in a class, as those are implicitly inline.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T09:20:28.790",
"Id": "470088",
"Score": "0",
"body": "Thanks, is passing by value better for any primitive type? or is it more dependent on the size of the type?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T11:26:15.183",
"Id": "470100",
"Score": "0",
"body": "Passing by reference is not the same as passing by pointer. You should by default pass everything by reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T12:27:23.850",
"Id": "470109",
"Score": "0",
"body": "@rav_kr We are not discussing passing by reference or pointer, but passing by reference or value. I know I should default pass everything by reference, but the answer above provides a reason why that is not always the case and why it could be better to pass by value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T20:11:05.597",
"Id": "470156",
"Score": "1",
"body": "@RickNijhuis Typically the built-in types are passed by value. User types are passed by value or reference depending on how they are used."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T18:38:36.283",
"Id": "239622",
"ParentId": "239619",
"Score": "10"
}
},
{
"body": "<blockquote>\n <p>Is the API easy to understand/implement by another user</p>\n</blockquote>\n\n<p>It depends on how it will be used I think. Maybe the API is just what you need in your project, but another user might want to have a function like <code>lookAt(const glm::vec3 &position)</code> to point the camera at a specific point, or perhaps wants to set the field of view of a perspective camera as an angle, instead of having to specify a \"zoom\" level.</p>\n\n<p>In particular, some functions set something to an absolute value, like <code>setPosition()</code>, others only do relative changes, like <code>rotate()</code>. It would be nice to have both relative and absolute setters for all parameters.</p>\n\n<blockquote>\n <p>Are there any obvious mistakes made regarding performance</p>\n</blockquote>\n\n<p>I don't see any big performance issues. However, consider that once you construct a <code>CameraController</code>, you cannot change the type of the camera (i.e., if you constructed a perspective one, it will always be a perspective camera). So <code>m_camera</code> is always the same during the lifetime of a <code>Camera</code>. If it was not a pointer, but an actual <code>Camera</code> instead, you wouldn't have to pay the price of indirection.</p>\n\n<p>You can do this by making <code>CameraController</code> templated, like so:</p>\n\n<pre><code>template<typename CameraType>\nclass CameraController {\n public:\n CameraController(const CameraType::Params &params);\n ...\n\n private:\n CameraType m_camera;\n};\n</code></pre>\n\n<p>To handle the constructor taking different types of parameters, you have to define the parameter structs inside the implementation of the <code>Camera</code> classes, like so:</p>\n\n<pre><code>class PerspectiveCamera: public Camera {\n public:\n struct Params {\n ...\n };\n\n PerspectiveCamera(const Params &params);\n ...\n};\n</code></pre>\n\n<p>But perhaps even better, just forget about <code>class CameraController</code>, and move its functionality into the base <code>class Camera</code>.</p>\n\n<blockquote>\n <p>Are there any missing features you would suspect to be in a camera controller</p>\n</blockquote>\n\n<p>As mentioned above, a <code>lookAt()</code> function, <code>setFOV()</code> and <code>setRotation()</code>. Also, rotating based on an axis and an angle works for simple rotations, but as soon as you are combining rotations in different axes, things get weird. For a first-person shooter, you probably want to separate the rotation into an angle for the compass direction you are looking at (yaw), one for whether you are looking up or down (pitch), and finally one for how your head is tilted (roll). You want to keep these three values, and construct the rotation matrix from them using <code>glm::gtx::euler_angles::eulerAngleYXZ</code>.</p>\n\n<p>For some applications, for example where you want to be able to rotate a sphere by clicking on a point an dragging it to a new position, you probably want to use <a href=\"https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation\" rel=\"nofollow noreferrer\">quaternions</a> to represent the current rotation.</p>\n\n<blockquote>\n <p>Is the API consistent regarding code style and practices</p>\n</blockquote>\n\n<p>Apart from possible different ways to structure your code as mentioned above, it looks fine. Good use of <code>const</code>, references (except for the <code>float</code>s) and smart pointers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T19:23:34.270",
"Id": "470021",
"Score": "1",
"body": "Thanks, I like your suggestion of moving it to the base class, this seems a better and clean solution. I'll take a look at the proposed functionality, the lookat seems like something I would definitly use in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T18:42:39.077",
"Id": "239624",
"ParentId": "239619",
"Score": "10"
}
},
{
"body": "<p>Using the above answers I have refactored my code and added some functionality.</p>\n\n<p><strong>Refactors:</strong></p>\n\n<ul>\n<li>Made all floats passed by value instead of reference(answer of @1201ProgramAlarm)</li>\n<li>Removed CameraController class and moved logic to Camera base class(answer of @G. Sliepen)</li>\n<li>More specific includes, instead of including glm.hpp now includes only needed definitions like glm/vec3.hpp(answer of @1201ProgramAlarm)</li>\n<li>Renamed \"radians\" in PerspectiveCameraParams to \"fov\" for more clarity </li>\n</ul>\n\n<p><strong>New features</strong> </p>\n\n<ul>\n<li>Added lookAt functionality(answer of @G. Sliepen)</li>\n<li>Added for all functions setting an absolute value also a relative function, per example setRotation and rotate(answer of @G. Sliepen) </li>\n<li>Added setFOV function for changing fov(answer of @G. Sliepen)</li>\n</ul>\n\n<p>Some features, specially regarding rotations still need to be added, I will update this answer when new features are added.</p>\n\n<p><strong>Camera</strong><br>\nAt first a pure interface, now contains shared logic of both types of camera's(perspective/orthographic)</p>\n\n<pre><code>// Camera.h\n#ifndef CHEETAH_ENGINE_RENDERER_CAMERA_H_\n#define CHEETAH_ENGINE_RENDERER_CAMERA_H_\n\n#include \"Core/Core.h\"\n\n#include <glm/mat4x4.hpp>\n#include <glm/vec3.hpp>\n\nnamespace cheetah\n{\n class CH_API Camera\n {\n public:\n Camera(const glm::vec3& position, const::glm::vec3& rotationAxis, const float rotationDegrees, const glm::vec3& up = glm::vec3(0.0f, 1.0f, 0.0f));\n virtual ~Camera() = default;\n\n // perspective/orthographic specific responsibilities\n virtual glm::mat4 getViewProjectionMatrix() const = 0;\n virtual glm::mat4 getProjectionMatrix() const = 0;\n virtual glm::mat4 getViewMatrix() const = 0;\n virtual float getFOV() const = 0;\n virtual float getZoom() const = 0;\n virtual float getAspectRatio() const = 0;\n\n virtual void setFOV(const float fov) = 0;\n virtual void setZoom(const float zoom) = 0;\n virtual void setAspectRatio(const float aspectRatio) = 0;\n virtual void setViewMatrix(const glm::mat4& viewMatrix) = 0;\n virtual void recalculateViewProjectionMatrix() = 0;\n\n virtual void zoom(const float zoom) = 0;\n\n // shared logic\n void setUp(const glm::vec3& up);\n void setPosition(const glm::vec3& position);\n void setRotation(const float degrees, const glm::vec3& axis);\n void translate(const glm::vec3& position);\n void rotate(const float degrees, const glm::vec3& axis);\n void lookAt(const glm::vec3& target);\n\n inline glm::vec3 getUp() const { return m_up; };\n inline glm::vec3 getPosition() const { return m_position; };\n inline glm::vec3 getRotationAxis() const { return m_rotationAxis; };\n inline float getRotationDegrees() const { return m_rotationDegrees; };\n\n private:\n float m_rotationDegrees;\n glm::vec3 m_rotationAxis;\n glm::vec3 m_position;\n glm::vec3 m_up;\n };\n}\n\n#endif // !CHEETAH_ENGINE_RENDERER_CAMERA_H_\n</code></pre>\n\n<pre><code>// Camera.cpp\n#include \"Camera.h\"\n\n#include <glm/gtc/matrix_transform.hpp>\n#include <glm/gtx/rotate_vector.hpp>\n\nnamespace cheetah\n{\n Camera::Camera(const glm::vec3& position, const::glm::vec3& rotationAxis, const float rotationDegrees, const glm::vec3& up)\n : \n m_position(position),\n m_rotationAxis(rotationAxis),\n m_rotationDegrees(rotationDegrees),\n m_up(up)\n {\n }\n\n void Camera::setUp(const glm::vec3& up)\n {\n m_up = up;\n }\n\n void Camera::setPosition(const glm::vec3& position)\n {\n m_position = position;\n setViewMatrix(glm::translate(glm::mat4(1.0f), position));\n }\n\n void Camera::setRotation(const float degrees, const glm::vec3& axis)\n {\n m_rotationAxis = axis;\n setViewMatrix(glm::rotate(getViewMatrix(), degrees - m_rotationDegrees, axis));\n m_rotationDegrees = degrees;\n }\n\n\n void Camera::translate(const glm::vec3& position)\n {\n m_position = position;\n setViewMatrix(glm::translate(getViewMatrix(), m_position));\n }\n\n void Camera::rotate(const float degrees, const glm::vec3& axis)\n {\n m_rotationDegrees += degrees;\n m_rotationAxis = axis;\n setViewMatrix(glm::rotate(getViewMatrix(), degrees, axis));\n }\n\n void Camera::lookAt(const glm::vec3& target)\n {\n setViewMatrix(glm::lookAt(m_position, target, m_up));\n }\n}\n</code></pre>\n\n<p><strong>PerspectiveCamera</strong><br>\nLow level, responsible for camera specific projection matrix</p>\n\n<pre><code>// PerspectiveCamera.h\n#ifndef CHEETAH_ENGINE_RENDERER_PERSPECTIVECAMERA_H_\n#define CHEETAH_ENGINE_RENDERER_PERSPECTIVECAMERA_H_\n\n#include \"Core/Core.h\"\n#include \"Camera.h\"\n\n#include <glm/vec3.hpp>\n#include <glm/mat4x4.hpp>\n\nnamespace cheetah\n{\n struct PerspectiveCameraParams\n {\n const float zNear = -1.0f;\n const float zFar = 1.0f;\n const float aspectRatio;\n const float zoom = 1.0f;\n const float fov = 45.0f;\n const glm::vec3 position = glm::vec3(0.0f);\n const glm::vec3 rotationAxis = glm::vec3(1.0f);\n const float rotationDegrees = 0.0f;\n };\n\n class CH_API PerspectiveCamera : public Camera\n {\n public:\n PerspectiveCamera(const PerspectiveCameraParams& params, const glm::vec3& up = glm::vec3(0.0f, 1.0f, 0.0f));\n\n\n inline glm::mat4 getViewProjectionMatrix() const override { return m_viewProjectionMatrix; };\n inline glm::mat4 getProjectionMatrix() const override { return m_projectionMatrix; };\n inline glm::mat4 getViewMatrix() const override { return m_viewMatrix; };\n inline float getFOV() const override { return m_fov; };\n inline float getZoom() const override { return m_zoom; };\n inline float getAspectRatio() const override { return m_aspectRatio; };\n\n void setFOV(const float fov) override;\n void setZoom(const float zoom) override;\n void setAspectRatio(const float aspectRatio) override;\n void setViewMatrix(const glm::mat4& viewMatrix) override;\n\n void zoom(const float zoom) override;\n\n void recalculateViewProjectionMatrix() override;\n\n private:\n float m_aspectRatio;\n float m_zoom;\n float m_zNear;\n float m_zFar;\n float m_fov;\n glm::mat4 m_projectionMatrix;\n glm::mat4 m_viewMatrix;\n glm::mat4 m_viewProjectionMatrix;\n };\n}\n\n#endif // !CHEETAH_ENGINE_RENDERER_PERSPECTIVECAMERA_H_\n</code></pre>\n\n<pre><code>#include \"PerspectiveCamera.h\"\n\n#include <glm/gtc/matrix_transform.hpp>\n\nnamespace cheetah\n{\n PerspectiveCamera::PerspectiveCamera(const PerspectiveCameraParams& params, const glm::vec3& up)\n :\n Camera(params.position, params.rotationAxis, params.rotationDegrees, up),\n m_projectionMatrix(glm::perspective(glm::radians(params.fov / params.zoom), params.aspectRatio, params.zNear, params.zFar)),\n m_viewMatrix(glm::rotate(glm::translate(glm::mat4(1.0f), params.position), params.rotationDegrees, params.rotationAxis)),\n m_viewProjectionMatrix(m_projectionMatrix* m_viewMatrix),\n m_aspectRatio(params.aspectRatio),\n m_zoom(params.zoom),\n m_zNear(params.zNear),\n m_zFar(params.zFar),\n m_fov(params.fov)\n {\n }\n\n void PerspectiveCamera::setViewMatrix(const glm::mat4& viewMatrix)\n {\n m_viewMatrix = viewMatrix;\n recalculateViewProjectionMatrix();\n }\n\n void PerspectiveCamera::setFOV(const float fov)\n {\n m_fov = fov;\n m_projectionMatrix = glm::perspective(glm::radians(m_fov / m_zoom), m_aspectRatio, m_zNear, m_zFar);\n recalculateViewProjectionMatrix();\n }\n\n void PerspectiveCamera::setZoom(const float zoom)\n {\n m_zoom = zoom;\n m_projectionMatrix = glm::perspective(glm::radians(m_fov / m_zoom), m_aspectRatio, m_zNear, m_zFar);\n recalculateViewProjectionMatrix();\n }\n\n void PerspectiveCamera::zoom(const float zoom)\n {\n m_zoom += zoom;\n m_projectionMatrix = glm::perspective(glm::radians(m_fov / m_zoom), m_aspectRatio, m_zNear, m_zFar);\n recalculateViewProjectionMatrix();\n }\n\n void PerspectiveCamera::setAspectRatio(const float aspectRatio)\n {\n m_aspectRatio = aspectRatio;\n m_projectionMatrix = glm::perspective(glm::radians(m_fov / m_zoom), aspectRatio, m_zNear, m_zFar);\n recalculateViewProjectionMatrix();\n }\n\n void PerspectiveCamera::recalculateViewProjectionMatrix()\n {\n m_viewProjectionMatrix = m_projectionMatrix * m_viewMatrix;\n }\n}\n</code></pre>\n\n<p><strong>Implementation</strong><br>\nPossible way of implementation</p>\n\n<pre><code>// MainCamera.h\n#ifndef GAME_MAINCAMERA_H_\n#define GAME_MAINCAMERA_H_\n\n#include \"Cheetah.h\"\n\nclass MainCamera : public cheetah::PerspectiveCamera\n{\npublic:\n MainCamera(const cheetah::PerspectiveCameraParams& params);\n void onUpdate(const float deltaTime);\n bool onWindowResize(const cheetah::WindowResizeEvent& event);\nprivate:\n void handleKeyInput(const float deltaTime);\n};\n\n#endif // !GAME_MAINCAMERA_H_\n</code></pre>\n\n<pre><code>// MainCamera.cpp\n#include \"MainCamera.h\"\n\nusing namespace cheetah;\nusing namespace math;\nusing namespace input;\n\nMainCamera::MainCamera(const cheetah::PerspectiveCameraParams& params)\n : PerspectiveCamera(params)\n{\n}\n\nbool MainCamera::onWindowResize(const WindowResizeEvent& event)\n{\n setAspectRatio(static_cast<float>(event.m_width) / static_cast<float>(event.m_height));\n return true;\n}\n\nvoid MainCamera::onUpdate(const float deltaTime)\n{\n handleKeyInput(deltaTime);\n}\n\nvoid MainCamera::handleKeyInput(const float deltaTime)\n{\n // reset\n if (Input::isKeyPressed(keys::R))\n {\n lookAt(vec3(0.0f, 0.0f, -20.0f));\n }\n\n // moving\n if (Input::isKeyPressed(keys::W))\n {\n translate(vec3(0.0f, -(0.01f * deltaTime), 0.0f));\n }\n if (Input::isKeyPressed(keys::A))\n {\n translate(vec3(-(0.001f * deltaTime), 0.0f, 0.0f));\n }\n if (Input::isKeyPressed(keys::S))\n {\n translate(vec3(0.0f, 0.01f * deltaTime, 0.0f));\n }\n if (Input::isKeyPressed(keys::D))\n {\n translate(vec3(0.001f * deltaTime, 0.0f, 0.0f));\n }\n if (Input::isKeyPressed(keys::Z))\n {\n translate(vec3(0.0f, 0.0f, 0.01f * deltaTime));\n }\n if (Input::isKeyPressed(keys::X))\n {\n translate(vec3(0.0f, 0.0f, -(0.01f * deltaTime)));\n }\n\n // rotating\n if (Input::isKeyPressed(keys::Q))\n {\n rotate(-(0.01f * deltaTime), vec3(0, 1, 0));\n }\n if (Input::isKeyPressed(keys::E))\n {\n rotate(0.01f * deltaTime, vec3(0, 1, 0));\n }\n\n // zooming\n if (Input::isKeyPressed(keys::C))\n {\n zoom(-(0.01f * deltaTime));\n }\n if (Input::isKeyPressed(keys::V))\n {\n zoom(0.01f * deltaTime);\n }\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T13:21:51.327",
"Id": "239658",
"ParentId": "239619",
"Score": "1"
}
},
{
"body": "<p><strong>Dirty Flag Pattern</strong> </p>\n\n<p>In all the getSomethingMatrix() you can apply the Dirty Flag Pattern described in the book Game Programming Patterns. This one ensure that calculations are only performed when they are needed. And, additionally, you will be able to reduce most of the code duplication inside setter functions. For example:</p>\n\n<pre><code>class CH_API PerspectiveCamera : public Camera \n{\npublic:\n // ... \n private:\n // ...\n bool m_dirty = true;\n};\n</code></pre>\n\n<p>.</p>\n\n<pre><code>void PerspectiveCamera::setZoom(const float& zoom)\n{\n m_zoom = zoom;\n m_dirty = true;\n}\n\nglm::mat4 PerspectiveCamera::getProjectionMatrix() \n{\n if(m_dirty)\n {\n recalculateViewProjectionMatrix();\n }\n return m_projectionMatrix;\n\n\nglm::mat4 PerspectiveCamera::getViewProjectionMatrix() \n{\n if(m_dirty) \n {\n recalculateViewProjectionMatrix();\n }\n return m_viewProjectionMatrix;\n} \n\nvoid PerspectiveCamera::recalculateViewProjectionMatrix() \n{\n m_projectionMatrix = glm::perspective(glm::radians(m_fov/m_zoom), m_aspectRatio, m_zNear, m_zFar);\n m_viewProjectionMatrix = m_projectionMatrix * m_viewMatrix;\n m_dirty = false;\n}\n</code></pre>\n\n<p>Note that this enforce you to remove the const statement of getter functions or make the matrix variables to be mutable. </p>\n\n<p>It also would be nice if you have a class Transform with everything related to position, rotation and scale. That way, the CameraController becomes a generic TransformController (with additional methods to control camera specific fields) and the logic inside MainCamera::handleKeyInput could be applied to any object. This class may be used to get any object model matrix in your game engine. It also makes possible to have transform hierarchies, like a camera attached to a player.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:03:06.597",
"Id": "240935",
"ParentId": "239619",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239624",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T17:59:34.130",
"Id": "239619",
"Score": "9",
"Tags": [
"c++",
"opengl"
],
"Title": "A camera controller API for my game engine"
}
|
239619
|
<p>This is the first time I am posting here, so please go easy on me : ).</p>
<p>I am also writing for the first time python code which uses <code>async</code> / <code>await</code> for streaming web-socket information.</p>
<p>My main goal is to:</p>
<ol>
<li>Connect to a web-socket</li>
<li>Stream info from web-socket</li>
<li>Continuously save the streaming info somewhere (to DB for example).</li>
</ol>
<p>My main concerns are:</p>
<ol>
<li>Whether the code below is streaming information from a web-socket correctly - to be clear: the code is working, but I am not 100% certain it's doing what I want it to do, albeit showing results as expected. There's a lot happening under the hood, hence my concern.</li>
<li>Whether it's also closing the connection to the web-socket.</li>
<li>How to wrap a function over it (i.e. the function that save the data somewhere).</li>
</ol>
<p>If you see other problems with it, please let me know.</p>
<pre><code>msg = {'message': 'subscribe'}
async def stream_websocket_info():
async with websockets.connect(WEBSOCKET_URL) as websocket:
await websocket.send(json.dumps(MESSAGE))
while True:
print(await websocket.recv())
# This is how I run it:
asyncio.get_event_loop().run_until_complete(stream_websocket_info())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T05:36:54.563",
"Id": "470068",
"Score": "0",
"body": "So is this code working? *Whether the code below is streaming information from a web-socket correctly* seems to allude that it isn't working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T13:36:11.023",
"Id": "470116",
"Score": "0",
"body": "The code is working and as an event occurs in the server, the client prints it. But since I am doing this for the first time and sine it's a convoluted subject, I wonder whether I am doing this right and what are potential places which may be future technical debt if I can say so."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T22:48:23.350",
"Id": "239630",
"Score": "3",
"Tags": [
"python",
"async-await",
"websocket"
],
"Title": "Is my async websocket python code correct?"
}
|
239630
|
<p>As I was <a href="https://twitch.tv/aaronchall" rel="nofollow noreferrer">streaming</a> I had a brilliant visitor suggest we write a blockchain in Python.</p>
<p>So we did.</p>
<p>Note that there is no validation or voting simulated here.</p>
<p>Here's the results, in <code>package/blockchain.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>from __future__ import annotations
# https://mypy.readthedocs.io/en/latest/running_mypy.html#missing-imports
from oscrypto.symmetric import aes_cbc_pkcs7_encrypt as encrypt # type: ignore
class Node:
__slots__ = 'prior_node', 'data', 'hash'
prior_node: Node
data: bytes
hash: bytes
def __init__(self, prior_node, key, data):
self.prior_node = prior_node
self.data = data
if prior_node is None:
init_vector = bytes(16)
else:
init_vector = _ensure_byte_length(prior_node.hash, 16)
key = _ensure_byte_length(key, 32)
self.hash = encrypt(key, data, init_vector)[1]
def __repr__(self):
return f'Node<{self.data}\n{self.hash}\n{self.prior_node}>'
def _ensure_byte_length(bytes_, length):
return bytes(bytes_.ljust(length, b'\x00')[:length])
class Chain:
__slots__ = 'nodes'
def __init__(self, key: bytes, data: bytes):
self.nodes = Node(None, key, data)
def __repr__(self):
return f'Chain:\n{self.nodes}'
def new_node(self, key, data):
self.nodes = node = Node(self.nodes, key, data)
return node
def __len__(self):
length = 0
nodes = self.nodes
while nodes:
length += 1
nodes = nodes.prior_node
return length
def main():
chain = Chain(b'the key', b'here is a bit of data')
chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
chain.new_node(b'hunter2', b'and finally here is some more')
print(chain)
if __name__ == '__main__':
main()
</code></pre>
<p>And here's a tiny test, <code>tests/test_blockchain.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>from package.blockchain import Chain
def test_blockchain():
chain = Chain(b'the key', b'here is a bit of data')
chain.new_node(b'P@$$w0rd', b'and here is a bit more data')
chain.new_node(b'hunter2', b'and finally here is some more')
assert len(chain) == 3
</code></pre>
<p>Note that we did require oscrypto and openssl to run this. </p>
<p>Ran coverage with pytest under Python 3.7. Ran with black and mypy as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:10:11.483",
"Id": "470037",
"Score": "1",
"body": "Have you edited this since you ran the code through black? Because black uses `\"` for string literals, and would change your inline comment to be PEP 8 compliant. Also it would add 2 empty lines between your top level functions and classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:24:53.707",
"Id": "470041",
"Score": "1",
"body": "@Peilonrayz silly me, I'm using nix-build and it's running black on the build directory and not the source... I should have known something was wrong with it when I didn't notice changes..."
}
] |
[
{
"body": "<ol>\n<li><p>By default mypy doesn't test much. This is because a large part of its philosophy is to allow dynamic and statically typed code at the same time. This is so migrating to mypy is easier and less daunting. Having thousands of errors when you start to port your legacy app is likely to scare a fair few mortals away.</p>\n\n<p>Please use the <code>--strict</code> flag to have typed Python, rather than hybrid Python.</p>\n\n<p>When you use the flag and you type all the functions and methods, you'll notice that there's an issue with <code>Node.prior_node</code>. Currently it's assigned the type <code>Node</code>, but we know that's a lie because we have <code>if prior_node is None</code>.</p></li>\n<li><p>I personally use <code>--ignore-missing-imports</code> rather than ignoring each import, as they quickly build up over time.</p></li>\n<li><p>Your <code>__repr__</code> are <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__repr__\" rel=\"nofollow noreferrer\">non standard</a>.</p>\n\n<blockquote>\n <p>Called by the <a href=\"https://docs.python.org/3/library/functions.html#repr\" rel=\"nofollow noreferrer\">repr()</a> built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <code><...some useful description...></code> should be returned.</p>\n</blockquote>\n\n<p>You probably want to be using <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__str__\" rel=\"nofollow noreferrer\"><code>__str__</code></a>.</p></li>\n<li><p>I find it a little confusing that <code>init_vector</code> is being assigned two different things. It would make more sense if you pass in an empty bytes to <code>_ensure_byte_length</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>prior_hash = b'' if prior_node is None else prior_node.hash\ninit_vector = _ensure_byte_length(prior_hash, 16)\n</code></pre>\n\n<p>You could change the ternary into a <code>getattr</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>prior_hash = getattr(prior_hash, 'hash', b'')\n</code></pre></li>\n<li><p>I would change <code>Node</code> to a <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclass</a>. Why write code when you can just not?</p>\n\n<p>This would require moving the hash generation into a class method.</p></li>\n<li><p>I would define an <code>__iter__</code> method on the node so that we can easily traverse the chain from any node.</p>\n\n<p>This makes the <code>__len__</code> method of <code>Chain</code> really simple and clean.</p></li>\n<li><p>I'd rename <code>_ensure_byte_length</code> to <code>_pad</code>. The function has two jobs, pad is well known and allows us to have a much shorter function name.</p></li>\n<li><code>_ensure_byte_length</code> doesn't need the extra <code>bytes</code> call.</li>\n<li>The method <code>Chain.add_node</code> is un-Pythonic. In Python it's standard to return nothing from a function with mutations.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nimport dataclasses\nfrom typing import Optional, Iterator\n\nfrom oscrypto.symmetric import aes_cbc_pkcs7_encrypt as encrypt\n\n\n@dataclasses.dataclass\nclass Node:\n prev_node: Optional[Node]\n data: bytes\n hash: bytes\n\n @classmethod\n def build(cls, key: bytes, data: bytes, prev_node: Optional[Node] = None) -> Node:\n prev_hash = b\"\" if prev_node is None else prev_node.hash\n hash = encrypt(_pad(key, 32), data, _pad(prev_hash, 16))[1]\n return cls(prev_node, data, hash)\n\n def __iter__(self) -> Iterator[Node]:\n node: Optional[Node] = self\n while node is not None:\n yield node\n node = node.prev_node\n\n\ndef _pad(bytes_: bytes, length: int) -> bytes:\n return bytes_.ljust(length, b\"\\x00\")[:length]\n\n\n@dataclasses.dataclass\nclass Chain:\n node: Node\n\n def add_node(self, key: bytes, data: bytes) -> None:\n self.node = Node.build(key, data, self.node)\n\n def __len__(self) -> int:\n return sum(1 for _ in self.node)\n\n\ndef main() -> None:\n chain = Chain(Node.build(b\"the key\", b\"here is a bit of data\"))\n chain.add_node(b\"P@$$w0rd\", b\"and here is a bit more data\")\n chain.add_node(b\"hunter2\", b\"and finally here is some more\")\n print(chain)\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T03:03:08.430",
"Id": "470062",
"Score": "0",
"body": "1. thx. 2. thx. 3. you quoted \"<...some useful description...>\" - I do that, and `__repr__` is a fallback for `__str__`. 4. will consider 5. maybe, what about `__new__`? 6. thx 7. pad, no, this will truncate - pad doesn't. 8. thx 9. eh, set returns self on mutating. I really don't like the `Node.build` - will `__new__` work? What about `__post_init__`? https://docs.python.org/3/library/dataclasses.html#post-init-processing - thanks for putting so much effort into reviewing - +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T03:29:34.777",
"Id": "470063",
"Score": "0",
"body": "@AaronHall 3. Please re-look at `Chain.__repr__`. No `__repr__` isn't a fallback for `__str__` it's a fallback for `str`. They achieve very different things. 7. Seems pedantic at the cost of nice usage. 9. Right and exceptions define the norm. Whatever. 9.b. New and post may work for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T14:44:53.760",
"Id": "470122",
"Score": "0",
"body": "@AaronHall 3. I think you failed to read \"If this is not possible\". 9. I made the mistake of trusting rando's on the internet. No, [set doesn't return self](https://pastebin.com/mSrbHTp6). Only the special i-op dunder methods do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T15:11:45.133",
"Id": "470126",
"Score": "0",
"body": "I had the recollection that sets were a source of inconsistency in that area, I wonder where I got that from."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T02:31:13.473",
"Id": "239636",
"ParentId": "239632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T00:34:09.433",
"Id": "239632",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"blockchain",
"encryption"
],
"Title": "Grokking the basics of BlockChain with Python"
}
|
239632
|
<p>I have a part of code that is loading a dataset and normalizing property values to [0, 1]. My implementation is:</p>
<pre><code>import pickle
import numpy as np
# -- load data
prop_1 = list(np.random.rand(10)*20)
prop_2 = list(np.random.rand(10)*10)
prop_3 = list(np.random.rand(10)*30)
# -- normalize
l_bound = []
l_bound.append(min(prop_1))
l_bound.append(min(prop_2))
l_bound.append(min(prop_3))
u_bound = []
u_bound.append(max(prop_1))
u_bound.append(max(prop_2))
u_bound.append(max(prop_3))
prop_1 = (np.array(prop_1) - l_bound[0]) / (u_bound[0] - l_bound[0])
prop_2 = (np.array(prop_2) - l_bound[1]) / (u_bound[1] - l_bound[1])
prop_3 = (np.array(prop_3) - l_bound[2]) / (u_bound[2] - l_bound[2])
</code></pre>
<p>However, the normalizing part of the code does not look graceful. Any suggestions on how to improve it? Can do this using a loop?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:41:00.287",
"Id": "470046",
"Score": "0",
"body": "Can you show the result of `prop_*` as loaded by `pickle`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:41:29.710",
"Id": "470047",
"Score": "0",
"body": "Also, why are you loading the same file three times?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:46:22.283",
"Id": "470048",
"Score": "0",
"body": "It's not the same file, it's 3 separate variables. Each variable is a list of property values for 2000 molecules."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:47:13.173",
"Id": "470049",
"Score": "0",
"body": "It... definitely looks like the same file to me. You use `f` three times. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:49:29.610",
"Id": "470051",
"Score": "0",
"body": "That's just how pickle works, you save data using: `with open(dataset_name, \"wb\") as f:\n pickle.dump(prop_1, f)\n pickle.dump(prop_2, f)\n pickle.dump(prop_3, f)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:51:09.277",
"Id": "470053",
"Score": "0",
"body": "OK; so it's one file containing three separate sections. Fair enough. Can you show an example of a couple of molecules? Otherwise this question is difficult to answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:57:13.047",
"Id": "470056",
"Score": "0",
"body": "Ah, I just mentioned that to clear things up, otherwise, I'm dealing with properties only in this subsection. So essentially, I'm loading 3 properties, then find lower and upper bounds for each list of property values, and then normalize each list so that the final output is in the interval [0,1]. Now, what I don't like is that I can't write a loop [it is possible I guess, I had few unsuccessful attempts though]. So if I had 10 properties, I would have had a longer script. So I was wondering if you can suggest how to write the normalization part in a loop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:58:35.870",
"Id": "470057",
"Score": "0",
"body": "Again. Please show sample data in the question. This question currently does not have enough context to be on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T02:04:09.543",
"Id": "470058",
"Score": "0",
"body": "I see that loading data is confusing you. I updated the data loading part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T00:57:04.187",
"Id": "470179",
"Score": "0",
"body": "What kind of data are you serializing/loading?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T02:06:38.733",
"Id": "470183",
"Score": "0",
"body": "@AMC 3 lists of floats, using pickle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T02:07:19.490",
"Id": "470184",
"Score": "0",
"body": "@Blade Lists? Is your code meant to work with numpy arrays, or plain Python lists?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T02:11:54.557",
"Id": "470185",
"Score": "0",
"body": "@AMC Non. It is supposed to be 'torch.Tensor'. But my data generation script is consist of a loop over inputs (molecules) and computes them using cheminformatic packages and is using 'append' to create my property vector. That's why it is a list. later on I convert it to torch tensor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T02:16:05.670",
"Id": "470186",
"Score": "0",
"body": "@AMC Also, the only reason I use numpy here is to mimic my data, nothing else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T19:58:10.497",
"Id": "470241",
"Score": "0",
"body": "@Blade _But my data generation script is consist of a loop over inputs (molecules) and computes them using cheminformatic packages and is using 'append' to create my property vector. That's why it is a list. later on I convert it to torch tensor._ Ah, alright. I was just asking to try to figure out if there is a better solution than using pickle."
}
] |
[
{
"body": "<p>I took a stab at this, not really knowing what you wanted. The function below yields the outcome of each calculation made in your program. You can pass any amount of <code>np.array</code> to it, aka any iterables, and it will make the calculation based on what you passed. Have a look:</p>\n\n<pre><code>from typing import Iterable, Any\nimport numpy as np\n\ndef normalize(*iterables: Iterable[Any]) -> Iterable[np.array]:\n for iterable in iterables:\n my_array = np.array(list(iterable))\n lower, upper = my_array.min(), my_array.max()\n yield (my_array - lower) / (upper - lower)\n</code></pre>\n\n<p>Thanks to <a href=\"https://codereview.stackexchange.com/users/123200/maarten-fabr%C3%A9\">@Maarten Fabré</a> for pointing out that real iterables were excluded from this program, and would fail. It now works with these, as displayed below. This function also now complies with PEP 0484 type hints regarding iterables.</p>\n\n<p>Here's how you could use this:</p>\n\n<pre><code>props = [list(np.random.rand(10)*20), list(np.random.rand(10)*10), list(np.random.rand(10)*30)]\n\nfor prop in normalize(array for array in props):\n print(prop)\n\nfor prop in normalize(props):\n print(prop)\n</code></pre>\n\n<p>I also tested the efficiency of your program against this one.</p>\n\n<pre><code>print(f\"OLD: {timeit.timeit(old_normalize, number=100000)} seconds.\")\nprint(f\"NEW: {timeit.timeit(normalize, number=100000)} seconds.\")\n</code></pre>\n\n<pre><code>OLD: 2.7710679 seconds.\nNEW: 0.0201071 seconds.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:08:58.980",
"Id": "470074",
"Score": "0",
"body": "your method would not work on a read iterable. Did you try `list(normalize((i for i in range(3))))`. You need to create the array first, and then take the min and max from that. That will be a lot faster for largers arrays too"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:14:48.527",
"Id": "470075",
"Score": "0",
"body": "`mypy` also complains about the type annotations. It should be `def normalize(*iterables: Iterable[Any])` or `iterable[float]` if you want to limit the operation to numbers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:25:44.643",
"Id": "470076",
"Score": "0",
"body": "[reference](https://www.python.org/dev/peps/pep-0484/#arbitrary-argument-lists-and-default-argument-values)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:37:10.230",
"Id": "470078",
"Score": "0",
"body": "@MaartenFabré Just updated, thanks for catching that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:43:03.137",
"Id": "470080",
"Score": "1",
"body": "That's not what I meant. Calling it with an iterable still will not work... you need something like this: `def normalize(*iterables: Iterable[Any]) -> np.array:\n for iterable in iterables:\n my_array = np.array(list(iterable))\n lower, upper = my_array.min(), my_array.max()\n yield (my_array - lower) / (upper - lower)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:55:40.360",
"Id": "470081",
"Score": "0",
"body": "@MaartenFabré I'm not really sure what you mean. Passing multiple types of iterables, including read iterables, has the expected output. What kind of iterables won't work that the OP requires? The most I see required are `list` and a read iterable since they state they might have ~10+ lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:57:50.793",
"Id": "470084",
"Score": "0",
"body": "the 'read' was a typo. I meant real iterable, as in not a container. One that exhausts.`list(normalize((i for i in range(3))))` still doesn't work on your method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T08:02:52.713",
"Id": "470086",
"Score": "1",
"body": "@MaartenFabré That makes a lot more sense. Thanks so much for the clarification. I'll community wiki this since you helped greatly in the process of fixing this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T08:31:35.940",
"Id": "470087",
"Score": "1",
"body": "Are you sure you included a `list` call in your timing? Because otherwise it is just the time needed to setup the generator."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T03:15:15.957",
"Id": "239637",
"ParentId": "239633",
"Score": "2"
}
},
{
"body": "<p>Since you have <code>numpy</code> arrays, you should use their vectorized methods wherever possible. This can make your code a lot faster:</p>\n\n<pre><code>In [1]: x = np.arange(10000000)\n\nIn [2]: %timeit max(x)\n988 ms ± 42.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n\nIn [3]: %timeit x.max()\n9.67 ms ± 114 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n\n<p>This includes not casting your arrays to <code>list</code>.</p>\n\n<p>I would also make this a function that normalizes a single array:</p>\n\n<pre><code>import pickle\nimport numpy as np\nfrom typing import Iterable, Any\n\ndef normalize_one(x: Iterable[Any]) -> np.ndarray:\n if not isinstance(x, np.ndarray):\n x = np.array(list(x))\n low, diff = x.min(), x.ptp()\n return (x - low) / diff\n\n# -- load data\nprop_1 = np.random.rand(10)*20\nprop_2 = np.random.rand(10)*10\nprop_3 = list(np.random.rand(10)*30\n\n# -- normalize\nprop_1 = normalize_one(prop_1)\nprop_2 = normalize_one(prop_2)\nprop_3 = normalize_one(prop_3)\n</code></pre>\n\n<p>If you do have many arrays that need to be normalized, you can always do it in a list comprehension:</p>\n\n<pre><code>properties = [prop_1, prop_2, prop_3]\nproperties = [normalize_one(prop) for prop in properties]\n</code></pre>\n\n<p>If you have many of them and they all have the same structure, I would use something like this (now limited to <code>numpy</code> arrays as input):</p>\n\n<pre><code>def normalize(x: np.ndarray, axis: int = 1) -> np.ndarray:\n \"\"\"Normalize the array to lie between 0 and 1.\n By default, normalizes each row of the 2D array separately.\n \"\"\"\n low, diff = x.min(axis=axis), x.ptp(axis=axis)\n # Indexing needed to help numpy broadcasting\n return (x - low[:,None]) / diff[:,None]\n\nproperties = np.random.rand(3, 10)\nproperties[0] *= 20\nproperties[1] *= 10\nproperties[2] *= 30\n\nproperties = normalize(properties)\n</code></pre>\n\n<p>For <code>props = np.random.rand(10000, 10)</code> I get the following timings:</p>\n\n<pre><code>Author Timed function call Time [s]\nBlade* list(normalize_blade(props)) 68.7 ms ± 749 µs\nLinny list(normalize_linny(*props)) 127 ms ± 1.42 ms\nGraipher [normalize_one(prop) for prop in props] 119 ms ± 7.4 ms\nGraipher normalize(props) 2.32 ms ± 113 µs\n</code></pre>\n\n<p>The code I used for the test with the code in the OP is this one, which is just the generalization to many properties:</p>\n\n<pre><code>def normalize_blade(properties):\n l_bound, u_bound = [], []\n properties = [list(prop) for prop in properties]\n for prop in properties:\n l_bound.append(min(prop))\n u_bound.append(max(prop))\n for i, prop in enumerate(properties):\n yield (np.array(prop) - l_bound[i]) / (u_bound[i] - l_bound[i])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T11:58:45.810",
"Id": "470104",
"Score": "0",
"body": "strange that `normalize_one` is slower than `normalize_blade`, using the list appends and builtin `min` and `max` instead of the `numpy methods`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T12:22:35.293",
"Id": "470108",
"Score": "0",
"body": "@MaartenFabré I agree, I was also surprised. It might be due to the `isinstance`, but I'm not sure. Or maybe `numpy.ptp` is slower than `numpy.max` plus one subtraction. Also, note that each property is only 10 elements long, as in the OP, so the built-in operations are still quite fast. If you see any obvious mistakes in my timing, let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T14:59:21.983",
"Id": "470124",
"Score": "0",
"body": "I don't see why it's slower either. If you write it as ` low, high = x.min(), x.max()\n return (x - low) / (high - low)` instead with `ptp` is about 25% faster, but still slower than OP. Removing the `isinstance` and `list` speeds it up a bit, but still not enough"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T08:03:17.300",
"Id": "239640",
"ParentId": "239633",
"Score": "5"
}
},
{
"body": "<h1>keep your raw data</h1>\n\n<p>You overwrite <code>props_x</code> with the normalized version. Better would be to make this a new variable</p>\n\n<h1>data structures</h1>\n\n<p>If you have more than 1 or 2 properties. Assigning them each to their own variable can become quite tedious. You need to gather them in a data structure. If they are all of the same length, a <code>numpy.array</code> or <code>pandas.DataFrame</code> can be the right structures. \nOtherwise a <code>dict</code> might be more appropriate</p>\n\n<pre><code>data_raw = {\n \"prop_1\": list(np.random.rand(10) * 20),\n \"prop_2\": list(np.random.rand(10) * 10),\n \"prop_3\": list(np.random.rand(10) * 30),\n}\n</code></pre>\n\n<h1>function</h1>\n\n<p>Almost each time you write a comment in your code denoting a section, you can make the code itself clearer by putting that section in a data structure, function, class, ...</p>\n\n<pre><code>def normalize(iterable: Iterable[Any]) -> np.array:\n \"\"\"Linearly scales the input to the interval [0, 1]\"\"\"\n my_array = np.array(list(iterable))\n lower, upper = my_array.min(), my_array.max()\n return (my_array - lower) / (upper - lower)\n</code></pre>\n\n<p>I even added a docstring explaining what the method does.</p>\n\n<pre><code>data_normalized = {\n name: normalize(data)\n for name, data in data_raw.items()\n}\n</code></pre>\n\n<h1>spacing</h1>\n\n<p>For code formatting, I trust <a href=\"https://github.com/psf/black\" rel=\"nofollow noreferrer\"><code>black</code></a> to make the correct choices for me.So no more <code>prop_1 =</code>, but 1 space around the <code>=</code>, ...</p>\n\n<p>The only coniguration I use there is maximum 79 character per line.</p>\n\n<p>Black integrates wellwith most IDEs and jupyter lab notebooks (<a href=\"https://black.readthedocs.io/en/stable/editor_integration.html\" rel=\"nofollow noreferrer\">docs</a>)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T08:18:36.527",
"Id": "239642",
"ParentId": "239633",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239640",
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T01:16:04.797",
"Id": "239633",
"Score": "6",
"Tags": [
"python",
"numpy"
],
"Title": "Improvement on data normalization"
}
|
239633
|
<p>The following snippet of C includes implementations for both Windows NT and POSIX-compliant systems to get the time (with microsecond resolution) since the Unix epoch. In the case of Windows NT, the time is registered as 100-nanosecond ticks since the NT epoch (1/1/1601), so it requires a bit of conversion.</p>
<p>I feel like this is the best solution I could've come up with, but it still feels a bit <em>clunky</em>. See if you can help:</p>
<pre class="lang-c prettyprint-override"><code>#if defined(__unix__) || defined(unix) || defined(__unix) || defined(__CYGWIN__)
#include <sys/time.h>
static struct timeval lnm_current_time;
#elif defined(_WIN32) || defined(__WINDOWS__)
#include <windows.h>
#include <sysinfoapi.h>
static FILETIME lnm_win32_filetime;
#else
#error lognestmonster: Neither Windows NT nor a POSIX-compliant system were detected.\
Implement your own system time functions or compile on a compliant system.
#endif
uint64_t lnm_getus(void) {
uint64_t us;
#if defined(__unix__) || defined(unix) || defined(__unix) || defined(__CYGWIN__)
gettimeofday(&lnm_current_time, NULL);
us = (lnm_current_time.tv_sec*1000000+lnm_current_time.tv_usec);
#elif defined(_WIN32) || defined(__WINDOWS__)
// get system time in ticks
GetSystemTimeAsFileTime(&lnm_win32_filetime);
// load time from two 32-bit words into one 64-bit integer
us = lnm_win32_filetime.dwHighDateTime;
us = us << 32;
us |= lnm_win32_filetime.dwLowDateTime;
// convert to microseconds
us /= 10;
// convert from time since Windows NT epoch to time since Unix epoch
us -= 11644473600000000ULL;
#endif
return us;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Using static file-scope variables </p>\n\n<pre><code>static struct timeval lnm_current_time;\n// ...\nstatic FILETIME lnm_win32_filetime;\n</code></pre>\n\n<p>makes your code thread-unsafe: Two “simultaneous” invocations of your function from different threads access the same memory. (For other potential drawbacks of static file-scope variables see for example <a href=\"https://softwareengineering.stackexchange.com/q/294737/83021\">Are file-scope <code>static</code> variables in C as bad as <code>extern</code> global variables?</a> on Software Engineering.)</p>\n\n<p>And there is no reason to use static variables here. With function local variables </p>\n\n<pre><code>uint64_t lnm_getus(void) {\n uint64_t us;\n#if defined(__unix__) || defined(unix) || defined(__unix) || defined(__CYGWIN__)\n struct timeval lnm_current_time;\n gettimeofday(&lnm_current_time, NULL);\n // ...\n#elif defined(_WIN32) || defined(__WINDOWS__)\n FILETIME lnm_win32_filetime;\n GetSystemTimeAsFileTime(&lnm_win32_filetime);\n // ...\n#endif\n return us;\n}\n</code></pre>\n\n<p>the variables are defined exactly where they are needed, which makes the code easier to read and to argue about, and avoids the threading problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T08:14:25.630",
"Id": "239641",
"ParentId": "239638",
"Score": "4"
}
},
{
"body": "<p>In larger programs, lots of "compiler switches" (#ifdefs) make the code very hard to read, "clunky" if you will. It's not an issue in a tiny program such as this, but for larger programs you should consider a more "polymorphic" approach.</p>\n<p>Like for example having a generic "epoch.h" as the platform-independent API. Link this with with a corresponding "epoch_unix.c" or "epoch_windows.c" file, where the C file contains everything OS-specific. Manage which one that gets linked using different builds and/or version control.</p>\n<hr />\n<p>Some minor details:</p>\n<ul>\n<li><p>You forgot <code>#include <stdint.h></code>.</p>\n</li>\n<li><p><code>lnm_current_time.tv_sec*1000000+lnm_current_time.tv_usec</code>. Make a habit of always declaring integer constants with a large enough type, no matter where they happen to be in an expression.</p>\n<p>That is, <code>1000000ULL</code>, or if you prefer <code>UINT64_C(1000000)</code>, the former giving type <code>unsigned long long</code> and the latter giving type <code>uint_least64_t</code>. The latter is ever so slightly more portable, but a bit harder to read.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T16:01:52.230",
"Id": "470230",
"Score": "0",
"body": "The multiplication will implicitly convert from `int` to the appropriate type, won't it? (And it's *epoch*, not *epoc*.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T06:59:07.037",
"Id": "470273",
"Score": "1",
"body": "@S.S.Anne _Only_ if `lnm_current_time.tv_sec` is of an appropriate type. Which is hard to tell, you have to dig deep in documentation to find out just what `time_t` actually is."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T12:41:14.363",
"Id": "239695",
"ParentId": "239638",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T03:29:27.093",
"Id": "239638",
"Score": "2",
"Tags": [
"c"
],
"Title": "Getting time since Unix epoch on both Windows NT and *NIX systems"
}
|
239638
|
<p>As some you you may know, handling disconnected entities in EF can be a bit of a headache. After a really long weekend, I managed to make it work for my use case and refactor the code to the best of my knowledge. However, I'm still not happy with it since every time I have to add a new entity to map, it requires a significant amount of effort + error prone code.</p>
<p>The major issues I find with my current implementation are:</p>
<ol>
<li><p>There is A LOT of boilerplatey code. Having to handle each property individually, specially owned types, makes the code very lengthy.</p></li>
<li><p>The code is VERY duplicated, specially owned types. However, even though I've tried some techniques, like using reflection to make it less so, it wouldn't work. For example, the <code>Reference</code> method that the context entry provides expects an actual property access, not a value, so I could't use the <code>GetProperty</code> helper I manufactured.</p></li>
<li><p>It's not scalable: if I add an owned type, say the address, to one of the relationships, say the BankInfo, then the code I have to write just multiplies, and the amount of branches is huge. This particularly bothers me because it's something I actually have to do down the line.</p></li>
</ol>
<p>With no further due, this is a simplified version of my working code. Please bear in mind that for simplicity I have not included ALL the POCO's, but I have their reference so the complexity can be noticed. Just assume they are a POCO (BankInfo, Doctor, Medicare, etc. classes)</p>
<pre><code>[Owned]
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zipcode { get; set; }
public string County { get; set; }
}
public class BankInfo
{
public int ID { get; set; }
[ForeignKey("Client")] public int ClientID { get; set; }
public Client Client { get; set; }
public string Phone { get; set; }
public string Bank { get; set; }
public string RoutingNumber { get; set; }
public string AccountNumber { get; set; }
}
public class MedicareAccount
{
public int ID { get; set; }
[ForeignKey("Client")] public int ClientID { get; set; }
public Client Client { get; set; }
public string MedicareNumber { get; set; }
public DateTime? PartAEffectiveDate { get; set; }
public DateTime? PartBEffectiveDate { get; set; }
}
public class Doctor
{
public int ID { get; set; }
[ForeignKey("Client")] public int ClientID { get; set; }
public Client Client { get; set; }
public string FullName { get; set; }
public string Office { get; set; }
public string Phone { get; set; }
}
public class Prescription
{
public int ID { get; set; }
[ForeignKey("Client")] public int ClientID { get; set; }
public Client Client { get; set; }
public string Instructions { get; set; }
public string Dosage { get; set; }
public string Frequency { get; set; }
public string Condition { get; set; }
public string StartDate { get; set; }
}
public class Client
{
public int ID { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
// Owned Types
public Address Address { get; set; }
public Address MailingAddress { get; set; }
// Relationships. BankInfo provided as an Example.
public BankInfo BankInfo { get; set; }
public MedicareAccount Medicare { get; set; }
public Doctor Doctor { get; set; }
public List<Prescription> Prescriptions { get; set; }
public Client()
{
Prescriptions = new List<Prescription>();
}
// In order to be able to access properties dynamically from
// ClientService - see below for usage.
public object this[string propertyName]
{
get
{
var property = GetType().GetProperty(propertyName);
return property?.GetValue(this, null);
}
set
{
var property = GetType().GetProperty(propertyName);
property?.SetValue(this, value, null);
}
}
}
public class ClientContext : IdentityDbContext
{
public ClientContext(DbContextOptions<ClientContext> options) : base(options)
{
}
public DbSet<Client> Clients { get; set; }
public DbSet<BankInfo> BankInfos { get; set; }
public DbSet<MedicareAccount> MedicareAccounts { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<Prescription> Prescriptions { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<MedicareAccount>()
.HasIndex(e => e.ClientID)
.IsUnique();
}
}
class ClientService
{
private ClientContext _context;
public ClientService(ClientContext context)
{
_context = context;
}
// This is the entry point to the service.
public async Task Save(Client client)
{
// Is the client being tracked by Entity Framework?
var isNotTracked = _context.Clients.Local.All(e => e.ID != client.ID);
var exists = ClientExists(client.ID);
if (exists && isNotTracked)
{
await HandleDisconnectedScenario(client);
}
else if (!exists)
{
_context.Add(client);
}
await _context.SaveChangesAsync();
}
public async Task<Client> FindById(int id)
{
return await _context.Clients
.Include(b => b.BankInfo)
.Include(b => b.Medicare)
.Include(b => b.Doctor)
.Include(b => b.Prescriptions)
.FirstOrDefaultAsync(m => m.ID == id);
}
private async Task HandleDisconnectedScenario(Client client)
{
var existingClient = await FindById(client.ID);
_context.Entry(existingClient).CurrentValues.SetValues(client);
// Handle simple one-to-one relationships
HandleOneToOneRelationship(existingClient, client, GetPropertyName(() => client.BankInfo));
HandleOneToOneRelationship(existingClient, client, GetPropertyName(() => client.Doctor));
HandleOneToOneRelationship(existingClient, client, GetPropertyName(() => client.Medicare));
// Handle owned types
if (existingClient.Address == null && client.Address != null)
{
_context.Entry(existingClient)
.Reference(a => a.Address).CurrentValue = client.Address;
}
else if (existingClient.Address != null && client.Address != null)
{
_context.Entry(existingClient.Address).CurrentValues.SetValues(client.Address);
}
else if (existingClient.Address != null && client.Address == null)
{
_context.Remove(existingClient.Address);
}
if (existingClient.MailingAddress == null && client.MailingAddress != null)
{
_context.Entry(existingClient)
.Reference(a => a.MailingAddress).CurrentValue = client.MailingAddress;
}
else if (existingClient.MailingAddress != null && client.MailingAddress != null)
{
_context.Entry(existingClient.MailingAddress).CurrentValues.SetValues(client.MailingAddress);
}
else if (existingClient.MailingAddress != null && client.MailingAddress == null)
{
_context.Remove(existingClient.MailingAddress);
}
// Handle one-to-many relationships
foreach (var prescription in existingClient.Prescriptions)
{
if (client.Prescriptions.All(p => p.ID != prescription.ID))
{
_context.Remove(prescription);
}
}
foreach (var prescription in client.Prescriptions)
{
var existingPrescription = existingClient.Prescriptions.FirstOrDefault(p => p.ID == prescription.ID);
if (existingPrescription == null)
{
existingClient.Prescriptions.Add(prescription);
}
else
{
_context.Entry(existingPrescription).CurrentValues.SetValues(prescription);
}
}
}
private void HandleOneToOneRelationship(Client existingClient, Client client, string property)
{
var currentValue = client[property];
var existingValue = existingClient[property];
if (existingValue == null && currentValue != null)
{
_context.Add(currentValue);
}
else if (existingValue != null && currentValue != null)
{
_context.Entry(existingValue).CurrentValues.SetValues(currentValue);
}
else if (existingValue != null)
{
_context.Remove(existingValue);
}
}
private static string GetPropertyName<T>(Expression<Func<T>> propertyExpression) =>
(propertyExpression.Body as MemberExpression)?.Member.Name;
}
</code></pre>
<p>For those who may find the <code>HandleDisconnectedScenario</code> method confusing due to my failure to maintain the level of abstraction, here is exactly the same method, same functionality, but without the <code>HandleOneToOne</code> abstraction, hence keeping it completely concrete.</p>
<pre><code>private async Task HandleDisconnectedScenario(Client client)
{
var existingClient = await FindById(client.ID);
_context.Entry(existingClient).CurrentValues.SetValues(client);
// Client Address
if (existingClient.Address == null && client.Address != null)
{
_context.Entry(existingClient)
.Reference(a => a.Address).CurrentValue = client.Address;
}
else if (existingClient.Address != null && client.Address != null)
{
_context.Entry(existingClient.Address).CurrentValues.SetValues(client.Address);
}
else if (existingClient.Address != null && client.Address == null)
{
_context.Remove(existingClient.Address);
}
// Mailing Address
if (existingClient.MailingAddress == null && client.MailingAddress != null)
{
_context.Entry(existingClient)
.Reference(a => a.MailingAddress).CurrentValue = client.MailingAddress;
}
else if (existingClient.MailingAddress != null && client.MailingAddress != null)
{
_context.Entry(existingClient.MailingAddress).CurrentValues.SetValues(client.MailingAddress);
}
else if (existingClient.MailingAddress != null && client.MailingAddress == null)
{
_context.Remove(existingClient.MailingAddress);
}
// BankInfo
if (existingClient.BankInfo == null && client.BankInfo != null)
{
_context.Add(existingClient.BankInfo = client.BankInfo);
}
else if (existingClient.BankInfo != null && client.BankInfo != null)
{
_context.Entry(existingClient.BankInfo).CurrentValues.SetValues(client.BankInfo);
}
else if (existingClient.BankInfo != null && client.BankInfo == null)
{
_context.Remove(existingClient.BankInfo);
}
// Doctor
if (existingClient.Doctor == null && client.Doctor != null)
{
_context.Add(existingClient.Doctor = client.Doctor);
}
else if (existingClient.Doctor != null && client.Doctor != null)
{
_context.Entry(existingClient.Doctor).CurrentValues.SetValues(client.Doctor);
}
else if (existingClient.Doctor != null && client.Doctor == null)
{
_context.Remove(existingClient.Doctor);
}
// Medicare
if (existingClient.Medicare == null && client.Medicare != null)
{
_context.Add(existingClient.Medicare = client.Medicare);
}
else if (existingClient.Medicare != null && client.Medicare != null)
{
_context.Entry(existingClient.Medicare).CurrentValues.SetValues(client.Medicare);
}
else if (existingClient.Medicare != null && client.Medicare == null)
{
_context.Remove(existingClient.Medicare);
}
// Prescriptions
foreach (var prescription in existingClient.Prescriptions)
{
if (client.Prescriptions.All(p => p.ID != prescription.ID))
{
_context.Remove(prescription);
}
}
foreach (var prescription in client.Prescriptions)
{
var existingPrescription = existingClient.Prescriptions.FirstOrDefault(p => p.ID == prescription.ID);
if (existingPrescription == null)
{
existingClient.Prescriptions.Add(prescription);
}
else
{
_context.Entry(existingPrescription).CurrentValues.SetValues(prescription);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T09:56:00.200",
"Id": "470089",
"Score": "1",
"body": "_\"this is a simplified version of my working code\"_ Please post the actual code. It's impossible to distinguish the simplifications from the real code. As it stands, your code is very contradictory - both abstract/boilerplatey and concrete. I'm unsure if this is due to your redactions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T10:21:37.697",
"Id": "470091",
"Score": "0",
"body": "@Flater I've added the redacted code like you requested, including the POCOs. As for the contradictions, indeed there is a slight contradiction regarding the way one-to-one relationships are handled compared to one-to-many (prescriptions) and owned types (addresses). This is because I found no way to refactor it in order to remove the duplication. I was only able to do it for the one2one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T10:25:35.733",
"Id": "470093",
"Score": "0",
"body": "I've also taken the liberty to add the unabstracted method, before I applied the refactoring."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-19T20:50:40.627",
"Id": "472486",
"Score": "0",
"body": "Did you read [this](https://docs.microsoft.com/en-us/ef/core/saving/disconnected-entities)? I think a great part of what you do here can be dealt with by EF's built-in methods for disconnected entities."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T08:57:39.920",
"Id": "239644",
"Score": "0",
"Tags": [
"c#",
".net",
"entity-framework-core"
],
"Title": "Handling disconnected entity scenario in Entity Framework Core"
}
|
239644
|
<p>I am a beginner in python. This is the <a href="https://www.hackerrank.com/challenges/nested-list/problem" rel="nofollow noreferrer">Nested Lists</a> problem from HaackerRank.</p>
<blockquote>
<p>Given the names and grades for each student in a Physics class of N
students, store them in a nested list and print the name(s) of any
student(s) having the second lowest grade.</p>
<p>Note: If there are multiple students with the same grade, order their
names alphabetically and print each name on a new line.</p>
</blockquote>
<p>I want to improve my code with better functions available in python and I want to decrease lines of code.</p>
<pre><code>if __name__ == '__main__':
scorecard = []
for _ in range(int(input())):
name = input()
score = float(input())
scorecard.append([name, score])
scorecard.sort(key = lambda x:x[1])
names = []
lowest_score = scorecard[0][1]
second_lowest = 0
for i in range(len(scorecard)):
if scorecard[i][1] > lowest_score and second_lowest == 0:
second_lowest = scorecard[i][1]
if second_lowest != 0 and scorecard[i][1] == second_lowest:
names.append(scorecard[i][0])
names.sort()
for name in names:
print(name)
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>I'd recommend separating the logic of getting the user input from the logic of building and sorting the nested list.</li>\n<li>Your code doesn't build a nested list in a way that's useful for solving the problem; I think what you want is a list of lists of names, where each list of names corresponds to a grade.</li>\n<li>Any time you want to group things into buckets (e.g. all the names that go with a grade), it's a good time to use a dictionary!</li>\n<li>Using list comprehensions is frequently a good way to express a loop in a shorter way.</li>\n<li>Type annotations make it easier to keep track of what your code is doing (and they let you use <code>mypy</code> to catch bugs).</li>\n</ol>\n\n<p>Here's my solution that uses a separate function to build the nested list, using a dictionary as an intermediate step to collect all the names for a given grade. Note that the type annotations tell you exactly where the names (strings) and grades (floats) are going at each step!</p>\n\n<pre><code>from collections import defaultdict\nfrom typing import Dict, List, Tuple\n\ndef build_grade_lists(grades: List[Tuple[str, float]]) -> List[List[str]]:\n \"\"\"\n Given a list of (name, grade) tuples, return a list of names for each grade.\n Each list is sorted, i.e.:\n the top level list is sorted from lowest to highest grade\n each list of names is sorted alphabetically\n \"\"\"\n grade_lists: Dict[float, List[str]] = defaultdict(list)\n for name, grade in grades:\n grade_lists[grade].append(name)\n return [sorted(grade_lists[grade]) for grade in sorted(list(grade_lists.keys()))]\n\nif __name__ == '__main__':\n scorecard = [(input(), float(input())) for _ in range(int(input()))]\n for name in build_grade_lists(scorecard)[1]:\n print(name)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T16:34:45.447",
"Id": "470133",
"Score": "1",
"body": "2 small improvements: your function can accept any finite `Iterable[Tuple[str, float]]`, not just lists, and `[sorted(names) for _, names in sorted(grade_list.items())]` expresses the final result clearer in my opinion."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T16:12:54.753",
"Id": "239668",
"ParentId": "239646",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239668",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T09:56:31.317",
"Id": "239646",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Nested Lists from HackerRank"
}
|
239646
|
<p>I started learning python online and I wrote a blackjack game as my first little project.
I would like to get some review on it if possible. (how to make it better , simpler , etc)</p>
<pre><code>from random import choice
cards = ['A', 2, 3, 4, 5, 6, 7, 8 , 9,'J','Q','K']*4
def get_card(name):
card = choice(cards)
cards.remove(card)
print(f'{name} got {card}')
return card
def hand(cards):
global dealer_total
dealer_total = 0
dealer_card = convert(get_card('The dealer'),dealer_total)
dealer_total += dealer_card
total = 0
card = convert(get_card('You'),total)
total += card
card = convert(get_card('You'),total)
total += card
if total == 21:
print('Blackjack! You Won!')
another_game()
check_total(total)
def convert(card,total):
if card == 'A':
if total > 10:
card = 1
else: card = 11
if card in ['K','Q','J']:
card = 10
return card
def check_total(total):
if total == 21:
print(f'You stand on a total of {total}. Lets see what the dealer gets:')
dealer_hand(total,dealer_total)
elif total > 21:
print(f'You stand on a total of {total}. You lost!')
another_game()
else:
another_card(total)
def another_game():
another_game = input('Would you like to play again ?').lower()
if another_game == 'yes':
cards = ['A', 2, 3, 4, 5, 6, 7, 8 , 9,'J','Q','K']*4
hand(cards)
elif another_game == 'no':
print('Goodbye !')
quit()
else:
raise ValueError('You entered the wrong value')
another_game()
def another_card(total):
another = input(f'You stand on a total of {total}. Would you like another card ? (Yes/No)').lower()
if another == 'yes':
card = convert(get_card('You'),total)
total += card
check_total(total)
elif another == 'no':
print('OK , lets see what the dealer gets')
print(f'Before fliiping the cards , the dealer stands on a total of {dealer_total}')
dealer_hand(total,dealer_total)
else:
raise ValueError('You entered the wrong value')
another_card(total)
def dealer_hand(total,dealer_total):
card = convert(get_card('The dealer'),dealer_total)
dealer_total += card
if dealer_total > 21:
print(f"Dealer's total is {dealer_total}. You won ! ")
another_game()
elif dealer_total > 16:
print(f'Dealers total is {dealer_total}.The dealer must stand.')
who_won(total,dealer_total)
elif dealer_total < 17:
print(f"Dealer's total is {dealer_total}. He must take another card.")
dealer_hand(total,dealer_total)
def who_won(my_total,dealer_total):
print(f'Your total is {my_total} , The dealers total is {dealer_total}')
if my_total > dealer_total:
print('You won !')
elif my_total < dealer_total:
print('You lost !')
else:
print('Its a tie !')
another_game()
print('Hello !')
hand(cards)
</code></pre>
<p>I highly appreciate it , thank you !!</p>
|
[] |
[
{
"body": "<h1>Naming things</h1>\n\n<p>Try to give proper names to things, such that they follow the usual conventions, are concise, unambiguous and to the point. There are a few things I would change:</p>\n\n<ul>\n<li>Rename <code>cards</code> to <code>deck</code>, to signify that it isn't just a random bunch of cards, but the actual deck you are drawing from.</li>\n<li>The function <code>hand()</code> is quite misnamed, it's not about managing just one hand of cards, but rather it implements the whole game. So perhaps <code>play_blackjack()</code> would be better?</li>\n<li>The function <code>convert()</code> has a very generic name, that doesn't tell anything about what it is converting from or to. It would be better named <code>convert_card_to_value()</code>.</li>\n</ul>\n\n<p>In general, variables describe things, so their names should usually be a noun, whereas functions describe actions, so they should be verbs.</p>\n\n<h1>Try to reorganize the code into classes</h1>\n\n<p>Classes make it easier to organize your code. I can think of at least three classes that you should make: <code>Card</code>, <code>Deck</code> and <code>Hand</code>.</p>\n\n<p>A <code>Card</code> is quite simple, it just is the color and number of the card, and has a member function to convert it to a value.</p>\n\n<p>A <code>Deck</code> is a collection of cards, with member functions like <code>shuffle()</code>, <code>draw()</code> and so on.</p>\n\n<p>A <code>Hand</code> is also a collection of cards, but has member functions <code>add()</code> and <code>get_value()</code>. The latter is important: you can't just add values of cards together to get the total value of a hand. Think about drawing an ace, 9, king in that order. Your current code converts card values the moment they are drawn, and only checks aces against the total so far. So your method would count this as 11 + 9 + 10 = 30, whereas the correct value is 1 + 9 + 10 = 20.</p>\n\n<h1>Avoid infinite recursion</h1>\n\n<p>Your code recursively calls itself indefinitely. While this might seem harmless at first, the problem is that you are using more and more stack space, until after enough games played you get a stack overflow. The proper way to deal with this is to structure some parts of your code as loops. For example, you want to have a function to play one game of blackjack, and that function should be called in a loop like so:</p>\n\n<pre><code>def another_game():\n while True:\n answer = input('Would you like to play again?').lower()\n if answer == 'yes':\n return True\n elif answer == 'no':\n return False\n else\n print('Please enter yes or no.')\n\n...\n\nprint('Hello!')\n\nwhile True:\n play_game();\n if not another_game():\n break\n\nprint('Goodbye!')\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T11:30:24.773",
"Id": "239654",
"ParentId": "239647",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T10:43:40.800",
"Id": "239647",
"Score": "3",
"Tags": [
"python"
],
"Title": "wrote a blackjack game in python , would like you get notes on it"
}
|
239647
|
<h1>Introduction</h1>
<p>I am recently learning Rust by reading <a href="https://doc.rust-lang.org/stable/book/" rel="nofollow noreferrer"><em>The Rust Programming Language</em></a> (a.k.a. the book). I have finished the first three chapters so far, and this is my attempt for the first exercise listed at the end of Chapter 3, which has a simple description:</p>
<blockquote>
<p>Convert temperatures between Fahrenheit and Celsius.</p>
</blockquote>
<p>My program repetitively prompts the user to input for a command (one of
<span class="math-container">\${^{\circ}\text{F}} \to {^{\circ}\text{C}}\$</span>,
<span class="math-container">\${^{\circ}\text{C}} \to {^{\circ}\text{F}}\$</span>, and quit), and asks for temperature values to be converted as floating-point values. If the user input cannot be properly interpreted, the program sends an error message and resumes executing if possible.</p>
<p>I have run <code>rustfmt</code> and <code>clippy</code> on my program. <code>rustfmt</code> taught me something new (removing <code>,</code> after <code>{}</code> in a <code>match</code> expression), and <code>clippy</code> did not report any problems. I have also tested the program with different inputs, and so far it seems to work properly.</p>
<p>Before moving on, I would like to know whether I am in the right direction. Feel free to point out edge cases I neglected, failures to conform to received Rust guidelines, or other things that I did wrong, so I can correct these mistakes as soon as possible and learn productively in the future.</p>
<h1>Code</h1>
<p><strong>src/main.rs</strong></p>
<pre><code>use std::io;
fn main() {
println!("This is a program that converts temperatures between Fahrenheit and Celsius.");
loop {
println!("\nEnter one of the following commands:");
println!(" - 0: convert from Fahrenheit to Celsius");
println!(" - 1: convert from Celsius to Fahrenheit");
println!(" - 2: quit");
let mut command = String::new();
match io::stdin().read_line(&mut command) {
Ok(_) => {}
Err(_) => {
println!("Failed to read command.");
continue;
}
}
let command: u32 = match command.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid command.");
continue;
}
};
match command {
0 => fahrenheit_to_celsius(),
1 => celsius_to_fahrenheit(),
2 => break,
_ => println!("Invalid command."),
}
}
}
fn fahrenheit_to_celsius() {
println!("Enter the temperature in Fahrenheit.");
let mut temperature = String::new();
match io::stdin().read_line(&mut temperature) {
Ok(_) => {}
Err(_) => {
println!("Failed to read temperature.");
return;
}
}
let temperature: f64 = match temperature.trim().parse() {
Ok(t) => t,
Err(_) => {
println!("Invalid temperature.");
return;
}
};
let converted = (temperature - 32.0) / 1.8;
println!("{} Fahrenheit = {} Celsius", temperature, converted);
}
fn celsius_to_fahrenheit() {
println!("Enter the temperature in Celsius.");
let mut temperature = String::new();
match io::stdin().read_line(&mut temperature) {
Ok(_) => {}
Err(_) => {
println!("Failed to read temperature.");
return;
}
}
let temperature: f64 = match temperature.trim().parse() {
Ok(t) => t,
Err(_) => {
println!("Invalid temperature.");
return;
}
};
let converted = temperature * 1.8 + 32.0;
println!("{} Celsius = {} Fahrenheit", temperature, converted);
}
</code></pre>
<p><strong>Cargo.toml</strong></p>
<pre><code>[package]
name = "temperature"
version = "0.1.0"
authors = ["L. F."]
edition = "2018"
[dependencies]
</code></pre>
<h1>Example session</h1>
<p>Here's an example <code>cargo run</code> session:</p>
<pre class="lang-none prettyprint-override"><code>This is a program that converts temperatures between Fahrenheit and Celsius.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
0
Enter the temperature in Fahrenheit.
200
200 Fahrenheit = 93.33333333333333 Celsius
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
0
Enter the temperature in Fahrenheit.
123.4
123.4 Fahrenheit = 50.77777777777778 Celsius
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
0
Enter the temperature in Fahrenheit.
cat
Invalid temperature.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
1
Enter the temperature in Celsius.
1.98e5
198000 Celsius = 356432 Fahrenheit
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
1
Enter the temperature in Celsius.
unicorn
Invalid temperature.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
3
Invalid command.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
dog
Invalid command.
Enter one of the following commands:
- 0: convert from Fahrenheit to Celsius
- 1: convert from Celsius to Fahrenheit
- 2: quit
2
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T10:48:16.547",
"Id": "239648",
"Score": "3",
"Tags": [
"beginner",
"rust",
"unit-conversion"
],
"Title": "Yet another Fahrenheit and Celsius converter"
}
|
239648
|
<p>I've created some controller for handling clicked links statistics. Does this class meet Single Responsibility Principle?</p>
<pre><code>class StatisticsController
{
protected $statisticsQuery;
public function __construct(StatisticsQuery $statisticsQuery)
{
$this->statisticsQuery = $statisticsQuery;
}
public function recordClickedLink(array $request)
{
(...)
if ($this->canRecordClick()) {
// record clicked link
}
(...)
}
public function getStatistics(array $request)
{
(...)
$someRequestParam = $request['id'];
$statistics = $this->statisticsQuery->get($someRequestParam);
(...)
}
protected function canRecordClick()
{
// returns true of false
}
}
</code></pre>
<p>If has two public methods. The first is responsible for saving clicked link to a database by delegating it to a model class. The second public method is responsible for getting statistics and it is the only method which use <code>$statisticsQuery</code> object passed to a class' constructor. Is it OK that <code>recordClickedLink</code> method doesn't need constructor's argument?</p>
<p>I wonder also if it is OK that my class contain <code>canRecordClick</code> method with logic for checking if link click can be saved during particular request.</p>
<p>If this class doesn't meet SRP, how can I refactor it?</p>
|
[] |
[
{
"body": "<p>As far as I can see in the code example you've provided, it seems that the <code>getStatistics</code> and <code>recordClickedLink</code> methods are independent of each other. So it seems intuitive to have in this case two controllers: a <code>StatisticsController</code> and a something like a <code>RecordController</code> where the two methods <code>recordClickedLink</code> and <code>canRecordClick</code> live. In that way the <code>StatisticsController</code> is responsible for statisics and the <code>RecordController</code> for the record.</p>\n\n<p>It is ok that the class contains <code>canRecordClick</code>, but <code>protected</code> means that any class extending the <code>StatisticsController</code> will be able to call this method too. If it will only be used in the <code>StatisticsController</code>, <code>private</code> would be better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T11:47:35.000",
"Id": "470102",
"Score": "0",
"body": "Do you think that constructor's argument can be considered when telling if this class applies SRP? I wonder if argument or arguments passed to constructor should be obligatorily used by all class' public methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T12:02:34.107",
"Id": "470105",
"Score": "0",
"body": "@SzymonCzembor The argument of a constructor or properties of a class can give a good indication but it is not a strict rule that each method should use all the properties of a class (there are probably some who disagree). Determining what falls under a single responsibility of a class can sometimes be difficult to determine and sometimes you also have to take into consideration how easy some code is to understand vs adding a new class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T12:18:10.913",
"Id": "470107",
"Score": "0",
"body": "And what do you think about this? If I have two classes (StatisticsController and RecordController) and then I need to change the way I record a link click (for example altering database table) in RecordController then I have to change also StatisticsController because data for calculating statistics come from the altered place. Does it imply that this two methods should be in one class, doesn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T13:16:11.300",
"Id": "470112",
"Score": "1",
"body": "If that is the case you could extract the code which alters and reads from the database to a separate repository class and pass that repository to both the StatisticsController and RecordController. Then when you change the way you record a link you only have to change the repository."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T11:21:16.557",
"Id": "239652",
"ParentId": "239651",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239652",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T11:09:17.247",
"Id": "239651",
"Score": "1",
"Tags": [
"php",
"controller",
"constructor"
],
"Title": "Passing argument to a constructor and using it only in some class methods"
}
|
239651
|
<p>I do not have an intention to ask for an answer, but I want to know if my answer is good for a two-week Python beginner?</p>
<p><strong>Question:<em></strong> (Automate the Boring Stuff with Python/ page 102)</em></p>
<p><strong><em><a href="https://automatetheboringstuff.com/2e/chapter4/#calibre_link-187" rel="nofollow noreferrer">Comma Code</a></em></strong></p>
<p>Say you have a list value like this: </p>
<pre><code>spam = ['apples', 'bananas', 'tofu', 'cats']
</code></pre>
<blockquote>
<p>Write a function that takes a list value as an argument and returns a
string with all the items separated by a comma and a space, with <code>and</code>
inserted before the last item. For example, passing the previous spam
list to the function would return:</p>
<blockquote>
<p>apples, bananas, tofu, and cats</p>
</blockquote>
<p>But your function should be able to work with any list value passed to
it.</p>
</blockquote>
<p><strong>My Answer:</strong></p>
<pre><code>spam = ['apples', 'bananas', 'tofu', 'cats']
def sentence(i):
for n in range(0, len(spam) - 1):
print(spam[n], end=', ')
print('and ' + spam[-1])
sentence(spam)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T13:22:34.957",
"Id": "470115",
"Score": "1",
"body": "Your function is not actually \"able to work with any list value passed to it., because it relies on the globally defined list `spam` and not the argument it is passed (which you named `i`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T14:18:33.350",
"Id": "470118",
"Score": "1",
"body": "Moreover, the implementation is incorrect, an empty list (`spam = []`) will result in an exception: `IndexError: list index out of range`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T16:41:19.420",
"Id": "470134",
"Score": "0",
"body": "Moreover, your function returns `None` instead of the string specified."
}
] |
[
{
"body": "<p>Your function isn't returning anything. You should be building a string and returning it from your function. <code>str.join()</code> will be useful for building your string, return it with the <code>return</code> keyword. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T02:21:00.600",
"Id": "470479",
"Score": "0",
"body": "After reviewing my code, I have realized that my function won't work if I use another list. I will consider your feedback so as to rewrite my program.\nThank you for letting me know the errors in my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T14:04:54.880",
"Id": "239660",
"ParentId": "239653",
"Score": "2"
}
},
{
"body": "<p>Since testing falls under the general heading of code review, I'm just going to review your testing strategy.</p>\n\n<p>The question says:</p>\n\n<blockquote>\n <p>your function should be able to work with any list value passed to it.</p>\n</blockquote>\n\n<p>but you are not testing this; you're only testing the single example that was given to you (and which, as it happens, you've hard-coded into your function). Here's how you could test it:</p>\n\n<pre><code>print(sentence(['eggs', 'bacon', 'spam', 'bacon']))\n</code></pre>\n\n<p>Does this print the string <code>eggs, bacon, spam, and bacon</code>? If not, why? (Try to understand the bug before you fix it -- don't just change things randomly until it works!)</p>\n\n<p>An even better test would be:</p>\n\n<pre><code>assert sentence(spam) == \"apples, bananas, tofu, and cats\"\nassert sentence(['eggs', 'bacon', 'spam', 'bacon']) == \"eggs, bacon, spam, and bacon\"\n</code></pre>\n\n<p>Add this to your program, and then fix the <code>sentence</code> function so that neither line of code causes your program to fail. This is called \"test driven development\" -- write the test first that says how you want the function to work, then write the function until the test passes!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T02:17:18.873",
"Id": "470477",
"Score": "0",
"body": "I am grateful to your reply. I have realized that my program, as you said, have been hard-coded with the `spam` list. After reading your review, I will check my code again with your two `assert` lines.\nOnce again, thank you for letting me know what to do next."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T15:39:15.573",
"Id": "239665",
"ParentId": "239653",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "239660",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T11:28:58.490",
"Id": "239653",
"Score": "0",
"Tags": [
"python",
"beginner"
],
"Title": "Comma separated string for list"
}
|
239653
|
<p>I'm trying to replicate Android's <a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java#27291" rel="nofollow noreferrer">GenerateViewId()</a> to assign a unique Tag to dynamically created UIViews in Xamarin.iOS.</p>
<pre><code>internal static class LayoutExtensions
{
// A tentative to mimmic Java's AtomicInteger used by GenerateViewId()
// https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/View.java#27291
private static int nextViewTag = 1;
internal static int GenerateViewTag(this UIView someView)
{
for(;;)
{
var result = nextViewTag;
var newValue = result + 1;
if (newValue > 0x00FFFFFF)
{
newValue = 1; // Roll over to 1, not 0.
}
if (nextViewTag == Interlocked.CompareExchange(ref nextViewTag, newValue, result))
{
return newValue;
}
}
}
}
</code></pre>
<p>What do you think?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T09:32:13.217",
"Id": "470207",
"Score": "1",
"body": "The result of the CAS compared to the *current* `nextViewTag`, instead of to `result`. Is that intentional, and what does that mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T11:26:32.333",
"Id": "470216",
"Score": "0",
"body": "I'm not sure. The Android method returns a boolean that tells if the sNextGeneratedId.compareAndSet succeeded."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T17:08:14.777",
"Id": "470340",
"Score": "0",
"body": "What is wrong with `Interlocked.Increment(int)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T06:10:18.540",
"Id": "470374",
"Score": "0",
"body": "@HenrikHansen I would like to be as close as possible as the original Java implementation. May be this is irrelevant. This is why I opened this question in the first place."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T13:01:23.897",
"Id": "239655",
"Score": "2",
"Tags": [
"c#",
"android",
"ios",
"xamarin"
],
"Title": "Java's AtomicInteger equivalent in c#"
}
|
239655
|
<p>I developed this small code to make my life easier when I work with remote machines over ssh tunnel crossing a bastion host. I would like to publich it so others could benefit/learn from it. </p>
<p>So I would appreciate your opinions for improvement or maybe I overlooked some issues in this approach.</p>
<p>Goal:</p>
<p>I have a postgres VM in a private subnet running on default local host with port 5432. I want to be able to reach this machine from my go code or to let PgAdming GUI reach it from my local machine.</p>
<p>the workflow as following: </p>
<ul>
<li>create ssh client to Bastion machine</li>
<li>from bastion client create a new client fo the postgres machine</li>
<li>forward the remote port to local listner </li>
</ul>
<p>Thanks!</p>
<p><strong>sshHelper</strong></p>
<pre class="lang-golang prettyprint-override"><code>package sshHelper
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"golang.org/x/crypto/ssh"
)
var home, err = os.UserHomeDir()
func SignKey(KeyName string) ssh.Signer {
pathToPrivateKey := filepath.FromSlash(fmt.Sprintf("%s/.ssh/%s", home, KeyName))
key, err := ioutil.ReadFile(pathToPrivateKey)
if err != nil {
panic(err)
}
// Create the Signer for this private key.
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
panic(err)
}
return signer
}
func CreateClient(user string, signer ssh.Signer, address string, port string) *ssh.Client {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
cleint, err := ssh.Dial("tcp", address+":"+port, config)
if err != nil {
panic(err)
}
return cleint
}
func ViaBastionConn(cleint *ssh.Client, user string, signer ssh.Signer, address string, port string) *ssh.Client {
conn, err := cleint.Dial("tcp", address+":"+port)
if err != nil {
log.Fatal(err)
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
ncc, chans, reqs, err := ssh.NewClientConn(conn, address+":"+port, config)
if err != nil {
log.Fatal(err)
}
newCleint := ssh.NewClient(ncc, chans, reqs)
return newCleint
}
func localListner(cleintBroker *ssh.Client, localAddress string, remoteAddress string) {
listener, err := net.Listen("tcp", localAddress)
if err != nil {
fmt.Println(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println(err)
}
forward(cleintBroker, conn, remoteAddress)
}
}
func forward(cleintBroker *ssh.Client, localConn net.Conn, remoteAddress string) {
remoteConn, err := cleintBroker.Dial("tcp", remoteAddress)
if err != nil {
fmt.Printf("Remote dial error: %s\n", err)
return
}
copyConn := func(writer, reader net.Conn) {
_, err := io.Copy(writer, reader)
if err != nil {
fmt.Println("")
fmt.Printf("io.Copy error: %s", err)
fmt.Println("")
}
}
go copyConn(localConn, remoteConn)
go copyConn(remoteConn, localConn)
}
</code></pre>
<p><strong>main.go</strong></p>
<pre class="lang-golang prettyprint-override"><code>package main
import (
sshM "lib/sshHelper"
)
const (
sshPort = "22"
postgresUser = "ubuntu"
bastionUser = "ubuntu"
bastionAddress = "54.xxx.xxx.xxx"
postgresAddress = "10.0.x.xxx"
localAddr = "localhost:5432"
remoteAddr= "localhost:5432"
)
func main() {
bastionKey := "bastion_key.pem"
postgresKey := "postgres_key.pem"
signerBastion := sshM.SignKey(bastionKey)
signerPostgres := sshM.SignKey(postgresKey)
clientBastion := sshM.CreateClient(bastionUser, signerBastion, bastionAddress, sshPort)
cleintPostgres:= sshM.ViaBastionConn(clientBastion, brokerUser, signerPostgres, postgresAddress, sshPort)
go localListner(cleintPostgres, localAddr, remoteAddr)
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T13:06:36.273",
"Id": "239656",
"Score": "1",
"Tags": [
"go",
"ssh"
],
"Title": "SSH Port Forwarding - golang"
}
|
239656
|
<p>EDIT: Added a block with the raw code at the bottom (suggested by a friendly user)</p>
<p>First post here. I sincerely hope that I am doing everything by the book. Also, I want to thank you in advance for any help and assistance that you may be able to provide me. I have been coding VBA for 2 weeks.</p>
<p><strong>Problem:</strong>
What can I do to make my code faster? I am certain it can be better and I've looked up a few things that I want to go ahead and test. I know the use of array is awesome, but I am not sure if it is needed here? I also know that my loops are causing a bottleneck, but I am not sure what a better alternative would be.</p>
<p>Again, THANK YOU.</p>
<p><strong>The XML format looks like this:</strong></p>
<pre class="lang-xml prettyprint-override"><code><xmldata>
<products>
<rownumber></rownumber>
<pkid></pkid>
<category></category>
<description>
</description>
<header>
</header>
<instock></instock>
<keywords>
</keywords>
<deliverytime></deliverytime>
<priceretail></priceretail>
<kostprice></kostprice>
<productid></productid>
<unit></unit>
<volume></volume>
<weight></weight>
<usr_sca_length></usr_sca_length>
<usr_sca_width></usr_sca_width>
<usr_sca_height></usr_sca_height>
<manufacturer></manufacturer>
</products>
</xmldata>
</code></pre>
<p><strong>Full Code with comments:</strong></p>
<pre class="lang-vb prettyprint-override"><code>Sub GetAPI()
</code></pre>
<p>Turns off stuff and clears sheets before going</p>
<pre class="lang-vb prettyprint-override"><code>Call ClearCells
Call TurnOffShit
</code></pre>
<p>LOAD API</p>
<pre class="lang-vb prettyprint-override"><code>Dim ws As Worksheet: Set ws = Worksheets("API")
Dim strURL As String
Dim strURLMain As String
Dim strURLUser As String
Dim strURLPassword As String
Dim strURLIndex As String
Dim strURLPage As String
Dim strURLEnd As String
Dim lastRow As Integer
</code></pre>
<p>Constructing URL
CUT OUT DETAILS. In this bit I store number of rows (10.000) and starting page (1) of API. More on why I chose 10.000 later in the comments</p>
<pre class="lang-vb prettyprint-override"><code>strURLMain = ""
strURLUser = ""
strURLPassword = ""
strURLIndex = ""
strURLPage = "1"
strURLEnd = ""
</code></pre>
<p>strURL is my startpage: I loop on this later until it = xmlLastPage</p>
<pre class="lang-vb prettyprint-override"><code>strURL = strURLMain & strURLUser & ":" & strURLPassword & strURLIndex & strURLPage & strURLEnd
Debug.Print ""
Debug.Print "API URL er: "; strURL
Debug.Print ""
</code></pre>
<p>Get API Response Data – this first one is to determine xmlLastPage – last page of API at given rows'</p>
<pre class="lang-vb prettyprint-override"><code>Dim httpRequest As New WinHttpRequest
httpRequest.SetTimeouts 0, 0, 0, 0
httpRequest.Open "GET", strURL, False
httpRequest.Send
Dim strResponse As String
strResponse = httpRequest.ResponseText
</code></pre>
<p>Output API Data Response into XML</p>
<pre class="lang-vb prettyprint-override"><code>Dim xmlDoc As New MSXML2.DOMDocument60
Dim xmldata As MSXML2.IXMLDOMNodeList, paging As MSXML2.IXMLDOMNode
Dim xmlpagesElement As MSXML2.IXMLDOMElement
xmlDoc.SetProperty "SelectionLanguage", "XPath"
xmlDoc.SetProperty "SelectionNamespaces", ""
If Not xmlDoc.LoadXML(strResponse) Then
MsgBox "Indlæsningsfejl ved afsnit 1.4"
End If
</code></pre>
<p>Finds the last page in our API. Our API crash at > 10.000 so I had to find a way to loop through the pages at a given # of rows
From conducting a basic time analysis on the different stages of the code, I concluded that Loops take up time and hence I want to minimize them (a max of 10.000 # of rows was hereby chosen)</p>
<pre class="lang-vb prettyprint-override"><code>Dim xmlPage As Integer
Dim xmlFirstPage As Integer
xmlFirstPage = 1
Set xmlpagesElement = xmlDoc.SelectSingleNode("xmldata/paging/pages[1]")
xmlLastPage = xmlpagesElement
Debug.Print ""
Debug.Print "Lastpage i XML/API er: "; xmlpagesElement.nodeTypedValue
Debug.Print ""
</code></pre>
<p>Loop through API pages one by one untill we hit and retrieve last page (xmlLastPage) and get product data</p>
<pre class="lang-vb prettyprint-override"><code>For xmlPage = xmlFirstPage To xmlLastPage
</code></pre>
<p>Get API Response Data – made another request to make it easier for me to loop on API pages</p>
<pre class="lang-vb prettyprint-override"><code> Dim httpRequest2 As New WinHttpRequest
Dim strResponse2 As String
strURL2 = strURLMain & strURLUser & ":" & strURLPassword & strURLIndex & xmlPage & strURLEnd
httpRequest2.SetTimeouts 0, 0, 0, 0
httpRequest2.Open "GET", strURL2, False
httpRequest2.Send
strResponse2 = httpRequest2.ResponseText
</code></pre>
<p>Output API Data Response into XML</p>
<pre class="lang-vb prettyprint-override"><code> Dim xmlDoc2 As New MSXML2.DOMDocument60
Dim xmldata2 As MSXML2.IXMLDOMNodeList, products As MSXML2.IXMLDOMNode
xmlDoc.SetProperty "SelectionLanguage", "XPath"
xmlDoc.SetProperty "SelectionNamespaces", ""
If Not xmlDoc2.LoadXML(strResponse2) Then
MsgBox "Indlæsningsfejl ved afsnit 1."
End If
</code></pre>
<p>Get Productdata</p>
<pre class="lang-vb prettyprint-override"><code>Set xmldata2 = xmlDoc2.SelectNodes("xmldata/products")
Debug.Print "Antal produkter fundet (på siden)", xmldata2.Length
</code></pre>
<p>Insert product data on rows
Doing the below loop to prevent errors. Slow. Other way to do it? I could for sure delete some of them, as some value will always be there (rownumber). “Description”, for instance is not always in a node and hence will throw an error</p>
<pre class="lang-vb prettyprint-override"><code>For Each products In xmldata2
lastRow = (Cells(Rows.Count, 2).End(xlUp).Row) + 1
Set pRowNumber = products.SelectSingleNode("rownumber")
If Not pRowNumber Is Nothing Then
Cells(lastRow, 2).Value = pRowNumber.Text
Else
Cells(lastRow, 2).Value = "<tom>"
End If
Set pCategory = products.SelectSingleNode("category")
If Not pCategory Is Nothing Then
Cells(lastRow, 3).Value = pCategory.Text
Else
Cells(lastRow, 3).Value = "<tom>"
End If
Set pDescription = products.SelectSingleNode("description")
If Not pDescription Is Nothing Then
Cells(lastRow, 4).Value = pDescription.Text
Else
Cells(lastRow, 4).Value = "<tom>"
End If
Set pHeader = products.SelectSingleNode("header")
If Not pHeader Is Nothing Then
Cells(lastRow, 5).Value = pHeader.Text
Else
Cells(lastRow, 5).Value = "<tom>"
End If
Set pInstock = products.SelectSingleNode("instock")
If Not pInstock Is Nothing Then
Cells(lastRow, 6).Value = pInstock.Text
Else
Cells(lastRow, 6).Value = "<tom>"
End If
Set pKeyword = products.SelectSingleNode("keywords")
If Not pKeyword Is Nothing Then
Cells(lastRow, 7).Value = pKeyword.Text
Else
Cells(lastRow, 7).Value = "<tom>"
End If
Set pPriceretail = products.SelectSingleNode("priceretail")
If Not pPriceretail Is Nothing Then
Cells(lastRow, 8).Value = pPriceretail.Text
Else
Cells(lastRow, 8).Value = "<tom>"
End If
Set pKostprice = products.SelectSingleNode("kostprice")
If Not pKostprice Is Nothing Then
Cells(lastRow, 9).Value = pKostprice.Text
Else
Cells(lastRow, 9).Value = "<tom>"
End If
Set pProductid = products.SelectSingleNode("productid")
If Not pProductid Is Nothing Then
Cells(lastRow, 10).Value = pProductid.Text
Else
Cells(lastRow, 10).Value = "<tom>"
End If
Set pUnit = products.SelectSingleNode("unit")
If Not pUnit Is Nothing Then
Cells(lastRow, 11).Value = pUnit.Text
Else
Cells(lastRow, 11).Value = "<tom>"
End If
Set pVolume = products.SelectSingleNode("volume")
If Not pVolume Is Nothing Then
Cells(lastRow, 12).Value = pVolume.Text
Else
Cells(lastRow, 12).Value = "<tom>"
End If
Set pWeight = products.SelectSingleNode("weight")
If Not pWeight Is Nothing Then
Cells(lastRow, 13).Value = pWeight.Text
Else
Cells(lastRow, 13).Value = "<tom>"
End If
Set pEan = products.SelectSingleNode("ean")
If Not pEan Is Nothing Then
Cells(lastRow, 14).Value = pEan.Text
Else
Cells(lastRow, 14).Value = "<tom>"
End If
Set pUsrScaLength = products.SelectSingleNode("usr_sca_length")
If Not pUsrScaLength Is Nothing Then
Cells(lastRow, 15).Value = pUsrScaLength.Text
Else
Cells(lastRow, 15).Value = "<tom>"
End If
Set pUsrScaWidth = products.SelectSingleNode("usr_sca_width")
If Not pUsrScaWidth Is Nothing Then
Cells(lastRow, 16).Value = pUsrScaWidth.Text
Else
Cells(lastRow, 16).Value = "<tom>"
End If
Set pUsrScaHeight = products.SelectSingleNode("usr_sca_height")
If Not pUsrScaHeight Is Nothing Then
Cells(lastRow, 17).Value = pUsrScaHeight.Text
Else
Cells(lastRow, 17).Value = "<tom>"
End If
Set pYoutube = products.SelectSingleNode("youtube")
If Not pYoutube Is Nothing Then
Cells(lastRow, 18).Value = pYoutube.Text
Else
Cells(lastRow, 18).Value = "<tom>"
End If
Next products
Next xmlPage
Call TurnOnShit
End Sub
Sub TurnOffShit()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
End Sub
Sub TurnOnShit()
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Sub ClearCells()
Range("B3:R200000").Clear
End Sub
</code></pre>
<hr>
<p><strong>Raw Code</strong></p>
<pre class="lang-vb prettyprint-override"><code>Sub GetAPI()
Call ClearCells
Call TurnOffShit
Dim ws As Worksheet: Set ws = Worksheets("API")
Dim strURL As String
Dim strURLMain As String
Dim strURLUser As String
Dim strURLPassword As String
Dim strURLIndex As String
Dim strURLPage As String
Dim strURLEnd As String
Dim lastRow As Integer
strURLMain = ""
strURLUser = ""
strURLPassword = ""
strURLIndex = ""
strURLPage = "1"
strURLEnd = ""
strURL = strURLMain & strURLUser & ":" & strURLPassword & strURLIndex &
strURLPage & strURLEnd
Debug.Print ""
Debug.Print "API URL er: "; strURL
Debug.Print ""
Dim httpRequest As New WinHttpRequest
httpRequest.SetTimeouts 0, 0, 0, 0
httpRequest.Open "GET", strURL, False
httpRequest.Send
Dim strResponse As String
strResponse = httpRequest.ResponseText
Dim xmlDoc As New MSXML2.DOMDocument60
Dim xmldata As MSXML2.IXMLDOMNodeList, paging As MSXML2.IXMLDOMNode
Dim xmlpagesElement As MSXML2.IXMLDOMElement
xmlDoc.SetProperty "SelectionLanguage", "XPath"
xmlDoc.SetProperty "SelectionNamespaces", ""
If Not xmlDoc.LoadXML(strResponse) Then
MsgBox "Indlæsningsfejl ved afsnit 1.4"
End If
Dim xmlPage As Integer
Dim xmlFirstPage As Integer
xmlFirstPage = 1
Set xmlpagesElement = xmlDoc.SelectSingleNode("xmldata/paging/pages[1]")
xmlLastPage = xmlpagesElement
Debug.Print ""
Debug.Print "Lastpage i XML/API er: "; xmlpagesElement.nodeTypedValue
Debug.Print ""
For xmlPage = xmlFirstPage To xmlLastPage
Dim httpRequest2 As New WinHttpRequest
Dim strResponse2 As String
strURL2 = strURLMain & strURLUser & ":" & strURLPassword & strURLIndex
& xmlPage & strURLEnd
httpRequest2.SetTimeouts 0, 0, 0, 0
httpRequest2.Open "GET", strURL2, False
httpRequest2.Send
strResponse2 = httpRequest2.ResponseText
Dim xmlDoc2 As New MSXML2.DOMDocument60
Dim xmldata2 As MSXML2.IXMLDOMNodeList, products As MSXML2.IXMLDOMNode
xmlDoc.SetProperty "SelectionLanguage", "XPath"
xmlDoc.SetProperty "SelectionNamespaces", ""
''
If Not xmlDoc2.LoadXML(strResponse2) Then
MsgBox "Indlæsningsfejl ved afsnit 1."
End If
Set xmldata2 = xmlDoc2.SelectNodes("xmldata/products")
Debug.Print "Antal produkter fundet (på siden)", xmldata2.Length
For Each products In xmldata2
lastRow = (Cells(Rows.Count, 2).End(xlUp).Row) + 1
Set pRowNumber = products.SelectSingleNode("rownumber")
If Not pRowNumber Is Nothing Then
Cells(lastRow, 2).Value = pRowNumber.Text
Else
Cells(lastRow, 2).Value = "<tom>"
End If
Set pCategory = products.SelectSingleNode("category")
If Not pCategory Is Nothing Then
Cells(lastRow, 3).Value = pCategory.Text
Else
Cells(lastRow, 3).Value = "<tom>"
End If
Set pDescription = products.SelectSingleNode("description")
If Not pDescription Is Nothing Then
Cells(lastRow, 4).Value = pDescription.Text
Else
Cells(lastRow, 4).Value = "<tom>"
End If
Set pHeader = products.SelectSingleNode("header")
If Not pHeader Is Nothing Then
Cells(lastRow, 5).Value = pHeader.Text
Else
Cells(lastRow, 5).Value = "<tom>"
End If
Set pInstock = products.SelectSingleNode("instock")
If Not pInstock Is Nothing Then
Cells(lastRow, 6).Value = pInstock.Text
Else
Cells(lastRow, 6).Value = "<tom>"
End If
Set pKeyword = products.SelectSingleNode("keywords")
If Not pKeyword Is Nothing Then
Cells(lastRow, 7).Value = pKeyword.Text
Else
Cells(lastRow, 7).Value = "<tom>"
End If
Set pPriceretail = products.SelectSingleNode("priceretail")
If Not pPriceretail Is Nothing Then
Cells(lastRow, 8).Value = pPriceretail.Text
Else
Cells(lastRow, 8).Value = "<tom>"
End If
Set pKostprice = products.SelectSingleNode("kostprice")
If Not pKostprice Is Nothing Then
Cells(lastRow, 9).Value = pKostprice.Text
Else
Cells(lastRow, 9).Value = "<tom>"
End If
Set pProductid = products.SelectSingleNode("productid")
If Not pProductid Is Nothing Then
Cells(lastRow, 10).Value = pProductid.Text
Else
Cells(lastRow, 10).Value = "<tom>"
End If
Set pUnit = products.SelectSingleNode("unit")
If Not pUnit Is Nothing Then
Cells(lastRow, 11).Value = pUnit.Text
Else
Cells(lastRow, 11).Value = "<tom>"
End If
Set pVolume = products.SelectSingleNode("volume")
If Not pVolume Is Nothing Then
Cells(lastRow, 12).Value = pVolume.Text
Else
Cells(lastRow, 12).Value = "<tom>"
End If
Set pWeight = products.SelectSingleNode("weight")
If Not pWeight Is Nothing Then
Cells(lastRow, 13).Value = pWeight.Text
Else
Cells(lastRow, 13).Value = "<tom>"
End If
Set pEan = products.SelectSingleNode("ean")
If Not pEan Is Nothing Then
Cells(lastRow, 14).Value = pEan.Text
Else
Cells(lastRow, 14).Value = "<tom>"
End If
Set pUsrScaLength = products.SelectSingleNode("usr_sca_length")
If Not pUsrScaLength Is Nothing Then
Cells(lastRow, 15).Value = pUsrScaLength.Text
Else
Cells(lastRow, 15).Value = "<tom>"
End If
Set pUsrScaWidth = products.SelectSingleNode("usr_sca_width")
If Not pUsrScaWidth Is Nothing Then
Cells(lastRow, 16).Value = pUsrScaWidth.Text
Else
Cells(lastRow, 16).Value = "<tom>"
End If
Set pUsrScaHeight = products.SelectSingleNode("usr_sca_height")
If Not pUsrScaHeight Is Nothing Then
Cells(lastRow, 17).Value = pUsrScaHeight.Text
Else
Cells(lastRow, 17).Value = "<tom>"
End If
Set pYoutube = products.SelectSingleNode("youtube")
If Not pYoutube Is Nothing Then
Cells(lastRow, 18).Value = pYoutube.Text
Else
Cells(lastRow, 18).Value = "<tom>"
End If
Next products
Next xmlPage
Call TurnOnShit
End Sub
Sub TurnOffShit()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
End Sub
Sub TurnOnShit()
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Sub ClearCells()
Range("B3:R200000").Clear
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T14:34:06.473",
"Id": "470119",
"Score": "4",
"body": "For doing things by the book, feel free [to read the book on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915). Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T00:50:43.490",
"Id": "470178",
"Score": "2",
"body": "You're doing great! May I suggest editing though, to have all the code of a module in the same code block? Makes it much easier for reviewers to copy the code into their IDE. Having multiple blocks like this might also be hiding indentation issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T06:42:16.953",
"Id": "470194",
"Score": "0",
"body": "Thanks! That makes a lot of sense. I actually thought about it, but I was scared that lack of commenting would be ill received. \n\nShould I edit it and provide a box with the full code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T07:33:04.167",
"Id": "470202",
"Score": "0",
"body": "Don't worry about whether your code looks bad. Just post it as-is, how it currently is in your editor. The whole deal, that's fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T18:43:33.263",
"Id": "470436",
"Score": "0",
"body": "Without having access to a good test case, it is hard to say exactly what is causing your slow-down, but, if I had to guess, I would say that the multiple cell writes are a likely suspect. I've rewritten you code to use arrays instead of writing cell by cell, which you can find [here](https://pastebin.com/PK85u2DD), but I am not sure if it works as I didn't want to deal with hosting xml files to test this. If it does work, then let me know, and i'll tidy up the code a little more and post it as an answer. Cheers,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T07:45:49.620",
"Id": "485905",
"Score": "1",
"body": "Hi @TaylorScott,\n\nJust saw your answer. Thank you so much. I'll try it out :-)!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T13:09:52.140",
"Id": "239657",
"Score": "5",
"Tags": [
"performance",
"vba",
"api",
"xml"
],
"Title": "Extract data from API using VBA & XML (Performance)"
}
|
239657
|
<p>I'm switching my neural network library over to using <a href="https://arrayfire.com/" rel="nofollow noreferrer">ArrayFire</a> for performance.</p>
<p>One of the features I am losing moving from <a href="https://lib.rs/crates/ndarray" rel="nofollow noreferrer">ndarray</a> is <a href="https://lib.rs/crates/ndarray_einsum_beta" rel="nofollow noreferrer">ndarray_einsum_beta</a>, as such I need to write my own function to carry out what I was using einsum for.</p>
<p>This function needs to be as fast as possible.</p>
<p>This is the function:</p>
<pre><code>fn arrayfire_weight_errors(errors:arrayfire::Array<f32>,activations:arrayfire::Array<f32>) -> arrayfire::Array<f32> {
let rows:u64 = errors.dims().get()[0];
let er_width:u64 = errors.dims().get()[1];
let act_width:u64 = activations.dims().get()[1];
let dims = arrayfire::Dim4::new(&[act_width,er_width,rows,1]);
let temp:arrayfire::Array<f32> = arrayfire::Array::<f32>::new_empty(dims);
for i in 0..rows {
let holder = arrayfire::matmul(
&arrayfire::row(&activations,i),
&arrayfire::row(&errors,i),
arrayfire::MatProp::TRANS,
arrayfire::MatProp::NONE
);
arrayfire::set_slice(&temp,&holder,i);
}
return temp
}
</code></pre>
<p>How could I improve this to make it better? (and hopefully faster)</p>
<p>(Apologies for using <code>arrayfire::</code> everywhere, this is a test project which uses a few other linear algebra libraries, so it's best to specify)</p>
<p>ndarray approach:</p>
<pre><code>fn ndarray_einsum(errors:ndarray::Array2<f32>,activations:ndarray::Array2<f32>) -> ndarray::ArrayD<f32> {
return ndarray_einsum_beta::einsum("ai,aj->aji", &[&errors, &activations]).unwrap();
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T19:52:58.077",
"Id": "239679",
"Score": "1",
"Tags": [
"rust",
"neural-network"
],
"Title": "A function for batch backpropagation of weight errors in a dense neural network layer"
}
|
239679
|
<p>In a particular social network friends are automatically allocated to users by the system and users cannot add friends of their choice on their own. There are currently N users on the social network, labeled from 2 to N+1.</p>
<p>For every ith user (where i ranges from 2 to N+1), the system allocated all the users labeled with multiples of i as the user's friends (if possible).</p>
<p>One day, all users of the social network come together for a meeting and form groups such that each person in a group is a direct friend or a friend of friend of every other person of that group.</p>
<p>Find the total number of groups.</p>
<p><strong>Input Specifications:</strong></p>
<p>Input1: N, denoting the number of users on the social network</p>
<p><strong>Output Specification:</strong>
your function should return the number of groups that can be formed on given conditions</p>
<p><strong>Example 1:</strong></p>
<p>Input1: 5
Output: 2</p>
<p>Explanation:
Two groups will be formed</p>
<pre><code>2,3,4,6
5
</code></pre>
<p><strong>Example 2:</strong></p>
<p>Input1: 10
Output: 3</p>
<p>Explanation:
Three groups will be formed:</p>
<pre><code>2,3,4,5,6,8,9,10
7
11
</code></pre>
<p><a href="https://stackoverflow.com/questions/60527097/how-to-find-the-total-number-of-groups-from-2-to-n-1">Solution suggestions</a></p>
<p>Please optimize my solution. My solution is working perfectly but doesn't look optimal.</p>
<pre><code>import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
public class SocialNetwork {
public static void main(String[] args) {
InputStreamReader r = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
int value = 0;
try {
value = Integer.parseInt(br.readLine());
} catch (IOException e) {
System.out.println(e.getMessage());
}
HashMap<Integer, List<Integer>> map = new HashMap<>();
for (int i = 2; i <= value + 1; i++) {
List<Integer> list = new ArrayList<>();
for (int j = 1; j * i <= value + 1; j++) {
int tempValue = j * i;
list.add(tempValue);
if (i != tempValue) {
List<Integer> addedList = map.get(tempValue);
if (addedList == null) {
addedList = new ArrayList<>();
}
if (!addedList.contains(i)) {
addedList.add(i);
map.put(tempValue, addedList);
}
}
}
List<Integer> currList = map.get(i);
if (currList != null)
currList.addAll(list);
else
currList = list;
map.put(i, currList);
}
// Iterate through all elements of map
Iterator<Entry<Integer, List<Integer>>> iterator = map.entrySet().iterator();
List<Integer> visitedKeys = new ArrayList<>();
List<Set<Integer>> listSet = new ArrayList<>();
while (iterator.hasNext()) {
Entry<Integer, List<Integer>> entry = iterator.next();
Integer key = entry.getKey();
List<Integer> keyValue = entry.getValue();
if (visitedKeys.contains(key)) {
continue;
}
Set<Integer> setItem = new HashSet<>();
updateSet(key, keyValue, visitedKeys, map, setItem);
listSet.add(setItem);
}
System.out.println("groups=" + listSet);
System.out.println("Number of groups=" + listSet.size());
}
private static void updateSet(Integer key, List<Integer> keyValue, List<Integer> visitedKeys,
HashMap<Integer, List<Integer>> map, Set<Integer> setItem) {
for (Integer item : keyValue) {
if (visitedKeys.contains(item)) {
continue;
}
if (!item.equals(key)) {
List<Integer> mapVal = map.get(item);
if (mapVal != null) {
updateSet(item, mapVal, visitedKeys, map, setItem);
}
}
visitedKeys.add(item);
setItem.add(item);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I start from mathematical consideration using one of the examples you provided:</p>\n\n<pre><code>Input: 10 output: 3\n\n2,3,4,5,6,8,9,10\n7\n11\n</code></pre>\n\n<p>All the elements multiple of 2 are in the set containing 2, the other sets will always contain just one prime number like {7} and {11} : if it were not so the number would be not prime and would be contained in another previous set.</p>\n\n<p>So instead of using the structure :</p>\n\n<blockquote>\n<pre><code>HashMap<Integer, List<Integer>> map = new HashMap<>();\n</code></pre>\n</blockquote>\n\n<p>It is better to use a <code>List</code> of <code>Set</code> considering that the set containing number 2 will be always present:</p>\n\n<pre><code>List<Set<Integer>> list = new ArrayList<>();\nSet<Integer> set = new HashSet<>();\nset.add(2);\nlist.add(set);\n</code></pre>\n\n<p>You can dismiss numbers multiple of 2 so you can use a loop starting from number 3 and with an increment of 2, so if you examining numbers from 3 to n included you can write:</p>\n\n<pre><code>public static List<Set<Integer>> createGroups(int n) {\n List<Set<Integer>> list = new ArrayList<>();\n Set<Integer> set = new HashSet<>();\n set.add(2);\n list.add(set);\n for (int i = 3; i <= n; i += 2) {\n //here your logic\n }\n return list;\n}\n</code></pre>\n\n<p>About the core of the loop if you have an odd number i so that i * 2 <= n , you are sure it will be contained in the set including number 2, like below:</p>\n\n<pre><code>if (i * 2 <= n) {\n list.get(0).add(i); <-- it is the set containing 2\n}\n</code></pre>\n\n<p>Otherwise you will check if one of the previously created sets contain a value dividing your number and add the number to this set if existing, for these you can use helper methods:</p>\n\n<pre><code>private static boolean isDivisor(int n, Set<Integer> set) {\n for (int elem : set) {\n if (n % elem == 0) {\n return true;\n }\n }\n return false;\n}\n\nprivate static boolean addedToOneSet(int n, List<Set<Integer>> list) {\n for (Set<Integer> set : list) {\n if (isDivisor(n, set)) { \n set.add(n);\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>The code of the method will include these helper functions:</p>\n\n<pre><code>public static List<Set<Integer>> createGroups(int n) {\n List<Set<Integer>> list = new ArrayList<>();\n Set<Integer> set = new HashSet<>();\n set.add(2);\n list.add(set);\n for (int i = 3; i <= n; i += 2) {\n if (i * 2 <= n) {\n list.get(0).add(i);\n } else {\n if (!addedToOneSet(i, list)) {\n Set<Integer> newset = new HashSet<>();\n newset.add(i);\n list.add(newset);\n }\n }\n }\n return list;\n}\n</code></pre>\n\n<p>Now the code of the class with some tests:</p>\n\n<pre><code>public class SocialNetwork {\n\n private static boolean isDivisor(int n, Set<Integer> set) {\n for (int elem : set) {\n if (n % elem == 0) {\n return true;\n }\n }\n return false;\n }\n\n private static boolean addedToOneSet(int n, List<Set<Integer>> list) {\n for (Set<Integer> set : list) {\n if (isDivisor(n, set)) { \n set.add(n);\n return true;\n }\n }\n return false;\n }\n\n public static List<Set<Integer>> createGroups(int n) {\n List<Set<Integer>> list = new ArrayList<>();\n Set<Integer> set = new HashSet<>();\n set.add(2);\n list.add(set);\n for (int i = 3; i <= n; i += 2) {\n if (i * 2 <= n) {\n list.get(0).add(i);\n } else {\n if (!addedToOneSet(i, list)) {\n Set<Integer> newset = new HashSet<>();\n newset.add(i);\n list.add(newset);\n }\n }\n }\n return list;\n }\n\n public static void main(String[] args) {\n System.out.println(createGroups(6)); //<-- [[2, 3], [5]]\n System.out.println(createGroups(11)); //<-- [[2, 3, 5, 9], [7], [11]]\n System.out.println(createGroups(20)); //<-- [[2, 3, 5, 7, 9, 15], [11], [13], [17], [19]]\n\n }\n\n}\n\n\n</code></pre>\n\n<p>The sizes of the lists (the groups) are the solution to the problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T17:13:24.517",
"Id": "239703",
"ParentId": "239681",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T21:07:22.537",
"Id": "239681",
"Score": "3",
"Tags": [
"java",
"algorithm"
],
"Title": "System generated Social Network"
}
|
239681
|
<p>I made a C# console math project where the user answers addition, subtraction, multiplication, division, power or square-root questions based on the difficulty they choose!</p>
<p>However, I am struggling to refactor one part of my code.</p>
<p>Here is my code:</p>
<pre><code>using System;
using System.Collections.Generic;
namespace mathstester
{
class Program
{
public enum UserDifficulty
{
Easy,
Normal,
Hard
}
public enum MathOperation
{
Addition = 1,
Subtraction = 2,
Multiplication = 3,
Division = 4,
Power = 5,
SquareRoot = 6
}
public static (int operationMin, int operationMax) GetPossibleOperationsByDifficulty(UserDifficulty userDifficulty)
{
switch (userDifficulty)
{
case UserDifficulty.Easy:
return (1, 4);
case UserDifficulty.Normal:
return (1, 5);
case UserDifficulty.Hard:
return (3, 7);
default:
throw new Exception();
}
}
public static (string message, double correctAnswer) GetMathsEquation(MathOperation mathOperation, UserDifficulty userDifficulty)
{
int number1;
int number2;
Random randomNumber = new Random();
switch (mathOperation)
{
case MathOperation.Addition:
number1 = randomNumber.Next(1000);
number2 = randomNumber.Next(1000);
return ($"{number1} + {number2}", number1 + number2);
case MathOperation.Subtraction:
number1 = randomNumber.Next(1000);
number2 = randomNumber.Next(1000);
return ($"{number1} - {number2}", number1 - number2);
case MathOperation.Multiplication:
number1 = userDifficulty == UserDifficulty.Easy ? randomNumber.Next(13) : randomNumber.Next(1000);
number2 = userDifficulty == UserDifficulty.Easy ? randomNumber.Next(13) : randomNumber.Next(1000);
return ($"{number1} * {number2}", number1 * number2);
case MathOperation.Division:
number1 = randomNumber.Next(10000);
number2 = randomNumber.Next(1000);
return ($"{number1} / {number2}", number1 / (double)number2);
case MathOperation.Power:
number1 = randomNumber.Next(13);
number2 = randomNumber.Next(5);
return ($"{number1} ^ {number2}", Math.Pow(number1, number2));
case MathOperation.SquareRoot:
number1 = randomNumber.Next(1000);
return ($"√{number1}", Math.Sqrt(number1));
default:
throw new Exception();
}
}
public class OperationQuestionScore
{
public int AdditionQuestion { get; set; }
public int AdditionScore { get; set; }
public int SubtractionQuestion { get; set; }
public int SubtractionScore { get; set; }
public int MultiplicationQuestion { get; set; }
public int MultiplicationScore { get; set; }
public int DivisionQuestion { get; set; }
public int DivisionScore { get; set; }
public int PowerQuestion { get; set; }
public int PowerScore { get; set; }
public int SquareRootQuestion { get; set; }
public int SquareRootScore { get; set; }
}
public static OperationQuestionScore Score()
{
return new OperationQuestionScore();
}
public static (int, OperationQuestionScore, OperationQuestionScore) RunTest(int numberOfQuestionsLeft, UserDifficulty userDifficulty)
{
int totalScore = 0;
Random random = new Random();
var (operationMin, operationMax) = GetPossibleOperationsByDifficulty(userDifficulty);
var score = Score();
var question = Score();
while (numberOfQuestionsLeft > 0)
{
int mathRandomOperation = random.Next(operationMin, operationMax);
MathOperation mathOperation = (MathOperation)mathRandomOperation;
var (message, correctAnswer) = GetMathsEquation(mathOperation, userDifficulty);
if (mathRandomOperation == 4 || mathRandomOperation == 6)
{
Console.Write($"To the nearest integer, What is {message} =");
}
else
{
Console.Write($"What is {message} =");
}
double userAnswer = Convert.ToDouble(Console.ReadLine());
if (Math.Round(correctAnswer) == userAnswer)
{
Console.WriteLine("Well Done!");
switch (mathOperation)
{
case MathOperation.Addition:
question.AdditionQuestion++;
score.AdditionScore++;
break;
case MathOperation.Subtraction:
question.SubtractionQuestion++;
score.SubtractionScore++;
break;
case MathOperation.Multiplication:
question.MultiplicationQuestion++;
score.MultiplicationScore++;
break;
case MathOperation.Division:
question.DivisionQuestion++;
score.DivisionScore++;
break;
case MathOperation.Power:
question.PowerQuestion++;
score.PowerScore++;
break;
case MathOperation.SquareRoot:
question.SquareRootQuestion++;
score.SquareRootScore++;
break;
}
totalScore++;
}
else
{
Console.WriteLine("Your answer is incorrect!");
switch (mathOperation)
{
case MathOperation.Addition:
question.AdditionQuestion++;
break;
case MathOperation.Subtraction:
question.SubtractionQuestion++;
break;
case MathOperation.Multiplication:
question.MultiplicationQuestion++;
break;
case MathOperation.Division:
question.DivisionQuestion++;
break;
case MathOperation.Power:
question.PowerQuestion++;
break;
case MathOperation.SquareRoot:
question.SquareRootQuestion++;
break;
}
}
numberOfQuestionsLeft--;
}
return (totalScore, score, question);
}
public static void Main(string[] args)
{
Dictionary<string, UserDifficulty> difficultyDictionary = new Dictionary<string, UserDifficulty>();
difficultyDictionary.Add("E", UserDifficulty.Easy);
difficultyDictionary.Add("N", UserDifficulty.Normal);
difficultyDictionary.Add("H", UserDifficulty.Hard);
string userInputDifficulty = "";
do
{
Console.WriteLine("What difficulty level would you like to do! Please type E for Easy, N for Normal and H for hard");
userInputDifficulty = Console.ReadLine().ToUpper();
} while (userInputDifficulty != "E" && userInputDifficulty != "N" && userInputDifficulty != "H");
UserDifficulty userDifficulty = difficultyDictionary[userInputDifficulty];
int numberOfQuestions = 0;
do
{
Console.WriteLine("How many questions would you like to answer? Please type a number divisible by 10!");
int.TryParse(Console.ReadLine(), out numberOfQuestions);
} while (numberOfQuestions % 10 != 0);
var (totalScore, score, question) = RunTest(numberOfQuestions, userDifficulty);
Console.WriteLine($"Total score: {totalScore} of {numberOfQuestions}");
if (userDifficulty == UserDifficulty.Easy)
{
Console.WriteLine($"Addition score: {score.AdditionScore} of {question.AdditionQuestion}");
Console.WriteLine($"Subtraction score: {score.SubtractionScore} of {question.SubtractionQuestion}");
Console.WriteLine($"Multiplication score: {score.MultiplicationScore} of {question.MultiplicationQuestion}");
}
else if (userDifficulty == UserDifficulty.Normal)
{
Console.WriteLine($"Addition score: {score.AdditionScore} of {question.AdditionQuestion}");
Console.WriteLine($"Subtraction score: {score.SubtractionScore} of {question.SubtractionQuestion}");
Console.WriteLine($"Multiplication score: {score.MultiplicationScore} of {question.MultiplicationQuestion}");
Console.WriteLine($"Division score: {score.DivisionScore} of {question.DivisionQuestion}");
}
else if (userDifficulty == UserDifficulty.Hard)
{
Console.WriteLine($"Multipication score: {score.MultiplicationScore} of {question.MultiplicationQuestion}");
Console.WriteLine($"Division score: {score.DivisionScore} of {question.DivisionQuestion}");
Console.WriteLine($"Power score: {score.PowerScore} of {question.PowerQuestion}");
Console.WriteLine($"Squareroot score: {score.SquareRootScore} of {question.SquareRootQuestion}");
}
}
}
}
</code></pre>
<p>In my "RunTest" function I've got two "switch" statements inside an "if-else" statement.
Without changing my code too much, I want to shorten the code by using only one "switch" statement inside my "if-else" statement.</p>
<p>I need help refactoring my code so I don't have so many loops inside a loop.</p>
|
[] |
[
{
"body": "<p>One way that you can simplify much of this code is by building out a set of classes to represent your different operations. You can then encapsulate the rules for that operation within those classes.</p>\n\n<p>To get started, you can define an abstract <code>Operation</code> class to define the shared properties and methods of the operations:</p>\n\n<pre><code>public abstract class Operation\n{\n protected readonly Random Random = new Random();\n\n private readonly string _operationName;\n\n public Operation(string operationName, params UserDifficulty[] userDifficulties)\n {\n _operationName = operationName;\n UserDifficulties = userDifficulties;\n }\n\n public int Question { get; set; }\n public int Score { get; set; }\n public UserDifficulty[] UserDifficulties { get; }\n public string GetScoreDisplay() => $\"{_operationName} score: {Score} of {Question}\";\n public abstract (string message, double correctAnswer) GetMathsEquation(UserDifficulty userDifficulty);\n}\n</code></pre>\n\n<p>You can then create a class for each of your different operations, and implement the base class accordingly. For example, <code>Addition</code> would look like:</p>\n\n<pre><code>public class Addition : Operation\n{\n public Addition() : base(\"Addition\", UserDifficulty.Easy, UserDifficulty.Normal)\n {\n }\n\n public override (string message, double correctAnswer) GetMathsEquation(UserDifficulty userDifficulty)\n {\n var number1 = Random.Next(1000);\n var number2 = Random.Next(1000);\n return ($\"{number1} + {number2}\", number1 + number2);\n }\n}\n</code></pre>\n\n<p>With these all in place, you can actually remove <em>every</em> <code>switch</code> statement in your code. This is because the specific operation logic is implemented in each class. All you need to do is construct a collection of the <code>Operation</code> objects and then call the appropriate methods. </p>\n\n<p>The <code>RunTest</code> would now look as follows:</p>\n\n<pre><code>public static (int, List<Operation>) RunTest(int numberOfQuestionsLeft, UserDifficulty userDifficulty)\n{\n int totalScore = 0;\n Random random = new Random();\n var operations = new List<Operation>\n {\n new Addition(),\n new Subtraction(),\n new Multiplication(),\n new Division(),\n new Power(),\n new SquareRoot(),\n }.Where(o => o.UserDifficulties.Contains(userDifficulty)).ToList();\n\n while (numberOfQuestionsLeft > 0)\n {\n int randomOperation = random.Next(operations.Count);\n Operation operation = operations[randomOperation];\n var (message, correctAnswer) = operation.GetMathsEquation(userDifficulty);\n if (operation is Division || operation is SquareRoot)\n {\n Console.Write($\"To the nearest integer, What is {message} =\");\n }\n else\n {\n Console.Write($\"What is {message} =\");\n }\n double userAnswer = Convert.ToDouble(Console.ReadLine());\n if (Math.Round(correctAnswer) == userAnswer)\n {\n Console.WriteLine(\"Well Done!\");\n operation.Score++;\n totalScore++;\n }\n else\n {\n Console.WriteLine(\"Your answer is incorrect!\");\n }\n operation.Question++;\n numberOfQuestionsLeft--;\n }\n return (totalScore, operations);\n}\n</code></pre>\n\n<p>And the usage of that method would look like:</p>\n\n<pre><code>var (totalScore, operations) = RunTest(numberOfQuestions, userDifficulty);\nConsole.WriteLine($\"Total score: {totalScore} of {numberOfQuestions}\");\n\nforeach (var operation in operations)\n{\n Console.WriteLine(operation.GetScoreDisplay());\n}\n</code></pre>\n\n<hr>\n\n<p>Here's another option that achieves your goal of reducing the number of switch statements in the <code>RunTest</code> method from two to one with fewer overall code changes:</p>\n\n<pre><code>public static (int, OperationQuestionScore, OperationQuestionScore) RunTest(int numberOfQuestionsLeft, UserDifficulty userDifficulty)\n{\n int totalScore = 0;\n Random random = new Random();\n var (operationMin, operationMax) = GetPossibleOperationsByDifficulty(userDifficulty);\n var score = Score();\n var question = Score();\n\n while (numberOfQuestionsLeft > 0)\n {\n int mathRandomOperation = random.Next(operationMin, operationMax);\n MathOperation mathOperation = (MathOperation)mathRandomOperation;\n var (message, correctAnswer) = GetMathsEquation(mathOperation, userDifficulty);\n if (mathRandomOperation == 4 || mathRandomOperation == 6)\n {\n Console.Write($\"To the nearest integer, What is {message} =\");\n }\n else\n {\n Console.Write($\"What is {message} =\");\n }\n\n Action<OperationQuestionScore> incrementQuestion;\n Action<OperationQuestionScore> incrementScore;\n switch (mathOperation)\n {\n case MathOperation.Addition:\n incrementQuestion = o => o.AdditionQuestion++;\n incrementScore = o => o.AdditionScore++;\n break;\n case MathOperation.Subtraction:\n incrementQuestion = o => o.SubtractionQuestion++;\n incrementScore = o => o.SubtractionScore++;\n break;\n case MathOperation.Multiplication:\n incrementQuestion = o => o.MultiplicationQuestion++;\n incrementScore = o => o.MultiplicationScore++;\n break;\n case MathOperation.Division:\n incrementQuestion = o => o.DivisionQuestion++;\n incrementScore = o => o.DivisionScore++;\n break;\n case MathOperation.Power:\n incrementQuestion = o => o.PowerQuestion++;\n incrementScore = o => o.PowerScore++;\n break;\n case MathOperation.SquareRoot:\n incrementQuestion = o => o.SquareRootQuestion++;\n incrementScore = o => o.SquareRootScore++;\n break;\n default:\n incrementQuestion = _ => { };\n incrementScore = _ => { };\n break;\n }\n\n double userAnswer = Convert.ToDouble(Console.ReadLine());\n if (Math.Round(correctAnswer) == userAnswer)\n {\n Console.WriteLine(\"Well Done!\");\n incrementQuestion(question);\n incrementScore(score);\n totalScore++;\n }\n else\n {\n Console.WriteLine(\"Your answer is incorrect!\");\n incrementQuestion(question);\n }\n numberOfQuestionsLeft--;\n }\n return (totalScore, score, question);\n}\n</code></pre>\n\n<p>As you can see, a single <code>switch</code> statement now exists before the <code>if</code>/<code>else</code> block. And two <code>Action</code> delegates are being created within the switch statement to represent the proper \"increment\" operation needed in the <code>if</code>/<code>else</code> block.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T23:01:49.647",
"Id": "470365",
"Score": "0",
"body": "Thanks @devNull But Is there a way so I don't need to change my code so much?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T01:54:37.317",
"Id": "470369",
"Score": "1",
"body": "@crazydanyal1414 I've edited my answer to include an additional option that only requires changing the code within the `RunTest` method"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T01:39:34.963",
"Id": "239720",
"ParentId": "239683",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "239720",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T23:42:13.513",
"Id": "239683",
"Score": "7",
"Tags": [
"c#",
"beginner",
"console",
"mathematics"
],
"Title": "C# random math questions project"
}
|
239683
|
<p>On a Manhattan grid, find the intersection of two paths closest to the origin. <code>input_3.txt</code> can be found <a href="https://adventofcode.com/2019/day/3/input" rel="nofollow noreferrer">here</a> and the prompts can be found in the <a href="https://adventofcode.com/2019/day/3" rel="nofollow noreferrer">original problem statement</a>.</p>
<pre><code>import re
with open("input_3.txt", "r") as f:
coordinates = [wire.split(",") for wire in f.read().splitlines()]
class Point:
def __init__(self, x: int, y: int, cumulative_steps: int):
self.x = x
self.y = y
self.cumulative_steps = cumulative_steps
def __eq__(self, other):
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
def __repr__(self):
return f"x:{self.x}, y:{self.y}"
class WirePath:
def __init__(self, **kwargs):
self.origin = Point(0, 0, 0)
self.path = kwargs.get("path", None)
self.points = [
self.origin,
]
self.current_point = None
if self.path:
self.generate_travelled_points(self.path)
def travel(self, direction, velocity):
start = self.origin if not self.current_point else self.current_point
# calculate cumulative steps for each point added
if direction in "RL":
# if R subtract negative (add), if L subtract (minus)
pos = -1 if direction == "R" else 1
# add all points between the two segments
new_points = [
Point(start.x - (pos * p), start.y, start.cumulative_steps + p)
for p in range(1, abs(velocity) + 1)
]
else:
# if U subtract negative (add), if D subtract (minus)
pos = -1 if direction == "U" else 1
new_points = [
Point(start.x, start.y - (pos * p), start.cumulative_steps + p)
for p in range(1, abs(velocity) + 1)
]
self.points.extend(new_points)
self.current_point = self.points[-1]
def generate_travelled_points(self, vectors: list):
for vector in vectors:
# extract the direction & velocity
r = re.compile("([a-zA-Z]+)([0-9]+)")
m = r.match(vector)
direction = m.group(1)
velocity = int(m.group(2))
# add the point to self.points
self.travel(direction, velocity)
def manhattan_distance_between_points(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
wire1 = WirePath(path=coordinates[0])
wire2 = WirePath(path=coordinates[1])
intersections = set([x for x in wire1.points if x.cumulative_steps != 0]).intersection(
[x for x in wire2.points if x.cumulative_steps != 0]
)
intersections_with_distance_from_origin = [
((x.x, x.y), manhattan_distance_between_points((x.x, x.y), (0, 0)))
for x in intersections
if x.cumulative_steps != 0
]
# part 1
closest_intersection = min(intersections_with_distance_from_origin, key=lambda t: t[1])
print(closest_intersection)
intersection_pairs = []
for intersection in intersections:
# find points from each wire that matches the hash
wire1_intersects = min(
[i for i in wire1.points if i == intersection], key=lambda t: t.cumulative_steps
)
wire2_intersects = min(
[i for i in wire2.points if i == intersection], key=lambda t: t.cumulative_steps
)
intersection_pairs.append([wire1_intersects, wire2_intersects])
min_steps = min(
intersection_pairs, key=lambda t: t[0].cumulative_steps + t[1].cumulative_steps
)
min_combined_steps_wire1 = min_steps[0].cumulative_steps
min_combined_steps_wire2 = min_steps[1].cumulative_steps
comb = min_combined_steps_wire1 + min_combined_steps_wire2
# part 2
print(
f"Min combined steps: {comb}, wire1: {min_combined_steps_wire1}, wire2: {min_combined_steps_wire2} at {min_steps}"
)
</code></pre>
<p>My code is quite slow (~7s on my pc) and I have a feeling it's a combination of:</p>
<ol>
<li>how I'm storing all points in memory instead of making use of inferred points by storing line fragments instead, and</li>
<li>my mishandling of the set iteration in the last part that attempts to find the respective pair of points (one for each wire) to get their respective <code>cumulative_steps</code>.</li>
</ol>
<p>I got a little confused as to the best way to treat this because a wire can cross an intersection multiple times (though I believe in this data set that ended up not occurring?) and as a result I needed not just find the intersections but the intersections and the min steps required for each wire to get to that intersection.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T00:29:34.127",
"Id": "474368",
"Score": "0",
"body": "The input file requires one to be logged in, since inputs differ by user. Can you provide a sample of your input data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-06T00:08:03.063",
"Id": "474475",
"Score": "0",
"body": "The endpoints of the segments tell you everything you need to know in order to calculate the intersection points, the lengths, etc. No need to define a point for each point on the segment. In fact, you shouldn't, because as you've seen it is too expensive."
}
] |
[
{
"body": "<p>These problems are typically performance-bound, and so it doesn't pay for you to design classes for such things as <code>Point</code> unless you are sure you need it.</p>\n\n<p>In this case, I don't think you need it.</p>\n\n<h2>Consider using segments rather than points</h2>\n\n<p>Consider a worst-case path. It would be a staircase, each segment of length 1. This would generate lines of length 1, making each line effectively a single point (since the origin is included in the previous line).</p>\n\n<p>If you have an algorithm that examines all the points your path traverses (which yours presently does), it would perform <em>exactly equal</em> to an algorithm that examines the line segments as discrete elements.</p>\n\n<p>On the other hand, a non-pessimal path would have at least one line segment of length > 1, which would improve performance.</p>\n\n<p>For this reason, I think you should rewrite your code to use line segments rather than points.</p>\n\n<h2>Tell, don't ask.</h2>\n\n<p>In the process of decoding the line segments, you use a regular expression, then discard the result, then use a series of string membership checks.</p>\n\n<p>This is all wasted time. You know there are only four possible valid inputs {D, L, R, U}. Check for them explicitly, and dispatch instantly to the appropriate code:</p>\n\n<pre><code>handlers = { \"U\" : self.up, \"D\": self.down, \"L\": self.left, \"R\": self.right }\n\nfor segment in line:\n move_to = handlers[segment[0]]\n move_to(int(segment[1:]))\n</code></pre>\n\n<p>Take care of updating your current position indicator in the handler. And <strong>encode the knowledge</strong> of what is happening in the different handlers:</p>\n\n<pre><code>def up(self, how_far: int):\n \"\"\"Add an upward line segment starting at cur_pos to the wire path.\"\"\"\n\n new_xy = Position(self.cur_pos.x, self.cur_pos.y + how_far)\n self.verticals.append((self.cur_pos, new_xy))\n self.cur_pos = new_xy\n</code></pre>\n\n<h2>Don't forget information</h2>\n\n<p>Knowing that a line segment is horizontal or vertical is valuable information. You should consider keeping your segments separate, or creating <code>named_tuple</code> types to differentiate between them.</p>\n\n<p>If you keep them separate, then coding intersection code is simpler: you can special-case all the different flavors (an argument for creating separate types!).</p>\n\n<h2>Be lazy</h2>\n\n<p>You know that you are looking for the closest intersection point. If you are checking a line segment that has a \"closest point\" which is farther away than your current best match, you could skip that segment entirely! </p>\n\n<p>It may or may not make sense to compute and track this information. You would have to write the code both ways to be sure. But your current approach is already <span class=\"math-container\">\\$N ^2\\$</span> so this might speed things up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T15:33:55.247",
"Id": "474424",
"Score": "0",
"body": "nice suggestions, thanks! can you show how you got to `N^2` (pardon the lack of mathjax)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T21:46:41.103",
"Id": "474472",
"Score": "1",
"body": "You are building a set of ordinal points for every location covered by each wire. So the wires have length \"N\" (and \"M\") and your intersection computation bangs the two sets against each other, so the time is \\$ N \\times M\\$, which I'm calling \\$N^2\\$ since there are no constraints on the wire lengths."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T01:13:50.063",
"Id": "241729",
"ParentId": "239684",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T01:11:43.310",
"Id": "239684",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Advent of Code 2019 Day 3: Crossed Wires"
}
|
239684
|
<p>I have a list of about 55k Accounts that I am cleaning up. 95% of them are from US/Canada which is what I'm most concerned with. I am going through record by record and will perform various checks and fill in or correct City, State, Zip, Country. I have a table with every City, State, and Zip for US and Canada that I check against. For this part, maybe 20% will be processed after grabbing the info.</p>
<p>I am doing a kind of proof of concept right now, and it's taking forever. I just hit the 1hr mark with 24,500 (Less than 7 records/sec) . I didn't expect this to take so long. Next will be running a similar process on the Contacts, and there are over 400k contacts. I'm afraid how long that will take!!</p>
<p>Is there a better way to do this to decrease the time taken?</p>
<p>Here is the code right now:</p>
<pre><code>-- MS SQL Server 15.0.2070.41
ALTER PROCEDURE [dbo].[SetLocationInfo]
AS
BEGIN
DECLARE
@maxRecords int = 0,
@cnt int = 1,
@city varchar(255),
@state varchar(255),
@zip varchar(255),
@country varchar(255)
SELECT TOP(1) @maxRecords = id2 FROM Account ORDER BY Id2 DESC
-- BEGIN LOOP
WHILE @cnt <= @maxRecords
BEGIN
-- Resets Variables
SET @city = NULL
SET @state = NULL
SET @zip = NULL
SET @country = NULL
-- Pulls BILLING Address Info from Record
SELECT
@city = [BillingCity],
@state = [BillingState],
@zip = [BillingPostalCode],
@country = [BillingCountry]
FROM [Account] WHERE Id2 = @cnt
-- Searches for and Sets BILLING Country
IF (@country IS NULL) OR ((@country != 'United States') AND (@country != 'Canada'))
BEGIN
SELECT TOP(1) @country = Country FROM [CityStateInfo]
WHERE
(City = @city AND State_abbr = @state) OR
(City = @city AND Zip = LEFT(@zip,5)) OR
(Zip = LEFT(@zip,5))
IF @country IS NOT NULL
UPDATE Account SET [BillingCountry] = @country WHERE Id2 = @cnt
END
-- Resets Variables
SET @city = NULL
SET @state = NULL
SET @zip = NULL
SET @country = NULL
-- Pulls SHIPPING Address Info from Record
SELECT
@city = [ShippingCity],
@state = [ShippingState],
@zip = [ShippingPostalCode],
@country = [ShippingCountry]
FROM [Account] WHERE Id2 = @cnt
-- Searches for and Sets SHIPPING Country
IF (@country IS NULL) OR ((@country != 'United States') AND (@country != 'Canada'))
BEGIN
SELECT TOP(1) @country = Country FROM [CityStateInfo]
WHERE
(City = @city AND State_abbr = @state) OR
(City = @city AND Zip = LEFT(@zip,5)) OR
(Zip = LEFT(@zip,5))
IF @country IS NOT NULL
BEGIN
PRINT CAST(@cnt AS varchar(10)) + ': ' + @country
UPDATE Account SET [ShippingCountry] = @country WHERE Id2 = @cnt
END
END
-- Increments Counter
SET @cnt = @cnt + 1
END
-- END LOOP
END
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T06:24:12.337",
"Id": "470192",
"Score": "0",
"body": "What specific SQL dialect are you using? May be such thing could be done with a single WITH statement."
}
] |
[
{
"body": "<p>Please update your questions with the relevant <strong>tags</strong>, although it is obvious you are using SQL Server here.</p>\n\n<p>If you run an <strong>execution plan</strong> in your query window, you will be able to see which specific bits are taking a lot time and whether SQL Server is using any indexes etc.</p>\n\n<p>It would be good if you gave a data sample and the table structure. Here are some ideas though.</p>\n\n<p>Is there a reason why you are using a WHILE loop instead of a cursor ? The idea here is that you start with ID 1 and increment until you reach the max ID but there must probably be gaps in your table... the approach is possibly wasteful if you are trying to update rows that don't even exist.</p>\n\n<p>Rather than work on the table <code>Account</code> directly (which may be in use or subject to locks), I would rather work on a partial copy using a <strong>temporary table</strong>.</p>\n\n<p>Step 1: create a temporary table with all the records from <code>Account</code> you want to fix, matching some criteria eg country empty</p>\n\n<pre><code>SELECT *\nINTO #Account\nFROM Account\nWHERE <add your criteria here>\n</code></pre>\n\n<p>Step 2: perform all your operations on that temporary table <code>#Account</code></p>\n\n<p>Step 3: update the original table based on the temporary table (UPDATE FROM):</p>\n\n<pre><code>UPDATE Account\nSET\n Account.ShippingCountry = #Account.ShippingCountry,\n Account.BillingCountry = #Account.BillingCountry,\n ...\nFROM #Account\nWHERE\n #Account.id2 = Account.id2\n</code></pre>\n\n<p>Here I am assuming that id2 is indeed an identity column that uniquely identifies each record. If it isn't, but instead is some kind of unindexed integer value, then each UPDATE requires a full table scan and there is a performance hit here. Again, can't tell without knowing the table structure for sure.</p>\n\n<p>If all this takes too much time, you can process the jobs in small chunks, for example pull 1000 records at a time using <code>SELECT TOP 1000</code>, and repeat until the table is cleaned.</p>\n\n<p>In short, updating a large table can be very slow if you cannot rely on some index, using an appropriate <code>WHERE</code> clause.</p>\n\n<p>Important remark regarding the temporary table approach: doing <code>SELECT INTO</code> creates a copy of the data but does not include the complete table structure, that is indexes, constraints. That mean the id column will be an ordinary integer and not a unique, indexed field. So I would add the index manually on that field to speed the <code>UPDATE FROM</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T15:09:06.200",
"Id": "470226",
"Score": "0",
"body": "\"Please update your questions with the relevant tags, although it is obvious you are using SQL Server here.\" should be a comment on the question and not be part of your review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T22:42:45.857",
"Id": "470247",
"Score": "0",
"body": "Thank you for your reply! Let's see. I've never used a Cursor before. I've read mixed things on them, so I stuck with what I know (I'm coming from traditional programming). The table had an id column already which was like a uuid, so I added id2 to use for the loop and make it easier to do on-off updates. I'm also not great with indicies (cringe). I learned a lot from your reply, thank you!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T14:11:20.203",
"Id": "239699",
"ParentId": "239688",
"Score": "3"
}
},
{
"body": "<p>You should be able to do this with a simple update command, no loops at all, something like this:</p>\n\n<pre><code>UPDATE Account SET [BillingCountry] = << some expression >>\nwhere isnull(BillingCountry,'') not in ( 'United States', 'Canada' )\n</code></pre>\n\n<p>I would recommend writing a function to compute the country, it probably makes it easier to test the results are correct before running the update. The function would take as parameters the City, State and Zipcode ( and perhaps the current value of Country if you you want that to be the result if it cannot be computed ), and return the computed country ( based on the CityStateInfo table you have ).</p>\n\n<p>This should run pretty fast, within a few seconds, provided the CityStateInfo table is appropriately indexed ( on both City,State_abbr and also on Zip ).</p>\n\n<p>Your expression for matching seems to be redundant:</p>\n\n<pre><code> (City = @city AND State_abbr = @state) OR \n (City = @city AND Zip = LEFT(@zip,5)) OR\n (Zip = LEFT(@zip,5))\n</code></pre>\n\n<p>The middle line can be removed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T20:51:32.337",
"Id": "470445",
"Score": "0",
"body": "I actually did this for my Contact table. I added Indicies to the CityStateInfo table. Copied what I need into a temp table, about 48k rows. Ran this update (31,500 rows) and it took 42min.\nUPDATE #Contact_Address SET [MailingCountry] = \n (SELECT TOP(1) Country FROM [ULTRA].[dbo].[CityStateInfo] WHERE City = [MailingCity] AND (State_long = [MailingState] OR State_abbr = [MailingState]) AND Zip = LEFT([MailingPostalCode],5))\n WHERE \n [MailingCountry] IS NULL AND \n [MailingCity] IS NOT NULL AND \n [MailingState] IS NOT NULL AND \n [MailingPostalCode] IS NOT NULL"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T21:17:05.957",
"Id": "470451",
"Score": "0",
"body": "@Dizzy49 I would check the execution plan to see if the indices are being used. It may be best to check the Zipcode first ( using that index ), then if that fails (to yield a country) check the City/State. I don't think it should be taking 42 minutes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T16:39:02.300",
"Id": "470559",
"Score": "0",
"body": "Not sure what was going on then, but every other time I've run it it's taken 12-14min which is more reasonable. I'm processing 3-4x as much as my last table, in a total of less than 30min vs HOURS :D I think I found where to view the Execution Plan, but I have no idea how to read it :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T20:04:38.543",
"Id": "470574",
"Score": "0",
"body": "@Dizzy49 If the plan says it's scanning a table, that's bad. Another approach might be to construct a view (or query) with the correct values ( using two left joins to the CityStateInfo table ), then update the Account table by selecting the correct value from the view (or query) with an id field."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T18:12:53.650",
"Id": "239822",
"ParentId": "239688",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239822",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T03:50:41.847",
"Id": "239688",
"Score": "1",
"Tags": [
"sql",
"sql-server"
],
"Title": "Faster/Better Processing for SQL While Loop"
}
|
239688
|
<p>The following is my attempt at parallelizing (I learned about parallel computing over the last weekend, so I'm very new to it) and making more efficient the code in my previous question <a href="https://codereview.stackexchange.com/questions/239504/block-bootstrap-estimation-using-java">Block Bootstrap Estimation using Java</a>. The text file text.txt can be found at <a href="https://drive.google.com/open?id=1vLBoNmFyh4alDZt1eoJpavuEwWlPZSKX" rel="nofollow noreferrer">https://drive.google.com/open?id=1vLBoNmFyh4alDZt1eoJpavuEwWlPZSKX</a> (please download the file directly should you wish to test it; there are some odd things about it that you will not pick up through even Notepad). This is a small 10 x 10 dataset with <code>maxBlockSize = 10</code>, but this needs to scale up to twenty 5000 x 3000 datasets with <code>maxBlockSize = 3000</code>, just to get an idea of scale.</p>
<pre><code>import java.io.FileInputStream;
import java.lang.Math;
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.DoubleStream;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.BrokenBarrierException;
import java.lang.InterruptedException;
public class BlockBootstrapTestParallel {
// Sum of a subarray, based on B(x, i, L) -- i is one-indexing
public static double sum(double[] x, int i, int L) {
return IntStream.range(i, i + L)
.parallel()
.mapToDouble(idx -> x[idx - 1])
.sum();
}
// Mean of a subarray, based on B(x, i, L) -- i is one-indexing
public static double mean(double[] x, int i, int L) {
return IntStream.range(i, i + L)
.parallel()
.mapToDouble(idx -> x[idx - 1])
.average()
.orElse(0);
}
// Compute MBB mean
public static double mbbMu(double[] x, int L) {
return IntStream.range(0, x.length - L + 1)
.parallel()
.mapToDouble(idx -> mean(x, idx + 1, L))
.average()
.orElse(0);
}
// Compute MBB variance
public static double mbbVariance(double[] x, int L, double alpha) {
return IntStream.range(0, x.length - L + 1)
.parallel()
.mapToDouble(idx -> (Math.pow(L, alpha) * Math.pow(mean(x, idx + 1, L) - mbbMu(x, L), 2)))
.average()
.orElse(0);
}
// Compute NBB mean
public static double nbbMu(double[] x, int L) {
return IntStream.range(0, x.length / L)
.parallel()
.mapToDouble(idx -> (mean(x, 1 + ((idx + 1) - 1) * L, L)))
.average()
.orElse(0);
}
// Compute NBB variance
public static double nbbVariance(double[] x, int L, double alpha) {
double varSum = IntStream.range(0, x.length / L)
.parallel()
.mapToDouble(idx -> (Math.pow(mean(x, 1 + ((idx + 1) - 1) * L, L) - nbbMu(x, L), 2)))
.average()
.orElse(0);
return Math.pow((double) L, alpha) * varSum;
}
// factorial implementation
public static double factorial(int x) {
double[] fact = {1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0, 3628800.0};
return fact[x];
}
// Hermite polynomial
public static double H(double x, int p) {
double out = IntStream.range(0, (p / 2) + 1)
.parallel()
.mapToDouble(idx -> (Math.pow(-1, idx) * Math.pow(x, p - (2 * idx)) /
((factorial(idx) * factorial(p - (2 * idx))) * (1L << idx))))
.sum();
out *= factorial(p);
return out;
}
// Row means
public static double[] rowMeans(double[][] x, int nrows, int ncols) {
return IntStream.range(0, nrows)
.parallel()
.mapToDouble(idx -> (mean(x[idx], 1, ncols)))
.toArray();
}
public static void duration(long start, long end) {
System.out.println("Total execution time: " + (((double)(end - start))/60000) + " minutes");
}
public static void main(String[] argv) throws InterruptedException, BrokenBarrierException, IOException {
final long start = System.currentTimeMillis();
FileInputStream fileIn = new FileInputStream("test.txt");
FileOutputStream fileOutMBB = new FileOutputStream("MBB_test.txt");
FileOutputStream fileOutNBB = new FileOutputStream("NBB_test.txt");
FileOutputStream fileOutMean = new FileOutputStream("means_test.txt");
Scanner scnr = new Scanner(fileIn);
PrintWriter outFSMBB = new PrintWriter(fileOutMBB);
PrintWriter outFSNBB = new PrintWriter(fileOutNBB);
PrintWriter outFSmean = new PrintWriter(fileOutMean);
// These variables are taken from the command line, but are inputted here for ease of use.
int rows = 10;
int cols = 10;
int maxBlockSize = 10; // this could potentially be any value <= cols
int p = 1;
double alpha = 0.1;
double[][] timeSeries = new double[rows][cols];
// read in the file, and perform the H_p(x) transformation
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
timeSeries[i][j] = H(scnr.nextDouble(), p);
}
scnr.next(); // skip null terminator
}
// row means
double[] sampleMeans = rowMeans(timeSeries, rows, cols);
for (int i = 0; i < rows; i++) {
outFSmean.print(sampleMeans[i] + " ");
}
outFSmean.println();
outFSmean.close();
final CyclicBarrier gate = new CyclicBarrier(3);
Thread mbbThread = new Thread(() -> {
try {
gate.await();
for (int j = 0; j < rows; j++) {
for (int m = 0; m < maxBlockSize; m++) {
outFSMBB.print(mbbVariance(timeSeries[j], m + 1, alpha) + " ");
}
outFSMBB.println();
}
outFSMBB.close();
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted!");
e.printStackTrace();
} catch (BrokenBarrierException e) {
System.out.println("Main Thread interrupted!");
e.printStackTrace();
}
});
Thread nbbThread = new Thread(() -> {
try {
gate.await();
for (int j = 0; j < rows; j++) {
for (int m = 0; m < maxBlockSize; m++) {
outFSNBB.print(nbbVariance(timeSeries[j], m + 1, alpha) + " ");
}
outFSNBB.println();
}
outFSNBB.close();
} catch (InterruptedException e) {
System.out.println("Main Thread interrupted!");
e.printStackTrace();
} catch (BrokenBarrierException e) {
System.out.println("Main Thread interrupted!");
e.printStackTrace();
}
});
// start threads simultaneously
mbbThread.start();
nbbThread.start();
gate.await();
// wait for threads to die
mbbThread.join();
nbbThread.join();
duration(start, System.currentTimeMillis());
}
}
</code></pre>
<p>If helpful, I have <s>8</s> 6 cores available with 64GB of RAM, as well as two GPUs that I have no idea how to use (Intel UHD Graphics 630, NVIDIA Quadro P620). I'll be looking over how to use these in the next few days if I have to.</p>
|
[] |
[
{
"body": "<p>You've got inefficiency here:</p>\n\n<pre><code> // Sum of a subarray, based on B(x, i, L) -- i is one-indexing\n public static double sum(double[] x, int i, int L) {\n return IntStream.range(i, i + L)\n .parallel()\n .mapToDouble(idx -> x[idx - 1])\n .sum();\n }\n</code></pre>\n\n<p>I don't know how big <code>L</code> is, but you are doing <code>idx - 1</code> that many times, distributed over all of the threads. You can easily move this out of the loop ...</p>\n\n<pre><code> return IntStream.range(i - 1, i + L - 1)\n .parallel()\n .mapToDouble(idx -> x[idx])\n .sum();\n</code></pre>\n\n<p>... so the subtraction is done exactly twice.</p>\n\n<hr>\n\n<p>Parallel stream in a parallel stream:</p>\n\n<pre><code>public static double mbbMu(double[] x, int L) { \n return IntStream.range(0, x.length - L + 1)\n .parallel()\n .mapToDouble(idx -> mean(x, idx + 1, L))\n .average()\n .orElse(0);\n}\n</code></pre>\n\n<p>The <code>mean(...)</code> function is trying to do things in a parallel stream. And this function is trying to do things in a parallel stream. So you've got parallel overhead, plus resource contention. With 8 cores, your outer stream will create 8 threads, which will each try to create 8 threads, for 8*8 threads on 8 cores!</p>\n\n<p>Eeek!</p>\n\n<p>Use parallel streams on the outermost streams, and leave all inner streams as serial.</p>\n\n<hr>\n\n<p>Try losing the indexing altogether, and stream the values directly with:</p>\n\n<pre><code> public static double sum(double[] x, int i, int L) {\n return Arrays.stream(x).skip(i-1).limit(L).sum();\n }\n</code></pre>\n\n<hr>\n\n<p>Avoid unnecessary work.</p>\n\n<pre><code> // Compute MBB variance\n public static double mbbVariance(double[] x, int L, double alpha) {\n return IntStream.range(0, x.length - L + 1)\n .parallel()\n .mapToDouble(idx -> (Math.pow(L, alpha) * Math.pow(mean(x, idx + 1, L) - mbbMu(x, L), 2)))\n .average()\n .orElse(0);\n }\n</code></pre>\n\n<p>How many times does this calculate <code>Math.pow(L, alpha)</code>? How many times is the value different? Maybe you want to move it out of the loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T22:47:44.083",
"Id": "239714",
"ParentId": "239689",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T04:58:55.343",
"Id": "239689",
"Score": "2",
"Tags": [
"java",
"performance"
],
"Title": "Block Bootstrap Estimation in Java - Part 2"
}
|
239689
|
<p>I am learning python by solving python module from HackerRank. This problem is <a href="https://www.hackerrank.com/challenges/finding-the-percentage/problem?isFullScreen=false" rel="nofollow noreferrer">Find the Percentage</a>. </p>
<blockquote>
<p>You have a record of N students. Each record contains the student's
name, and their percent marks in Maths, Physics and Chemistry. The
marks can be floating values. The user enters some N integer followed
by the names and marks for N students. You are required to save the
record in a dictionary data type. The user then enters a student's
name. Output the average percentage marks obtained by that student,
correct to two decimal places.</p>
<p><strong>Sample Input 0</strong></p>
<pre><code>3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika
</code></pre>
<p><strong>Sample Output 0</strong></p>
<pre><code>56.00
</code></pre>
</blockquote>
<p>I need to improve this code by using better functions available in python. </p>
<pre><code>def percentage(name):
"""
Find percentage of marks of the student
"""
marks = student_marks[name]
total_marks = 0
for mark in marks:
total_marks += mark
return format(total_marks/len(marks), '.2f')
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
print(percentage(query_name))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T10:02:54.817",
"Id": "470209",
"Score": "1",
"body": "What do you need to improve about the code and why? Did you write this code? Please clarify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T10:25:38.693",
"Id": "470210",
"Score": "0",
"body": "Yes, I wrote this and I am beginner in Python. I want to learn about other modules and functions which will help me to solve this problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T05:50:55.750",
"Id": "470268",
"Score": "0",
"body": "(To the flagger: What gave rise to flag *not implemented or not working as intended*?)"
}
] |
[
{
"body": "<p>For a beginner this is some good code. I would make some additional adjustments.</p>\n\n<ul>\n<li>One-line docstrings should be on one line, not over 3. And should end with a period.</li>\n<li>You should only pass the marks to <code>percentage</code> and not rely on a global <code>student_marks</code>.</li>\n<li>You can use <code>sum</code> to compute <code>total_marks</code>.</li>\n<li>I'm not a fan of having <code>format</code> in the <code>percentage</code> function.</li>\n<li>You should move all the main code into a main function, <code>if __name__ == '__main__':</code> should really only call this.</li>\n<li>It's more idiomatic to use comprehensions than <code>map</code>, even more so when you have <code>list(map(...))</code>.</li>\n<li>It's pretty rude to call a student a query. You can just use name.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def percentage(marks):\n \"\"\"Find percentage of marks of the student.\"\"\"\n return sum(marks) / len(marks)\n\n\ndef main():\n \"\"\"Main code.\"\"\"\n n = int(input())\n student_marks = {}\n for _ in range(n):\n name, *scores = input().split()\n student_marks[name] = [float(score) for score in scores]\n name = input()\n result = percentage(student_marks[name])\n print(format(result, '.2f'))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<ul>\n<li>You can use <code>statistics.mean</code> rather than a custom made <code>percentage</code>.</li>\n<li><p>You can change the for loop into two comprehensions, a generator and dictionary comprehension.</p>\n\n<p><strong>Note</strong>: I don't think comprehensions are better here, but are an 'as good' alternate.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import statistics\n\n\ndef main():\n \"\"\"Main code.\"\"\"\n _marks = (input().split() for _ in range(int(input())))\n student_marks = {\n name: [float(score) for score in scores]\n for name, *scores in _marks\n }\n result = statistics.mean(student_marks[input()])\n print(format(result, '.2f'))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T07:40:06.660",
"Id": "470277",
"Score": "0",
"body": "`You can use statistics.mean` during input and have that average the value kept in the dict - as per problem statements, the individual scores are as important as the subjects they have been credited for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T13:05:08.627",
"Id": "239696",
"ParentId": "239690",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "239696",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T09:54:11.333",
"Id": "239690",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Find the Percentage from HackerRank"
}
|
239690
|
<p>Recently I wrote a validator for some objects. To increase usability the validator gives the user hints on how to fix some of the found issues. Since the application is around something programmatic, and that many of the issues wouldn't make sense without identifying a path to an object; I decided to build a navigator.</p>
<p>At first I didn't have this so I just used <code>getattr</code> and defaulted to the very helpful <code><Unknown></code> value if that failed to get the value. This resulted in some useful; some less useful messages.</p>
<p>Upon completing the V1 of the below code I had the clever idea of allowing the validator to just fix the fixable issues. Since this is a flag, it allows the user to get a working version and then come back and clean it up once it works. However this quickly showed some errors in my initial design as I didn't plan for setting and deleting values.</p>
<hr>
<p>I feel like given how catastrophically V1 failed V2 isn't going to be much better. Unlike with V1, with V2 I followed TDD, and so the code slowly built up over some time. This has caused a lot of the nuance to just disappear and I find <code>_parse</code> to be a bit of an eyesore.</p>
<p>I have added a full description on what this achieves in the code, however a short overview would be that it's similar to <code>eval()</code> just it's not evil.</p>
<ul>
<li>Attribute indexing similar to standard Python. <code>data.foo.bar.baz</code>.</li>
<li>Escape special (all) characters using a slash \.</li>
<li>Index items using brackets. <code>data["key1"]["key2"]</code>.</li>
<li>Allow two literals strings or integers, <code>1</code> and <code>"key"</code>.</li>
</ul>
<p>However it acts quite a bit differently as each level has <code>data</code> implicitly prepended - if it is not a literal.</p>
<ul>
<li><code>[["key"]]</code> would be the same as <code>data[data["key"]]</code> in Python, and</li>
<li><code>[foo]</code> would be the same as <code>data[data.foo]</code> rather than <code>data["foo"]</code>.</li>
</ul>
<p>I would like a review of any or all of my code. However changes that reduce version compatibility are generally unhelpful.</p>
<pre class="lang-py prettyprint-override"><code>import dataclasses
from typing import Any, Iterator, List, NoReturn, Optional, Union, cast
@dataclasses.dataclass
class Attr:
_index: "Path"
def get(self, root_obj: Any, obj: Any) -> Any:
"""Get attribute from object."""
return getattr(obj, self._index.get(root_obj))
def set(self, root_obj: Any, obj: Any, value: Any) -> Any:
"""Set object's attribute to value."""
setattr(obj, self._index.get(root_obj), value)
def delete(self, root_obj: Any, obj: Any) -> Any:
"""Delete object's attribute."""
delattr(obj, self._index.get(root_obj))
@dataclasses.dataclass
class Item:
_index: "Path"
def get(self, root_obj: Any, obj: Any) -> Any:
"""Index object."""
return obj[self._index.get(root_obj)]
def set(self, root_obj: Any, obj: Any, value: Any) -> Any:
"""Set object's index to value."""
obj[self._index.get(root_obj)] = value
def delete(self, root_obj: Any, obj: Any) -> Any:
"""Delete object's index."""
del obj[self._index.get(root_obj)]
@dataclasses.dataclass
class Literal:
_index: Any
def get(self, root_obj: Any, obj: Any) -> Any:
"""Get literal value."""
return self._index
def set(self, root_obj: Any, obj: Any, value: Any) -> NoReturn:
"""Unable to change a literal, the path is misconfigured."""
raise TypeError("Can't set to a literal")
def delete(self, root_obj: Any, obj: Any) -> NoReturn:
"""Unable to delete a literal, the path is misconfigured."""
raise TypeError("Can't delete a literal")
@dataclasses.dataclass
class Path:
_nodes: List[Union[Attr, Item, Literal]]
@classmethod
def from_str(cls, value: str) -> "Path":
"""
Build a path from string form.
Without any special characters this works the same way that
`getattr` and friends works.
>>> assert '1'.isnumeric()
>>> assert getattr('1', 'isnumeric')()
>>> assert Path.from_str('isnumeric').get('1')()
You can get the same functionality as attrgetter with one
argument by splitting by period.
>>> import datetime
>>> import operator
>>> assert (
... operator.attrgetter('date.today')(datetime)()
... == Path.from_str('date.today').get(datetime)()
... )
You can index an item using square brackets.
Like we're used to in Python.
>>> data = ['foo', 'bar', 'baz']
>>> assert data[1] == 'bar'
>>> assert Path.from_str('[1]').get(data) == 'bar'
You can index a dictionary by indexing by a string literal.
>>> data = {'foo': 'bar'}
>>> assert data['foo'] == 'bar'
>>> assert Path.from_str('["foo"]').get(data) == 'bar'
You can escape characters by using a period.
>>> data = {'foo.bar': 'baz'}
>>> assert data['foo.bar'] == 'baz'
>>> assert Path.from_str('["foo\\.bar"]').get(data) == 'baz'
You can set and delete by using those methods instead.
And you can mix all the above together to walk complex paths.
>>> data = {'foo': 'bar', 'bar': 'baz'}
>>> assert Path.from_str('[["foo"]]').get(data) == 'baz'
>>> class Test:
... foo = ['bar', 'baz']
>>> assert Path.from_str('foo[1]').get(Test) == 'baz'
"""
return cls(list(_parse(iter(value))))
def get(self, obj: Any) -> Any:
"""Walk the path and get the resulting value."""
root_obj = obj
for node in self._nodes:
obj = node.get(root_obj, obj)
return obj
def set(self, obj: Any, value: Any) -> Any:
"""Set the leaf node to the entered value."""
root_obj = obj
for node in self._nodes[:-1]:
obj = node.get(root_obj, obj)
self._nodes[-1].set(root_obj, obj, value)
def delete(self, obj: Any) -> Any:
"""Delete the leaf node."""
root_obj = obj
for node in self._nodes[:-1]:
obj = node.get(root_obj, obj)
self._nodes[-1].delete(root_obj, obj)
STRING_DELIMITERS = {'"', "'"}
Split = Union[None, str]
def _parse(
chars: Iterator[str],
end: Optional[str] = None,
) -> Iterator[Union[Attr, Item, Literal]]:
"""
Parse a string into an easy to use representation.
- Non-special characters are just appended to segment. It's a
list to prevent the <span class="math-container">\$O(n^2)\$</span> time complexity immutable
strings would have.
This is later parsed by :code:`_convert` to yield its correct
representation. This function only yields from this function.
- Split stores the previous form of split.
This can be "" - no split, a . or [ for a period or bracket split,
or None for a character that split the segment but can't split.
An example of None would be a string literal in the middle of
a segment 'foo"bar"baz'. This is not a legal construct.
That should be '"foobarbaz"'.
- This function is recursive only when interpreting the [ split.
This means foo[0].bar would have four segments. Both foo and 0
will have a split of "". As they're the start of their own
parse function. bar would have the split . as it follows a period.
The empty list between ]. would have the split None. This is
as "[foo]bar.baz" doesn't make much sense.
"""
segment = []
split: Split = ""
for char in chars:
if char == "\\":
segment.append(next(chars))
elif char in STRING_DELIMITERS:
if segment:
raise ValueError(
"String literal can't start in the middle of an attribute"
)
yield from _convert(split, _extract_string(chars, char))
split = None
elif char == ".":
yield from _convert(split, segment)
segment = []
split = "."
elif char == "[":
if segment:
yield from _convert(split, segment)
segment = []
yield from _convert("[", _parse(chars, "]"))
split = None
elif char == "]":
if char == end:
break
raise ValueError("Found a close bracket without a matching open bracket")
else:
segment.append(char)
else:
if end:
raise ValueError("Found an open bracket without a matching close bracket")
if segment:
yield from _convert(split, segment)
def _convert(
split: Split,
segment: Union[List[str], Iterator[Union[Attr, Item, Literal]]],
) -> Iterator[Union[Attr, Item, Literal]]:
"""
Convert a segment into an attribute, item or literal.
All leaf nodes are Literals, these are normally plain old strings.
However if the first segment (split == "") starts with an integer
then we will convert the segment to an integer. This allows us to
index lists.
If we have an illegal split, None, with content in the segment
then we raise here.
Whilst not a segment we pass the result of recursive _parse calls
through this function. These are converted into an Item index with
the result given to the containing Path.
Everything else is just converted to an attribute with a path
containing a single literal.
You should notice that this means "1" is a valid path and would
just return the integer 1.
>>> assert Path.from_str('1').get(None) == 1
"""
if split is None:
if segment:
raise ValueError("String literals can't end halfway through an attribute")
return
if split == "[":
_segment = cast(Iterator[Union[Attr, Item, Literal]], segment)
yield Item(Path(list(_segment)))
return
value = "".join(cast(List[str], segment))
if split == "":
if not value:
return
elif value[0].isnumeric():
yield Literal(int(value))
return
elif value[0] in STRING_DELIMITERS:
yield Literal(value[1:-1])
return
yield Attr(Path([Literal(value)]))
def _extract_string(chars: Iterator[str], literal: str) -> List[str]:
"""Extract string with matching delimiter."""
segment = []
for char in chars:
if char == "\\":
char = next(chars)
elif char == literal:
break
segment.append(char)
else:
raise ValueError("String literal doesn't have a closing delimiter")
return [literal] + segment + [literal]
</code></pre>
<p>To test the code just run <code>python foo.py</code> and it'll run all the tests.<br>
When working with the code, you may want to move the <code>Path.from_str</code> tests above the class <code>Test</code>.</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == "__main__":
class Test:
foo = {"bar": 1, "baz": 2}
bar = "baz"
assert Path.from_str("foo").get(Test) == {"bar": 1, "baz": 2}
assert Path.from_str(".foo").get(Test) == {"bar": 1, "baz": 2}
assert Path.from_str('foo["bar"]').get(Test) == 1
assert Path.from_str('foo["baz"]').get(Test) == 2
assert Path.from_str("bar").get(Test) == "baz"
assert Path.from_str("bar[0]").get(Test) == "b"
assert Path.from_str("bar[1]").get(Test) == "a"
assert Path.from_str("bar[2]").get(Test) == "z"
path = Path.from_str("foo[bar]")
assert path.get(Test) == 2
path.set(Test, 3)
assert path.get(Test) == 3
data = {"foo": "bar", "bar": "baz"}
assert Path.from_str('[["foo"]]').get(data) == "baz"
assert Path.from_str("1") == Path([Literal(1)])
assert Path.from_str('"a"') == Path([Literal("a")])
assert Path.from_str("a") == Path([Attr(Path([Literal("a")]))])
assert Path.from_str("a\\.b") == Path([Attr(Path([Literal("a.b")]))])
assert Path.from_str("a.b") == Path(
[Attr(Path([Literal("a")])), Attr(Path([Literal("b")]))]
)
assert Path.from_str(".a") == Path([Attr(Path([Literal("a")]))])
assert Path.from_str('["a"]') == Path([Item(Path([Literal("a")]))])
assert Path.from_str("[a]") == Path([Item(Path([Attr(Path([Literal("a")]))]))])
assert Path.from_str("a[b]") == Path(
[Attr(Path([Literal("a")])), Item(Path([Attr(Path([Literal("b")]))])),]
)
for work in ["a[b]", '"a"[b]', "[a].b", "[a][b]"]:
try:
Path.from_str(work)
except:
print(work)
raise
for fail in ["[a]b", 'a"b"', '"b"c', '[a]"b"', '"a', 'a"', "[a", "a]"]:
try:
ret = Path.from_str(fail)
except:
pass
else:
print(fail, ret)
assert False
import doctest
doctest.testmod()
</code></pre>
|
[] |
[
{
"body": "<p>This is just a quick answer. I don't know exactly what other constraints you have, but it feels very clumsy to have to do something like this:</p>\n\n<pre><code>path = Path.from_str(\"foo[bar]\")\nassert path.get(Test) == 2\npath.set(Test, 3)\nassert path.get(Test) == 3\n</code></pre>\n\n<p>I would instead consider for <code>Path</code> to take the object the path will be taken off and be a wrapper for <code>__getitem__</code> and <code>__setitem__</code> (and probably <code>__delitem__</code> as well, for completeness sake), so that this snippet could become:</p>\n\n<pre><code>test = PathWrapper(Test)\nassert test[\"foo[bar]\"] == 2\ntest[\"foo[bar]\"] = 3\nassert test[\"foo[bar]\"] == 3\n</code></pre>\n\n<p>This has the advantage that it would also work as a class decorator, so you can add this functionality to classes already upon definition if wanted. Implementation left as an exercise ;)</p>\n\n<p>The tests for the internal representation of some common paths would then probably use some <code>PathWrapper._internal_model</code> property or something.</p>\n\n<p>In addition, as soon as your tests become more than three cases or so, I would recommend going for a more programmatic way. For most of your cases an array of input and expected output would be fine to iterate over, but not for the cases where you modify the path. It might be worth it to at least use the <code>unittest</code> module, which does not add too much overhead (code wise). For the <code>doctest</code> module you probably have too many test cases already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T12:16:26.267",
"Id": "470218",
"Score": "1",
"body": "I was thinking of adding a top level function for get, set and del. Do you think that's better or worse than you've proposed? I'm confused what `Path._internal_model` is, is that meant to be `PathWrapper._internal_model`? I agree with the last paragraph, but given that [pytest has doctest support](https://docs.pytest.org/en/latest/doctest.html) I'd just use that, my setup's just a bit messed up atm"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T11:44:58.377",
"Id": "239692",
"ParentId": "239691",
"Score": "7"
}
},
{
"body": "<p>First of all, nice code. I like the documentation and the type hints. One thing you could do is to follow a style convention for your docstrings; see some examples <a href=\"https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format\">here</a>.</p>\n\n<p>For me, I think the most glaring thing is that you have all of your tests in a main function. I would separate these tests by type and move them over to individual files, and I would personally use (and recommend) pytest; you could pass in an instance of your class as a fixture. If you end up with a few files of tests, I'd keep these in a separate folder and would create a <code>Makefile</code> for running them.</p>\n\n<p>One thing I noticed is that you specify return type <code>Any</code> for some methods that don't really return anything, such as <code>Attr.set</code>.</p>\n\n<p>You also have some repeated code that you could refactor out; see the methods of <code>Path</code>:</p>\n\n<pre><code>def set(self, obj: Any, value: Any) -> Any:\n \"\"\"Set the leaf node to the entered value.\"\"\"\n root_obj = obj\n for node in self._nodes[:-1]:\n obj = node.get(root_obj, obj)\n self._nodes[-1].set(root_obj, obj, value)\n\ndef delete(self, obj: Any) -> Any:\n \"\"\"Delete the leaf node.\"\"\"\n root_obj = obj\n for node in self._nodes[:-1]:\n obj = node.get(root_obj, obj)\n self._nodes[-1].delete(root_obj, obj)\n</code></pre>\n\n<p>which could be something like:</p>\n\n<pre><code>def set(self, root_obj: Any, value: Any) -> None:\n \"\"\"Set the leaf node to the entered value.\"\"\"\n self._nodes[-1].set(\n root_obj,\n find_node(root_obj),\n value\n )\n\ndef delete(self, root_obj: Any, value: Any) -> None:\n \"\"\"Delete the leaf node.\"\"\"\n self._nodes[-1].delete(\n root_obj,\n find_node(root_obj)\n )\n\ndef find_node(self, root_obj: Any) -> Any:\n \"\"\"Traverses tree and finds leaf node\"\"\"\n obj = root_obj\n for node in self._nodes[:-1]:\n obj = node.get(root_obj, obj)\n return obj\n</code></pre>\n\n<p>Finally, there are some places where I think you would benefit from more whitespace---one example is just before the following in the function <code>_parse</code>.</p>\n\n<pre><code> if segment:\n yield from _convert(split, segment)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T12:43:00.477",
"Id": "470219",
"Score": "0",
"body": "Please can you elaborate on your first point. Am I not following conventions? Pretty sure I am, so any additional information here - pointing to where I'm not - would be helpful. I'm not a fan of make, I use tox and nox. As for whitespace black's output can be good, but some of it is aweful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T17:16:02.777",
"Id": "470233",
"Score": "0",
"body": "I mean to use the docstring to clarify arguments and return type, and to mention possible exceptions and errors raised.\nAbout make vs tox/nox, your preference; I just like having a separate way of running the tests.\nI agree about black. I just got a bit caught reading some of the lines because I first thought they were logically closer to the functionality above, but whitespace is a preference so that was a very minor comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T17:25:02.207",
"Id": "470234",
"Score": "0",
"body": "Could I clarify do you mean \"to clarify {argument and return} type\", \"to clarify argument and {return} type\" or \"to clarify {argument and return} value(s)\". Because clarifying the type seems a bit redundant. Yeah using make/tox/nox as a command to run tests is nice :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T17:31:38.790",
"Id": "470236",
"Score": "0",
"body": "The third in this case since we're dealing with `Any`—perhaps I should be more careful with my terminology...\nCan I ask: how do you like dealing with tox/nox? Are you working in Python exclusively?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T17:39:05.247",
"Id": "470237",
"Score": "2",
"body": "Ok that makes more sense. :) Yes I work exclusively with Python. I used tox for a little bit, but hit a wall where I needed to have more control than an ini. So I mostly use nox now. Here is the skeleton [nox.py](https://github.com/Peilonrayz/skeleton_py/blob/master/noxfile.py) file I use. To note the `[:-1]` is not superfluous and actually breaks the code so very severely. It changes the path from `foo.bar` to `foo.bar.bar`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T12:34:22.823",
"Id": "239694",
"ParentId": "239691",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "239692",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T11:26:24.493",
"Id": "239691",
"Score": "9",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "Navigate objects from a path provided as a string"
}
|
239691
|
<p>i am trying to create a semicircle menu with animations and texts.
Currently i try to position the texts in the semicircle which is only working with a specific window-width and browser.</p>
<p>This is my current approach: <a href="https://codepen.io/Jxner/pen/xxGBKYJ" rel="nofollow noreferrer">https://codepen.io/Jxner/pen/xxGBKYJ</a></p>
<pre class="lang-css prettyprint-override"><code>.menu {
padding: 0;
list-style: none;
position: relative;
margin: 150px auto;
width: 70%;
height: 0;
padding-top: 70%;
}
@media all and (max-width: 320px) {
.menu {
width: 230px;
height: 230px;
padding: 0;
}
}
@media all and (min-width: 700px) {
.menu {
width: 1080px;
height: 1080px;
padding: 0;
}
}
.menu li {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
clip-path: url(#sector);
</code></pre>
<pre class="lang-html prettyprint-override"><code><meta name="viewport" content="width=device-width, initial-scale=1.0">
<div id="wrapper">
<div id="left">
<ul class="menu" id="navigation_menu">
<li class="one edge">
<span class="icon_one">One</span>
<li/>
<li class="one" id="cat1">
<a href="#" onclick="clicked_cat1()">
</a>
</li>
<li class="two edge">
<span class="icon_two">Two</span>
</li>
<li class="two" id="cat1">
<a href="#" onclick="clicked_cat1()">
</a>
</li>
<li class="three edge">
<span class="icon_three">Three</span>
</li>
<li class="three" id="cat1">
<a href="#" onclick="clicked_cat1()">
</a>
</li>
</ul>
</div>
<svg height="0" width="0">
<defs>
<clipPath clipPathUnits="objectBoundingBox" id="sector">
<path fill="none" stroke="#111" stroke-width="1" class="sector" d="M0.5,0.5 l0.5,0 A0.5,0.5 0 0,0 0.75,.066987298 z"></path>
</clipPath>
</defs>
</svg>
</code></pre>
<p>I am fairly new to css, so this seems like a really laborious way just to create a semicircle with 3 segments and an edge for each one.</p>
<p>How can i improve my code to better scale and run it in different browsers and how can i fix my text to the "pie-segments" so it doesn't disappear with different window sizes?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T12:00:17.043",
"Id": "239693",
"Score": "2",
"Tags": [
"html",
"css"
],
"Title": "Semicircle Navigationmenu with html, css and js"
}
|
239693
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.