body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I know I could've used a <code><meter></code> element, but I wanted to try implementing from scratch. The positions are a bit hacky, and I tried to make it responsive but ended up using <code>px</code> anyway. I would like some advice on when and how to use sizing units, if possible. Thanks!</p>
<p>P.S. Please don't mind the goofy variable names. I tend to use good names but this one was sort of hacked together :D</p>
<p>HTML:</p>
<pre><code><head>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Titillium+Web:wght@200&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<div class="wrapper">
<div class="meter-container">
<span>Sci-fi juice meter</span>
<div class="energy-meter">
<div class="energy stable-juice-anim"></div>
</div>
</div>
<div class="animated-button">
<span>Click</span>
</div>
</div>
</code></pre>
<p>CSS:</p>
<pre><code>body {
display: flex;
height: 100vh;
width: 100vw;
margin: 0;
}
video {
min-height: 300px;
min-width: 300px;
max-height: 600px;
max-height: width: 600px;
}
.dark {
background-color: rgb(10, 10, 10) !important;
}
.wrapper {
display: flex;
height: 100%;
width: 100%;
align-items: center;
justify-content: center;
background-color: rgba(60, 60, 60, 0.2);
overflow: hidden;
}
.meter-container {
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
position: fixed;
top: 5vh;
left: 70vw;
height: 200px;
width: 150px;
}
.meter-container span {
flex: 0.1;
font-size: 0.7em;
}
.energy-meter {
display: flex;
align-items: flex-end;
flex: 1;
border: 2px solid;
border-radius: 5.4%;
height: 80%;
width: 20%;
overflow: hidden;
}
.energy {
position: relative;
background-color: rgb(50, 255, 50);
margin-bottom: -50px;
height: 50%;
width: 100%;
}
.animated-button {
display: flex;
align-items: center;
justify-content: center;
height: 100px;
width: 100px;
background-color: white;
box-shadow: 0px 0px 5px 10px rgba(60, 60, 60, 0.2);
border-radius: 50%;
}
.animated-button span {
font-family: "Titillium Web";
font-size: 2em;
cursor: default;
}
.button-anim {
animation: shrink, shake, implode, explode;
animation-duration: 1s, 0.2s, 1s, 2s;
animation-delay: 0s, 0s, 1s, 2s;
animation-iteration-count: 1, 5, 1, 1;
animation-fill-mode: forwards;
}
.fade-anim {
animation: disappear 1s;
animation-fill-mode: forwards;
}
.stable-juice-anim {
animation: energy-stable 7s infinite;
}
.overflowing-juice-anim {
animation: energy-overflow 3s;
}
@keyframes energy-stable {
0% {
transform: scaleY(1);
}
25% {
transform: scaleY(1.1);
}
50% {
transform: scaleY(1);
}
75% {
transform: scaleY(0.9);
}
100% {
transform: scaleY(1);
}
}
@keyframes energy-overflow {
from {
transform: scaleY(1);
}
to {
transform: scaleY(4.6);
background-color: rgb(255, 0, 0);
}
}
@keyframes disappear {
from {
opacity: 1;
}
to {
opacity: 0;
display: none;
}
}
@keyframes shrink {
from {
transform: scale(1);
}
to {
transform: scale(0.5);
background-color: rgb(10, 10, 10);
box-shadow: none;
}
}
@keyframes shake {
0% {
transform: translate(-2.5%, -2.5%), scale(0.5);
}
20% {
transform: translate(5%, 5%) scale(0.5);
}
40% {
transform: translate(-2.5%, -2.5%) scale(0.5);
}
50% {
transform: translate(2.5%, -2.5%) scale(0.5);
}
60% {
transform: translate(-5%, 5%), scale(0.5);
}
80% {
transform: translate(2.5%, -2.5%) scale(0.5);
}
100% {
transform: translate(-2.5%, -2.5%) scale(0.5);
}
}
@keyframes implode {
from {
transform: scale(0.5);
}
to {
transform: scale(0);
}
}
@keyframes explode {
from {
transform: scale(0);
}
to {
transform: scale(200);
background-color: rgb(10, 10, 10);
}
}
</code></pre>
<p>JS:</p>
<pre><code>"use strict";
let buttonElement = document.getElementsByClassName("animated-button")[0];
let wrapperElement = document.getElementsByClassName("wrapper")[0];
let energyElement = document.getElementsByClassName("energy")[0];
let energyMeterContainerElement = document.getElementsByClassName("meter-container")[0];
buttonElement.onclick = (e) => {
let buttonTextElement = buttonElement.firstElementChild;
buttonTextElement.classList.add("fade-anim");
setTimeout(() => {
buttonElement.classList.add("button-anim");
energyElement.classList.remove("stable-juice-anim");
energyElement.classList.add("overflowing-juice-anim");
setTimeout(() => {
wrapperElement.classList.add("dark");
let lolElement = document.createElement("video");
lolElement.src = "https://ak.picdn.net/shutterstock/videos/1054729307/preview/stock-footage-aerial-view-of-the-sunsets-over-sea-beautiful-sea-waves-pink-sand-and-amazing-sea-summer-sunset.mp4";
lolElement.setAttribute("autoplay", "");
lolElement.setAttribute("muted", "");
wrapperElement.appendChild(lolElement);
wrapperElement.removeChild(energyMeterContainerElement);
}, 3000);
setTimeout(() => wrapperElement.removeChild(buttonElement), 4000);
}, 1000);
buttonElement.onclick = undefined;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T11:10:52.280",
"Id": "256965",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"html",
"css",
"animation"
],
"Title": "CSS animated button and custom meter made of divs"
}
|
256965
|
<p>Any idea how to shorten and improve the program?
it's going to take a list included of 22 people and split them into two teams and return the names and teams</p>
<pre><code>import random
# list of teams
teams = ['A', 'B']
# list of players which is inculded of 22 people
players = ['a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v']
# takes the list of names
class Human:
def __init__(self, name):
self.name = name
# distribure names and people to teams randomly and it inherits names from Human class
class Player(Human):
def get_team(self):
teams = dict()
random.shuffle(self.name)
teams['A'] = self.name[0::2]
teams['B'] = self.name[1::2]
return teams
my_team = Player(players)
my_team = my_team.get_team()
for team, name in my_team.items():
print(team, name)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:37:51.840",
"Id": "507469",
"Score": "0",
"body": "`Human` doesn't seem to be the best name and the class also seems unneccessary - why does `Player` inherit from it instead of just taking the list itself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:42:29.377",
"Id": "507471",
"Score": "0",
"body": "Yes, you're right `Human` is not appropriate to name this class, I'm new to OOP so I want to force myself to use classes even if sounds silly :)"
}
] |
[
{
"body": "<p>Honestly, your code is pretty compact already. There are really only 2 areas that I think can be shortened.</p>\n<ol>\n<li>The <code>get_team</code> method of <code>Player</code>.</li>\n</ol>\n<pre><code> def get_team(self):\n random.shuffle(self.name)\n return {'A':self.name[0::2], 'B':self.name[1::2]}\n</code></pre>\n<p>If you want to improve readability, you can set the dictionary to <code>team</code> and then return <code>team</code>.</p>\n<ol start=\"2\">\n<li>The last couple of lines.</li>\n</ol>\n<pre><code>my_team = Player(players).get_team()\nfor team, name in my_team.items():\n print(team, name)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:49:20.607",
"Id": "256988",
"ParentId": "256966",
"Score": "2"
}
},
{
"body": "<p>The concept is good, but there is room for improvement. Here are some problems I see:</p>\n<h3>Misleading names</h3>\n<p>Clear names are very important in coding, because they make it easy or hard for other people (including your future self) to understand what you have written. Some of the names you have used do not match what the code actually does, which is confusing.</p>\n<ul>\n<li>Based on the name of the <code>Human</code> class, I'd expect an instance of this class to represent <em>one human</em>, but that is not how it is used (see below).</li>\n<li>Based on the name of the <code>Player</code> class, and the way it extends <code>Human</code>, I'd expect an instance of this class to represent <em>one player</em>; if so, then there should be 22 instances of the class, or one object for each name in the <code>players</code> list. Instead, it seems to represent <em>all the players at once</em>, which its name does not imply.</li>\n<li>I would expect the <code>name</code> attribute of <code>Human</code> to store a single name, but <code>Player</code> stuffs an entire <em>list</em> of player names into that attribute.</li>\n</ul>\n<p>At minimum, these names should be made plural (<code>Humans</code>, <code>names</code>, <code>Players</code>, etc.) to reflect their contents. It would be even better to give <code>Player</code> a name that describes what it actually does, or what it is responsible for within the program.</p>\n<h3>Unnecessary hierarchy, part 1: only one subclass</h3>\n<p>You mentioned in a comment that you are trying to practice your OOP skills, so "[you] want to force [yourself] to use classes even if it sounds silly". Practice is good, but part of good OOP is understanding why and how to use classes and objects effectively...and that includes knowing when <em>not</em> to use them, or when not to use certain parts of them.</p>\n<p>For example: why do you need both a <code>Human</code> class and a <code>Player</code> subclass? In the program that you have now, the only humans are players; therefore there is no advantage to having two classes. You could do everything in the <code>Player</code> class and drop the <code>Human</code> class altogether, or vice versa. On the other hand, if you already have plans to expand your program to include <em>non</em>-player humans (e.g. coaches, referees), then a <code>Human</code> superclass might make sense. The structure of the code should fit your use case.</p>\n<h3>Unnecessary hierarchy, part 2: superclass does nothing</h3>\n<p>A subclass is supposed to have a "type of" or "kind of" relationship to its superclass, e.g. a <code>Square</code> is a kind of <code>Rectangle</code>, or a <code>Dog</code> is a kind of <code>Animal</code>. The problem is that your code does not gain much from defining <code>Player</code> as a kind of <code>Human</code>. Since <code>Human</code> has no defined behaviors and barely any data, inheriting from it doesn't provide many benefits. It would be simpler and more flexible to use composition instead of inheritance, by creating or importing a <code>Human</code> object <em>inside</em> the <code>Player</code> object.</p>\n<h3>Unnecessary use of internal state / object attributes</h3>\n<p>One of the nice things about objects is that they can create and maintain an internal state--a little chunk of data that it hides away from the rest of the program. (Keeping separate things separate is called <em>encapsulation</em> or <em>separation of concerns</em>, and it makes programs much easier to think about and easier to debug.) In Python, internal state is stored in object attributes, like <code>Human</code>'s <code>self.name</code>. But you have to know when to use internal state and when not to use it. Keeping multiple copies of the same data in different places, or multiple references to the same data object, can cause confusion and lead to bugs.</p>\n<p>Your <code>get_team()</code> method takes a list of players, splits the players between two known teams, and then returns a <code>dict()</code> with that information. This method is called only once in your entire program. So, what is the advantage of having the <code>Player</code> object store the list of player names inside itself? In the current code, there is no advantage. You could easily change <code>get_team()</code> to a class method (which can be called without instantiating an object) that takes the player names as a parameter.</p>\n<h3>Hardcoded assumptions</h3>\n<pre><code># list of teams\nteams = ['A', 'B']\n</code></pre>\n<p>Since you defined this <code>teams</code> list at the top of the code, I would assume that editing that list would change the program output. But when I look closer, I can see that this list is not even used. Your <code>get_team()</code> method is explicitly written to split the players into two teams named 'A' and 'B', regardless of what is in the list above.</p>\n<pre><code> teams['A'] = self.name[0::2]\n teams['B'] = self.name[1::2]\n return teams\n</code></pre>\n<p>This is not very flexible, especially if you want to import the team names from outside the program (e.g. from user input, or from a config file). A better method would take a list of teams as an input, count the number of teams, and then split the players accordingly.</p>\n<hr />\n<p>Here's how I might write it:</p>\n<pre><code>TEAMS = ('A', 'B') # Replaced mutable list with immutable tuple.\n # Names of constants should be in all-caps.\nPLAYERS = ('a', 'b', 'c', 'd', 'e',\n 'f', 'g', 'h', 'i', 'j',\n 'k', 'l', 'm', 'n', 'o',\n 'p', 'q', 'r', 's', 't',\n 'u', 'v')\n\nclass TeamAssigner:\n def assign_players_to_teams(teams, players):\n players_on_teams = dict()\n randomized_players = random.sample(players, len(players)) # changed to .sample because .shuffle doesn't work on tuples / immutable sequences\n for i, team in enumerate(teams):\n players_on_teams[team] = randomized_players[i::len(teams)]\n return players_on_teams\n\nmy_teams = TeamAssigner.assign_players_to_teams(TEAMS, PLAYERS)\nfor team, name in my_teams.items():\n print(team, name)\n</code></pre>\n<p>Of course, this is only what I would write if I was not planning to expand the program in the future. If you have plans to make the program bigger and make it do more things, then some of these decisions might be the wrong ones. For instance, if you wanted the ability to move players from one team to another <em>after</em> the initial split, then you would need a class that <em>did</em> keep an internal state of who is on which team...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T20:56:49.213",
"Id": "256994",
"ParentId": "256966",
"Score": "3"
}
},
{
"body": "<p>This problem doesn't really need a class to solve it. Jack Diederich's <a href=\"https://pyvideo.org/pycon-us-2012/stop-writing-classes.html\" rel=\"nofollow noreferrer\">Stop Writing Classes</a> is very relevant here, and like the examples shown in the talk, <code>Human</code> and <code>Player</code> probably shouldn't be classes in the first place.</p>\n<p>All we need is a function that takes in a list of players, and returns the teams:</p>\n<pre class=\"lang-python prettyprint-override\"><code>import random\n\ndef get_teams(players):\n randomly_ordered_players = random.sample(players, len(players))\n return {\n "A": randomly_ordered_players[0::2],\n "B": randomly_ordered_players[1::2],\n }\n</code></pre>\n<p>Note that we're using <code>random.sample</code> here which returns a new randomly-ordered list instead of shuffling the list in place. This is cleaner because we don't mutate the input list.</p>\n<hr />\n<p>We can make the function more flexible by also taking in a list of team names, so we can divide players up into any number of teams. This is @MJ713's solution using a <a href=\"https://www.python.org/dev/peps/pep-0274/\" rel=\"nofollow noreferrer\">dict comprehension</a>:</p>\n<pre class=\"lang-python prettyprint-override\"><code>import random\n\ndef get_teams(teams, players):\n randomly_ordered_players = random.sample(players, len(players))\n number_of_teams = len(teams)\n return {\n teams[i]: randomly_ordered_players[i::number_of_teams]\n for i in range(number_of_teams)\n }\n</code></pre>\n<p>Example:</p>\n<pre class=\"lang-python prettyprint-override\"><code>for team_name, players in get_teams(\n ["A", "B"], ["a", "b", "c", "d", "e", "f", "g", "h"]\n).items():\n print(team_name, players)\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>A ['e', 'f', 'a', 'g']\nB ['h', 'b', 'd', 'c']\n</code></pre>\n<pre class=\"lang-python prettyprint-override\"><code>for team_name, players in get_teams(\n ["A", "B", "C", "D"], ["a", "b", "c", "d", "e", "f", "g", "h"]\n).items():\n print(team_name, players)\n</code></pre>\n<pre class=\"lang-none prettyprint-override\"><code>A ['d', 'b']\nB ['e', 'g']\nC ['h', 'c']\nD ['f', 'a']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T05:16:17.223",
"Id": "257007",
"ParentId": "256966",
"Score": "2"
}
},
{
"body": "<p>This could be a good application for <code>grouper()</code> from <a href=\"https://docs.python.org/3.8/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\">Itertools Recipies</a>:</p>\n<pre><code>from itertools import zip_longest\nfrom random import shuffle\n\nplayers = ['a', 'b', 'c', 'd', 'e',\n 'f', 'g', 'h', 'i', 'j',\n 'k', 'l', 'm', 'n', 'o',\n 'p', 'q', 'r', 's', 't',\n 'u', 'v']\n\n\ndef grouper(iterable, n, fillvalue=None):\n "Collect data into fixed-length chunks or blocks"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n\nshuffle(players)\n\nteam_a, team_b = grouper(players, 11, '')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T09:59:56.960",
"Id": "507573",
"Score": "2",
"body": "it gives me `too many values to unpack`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:27:18.207",
"Id": "507625",
"Score": "1",
"body": "@Xus, the second arg to `grouper` should be the number of players per team. I had the number of teams. Fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:23:02.733",
"Id": "508116",
"Score": "0",
"body": "This solution hardcodes 3 assumptions: number of players, number of teams, size of each team. Modifying any of these without modifying the other two may cause problems. If players are added, or teams are removed, or the team size is shrunk, then some players will be \"lost\"; they will not be on any team in the program output. Opposite changes (more players XOR more teams XOR larger teams) will yield \"hollow teams\" that have too-few or zero players. My own answer assumed team size is not fixed and split players pseudo-evenly, but most games DO have fixed team sizes..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T06:03:10.110",
"Id": "257009",
"ParentId": "256966",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256994",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T11:16:38.067",
"Id": "256966",
"Score": "4",
"Tags": [
"python",
"classes"
],
"Title": "random team distributer"
}
|
256966
|
<p>I have made a random password generator using a class called <code>password</code> and a method called <code>generate</code>.</p>
<p>My program works as it should. It generates a random password determined by the users preferences for length, upper or lowercase, numbers and special characters.</p>
<p>I was just wondering if there was a way to refactor the numerous <code>if statements</code> I have used to determine what sort of password the program would generate.</p>
<p>Any other suggestions for improvements I could make would also be helpful. Thanks a ton :D</p>
<p>Code:</p>
<pre><code>import random
import string
class password:
def __init__(self, length, string_method, numbers=True, special_chars=False):
self.length = length
self.string_method = string_method
self.numbers = numbers
self.special_chars = special_chars
def generate(self, iterations):
# Checking what type of string method the user has asked for
if self.string_method == 'upper':
stringMethod = string.ascii_uppercase
elif self.string_method == 'lower':
stringMethod = string.ascii_lowercase
elif self.string_method == 'both':
stringMethod = string.ascii_letters
# Checking if the user has asked for numbers or not
if self.numbers == True:
stringNumbers = string.digits
elif self.numbers == False:
stringNumbers = ''
# Checking if the user has asked for special characters or not
if self.special_chars == True:
stringSpecial = string.punctuation
elif self.special_chars == False:
stringSpecial = ''
characters = stringMethod + stringNumbers + stringSpecial
# Generating the password
for p in range(iterations):
output_password = ''
for c in range(self.length):
output_password += random.choice(characters)
print(output_password)
# Test
password1 = password(20, 'lower', True, False) # password length = 20, string method is lowercase, numbers are true and special characters are false
password1.generate(3) # generate the random password 3 times<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T12:01:49.287",
"Id": "507454",
"Score": "0",
"body": "You can store various thinks in a dict, then access them on a the key. I've not pythoned for a long time, so I'm not confident enough to write a whole answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T12:04:26.243",
"Id": "507455",
"Score": "0",
"body": "thanks for the comment. i will look in this :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T12:13:47.230",
"Id": "507457",
"Score": "1",
"body": "Why not use `if`-`else` instead of `if`-`elif`? What happens with unexpected input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T08:41:34.907",
"Id": "507560",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>You can use the ternary operation to reduce the vertical space, i.e. <code>x = a if condition else b</code>. This sets <code>x</code> to <code>a</code> if <code>condition</code> is true and to <code>b</code> otherwise.</p>\n<p>You can also use a dictionary to map a string to some object, like</p>\n<pre><code>the_map = {'a': 4, 'b': 7, 'c': 43}`\nx = the_map['c']\n</code></pre>\n<p>This will set <code>x</code> to <code>43</code>.</p>\n<p>Then you can evaluate everything in the initializer instead. So it's not less if checks per se, but it's a bit cleaner, and you can call <code>generate</code> multiple times without needing to do the checks.</p>\n<pre><code>import random\nimport string\n\nclass Password:\n def __init__(self, length, string_method, numbers=True, special_chars=False):\n self.length = length\n self.string_method = {\n 'upper': string.ascii_uppercase,\n 'lower': string.ascii_lowercase,\n 'both': string.ascii_letters\n }[string_method]\n self.numbers = string.digits if numbers else ''\n self.special_chars = string.punctuation if special_chars else ''\n\n def generate(self, iterations):\n characters = self.string_method + self.numbers + self.special_chars\n\n # Generating the password\n for p in range(iterations):\n output_password = ''\n for c in range(self.length):\n output_password += random.choice(characters)\n print(output_password)\n\n# Test\n\npassword = Password(20, 'lower', True, False)\npassword.generate(3) # generate the random password 3 times\n</code></pre>\n<p>If you actually want less checks, then just pass in the characters directly. Passing in the length and which characters you want to use into password generator seems perfectly legitimate and straight-forward. This also allows you to do more complex things like generating a password with just vowels, without even numbers, or maybe if you want to exclude certain punctuation.</p>\n<pre><code>import random\nimport string\n\nclass Password:\n def __init__(self, length, characters):\n self.length = length\n self.characters = characters\n\n def generate(self, iterations):\n # Generating the password \n for p in range(iterations):\n output_password = ''\n for c in range(self.length):\n output_password += random.choice(self.characters)\n print(output_password)\n\n# Test\n\npassword = Password(20, string.ascii_lowercase + string.digits)\npassword.generate(3) # generate the random password 3 times\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T12:12:07.393",
"Id": "256969",
"ParentId": "256967",
"Score": "2"
}
},
{
"body": "<p>Since you eventually combine the different char sets anyway, you might as well do that right away, with one <code>if</code> per char set. And <code>random.choices</code> saves a loop.</p>\n<pre><code>class password:\n def __init__(self, length, string_method, numbers=True, special_chars=False):\n self.length = length\n self.chars = ''\n if string_method != 'lower':\n self.chars += string.ascii_uppercase\n if string_method != 'upper':\n self.chars += string.ascii_lowercase\n if numbers:\n self.chars += string.digits\n if special_chars:\n self.chars += string.punctuation\n\n def generate(self, iterations):\n for _ in range(iterations):\n print(''.join(random.choices(self.chars, k=self.length)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:26:56.373",
"Id": "256982",
"ParentId": "256967",
"Score": "1"
}
},
{
"body": "<h1>Nomenclature</h1>\n<p>Your class is called <code>password</code>. A password is usually a string representing a secret. Your class, however, does not represent such a thing. It merely stores information about how a password should be generated. Hence a better name would be <code>PasswordGenerator</code>.</p>\n<h1><a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">Stop writing classes</a></h1>\n<p>Your class has two methods, one of which is <code>__init__</code>. This is usually a sign, that you should not be writing a class in the first place. Try an imperative approach instead.</p>\n<h1>Separate your concerns</h1>\n<p>Most of your business logic is done in <code>generate()</code>. It, however does multiple things, that we can split up into different functions.</p>\n<pre><code>import random\nimport string\nfrom typing import Iterator\n\n\ndef get_pool(*, upper: bool = True, lower: bool = True,\n numbers: bool = False, special: bool = False) -> str:\n """Returns a character pool for password generation."""\n \n pool = []\n \n if upper:\n pool.append(string.ascii_uppercase)\n \n if lower:\n pool.append(string.ascii_lowercase)\n \n if numbers:\n pool.append(string.digits)\n \n if special:\n pool.append(string.punctuation)\n \n if pool:\n return ''.join(pool)\n\n raise ValueError('Pool is empty.')\n \n\ndef generate(length: int, pool: str) -> str:\n """Generates a password with the given length from the given pool."""\n\n return ''.join(random.choices(pool, k=length))\n \n\ndef generate_multiple(amount: int, length: int, pool: str) -> Iterator[str]:\n """Generates a password with the given length from the given pool."""\n\n for _ in range(amount):\n yield generate(length, pool)\n \n \ndef main():\n """Showcase the above code."""\n \n pool = get_pool(upper=False, lower=True, numbers=True, special=False)\n\n for password in generate_multiple(3, 20, pool):\n print(password)\n \n \nif __name__ == '__main__':\n main()\n</code></pre>\n<h1>Document your code</h1>\n<p>Your use case is a good example why code documentation is important. The user could be lead to believe, that e.g. <code>numbers=True</code> guarantees that the password will contain numbers, which it does not. It merely extends the password generation pool with numbers, so that the likelihood of generating a password with a number in it is > 0. However, by chance, an arbitrarily generated password might still contain no number. Those kind of behavioral quirks should be documented.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:31:49.287",
"Id": "507927",
"Score": "0",
"body": "my program has changed somewhat since I asked this question but do you think the same rules apply? GitHub: https://github.com/lunAr-creator/pw-gen/blob/main/pw_gen/__init__.py"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:48:13.910",
"Id": "507930",
"Score": "0",
"body": "If your program changed (significally), and you want to have it reviewed, you're free to post a new follow-up question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:54:38.367",
"Id": "507931",
"Score": "0",
"body": "ok. ill post a new-follow up question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:59:01.540",
"Id": "507932",
"Score": "0",
"body": "link to new question: https://codereview.stackexchange.com/questions/257185/i-have-made-a-library-for-generating-passwords-i-was-wondering-if-the-code-is-g"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:06:21.813",
"Id": "257184",
"ParentId": "256967",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "256969",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T11:43:11.870",
"Id": "256967",
"Score": "2",
"Tags": [
"python"
],
"Title": "Is there anyway to use less if statements in my function?"
}
|
256967
|
<p>I want to calculate the <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ttest_ind.html" rel="nofollow noreferrer">scipy.stats.ttest_ind()</a> for numeric columns in a pandas DataFrame with the binary target variable.</p>
<pre><code>import pandas as pd
from scipy import stats
</code></pre>
<pre><code>def calculate_tStatistic(df, target, numeric_cols):
"""
Calculate the t-test on TWO RELATED samples of scores, a and b.
This is a two-sided test for the null hypothesis that 2 related or
repeated samples have identical average (expected) values.
Params
=====================================
df : dataframe
target : target column name(str)
numeric_cols : list of numeric columns
Return
=======================================
results_df : A dataframe with features and t-statistic p-val
"""
# create an empty dictionary
t_test_results = {}
# loop over column_list and execute code
for column in numeric_cols:
group1 = df.where(df[target] == 0).dropna()[column]
group2 = df.where(df[target] == 1).dropna()[column]
# add the output to the dictionary
t_test_results[column] = stats.ttest_ind(group1,group2)
results_df = pd.DataFrame.from_dict(t_test_results,orient='Index')
results_df.columns = ['t-statistic','t_stat_pval']
results_df.reset_index(inplace=True)
results_df.rename(columns = {"index":"x"}, inplace=True)
return results_df
</code></pre>
<p><strong>Sample</strong></p>
<pre><code>import seaborn as sns
titanic = sns.load_dataset("titanic")
</code></pre>
<pre><code>calculate_tStatistic(titanic, "survived", ["age", "fare"])
</code></pre>
<p><strong>Results</strong></p>
<pre><code> x t-statistic t_stat_pval
0 age 3.479558 0.000630
1 fare -1.767759 0.078795
</code></pre>
<p><strong>Can someone confirm that I'm actually doing it the right way?</strong></p>
<p><strong>Is there a better / more elegant / more accurate way to do this??</strong></p>
|
[] |
[
{
"body": "<p>There may be a bug in your code. Look at these two lines:</p>\n<pre class=\"lang-py prettyprint-override\"><code> group1 = df.where(df[target] == 0).dropna()[column]\n group2 = df.where(df[target] == 1).dropna()[column]\n</code></pre>\n<p>What is happening here? First, the <code>where</code> method sets all rows in which your condition (<code>df[target] == 0</code>) is not true to <code>NaN</code>. Then, you drop the <code>NaN</code> values by using <code>dropna()</code>. The problem: The <code>dropna()</code> method removes all rows where at least one element is <code>NaN</code>, but this not only applies to the rows not meeting your condition, but also to other rows. For example, check out the <code>deck</code> column in the dataset, it has lots of rows with <code>NaN</code> values and all of them get completely removed (that is the <em>entire</em> row). This is not what you want, I guess.</p>\n<p>My suggestion:</p>\n<pre class=\"lang-py prettyprint-override\"><code> group1 = df.loc[df[target]==0, column].dropna()\n group2 = df.loc[df[target]==1, column].dropna()\n\n</code></pre>\n<p>This code first extracts the column of interest and then removes the <code>NaN</code> values. Not the other way around. In this way, you avoid removing too many lines. In addition, I use <code>loc</code> to select the values, as this is the preferred pandas method, when you need to index rows and columns simultaneously, as opposed to chained indexing like <code>df[idx1][idx2]</code>. Fore more details see here:\n<a href=\"https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\" rel=\"nofollow noreferrer\">https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy</a></p>\n<hr />\n<p>A thing I just learned: As an alternative to using the <code>dropna()</code> method, you can set the nan_policy to 'omit' when calling the <code>stats.ttest_ind</code> function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>stats.ttest_ind(group1, group2, nan_policy='omit')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T22:58:17.230",
"Id": "257115",
"ParentId": "256968",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T11:52:35.720",
"Id": "256968",
"Score": "1",
"Tags": [
"python",
"pandas",
"statistics"
],
"Title": "T-test Independence for a Pandas DataFrame"
}
|
256968
|
<p>I have 3 checkbox's with 8 different combinations and outcomes.</p>
<ul>
<li>Selecting no checkboxes shows no divs.</li>
<li>Selecting one checkbox shows the colored div.<br />
For example; clicking the red checkbox.</li>
<li>Selecting two checkboxes shows the color1+color2 div. But doesn't show either of the single colored divs.<br />
For example; clicking the red and green checkboxes shows the redgreen div. But ensures both the red and green div boxes are hidden so there's only ever one div box showing.</li>
<li>Selecting all the checkboxes shows the rgb div. And doesn't show any other divs.</li>
</ul>
<p>It does work I was wondering if this can be wrote more efficient?</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>$('input[type="checkbox"]').click(function () {
$('.box').hide();
if ($('#red').is(':checked')) $('.red.box').show();
if ($('#green').is(':checked')) $('.green.box').show();
if ($('#blue').is(':checked')) $('.blue.box').show();
if ($('#red').is(':checked') && $('#green').is(':checked')) $('.redgreen.box').show() && $('.red.box, .green.box').hide();
if ($('#red').is(':checked') && $('#blue').is(':checked')) $('.redblue.box').show() && $('.red.box, .blue.box').hide();
if ($('#green').is(':checked') && $('#blue').is(':checked')) $('.greenblue.box').show() && $('.green.box, .blue.box').hide();
if ($('#red').is(':checked') && $('#green').is(':checked') && $('#blue').is(':checked')) $('.rgb.box').show() && $('.red.box, .green.box, .greenblue, .redblue, .redgreen.box, .blue.box').hide();
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {
padding: 20px;
display: none;
margin-top: 20px;
border: 1px solid #000;
}
.redblue .redgreen .greenblue {
border: 1px solid black;
}
.rgb {
border: 1px dashed black;
}
.red {
background: #ff0000;
}
.green {
background: #00ff00;
}
.blue {
background: #0000ff;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label>
<input type="checkbox" id="red" name="colorCheckbox" value="red">red</label>
<label>
<input type="checkbox" id="green" name="colorCheckbox" value="green">green</label>
<label>
<input type="checkbox" id="blue" name="colorCheckbox" value="blue">blue</label>
</div>
<div class="red box"><strong>red</strong></div>
<div class="green box"><strong>green</strong></div>
<div class="blue box"><strong>blue</strong></div>
<div class="redgreen box"><strong>red green</strong></div>
<div class="redblue box"><strong>red blue</strong></div>
<div class="greenblue box"><strong>green blue</strong></div>
<div class="rgb box"><strong>rgb</strong></div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:34:50.273",
"Id": "507468",
"Score": "0",
"body": "This question is lacking any explanation of what the code should _do_. \"3 checkbox's with 8 different combinations and outcomes\" doesn't explain what value this has to the user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:38:42.730",
"Id": "507470",
"Score": "0",
"body": "No value for the user. But I've now explained in the OP what the outcome should be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T13:56:21.523",
"Id": "507474",
"Score": "2",
"body": "@Lowis I think what Toby Speight meant by value was \"what problem does your code solve for a user of your code\" or \"how does your code implement a feature a user of your code may want\". As such I think Toby is asking why you wrote the code, less what is your code doing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T07:26:21.223",
"Id": "507552",
"Score": "1",
"body": "(Time and again I'm baffled just where coders state concern about efficiency. Maintainability first, with testability&readability important aspects!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T10:29:54.457",
"Id": "507673",
"Score": "0",
"body": "@greybeard It might be a non-native translation thing. English does not seem to be Lowis' first language."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T17:37:55.873",
"Id": "507704",
"Score": "0",
"body": "@konijn Move along now."
}
] |
[
{
"body": "<p>A few notes on your code:</p>\n<ul>\n<li>If you don't need supporting of very old or non-standard browsers, and given that your project does not relies heavily on jQuery, vanilla JavaScript can do the same work, without jQuery's overhead.</li>\n<li>On each checkbox click, all coloured divs are queried again and again (<code>jQuery('.box')</code>), which is unnecessary as there are no changes in the DOM.</li>\n<li>All checkboxes are queried multiple times, instead of selecting them once.</li>\n<li>The if-then structure is quite cumbersome: <em>if #red is checked, show .red.box. Then, if #green is also checked, hide .red.box and show .redgreen.box. Then, if #blue is checked too, hide .redgreen.box and show .rbg.box.</em> One way for improving this part would be to first determine exactly which box should be checked and show only that box.</li>\n<li>Personally, I would have used combinations of the <code>.red</code>/<code>.green</code>/<code>.blue</code> classes, instead of putting a different class for each combination (e.g. <code>.box.red.green.blue</code> instead of <code>.box.rgb</code>). That way each checkbox corresponds with a particular div class.</li>\n</ul>\n<p>Here is my take on the problem/homework/exercise, that addresses most of the above remarks (no CSS/HTML changes; still using jQuery):</p>\n<pre><code> const RED = 1;\n const GREEN = 2;\n const BLUE = 4;\n\n const DIV_CLASSES_MAP = [null, '.red', '.green', '.redgreen', '.blue', '.redblue', '.greenblue', '.rgb'];\n const DIVS = $('.box');\n const RED_TICK = $('#red');\n const GREEN_TICK = $('#green');\n const BLUE_TICK = $('#blue');\n\n let activeDiv = DIVS.filter(':visible');\n $('input[name="colorCheckbox"]').on('click', onCheckboxChange);\n\n function onCheckboxChange() {\n const redBit = RED_TICK.is(':checked') ? RED : 0;\n const greenBit = GREEN_TICK.is(':checked') ? GREEN : 0;\n const blueBit = BLUE_TICK.is(':checked') ? BLUE : 0;\n const mask = redBit + greenBit + blueBit;\n const activeClass = DIV_CLASSES_MAP[mask];\n activeDiv.hide();\n activeDiv = DIVS.filter(activeClass).show();\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T06:01:51.003",
"Id": "507547",
"Score": "0",
"body": "Welcome to Code Review! You have contributed an alternate solution, but you have not reviewed the code. \"Every answer must make at least one **insightful observation** about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted.\" Please see [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer) for guidance on how to improve your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:05:01.593",
"Id": "507650",
"Score": "0",
"body": "I don't need support for older or non-standard browsers so I'll look into a javascript alternative. Does your solution use less queries on the checkbox/s? Thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:13:49.727",
"Id": "256980",
"ParentId": "256970",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T12:14:58.113",
"Id": "256970",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Selecting multiple checkboxes to show similar but different boxes"
}
|
256970
|
<p>I have built a housekeeping script and I would like to improve it.
I have a JSON file with the details such as directory path, number of days after which the directory or file should be zipped, deletion period for the zip as well as if it's files or directories that we are zipping.</p>
<p>Config JSON file:</p>
<pre><code>{
"foo": [
{
"path": "/the/directory/to/be/zipped/",
"nr_files_not_zip": "7",
"deletion_period": "7",
"file_or_directory": "files"
}
]
</code></pre>
<p>}</p>
<p>For housekeeping, I have tried to use a factory design pattern as there are potentially different file selection requirements but for the moment I am only selecting the files to be zipped based on their mod date.
The script loads the config and creates the housekeeping object through a factory method. Then based on the zip period, deletion period as well as the zip-type it zips and deletes the appropriate files or directories.</p>
<p>I have been using python for a couple of years and I trying to improve. I would really appreciate any feedback regarding the code improvements and best practices.
The housekeeping script:</p>
<pre><code>#!/usr/bin/python
import abc
import os
import sys
import json
import datetime
import time
import zipfile
import shutil
#abstract housekeeping
class housekeeping(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def pick_files(self):
pass
@abc.abstractmethod
def files_to_be_zipped(self):
pass
@abc.abstractmethod
def sort_deletion(self):
pass
@abc.abstractmethod
def get_type(self):
pass
@abc.abstractmethod
def get_directory(self):
pass
@abc.abstractmethod
def get_deletion_period(self):
pass
#houskeeping foo concrete class
class housekeeping_foo(housekeeping):
def __init__(self,directory, normal_files,zipped_files,nr_to_leave,deletion_period,type_to_zip):
self.normal_files = normal_files
self.zipped_files = zipped_files
self.nr_to_leave = nr_to_leave
self.deletion_period = deletion_period
self.directory = directory
self.type_to_zip = type_to_zip
#grabs the files, directories and zip files and stores them in a specif hashmap
def pick_files(self):
for dir_name, subdirList, fileList in os.walk(self.directory):
for file_name in fileList:
full_path = dir_name + "/" + file_name
if os.path.exists(full_path) and not file_name.startswith('.'):
if not full_path.endswith('.zip') and not full_path.endswith('.gz'):
mod_time = os.path.getmtime(full_path)
last_modified_date = datetime.datetime.fromtimestamp(mod_time)
self.normal_files.update({full_path: last_modified_date})
else:
mod_time = os.path.getmtime(full_path)
last_modified_date = datetime.datetime.fromtimestamp(mod_time)
self.zipped_files.update({full_path: last_modified_date})
return self.normal_files, self.zipped_files
#removes the files which not be zipped. Based on the mod date for this particular object
def files_to_be_zipped(self):
for key, value in self.normal_files.items():
str_date = value.date()
today = datetime.datetime.now().date()
difference = str(today - str_date)
if "days" in difference:
date = difference.split(" ", 1)[0]
else:
date = 0
if int(date) > int(self.nr_to_leave):
print("file to be zipped")
else:
del self.normal_files[key]
return self.normal_files
#removes the files which should not be included in deletion
def sort_deletion(self):
for key, value in self.zipped_files.items():
time_since_insertion = str(datetime.datetime.now() - value)
if "days" in time_since_insertion:
days = int(time_since_insertion.split(' ',1)[0])
else:
days = 0
if days < int(self.deletion_period):
del self.zipped_files[key]
return self.zipped_files
#return zip type
def get_type(self):
return self.type_to_zip
#return directory
def get_directory(self):
return self.directory
#return deletion period
def get_deletion_period(self):
return self.deletion_period
class housekeeping_factory:
def create_housekeeping(self,name, directory, normal_files,zipped_files,nr_to_leave,deletion_period,type_to_zip):
if name == "foo":
return housekeeping_foo(directory,normal_files,zipped_files,nr_to_leave,deletion_period,type_to_zip)
#loading JSON config file
def load_config(directory_name):
with open('housekeeping.config.json') as f:
data = json.load(f)
for config_items in data[directory_name]:
directory_name_wih_full_path = config_items["path"]
nr_to_leave = config_items["nr_files_not_zip"]
deletion_period = config_items["deletion_period"]
type_to_zip = config_items["file_or_directory"]
return directory_name_wih_full_path, nr_to_leave, deletion_period, type_to_zip
#creates the housekeeping object strips the files and directories which should not be included in the zipping or deletion
def housekeeping_client():
normal_files = {}
zipped_files = {}
if len(sys.argv) == 2:
directory_name = sys.argv[1]
directory_name_wih_full_path, nr_to_leave, deletion_period, type_to_zip = load_config(directory_name)
factory = housekeeping_factory()
housekeeping_shape = factory.create_housekeeping(directory_name, directory_name_wih_full_path,normal_files,zipped_files,nr_to_leave,deletion_period,type_to_zip)
housekeeping_shape.pick_files()
files_to_zip = housekeeping_shape.files_to_be_zipped()
to_delete = housekeeping_shape.get_deletion_period()
if to_delete != "NA":
file_to_del = housekeeping_shape.sort_deletion()
else:
file_to_del = {}
zip_type = housekeeping_shape.get_type()
file_directory = housekeeping_shape.get_directory()
run_housekeeping_client(files_to_zip,file_to_del,zip_type, file_directory)
else:
print("Wrong number of arguments...")
#depending on the zip type a zip directory or zip file methods will be called
def run_housekeeping_client(files_to_zip,file_to_del,zip_type, file_directory):
for key, value in files_to_zip.items():
directory_full_path_with_file = key
if zip_type == "files":
zip_the_file(key, key)
os.remove(directory_full_path_with_file)
elif zip_type == "directory":
zip_the_directory(key)
shutil.rmtree(directory_full_path_with_file)
####################################################
if len(file_to_del.keys()) != 0:
for key, value in file_to_del.items():
directory_full_path_with_file = key
os.remove(directory_full_path_with_file)
#zipping directories
def zip_the_directory(dir_name):
file_with_zip = dir_name
file_to_zip = dir_name + ".zip"
zip_File = zipfile.ZipFile(file_to_zip,'w', zipfile.ZIP_DEFLATED)
directory_path = dir_name.split("/")[-1]
lenDirPath = len(directory_path)
for root, dirs, files in os.walk(file_with_zip):
for file in files:
filePath = os.path.join(root, file)
zip_File.write(filePath , filePath[lenDirPath :])
zip_File.close()
#zipping files
def zip_the_file(file_name):
file_with_zip = file_name + ".zip"
file_to_zip = file_name
directory_path = file_name.split("/")[-1]
len_dir_path = len(directory_path)
with zipfile.ZipFile(file_with_zip, 'w', compression=zipfile.ZIP_DEFLATED) as zip_file:
zip_file.write(file_to_zip, file_to_zip[len_dir_path :])
print("file has been zipped")
if __name__== '__main__':
housekeeping_client()
</code></pre>
|
[] |
[
{
"body": "<pre><code>class housekeeping(object):\n \n __metaclass__ = abc.ABCMeta\n</code></pre>\n<p>looks nicer as</p>\n<pre><code>class housekeeping(metaclass = abc.ABCMeta):\n</code></pre>\n<p>This isn't Java, you don't need getter methods for your properties - just access them directly. On a related note, your factory method doesn't need a class, it can just be a normal function.</p>\n<p>I'm not quite sure what this code is supposed to do (from <code>files_to_be_zipped</code>), but it seems incredibly hacky. Shouldn't <code>date = (today - str_date).days</code> do the same thing? Same thing for similar code in <code>sort_deletion</code>.</p>\n<pre><code>difference = str(today - str_date)\nif "days" in difference:\n date = difference.split(" ", 1)[0]\nelse:\n date = 0\n</code></pre>\n<p>Why is this a loop? You only ever return the last item's values. Just remove the extraneous array from the config file. And I think this is an indent error anyways.</p>\n<pre><code>def load_config(directory_name):\n with open('housekeeping.config.json') as f:\n data = json.load(f)\n for config_items in data[directory_name]:\n directory_name_wih_full_path = config_items["path"]\n nr_to_leave = config_items["nr_files_not_zip"]\n deletion_period = config_items["deletion_period"]\n type_to_zip = config_items["file_or_directory"]\n return directory_name_wih_full_path, nr_to_leave, deletion_period, type_to_zip\n</code></pre>\n<p>These lines should be moved to a separate function (or even a concrete method on the ABC) to separate the input handling from the actual housekeeping code.</p>\n<pre><code> housekeeping_shape.pick_files()\n files_to_zip = housekeeping_shape.files_to_be_zipped()\n to_delete = housekeeping_shape.get_deletion_period()\n if to_delete != "NA":\n file_to_del = housekeeping_shape.sort_deletion()\n else: \n file_to_del = {}\n zip_type = housekeeping_shape.get_type()\n file_directory = housekeeping_shape.get_directory()\n run_housekeeping_client(files_to_zip,file_to_del,zip_type, file_directory)\n</code></pre>\n<p><code>run_housekeeping_client</code> seems misnamed - it never does anything related to the housekeeping class.</p>\n<p>You also have an inconsistent naming convention - some of your variables are in <code>camelCase</code> instead of <code>snake_case</code> (as recommended by PEP 8).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:22:31.880",
"Id": "257124",
"ParentId": "256971",
"Score": "2"
}
},
{
"body": "<p>I noticed some of your indentation appears wrong in the code you have provided, so I'll not be able to comment on those particular sections as my assumptions could be invalid.</p>\n<p>But the first thing I would suggest is to look into the <code>Pathlib</code> library since you are dealing with files, for example here's my refactoring of your <code>pick_files</code> method:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\n\nclass housekeeping_foo(housekeeping):\n def __init__(self, directory, normal_files, zipped_files, nr_to_leave, deletion_period, type_to_zip):\n ...\n ...\n self.directory = Path(directory)\n ...\n\n def pick_files(self):\n for item in self.directory.iterdir():\n if item.is_file() and not item.name.startswith("."):\n modification_time = os.path.getmtime(str(item))\n last_modified_date = datetime.datetime.fromtimestamp(modification_time)\n if item.suffix in (".gz", ".zip"):\n self.zipped_files.update({str(item): last_modified_date})\n else:\n self.normal_files.update({str(item): last_modified_date})\n return self.normal_files, self.zipped_files\n</code></pre>\n<p>I find it much easier to read vs. using os.path and its assistants. Outside of using Pathlib, I also made some other changes:</p>\n<ol>\n<li><p>I moved the <code>modification_time</code> and <code>last_modified_date</code> variables up above the if statement as these were common to both branches.</p>\n</li>\n<li><p>Another thing I changed was I check if the suffix (the extension) of the file is either ".gz" or ".zip" by checking if the extension is in a tuple, this avoids having to have two if statements as before.</p>\n</li>\n<li><p>Since we were also acting on both if it was a compressed file and if it wasn't, I switched the logic around to avoid having a <code>not</code> statement (I think it's easier to read, you may disagree).</p>\n</li>\n</ol>\n<p>Another thing that jumps out at me that the other commentor has also talked about is the <code>load_config</code> method. Personally I would avoid returning more than 2 values from a method like you have here, instead I would just return the dictionary like so:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def load_config(directory_name):\n with open("housekeeping.config.json") as file:\n data = json.load(file)\n return data[directory_name]\n</code></pre>\n<p>then you can pass this config object through to the <code>create_housekeeping</code> method on the factory to access the items within it:</p>\n<pre><code> def create_housekeeping(self, name, normal_files, zipped_files, config):\n if name == "foo":\n return housekeeping_foo(\n config['directory'],\n normal_files,\n zipped_files,\n config['nr_to_leave'],\n config['deletion_period'],\n config['type_to_zip'],\n )\n</code></pre>\n<p>This means the 'knowledge' of which config items are needed is stored in the factory, and the <code>load_config</code> method deals with just that, loading all of the config.</p>\n<p>You could even take it a step further and pass the config through again to the objects constructor.</p>\n<p>These are just two things I felt I could easily contribute with, but if you'd like any more feedback on a specific area or want to ask a question please feel free to do so!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T23:51:01.037",
"Id": "257168",
"ParentId": "256971",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T14:15:14.830",
"Id": "256971",
"Score": "4",
"Tags": [
"python",
"design-patterns",
"json"
],
"Title": "Housekeeping script improvements"
}
|
256971
|
<p>I have written a short function as part of my program that strips the quotation marks (") from a list of lists. An example of the input data is:</p>
<pre class="lang-py prettyprint-override"><code>[['"foo"', '"Spam"', '123', '"Angry Badger"'],
['"dead"', '"Parrot"', '321', '987']]
</code></pre>
<p>The target result would be:</p>
<pre class="lang-py prettyprint-override"><code>[['foo', 'Spam', '123', 'Angry Badger'],
['dead', 'Parrot', '321', '987']]
</code></pre>
<p>This code I am using to parse this is:</p>
<pre class="lang-py prettyprint-override"><code>def quote_strip(input_file):
for k1, v1 in enumerate(input_file):
for k2, v2 in enumerate(v1):
input_file[k1][k2] = v2.lstrip('"').rstrip('"')
return input_file
</code></pre>
<p>This works fine, but I am pretty sure there is a way of making this a single line. I just always seem to mess up comprehensions when they have the <code>=</code> sign in them like this.</p>
<p>Any feedback would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T15:49:46.800",
"Id": "507476",
"Score": "0",
"body": "Since you've got to traverse a 2D array in Python, your code will be minimum 2 lines just for the traversal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T15:53:44.090",
"Id": "507477",
"Score": "2",
"body": "@RussJ Unless one were to use a list comprehension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T15:59:14.003",
"Id": "507478",
"Score": "0",
"body": "I agree with @Peilonrayz - it is easy enough to write `[x for i in file for x in i]`. It is just the `=` that is throwing me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:05:40.223",
"Id": "507479",
"Score": "0",
"body": "You just need `new_input_file = [ ... ]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:10:25.433",
"Id": "507480",
"Score": "0",
"body": "But if you do that with this case it will just add each `v2` item to that list in a single go. I want to maintain the shape of the original list, just with the `\"` stripped out"
}
] |
[
{
"body": "<blockquote>\n<p>I just always seem to mess up comprehensions when they have the <code>=</code> sign in them like this.</p>\n</blockquote>\n<p>I found the best way to think about comprehensions is instead think of comprehensions as <code>.append</code>s.</p>\n<p>Lets change your inner loop to use <code>.append</code> instead.\nWe don't need to use <code>enumerate</code> as we'll be building a new list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def quote_strip(input_file):\n for k1, v1 in enumerate(input_file):\n inner_list = []\n for v2 in v1:\n inner_list.append(v2.lstrip('"').rstrip('"'))\n input_file[k1] = inner_list\n return input_file\n</code></pre>\n<p>We can now change the code to a comprehension.\nI'll show you a pattern which we can just copy:</p>\n<pre class=\"lang-py prettyprint-override\"><code>my_list = []\nfor item in other_list:\n my_list.append(item + 1)\n</code></pre>\n<p>becomes:</p>\n<pre class=\"lang-py prettyprint-override\"><code>my_list = [\n item + 1\n for item in other_list\n]\n</code></pre>\n<p>We just move whatever is in the <code>append(...)</code> to the top of the comprehension.\nAnd move the for loop into the bottom of the list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def quote_strip(input_file):\n for k1, v1 in enumerate(input_file):\n inner_list = [\n v2.lstrip('"').rstrip('"')\n for v2 in v1\n ]\n input_file[k1] = inner_list\n return input_file\n</code></pre>\n<p>You should notice we can remove the need for assigning to the name <code>inner_list</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def quote_strip(input_file):\n for k1, v1 in enumerate(input_file):\n input_file[k1] = [\n v2.lstrip('"').rstrip('"')\n for v2 in v1\n ]\n return input_file\n</code></pre>\n<p>Now we can change the loop to use <code>.append</code> again.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def quote_strip(input_file):\n output_list = []\n for v1 in input_file:\n output_list.append([\n v2.lstrip('"').rstrip('"')\n for v2 in v1\n ])\n return output_list\n</code></pre>\n<p>And again we can change the code to a list comprehension.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def quote_strip(input_file):\n return [\n [\n v2.lstrip('"').rstrip('"')\n for v2 in v1\n ]\n for v1 in input_file\n ]\n</code></pre>\n<h2>Extra</h2>\n<blockquote>\n<p>I am pretty sure there is a way of making this a single line</p>\n</blockquote>\n<p>We can put the comprehension on one line but please <em>do not do so</em>.\nHow many lines of code you write is not important, how easy to read your code is.\nPutting the comprehension on one line will make your code harder to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:15:15.547",
"Id": "507481",
"Score": "1",
"body": "also see this SO example of nested list comprehensions, which may be handy: https://stackoverflow.com/a/8050243/1075247"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T08:24:50.790",
"Id": "507559",
"Score": "1",
"body": "Why is something like this hard to read?: `A = [[el.strip('\"') for el in lst] for lst in A]`. Just curious"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T09:30:38.030",
"Id": "507568",
"Score": "1",
"body": "@joostblack When skim reading code, you can easily mistake the code as many things, so you need to actually read the code rather than skim read. Additionally coding with a focus on line count increases code density, notice how the OP's code is easier to skim read than many of the intermediary steps in my answer. Because the density of my code is more than the OP's. After reading hundreds of people's code I find the code which uses multi-line comprehensions easier to read. Hard to read code is the accumulation of all the little parts of code which stop you skim reading."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:14:09.637",
"Id": "256974",
"ParentId": "256972",
"Score": "5"
}
},
{
"body": "<p>I am by no means an expert, and this is my first answer here. I'm sorry if it's not up to the mark.</p>\n<p>What I understand from your question is that your goal is to make your function <em>shorter</em>. We'll start off iterating through parent list and mapping a lambda to each child. The lambda uses "str.strip()" which strips from both sides of a string.</p>\n<pre><code>def v1(in_l):\n for i, l in enumerate(in_l):\n in_l[i] = list(map(lambda x: x.strip('"'), l))\n return in_l\n</code></pre>\n<p>(Apologies if the variable names seem cryptic. I wanted to keep it as short as possible.)</p>\n<p>This function could be shortened with a list comprehension:</p>\n<pre><code>def v2(in_l):\n return [list(map(lambda x: x.strip('"'), l)) for l in in_l]\n</code></pre>\n<p>And you could shorten it further with a lambda:</p>\n<pre><code>v3 = lambda in_l: [list(map(lambda x: x.strip('"'), l)) for l in in_l]\n</code></pre>\n<p>For readability, I would suggest going with the first one.\nI ran <code>timeit.timeit</code> on each (including your own implementation), with the example list you provided as a test case and <code>number = 10000</code>.</p>\n<p>All of them clocked in at around <code>0.015</code>. V1 and V2 seemed to fluctuate between <code>0.015</code> and <code>0.040</code>. V3 and your function remained around <code>0.015</code> consistently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:27:41.837",
"Id": "507484",
"Score": "3",
"body": "TLDR: Your function is fine. Shortening it provides no performance boost at all and sacrifices readability."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:26:27.580",
"Id": "256975",
"ParentId": "256972",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "256974",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T15:26:47.250",
"Id": "256972",
"Score": "3",
"Tags": [
"python"
],
"Title": "Stripping Quotations from a List of Lists"
}
|
256972
|
<p>I'm using a script that converts a CSV file into GeoJSON in order to display it on a map. <a href="http://digitalwaterfall.space/ypsilandlords/searchable-map-template-csv/" rel="nofollow noreferrer">You can see it for yourself here.</a> The CSV has about four thousand rows. It's quite slow. I'm wondering what is slowing it down and how I can speed it up.</p>
<pre><code>function latLonColumnsToNumbers(data, latName, lonName) {
return data.map(function(item) {
if (item.hasOwnProperty(latName)) {
item[latName] = parseFloat(item[latName]);
if (isNaN(item[latName])) { //check if row has blank lat/long, and if so, flag it
var latFlag = 1;
} else {
latFlag = 0;
}
}
if (item.hasOwnProperty(lonName)) {
item[lonName] = parseFloat(item[lonName]);
if (isNaN(item[lonName])) {
var lonFlag = 1;
} else {
lonFlag = 0;
}
}
if (latFlag == 1 || lonFlag == 1) { //if row has no lat/long, then assign it to the approximate center of the map
item[latName] = 42.2;
item[lonName] = ~83.6;
return item;
}
else {
return item;
}
});
</code></pre>
<p>I know that a faster way to do this would be to turn the CSV into a sql database and call it with PHP but that involves using a lot of server-side stuff like NodeJS, Ajax, etc that I am not (yet) familiar with. So I would like to keep using the CSV for now until I learn how to do that.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T17:37:00.740",
"Id": "507489",
"Score": "0",
"body": "Are you certain that that the performance problem is in this function specifically, and not some other part of the process? Or are you just guessing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T17:38:07.743",
"Id": "507490",
"Score": "0",
"body": "Could you give a little more context? Some sample calls with plausible values for the arguments would help reviewers - a set of unit-tests would really, really help."
}
] |
[
{
"body": "<p>The slowest part is probably the <code>parseFloat</code>s, but I can't think of a faster way.</p>\n<p>One thing that stands out to me is the use of <code>map</code>, but at the same time you are modifying the items, so in the end you have two arrays with the same content. You probably can save some time just keeping the same array by using <code>forEach</code> (or a normal <code>for</code> loop which is probably even faster).</p>\n<p>Also using global variables (<code>var</code>) and integers where you could use boolean won't help. I also don't see the need for <code>hasOwnProperty</code>.</p>\n<p>What is the point of <code>~83.6</code> (which equals <code>-84</code>)?</p>\n<p>I'd simplify the whole thing to to:</p>\n<pre><code>function latLonColumnsToNumbers(data, latName, lonName) {\n data.forEach(item => {\n item[latName] = parseFloat(item[latName]);\n item[lonName] = parseFloat(item[lonName]);\n \n if (isNaN(item[latName]) || isNaN(item[lonName])) { \n item[latName] = 42.2; \n item[lonName] = ~83.6; // or just -84\n } \n });\n\n // The return isn't needed either. Just use the original array after calling the function.\n return data;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T17:44:19.660",
"Id": "256978",
"ParentId": "256976",
"Score": "1"
}
},
{
"body": "<p>From a short review;</p>\n<ul>\n<li><p>Old school <code>for</code> loops still beat <code>map</code></p>\n</li>\n<li><p>Prevent repeated object[string] access, like accesssing several times <code>item[latName]</code>, because it is relatively slow</p>\n</li>\n<li><p>Is it absolutely necessary to create a new object? I have a suspicion that modifying the object would be faster. (Yes, not great practice, but you are looking for speed, you should try this)</p>\n</li>\n<li><p>One more thing, I was hesitant to mention this but, but the plus operator can be faster than <code>parseFloat</code> according to jsperf. So you could just go for</p>\n<pre><code> const newLat = +item[latName];\n const newLong = +item[longName];\n</code></pre>\n</li>\n</ul>\n<p>give it a shot, let us know ;)</p>\n<p>This is my counter proposal with in place conversion;</p>\n<pre><code>function convertLocationToNumbers(data, latName, longName) {\n const dataLength = data.length;\n for(let i = 0; i < dataLength; i++){\n const item = data[i];\n //Dont check for hasownproperty, just go!\n const newLat = +item[latName];\n const newLong = +item[longName];\n if(isNaN(newLat) || isNaN(newLong ){\n item[latName] = 42.2; \n item[lonName] = ~83.6;\n }else{\n item[latName] = newLat; \n item[lonName] = newLong;\n } \n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:48:55.703",
"Id": "256984",
"ParentId": "256976",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T16:55:28.660",
"Id": "256976",
"Score": "2",
"Tags": [
"javascript",
"performance",
"leaflet"
],
"Title": "Speed up javascript code to convert csv to geojson"
}
|
256976
|
<p>I have a plan to make something to solve this stuff:</p>
<p>You have 7 chips that are on the run. each has some cargo loaded. And also there's <code>where</code> record on each.Latter could be either <code>track</code> means running(or gone offroad) or <code>tobeauty</code> means it reaches its finish. Where <code>.cargo = -1</code> means it's gone . And finally i need one of three : all is gone, at least one is on finish and others either are on finish or gone , and show is in progress so neither of these two. Only first two will be checked so thrd will be just anything else.</p>
<p>I've done it like this finally:</p>
<pre class="lang-pascal prettyprint-override"><code>uses crt;
type
trail_type = (blue ,desert ,white ,green ,violet ,wood ,coldgreen) ;
palmtree = (none ,apple ,appricot ,grape ,pineapple ,lemon);
catchinon = (track, tobeauty);
type
ontherun = Record
trail : trail_type;
cargo : Currency;
miles : Integer;
where : catchinon;
end;
Var
rec_b : array[1..7] of ontherun;
fruit : palmtree;
k : Integer;
Function Ternary(x : Boolean ; b : palmtree ; c : palmtree ) : palmtree;
begin
if x then
Ternary := b
else
Ternary := c;
end;
begin
{testing part}
{ rec_b[4].cargo := -1;
rec_b[5].where := tobeauty;
rec_b[7].where := tobeauty;
rec_b[1].cargo := -1;
rec_b[3].where := tobeauty;
fruit := none;}
{for k := 1 to 7 do
rec_b[k].where := tobeauty;}
for k := 1 to 7 do
rec_b[k].cargo := -1;
rec_b[7].where := tobeauty;
rec_b[7].cargo := 20;
{testing part ended}
fruit := none;
for k := 1 to 7 do
begin
fruit := Ternary((rec_b[k].where = tobeauty) and ( fruit in [none , pineapple]), appricot , fruit );
fruit := Ternary((rec_b[k].cargo = -1) and ( not (fruit in [grape])), lemon , fruit);
fruit := Ternary((rec_b[k].where = track) and ( fruit in [ none , appricot , apple , pineapple]), grape , fruit);
fruit := Ternary((rec_b[k].cargo = -1) and ( fruit in [lemon ]), pineapple , fruit);
fruit := Ternary((rec_b[k].where = tobeauty) and ( fruit in [pineapple, appricot]), apple , fruit );
end;
Writeln(fruit);
end.
</code></pre>
<p>Are there some tricks on that do you know?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T18:26:33.653",
"Id": "256981",
"Score": "2",
"Tags": [
"pascal"
],
"Title": "max() without arithmetics or so"
}
|
256981
|
<p>Let's say I want to write a super simple Python program to ask a user for their personal information and list it back out in a "pretty" format.</p>
<pre><code>def get_info():
first = input("enter your first name: ")
while not first.isalpha():
first = input("enter your first name: ")
last = input("enter your last name: ")
while not last.isalpha():
last = input("enter your last name: ")
age = input("enter your age: ")
while not age.isnumeric():
age = input("enter your age: ")
age = int(age)
has_pet = input("do you have a pet?: ").lower()
while has_pet not in ["yes", "no", "y", "n"]:
has_pet = input("do you have a pet?: ").lower()
if "y" in has_pet:
has_pet = True
else:
has_pet = False
return [first, last, age, has_pet]
def print_info(info):
first, last, age, has_pet = info
print(f"Name: {first} {last}")
print(f"Age: {age}")
print(f"Has pet: {has_pet}")
print_info(get_info())
</code></pre>
<p>Clearly, I have violated DRY multiple times.<br>
(1) Should I just throw the <code>input()</code> functions away and use arguments (with <code>sys.argv</code>)?<br>
(2) The reason I can't use recursion is because I would have to ask the user for all of their information again if they mess up on, like, answering the pet question for example. Is there another way to clean up this code without sacrificing speed / resources?</p>
|
[] |
[
{
"body": "<p>You could abstract the character checking into a function, and do one print statement:</p>\n<pre><code>def get_info():\n def valid_check(alpha, message):\n """\n Assumes:\n alpha is a boolean discerning whether to check for alpha or numeric\n message is an input request string\n Returns:\n validated input, in string or int type according to alpha\n """\n assert type(alpha) == bool, "alpha should be boolean"\n if alpha:\n inp = input("%s: " % message)\n while not inp.isalpha():\n inp = input("%s: " % message)\n return inp\n else:\n inp = input("%s: " % message)\n while not inp.isnumeric():\n inp = input("%s: " % message)\n return int(inp)\n\n first = valid_check(True,"enter your first name")\n last = valid_check(True,"enter your last name")\n age = valid_check(False,"enter your age")\n \n has_pet = input("do you have a pet?: ").lower()\n while has_pet not in ["yes", "no", "y", "n"]:\n has_pet = input("do you have a pet?: ").lower()\n\n if "y" in has_pet:\n has_pet = True\n else:\n has_pet = False\n \n return [first, last, age, has_pet]\n\ndef print_info(info):\n first, last, age, has_pet = info\n print(f"Name: {first} {last}\\nAge: {age}\\nHas pet: {has_pet}")\n\nprint_info(get_info())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T20:58:37.333",
"Id": "507518",
"Score": "1",
"body": "Can you explain the changes you've made - how and why the changes you've made are better than the OP's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T07:50:15.960",
"Id": "507669",
"Score": "0",
"body": "@Peilonrayz The OP asked to implement DRY. my code isn't the best answer here, but it does abstract the input request into a function which could be reused"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T20:30:48.960",
"Id": "256991",
"ParentId": "256986",
"Score": "0"
}
},
{
"body": "<p>Yes, abandon <code>input()</code>, which is usually a less powerful and flexible choice.\nHere's an approximation of your code using\n<a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a>. Notice several\nthings: (1) very little repetition in our code; (2) much less algorithmic code,\nwhich means fewer chances for error; (3) greater simplicity overall\nand thus higher readability;\n(4) good validation and user help messages out of the box; (5) many other\npossibilities (see the library's documentation); (6) less hassle for\nusers to run the code repeatedly or in any kind of automated context;\nand (7) less hassle during development of the code, for the same reason.</p>\n<pre><code># Usage examples:\n\n$ python demo.py George Washington 289 --pet\nNamespace(age=289, first_name='George', last_name='Washington', pet=True)\n\n# The code:\n\nimport argparse\nimport sys\n\ndef main(args):\n ap, opts = parse_args(args)\n print(opts)\n\ndef parse_args(args):\n ap = argparse.ArgumentParser()\n ap.add_argument('first_name', type = personal_name)\n ap.add_argument('last_name', type = personal_name)\n ap.add_argument('age', type = int)\n ap.add_argument('--pet', action = 'store_true')\n opts = ap.parse_args(args)\n return (ap, opts)\n\ndef personal_name(x):\n if x.isalpha():\n return x\n else:\n raise ValueError(f'Invalid name: {x}')\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n</code></pre>\n<p>But if you cannot or do not want to take that route, the roll-your-own approach\nlooks similar in spirit: we need a general-purpose function to get input;\nit needs to take some type of text or label to tell the user what we are asking\nfor; and it needs a converter/validator to check the reply.\nHere's a rough sketch of the new or different parts:</p>\n<pre><code>def main(args):\n d = dict(\n first = get_input(label = 'first name', convert = personal_name),\n last = get_input(label = 'last name', convert = personal_name),\n age = get_input(label = 'age', convert = int),\n pet = get_input(label = 'pet status [y/n]', convert = yesno),\n )\n print(d)\n\ndef yesno(x):\n if x in ('yes', 'y'):\n return True\n elif x in ('no', 'n'):\n return False\n else:\n raise ValueError(f'Invalid yes-no: {x}')\n\ndef get_input(label, convert):\n while True:\n reply = input(f'Enter {label}: ')\n try:\n return convert(reply)\n except (ValueError, TypeError):\n print('Invalid reply')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T20:34:42.867",
"Id": "256992",
"ParentId": "256986",
"Score": "1"
}
},
{
"body": "<p>I don't see much of a reason to use <code>sys.argv</code> or the superior <code>argparse</code>.\nBoth seem like added complexity for not much benefit.</p>\n<p>You can DRY your code in two ways:</p>\n<ul>\n<li><p><strong>Do while loop</strong><br />\nPython doesn't have do while loops, but we can mimic one by using <code>while True:</code> and ending the block with an <code>if</code> to break from the loop.</p>\n<p>Doing so we can use one string rather than two.</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n first = input("enter your first name: ")\n while first.isalpha():\n break\n</code></pre>\n</li>\n<li><p><strong>Custom input</strong><br />\nWe can expand <code>input</code> to have the functionality you want.</p>\n<p>We can see your loops have two similar parts:</p>\n<ol>\n<li><p>Transform the value.<br />\n<code>int(age)</code> and <code>str.lower()</code></p>\n</li>\n<li><p>Validate the value.<br />\n<code>str.isalpha()</code></p>\n</li>\n</ol>\n<p>As such we can build a function to do everything your while loops are doing.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def super_input(prompt, *, transform=lambda v: v, validate=lambda v: True, input=input):\n while True:\n try:\n value = transform(input(prompt))\n except ValueError:\n pass\n else:\n if validate(value):\n return value\n</code></pre>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def get_info():\n first = super_input("enter your first name: ", validate=str.isalpha)\n last = super_input("enter your last name: ", validate=str.isalpha)\n age = super_input("enter your age: ", transform=int)\n has_pet = super_input(\n "do you have a pet?: ",\n transform=str.lower,\n validate=lambda v: v in ["yes", "no", "y", "n"]\n )\n return first, last, age, has_pet.startswith("y")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T21:18:56.097",
"Id": "256996",
"ParentId": "256986",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:00:21.917",
"Id": "256986",
"Score": "1",
"Tags": [
"python"
],
"Title": "DRY input-checking in python"
}
|
256986
|
<p>For more information on Blazor, see the <a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-5.0" rel="nofollow noreferrer">Introduction/Overview in Microsoft's documentation</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:58:02.723",
"Id": "256989",
"Score": "0",
"Tags": null,
"Title": null
}
|
256989
|
Blazor is a free and open-source web framework being developed by Microsoft. It supports incremental updates to a virtual DOM, enables UI code to be written in C# with JS interoperability, can run from either server or client, and sends data over a constant SignalR connection instead of http request/response cycles.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T19:58:02.723",
"Id": "256990",
"Score": "0",
"Tags": null,
"Title": null
}
|
256990
|
<p>This is a student project of mine. I got 4/5 points but I suspect there's a lot of weird stuff in there. I never had a chance to hear my teacher's feedback about it and it bothers me so I figured somebody could take a glance at it and provide some feedback.</p>
<h3>Quick documentation</h3>
<blockquote>
<p>First we run "Server" program that opens ports provided by runtime args[] parameters listening in parallel in separate threads.<br />
Next we run "Client" passing to the constructor hostname and list of ports to knock. We can run many clients or set numberofclients variable in code.</p>
<p>Server UDP sockets have access to synchronized data structure that stores information about incoming connections with sockets.<br />
After each connection program checks if order of connections is same as key. If <em>yes</em> then server sends message with TCP port to the socket of unauthorized yet client that sent correct combination of ports and another thread is run with TCP socket listening for authorized client. Authorized client connects to TCP socket and exchanges short information with the server. After the exchange TCP socket closes.</p>
<p>Enter key closes program and every thread and socket is freed.</p>
</blockquote>
<h3>Server</h3>
<pre class="lang-java prettyprint-override"><code>package com.company;
import java.io.IOException;
import java.net.*;
import java.util.*;
import java.util.stream.Collectors;
public class Server implements Runnable{
byte[] buffer = new byte[2048];
byte[] sendBuffer = new byte[2048];
List<DatagramSocket> socketList;
Map<InetSocketAddress, List<Integer>> internalMap;
Map<InetSocketAddress, List<Integer>> guestMap;
List<Integer> key;
Server(Integer... ports) throws SocketException {
this.key = new ArrayList<>();
//key.addAll(Arrays.asList(ports));
for(Integer portnumber : ports)
key.add(portnumber);
this.socketList = new ArrayList<>();
this.internalMap = new HashMap<>();
this.guestMap = Collections.synchronizedMap(internalMap);
List<Integer> uniquePorts = key.stream().distinct().collect(Collectors.toList());
for(Integer port: uniquePorts){
DatagramSocket socket = new DatagramSocket(port);
socketList.add(socket);
}
System.out.println("Zajete porty: ");
socketList.forEach(n -> System.out.print(n.getLocalPort() + ", "));
System.out.println();
this.key = socketList.stream().map(DatagramSocket::getLocalPort).collect(Collectors.toList());
}
@Override
public void run() {
for(DatagramSocket socket : socketList){
Thread t = new Thread(){
boolean running;
@Override
public void run() {
while(true){
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
try {
socket.receive(packet);
ProtocolMessage msgRecvd = new ProtocolMessage(packet.getData());
System.out.println(msgRecvd); //dbgging
if(!msgRecvd.equals(Protocol.synMessage))
throw new ProtocolException("Request not recognized, possibly malformed");
InetAddress address = packet.getAddress();
int port = packet.getPort();
InetSocketAddress guest = new InetSocketAddress(address,port);
if(guestMap.containsKey(guest)){
guestMap.get(guest).add(socket.getLocalPort()); //refactor it later
if(guestMap.get(guest).equals(key)){
ServerClientService serverClientService = new ServerClientService();
int establishedPort = serverClientService.serverSocket.getLocalPort();
System.out.println("Guest: " + address + ":" + port+ " authenticated sending tcp port: " + establishedPort);
ProtocolMessage auth = Protocol.authSuccess;
auth.setValue(establishedPort);
sendBuffer = auth.toByte();
socket.send(new DatagramPacket(sendBuffer,sendBuffer.length, address, port));
serverClientService.run();
}
else if(key.size() < guestMap.get(guest).size()){
guestMap.remove(guest);
}
}
else{
List<Integer> list = new ArrayList<>();
List<Integer> synchlist = Collections.synchronizedList(list);
synchlist.add(socket.getLocalPort());
guestMap.put(guest, synchlist);
}
sendBuffer = Protocol.ackMessage.toByte();
DatagramPacket confirmation = new DatagramPacket(sendBuffer, sendBuffer.length, address, port);
socket.send(confirmation);
}catch (SocketTimeoutException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
t.setDaemon(true); //inne wątki nie moga istniec bez procesu main
t.start();
}
Scanner s = new Scanner(System.in);
System.out.println("Naciśnij \"Enter\" aby wyjść.....");
s.nextLine();
}
}
</code></pre>
<h3>Server-Client TCP service</h3>
<pre class="lang-java prettyprint-override"><code>package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerClientService implements Runnable {
ServerSocket serverSocket;
ServerClientService(){
try {
serverSocket = new ServerSocket(0);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Port niedostepny");
}
}
@Override
public void run() {
try( Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))
)
{
String query = in.readLine();
System.out.println(query);
String response = "hello there client " + getPort();
out.println(response);
out.flush();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getPort() {
return serverSocket.getLocalPort();
}
}
</code></pre>
<h3>Client</h3>
<pre class="lang-java prettyprint-override"><code>package com.company;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
public class Client {
byte[] sendBuffer;
byte[] recvBuffer;
DatagramSocket socket;
String hostName;
List<Integer> key;
Client(String address, int... ports) throws SocketException {
this.key = new ArrayList<>();
this.sendBuffer = new byte[2048];
this.recvBuffer = new byte[2048];
this.socket = new DatagramSocket();
this.hostName = address;
for(int i : ports)
this.key.add(i);
}
public void run() {
try {
InetAddress inetAddress = InetAddress.getByName(hostName);
for(Integer port : key){
sendBuffer = Protocol.synMessage.toByte();
DatagramPacket packet = new DatagramPacket(sendBuffer, sendBuffer.length, inetAddress,port);
socket.send(packet);
//System.out.println("sent: " + new ProtocolMessage(sendBuffer));
DatagramPacket returnPacket = new DatagramPacket(recvBuffer, recvBuffer.length);
returnPacket.setLength(returnPacket.getLength());
socket.setSoTimeout(5000);
try {
socket.receive(returnPacket);
} catch (SocketTimeoutException e){
System.err.println("No response, probably invalid authentication");
}
ProtocolMessage response = new ProtocolMessage(returnPacket.getData());
System.out.println(response); //debugging
if (response.equals(Protocol.ackMessage)) {
//proceed
continue;
}
else if(response.equals(Protocol.authSuccess)){
//connect to sent tcp port
int portNumber = response.value;
startTcpConnection(portNumber);
break;
}
else{
throw new ProtocolException("Response not recognized, possibly malformed");
//should like catch it and try again perhaps
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
socket.close();
}
public void startTcpConnection(int port ){
try(Socket tcpSocket = new Socket(hostName, port);
PrintWriter out = new PrintWriter(tcpSocket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(tcpSocket.getInputStream()));)
{
out.println("Client " + port + ": hello");
out.flush();
String response = in.readLine();
System.out.println(response);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<h3>Common protocol</h3>
<pre class="lang-java prettyprint-override"><code>package com.company;
public class Protocol {
final static ProtocolMessage synMessage = new ProtocolMessage(1);
final static ProtocolMessage ackMessage = new ProtocolMessage(2);
final static ProtocolMessage authSuccess = new ProtocolMessage(3);
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package com.company;
import java.nio.ByteBuffer;
public class ProtocolMessage {
int type;
int value;
ProtocolMessage(int type, int value){
this.type = type;
this.value = value;
}
ProtocolMessage(int type){
this.type = type;
this.value = 0;
}
ProtocolMessage(byte[] bytes){
ByteBuffer wrapped = ByteBuffer.wrap(bytes);
this.type = wrapped.getInt(0);
this.value = wrapped.getInt(50);
}
public byte[] toByte(){
ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
byteBuffer.putInt(0,this.type);
byteBuffer.putInt(50,this.value);
return byteBuffer.array();
}
@Override
public String toString(){
return type + ":" + value;
}
@Override
public boolean equals(Object o){
ProtocolMessage another = (ProtocolMessage) o;
if(another.type == this.type)
return true;
else
return false;
}
void setValue(int value){
this.value = value;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not going to look at the code for what is does, but I can give you some feedback on how it looks / is styled, and where you might improve.</p>\n<h2>Exception handling</h2>\n<p>Your current exception handling consist of print errors with a stack trace. There is no explicit error handling or comments about what should be done.</p>\n<h2>Unnecessary code</h2>\n<p>Code like this:</p>\n<pre><code> if(another.type == this.type)\n return true;\n else\n return false;\n</code></pre>\n<p>Is really too verbose. It should be:</p>\n<pre><code> return (another.type == this.type);\n</code></pre>\n<h2>Missing access modifiers</h2>\n<pre><code>public class ProtocolMessage {\n int type;\n int value;\n</code></pre>\n<p><code>type</code> and <code>value</code> could be <code>private</code>, (and <code>final</code>). Prefer classes to be as "closed" as possible.</p>\n<h2>Missing comments/javadoc</h2>\n<p>You should document WHY you have a class or a piece of code that is not directly obvious:</p>\n<pre><code> ProtocolMessage(byte[] bytes){\n ByteBuffer wrapped = ByteBuffer.wrap(bytes);\n this.type = wrapped.getInt(0);\n this.value = wrapped.getInt(50);\n }\n</code></pre>\n<p>What is the <code>50</code>? Why is it there?</p>\n<h2>Simplify methods</h2>\n<p>Your <code>run()</code> method in <code>Server</code> has many many nested levels of code. Try to extract pieces of logic so that they have exactly one purpose.</p>\n<h2>Safe equals</h2>\n<p>Your <code>equals()</code> method breaks if <code>null</code> or any class other than a <code>ProtocolMessage</code> is provided... make it safe by checking for null and same type ..</p>\n<pre><code>public boolean equals(final Object other) {\n if (null == other) {\n return false;\n }\n if (!(other instanceof ProtocolMessage)) {\n return false;\n }\n // equals as you had it.\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T08:34:36.557",
"Id": "257054",
"ParentId": "256995",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T21:16:23.113",
"Id": "256995",
"Score": "1",
"Tags": [
"java",
"thread-safety",
"socket",
"udp"
],
"Title": "Java UDP port knocking authentication. Many clients at the same time"
}
|
256995
|
<p>I just started learning Python and this is the first code I wrote. It's a Random Walk generator. I think I got it to work pretty well but I'm also sure there are more effective and less clunky ways to do this. Could you give me some tips on what to change to make the code shorter/more optimized and just objectively more "pythonian" and better?</p>
<pre><code># Random Walk in two dimensions
import random
steps = "a"
maximal = "a"
minimal = "a"
Xstep = 0
Ystep = 0
StepSize = 0
PosNeg = 0
def new_line():
print(" ")
def invalid_enter_number():
print("Invalid input! Enter a number.")
new_line()
def invalid_enter_positive():
print("Invalid input! Enter a positive number.")
new_line()
new_line()
print("Random Walk in two dimensions")
new_line()
while type(steps) != int:
try:
steps = int(input("How many steps should be done? "))
while steps <= 0:
invalid_enter_positive()
steps = int(input("How many steps should be done? "))
except:
steps = ValueError
invalid_enter_number()
continue
while type(maximal) != int:
try:
maximal = int(input("How big is the biggest possible step? "))
while maximal <= 0:
invalid_enter_positive()
maximal = int(input("How big is the biggest possible step? "))
except:
maximal = ValueError
invalid_enter_number()
continue
if maximal != 1:
while type(minimal) != int:
try:
minimal = int(input("How big is the smallest possible step? "))
while minimal <= 0 or minimal >= maximal:
if minimal <= 0:
invalid_enter_positive()
minimal = int(input("How big is the smallest possible step? "))
else:
print("Number must be smaller than the biggest possible step!")
new_line()
minimal = int(input("How big is the smallest possible step? "))
except:
minimal = ValueError
invalid_enter_number()
continue
else:
minimal = 1
new_line()
print("Number of steps:", steps)
if maximal != 1:
print("Step size range:", minimal, "-", maximal)
else:
print("Step size: 1")
new_line()
print("Steps:")
while steps > 0:
StepSize = random.randint(minimal, maximal)
PosNeg = random.randint(0, 1)
chance = random.randint(0, 1)
if chance == 0 and PosNeg == 0:
Xstep += StepSize
elif chance == 0 and PosNeg == 1:
Xstep -= StepSize
elif chance == 1 and PosNeg == 0:
Ystep += StepSize
else:
Ystep -= StepSize
print("X:", Xstep, " Y:", Ystep)
steps -= 1
</code></pre>
|
[] |
[
{
"body": "<p>Here's one suggestion; other readers will probably offer more.\nSeveral times, you need to get an integer from the user. You\ncould create a function to handle such details. The code\nbelow shows what the function might look light and how you\nwould use it.</p>\n<pre><code>def int_from_user(prompt):\n while True:\n try:\n n = int(input(prompt + ' '))\n if n > 0:\n return n\n else:\n raise ValueError()\n except ValueError:\n print('Invalid input! Enter a positive number.')\n\nsteps = int_from_user('How many steps should be done?')\nprint(steps)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T21:15:27.953",
"Id": "507646",
"Score": "0",
"body": "Awesome, thanks! Just one question: What does the `raise` do? If the input value isn't > 0 but also isn't a string so it doesn't make a ValueError then this `raise` forces a ValueError?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T21:40:10.353",
"Id": "507648",
"Score": "0",
"body": "@Vojta Yes, try to convert to int, which can fail. Then check for positive-int and, on failure, raise any ValueError merely to trigger the except-clause. It's just a technique so we don't have to duplicate the printing logic. A reasonable alternative (maybe even a better one!) is to define the error message in a variable before the while-loop; then, in the else-clause, just print it -- no need for the semi-mysterious empty ValueError. But there probably are situations where the technique (raising to trigger your own except-clause) is still useful to know about."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T02:33:47.520",
"Id": "257001",
"ParentId": "256998",
"Score": "2"
}
},
{
"body": "<p>If your concern is speed, I would have some suggestions:</p>\n<p>You use the randint function 3x per step, while you only need it once: Just use random.choice() or numpy.randint() to directly select from a range of positive or negative step-sizes. This also gets rid of the excessive if statements. The slowest part is the print! Instead of printing every step, you should only print whenever needed, i.e. every 1000th step. Also instead of the while loop, python is actually faster using for loops.</p>\n<p>Here is an example of a 3d random walk with 500 particles in a cube. It's 3d because it generates 3 coordinates per particle. You can change the dimensionality yourself.</p>\n<pre><code>N = 500 #simulating 500 particels at once\nsimulation_length = 10**6\ncenters = np.random.randint(-500,500,N*3) #cube of length 1000\n\nfor i in range(simulation_length):\n centers += np.random.randint(-2,3,N*3)\n centers = np.clip(centers,-500,500) #cant go outside box, alternatively, you may want to create symetric boundary conditions\n\n #here you would calculate something?\n\n if i%10000 == 0:\n print(i)\n</code></pre>\n<p>This code is not the best possible either; you would need to have a look at the validity of the simulation itself (is a strict grid valid?), and @performace it would surely benefit from multi-processing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T13:42:58.017",
"Id": "507848",
"Score": "0",
"body": "`N = 500`\n`centers = np.random.randint(-500, 500, N*3)` This just gives me 1500 random numbers between -500 and 500 right? How is that a cube of length 1000? Sorry for a dumb question, I think the jump from 2D to 3D is confusing me..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T10:05:22.790",
"Id": "507910",
"Score": "0",
"body": "If you want to describe a single particle in 2d space, then you would need to generate 2 random numbers, or start at (0,0). Here we describe 500 particles in 3d, hence 1500 numbers."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T23:01:10.833",
"Id": "257116",
"ParentId": "256998",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "257001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-10T23:19:39.957",
"Id": "256998",
"Score": "2",
"Tags": [
"python",
"random"
],
"Title": "Random walk generator - looking for optimizations (Python)"
}
|
256998
|
<p>I have started a hobby project and would like to integrate better and more thorough testing practices. Since I am not too used to it, I'd love to have some feedback on the sample code below. In particular, I'd be interested in the best practices surrounding setting up data necessary to feed a particular testing function or set of functions. As it probably matters, I intend to use <code>pytest</code>.</p>
<p>Here is the sample code from the first testing module in my repo so far:</p>
<pre><code>from accounts import Account
from accounts import AccountRollup
from accounts import AccountType
from accounts import AmountType
from accounts import JournalEntry
from accounts import JournalEntryLeg
# Setup chart of accounts
cash_account = Account(1, "Cash", AccountType.Asset)
mortgage_account = Account(2, "Mortgage", AccountType.Liability)
revenue_account = Account(3, "Revenues", AccountType.Income)
balance_sheet = AccountRollup([cash_account, mortgage_account])
income_statement = AccountRollup(revenue_account)
chart_of_accounts = AccountRollup([balance_sheet, income_statement])
def test_journal_entry_balance():
# Journal entry is balanced if Debit == Credit
jnl = JournalEntry(
[
JournalEntryLeg(cash_account, 50, AmountType.Debit),
JournalEntryLeg(cash_account, 50, AmountType.Debit),
JournalEntryLeg(mortgage_account, 100, AmountType.Credit),
]
)
assert jnl.is_balanced()
# Journal entry is not balanced if Debit != Credit
jnl = JournalEntry(
[
JournalEntryLeg(cash_account, 100, AmountType.Debit),
JournalEntryLeg(mortgage_account, 50, AmountType.Credit),
]
)
assert not jnl.is_balanced()
# Journal entry is not balanced even if posting negative amounts
jnl = JournalEntry(
[
JournalEntryLeg(cash_account, 100, AmountType.Debit),
JournalEntryLeg(mortgage_account, -100, AmountType.Debit),
]
)
assert not jnl.is_balanced()
# Test floating-point precision (This test should fail, just testing pytest)
jnl = JournalEntry(
[
JournalEntryLeg(cash_account, 100, AmountType.Debit),
JournalEntryLeg(mortgage_account, 99.9, AmountType.Credit),
]
)
assert jnl.is_balanced()
</code></pre>
<p>If I had to guess areas of improvement:</p>
<ul>
<li>I find the code very repetitive and verbose. It could probably be worthwhile grouping variable assignments and assertions together instead of separated by test case.</li>
<li>Set variable assignments in global variables doesn't look very too clean.</li>
</ul>
|
[] |
[
{
"body": "<p>Definitely not the most important issue, but at least for my brain, this is a\ncase where some short convenience variables -- with contextual help and a\nnarrow scope -- can really help code readability scannability. Just\nhas a nicer vibe too.</p>\n<pre><code>def get_journal_entry(*tups):\n return JournalEntry([JournalEntryLeg(*t) for t in tups])\n\ndef test_journal_entry_balance():\n ca = cash_account\n mo = mortgage_account\n d = AmountType.Debit\n c = AmountType.Credit\n\n # Journal entry is balanced if Debit == Credit\n jnl = get_journal_entry(\n (ca, 50, d),\n (ca, 50, d),\n (mo, 100, c),\n )\n assert jnl.is_balanced()\n\n # Journal entry is not balanced if Debit != Credit\n jnl = JournalEntry(\n (ca, 100, d),\n (mo, 50, d),\n )\n assert not jnl.is_balanced()\n\n # Journal entry is not balanced even if posting negative amounts\n jnl = JournalEntry(\n (ca, 100, d),\n (mo, -100, d),\n )\n assert not jnl.is_balanced()\n\n # Test floating-point precision (This test should fail, just testing pytest)\n jnl = JournalEntry(\n (ca, 100, d),\n (mo, 99.9, c),\n )\n assert jnl.is_balanced()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T03:04:15.983",
"Id": "257002",
"ParentId": "256999",
"Score": "1"
}
},
{
"body": "<p>The first thing I would point out is that currently, you have multiple test cases (or multiple asserts) inside a single test function. A major downside of this is that if any of the asserts fail, the test function will exit immediately and not run the remaining test cases, making locating and debugging failing tests all that bit harder.</p>\n<p>There are a couple of approaches to fix this:</p>\n<ol>\n<li><p>Have a separate test function for each, with the name of the function describing precisely what the test does. I typically follow the format of <code>test_<subject>_with_<something>_check_<condition></code>. For example, you could split your current code into 4 separate test functions named:</p>\n<ul>\n<li><code>test_balance_with_debit_equal_to_credit_check_balanced</code></li>\n<li><code>test_balance_with_debit_greater_than_credit_check_not_balanced</code></li>\n<li><code>test_balance_with_negative_balance_amounts_check_not_balanced</code></li>\n<li><code>test_balance_with_small_float_difference_check_not_balanced</code></li>\n</ul>\n</li>\n<li><p>Use pytest's <a href=\"https://docs.pytest.org/en/stable/parametrize.html\" rel=\"nofollow noreferrer\">parameterize</a> functionality to create sub-tests for us. I personally wouldn't use this approach for the code you have provided, I favour the more explicit result of #1 until we had many more test cases to consider.</p>\n</li>\n</ol>\n<p>As for the global variables, for the size of this, I don't think it's too bad but you might find pytest's <a href=\"https://docs.pytest.org/en/stable/fixture.html\" rel=\"nofollow noreferrer\">fixtures</a> concept useful in the future. These are useful for employing an Arrange-Act-Assert (AAA) pattern of testing[1][2] and allow you to extract common data or setup to be reused easily.</p>\n<pre class=\"lang-py prettyprint-override\"><code>@pytest.fixture\ndef cash_account():\n return Account(1, "Cash", AccountType.Asset)\n\n@pytest.fixture\ndef mortgage_account():\n return Account(2, "Mortgage", AccountType.Asset)\n\n@pytest.fixture\ndef revenue_account():\n return Account(3, "Revenues", AccountType.Asset)\n\n# name the fixtures you would like to use as parameters to the test\ndef test_balance_with_debit_equal_to_credit_check_balanced(cash_account, mortgage_account):\n journal = JournalEntry(\n [\n JournalEntryLeg(cash_account, 50, AmountType.Debit),\n JournalEntryLeg(cash_account, 50, AmountType.Debit),\n JournalEntryLeg(mortgage_account, 100, AmountType.Credit),\n ]\n )\n\n assert jnl.is_balanced()\n</code></pre>\n<p>You can also build fixtures from other fixtures like so:</p>\n<pre><code>@pytest.fixture\ndef account_charter(cash_account, mortgage_account, revenue_account):\n balance_sheet = AccountRollup([cash_account, mortgage_account])\n income_statement = AccountRollup(revenue_account)\n\n return AccountRollup([balance_sheet, income_statement])\n</code></pre>\n<p>The <code>chart_of_accounts</code> variable is unused in the example you provided so I'm not sure if this particular example is relevant but hopefully, you will find a use for the technique elsewhere.</p>\n<h3>Useful Reading</h3>\n<p>Pytest covers a bit about AAA in its fixtures documentation I linked above but I also very much liked these blog posts on the topic:</p>\n<p>[1] - <a href=\"https://jamescooke.info/arrange-act-assert-pattern-for-python-developers.html\" rel=\"nofollow noreferrer\">AAA Testing Pattern: Part 1</a></p>\n<p>[2] - <a href=\"https://jamescooke.info/aaa-part-2-extracting-arrange-code-to-make-fixtures.html\" rel=\"nofollow noreferrer\">AAA Testing Pattern: Part 2</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T21:35:54.327",
"Id": "257371",
"ParentId": "256999",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T00:24:26.063",
"Id": "256999",
"Score": "2",
"Tags": [
"python",
"unit-testing"
],
"Title": "Python unit testing"
}
|
256999
|
<p>I am working on an e-commerce website.</p>
<p>I want to track 2 events in Google Analytics (I would need to send these events to Analytics):</p>
<ol>
<li>when a buyers contacts a sellers (an email will be sent through the
website)</li>
<li>when a job seeker applies for a job (job seeker would be redirected to the employer's website)</li>
</ol>
<p>According to <a href="https://developers.google.com/analytics/devguides/collection/gtagjs/events" rel="nofollow noreferrer">Google Documentation</a>, I would need to send an event to Google Analytics using the code below:</p>
<pre><code>gtag('event', 'aaa', {
'event_category' : 'bbb',
'event_label' : 'ccc'
});
</code></pre>
<p>So basically I need to put the above code on the <code>onclick</code> event of a button/link. Also note that I only want to trigger these events in the <strong>production</strong> environment.</p>
<p>My website is implemented in ASP.NET MVC, and I want to pass the following info as <em>event name</em>, <em>event category</em> and <em>event label</em>:</p>
<ul>
<li>Event Name: <em>email_sent</em> or <em>job_redirect</em></li>
<li>Category: Category of the product (for example: <em>Sports > Team > Football</em> or <em>Jobs > IT > Programmer</em>)</li>
<li>Event label: <code>$"{BuyerName}, {SellerName}"</code></li>
</ul>
<p>The <em>Category</em>, <em>BuyerName</em> and <em>SellerName</em> are not available in the PartialView which sends the email... I could change the PartialView Model and include this info... but I though it is easier to keep this information in the <code>ViewBag</code> and include it in the Layout so any page that want to send the event, can access this info.</p>
<p>So this is what I have done in the page Layout:</p>
<p><strong>_layout.cshtml</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en-nz">
<head>
@if (EnvironmentConfig.IsProdEnvironment)
{
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-144340016-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'UA-144340016-1');
</script>
<!-- End Google Analytics -->
<meta name="ga_category" content="@ViewBag.GaCategory" />
<meta name="ga_label" content="@ViewBag.GaLabel" />
}
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title</title>
<meta name="description" content="@ViewBag.Description">
// more code...
</code></pre>
<p>Obviously I need to set the <code>ViewBag</code> in every page that displays a product or job... I have decided to do this in the 'AdBaseController'... <code>AdBase</code> is the base class for all ad types... for example 'Job', 'Car', 'House' and 'Product' are all inherited from <code>AdBase</code></p>
<p><strong>AdBaseController.cs</strong></p>
<pre><code>[Authorize]
[AllowImpersonator]
public class AdBaseController : ShoplessBaseController
{
protected void SetDisplayPageMetaData(AdBaseViewModel adBaseViewModel)
{
ViewBag.Title = adBaseViewModel.Title;
ViewBag.Description = adBaseViewModel.OgDescription;
ViewBag.Keywords = $"{adBaseViewModel.Title} {adBaseViewModel.CombinedCategoryViewModel.GetCombineCategoryName()}";
if (EnvironmentConfig.IsProdEnvironment)
{
// used for Google Analytics events
ViewBag.GaCategory = adBaseViewModel.CombinedCategoryViewModel.CategoryFullName;
ViewBag.GaLabel = $"Buyer: {GetUserEmail()}";
}
if (adBaseViewModel.CombinedCategoryViewModel.UseOgImageForAd)
{
ViewBag.OgImageCanonicalUrl = adBaseViewModel.CombinedCategoryViewModel.OgImageCanonicalUrl;
}
else if (adBaseViewModel.Photos.Any() && adBaseViewModel.Photos[0] != null)
{
ViewBag.OgImageCanonicalUrl = ShoplessUrlHelper.GetCanonicalUrl(adBaseViewModel.MainPhotoAbsolutePath);
}
}
}
</code></pre>
<p>Now when I want to display any ad types (e.g. Job, Car, House, etc) I would have to call <code>SetDisplayPageMetaData</code> in the <code>Display</code> Action method, example:</p>
<p><strong>JobController.cs</strong></p>
<pre><code>// [Authorize] <-- inherited from base
public class JobController : AdBaseController
{
private readonly AdService<Job, JobViewModel> _adService;
private readonly JobApplicationService _jobProfileService;
public JobController(AdService<Job, JobViewModel> adService, AdCommonService adCommonService, JobApplicationService jobProfileService)
: base(adCommonService)
{
_adService = adService;
_jobProfileService = jobProfileService;
}
[HttpGet]
[AllowAnonymous]
public ActionResult Display(long adBaseId)
{
JobViewModel jobViewModel = _adService.GetActiveAd(adBaseId);
if (jobViewModel != null)
{
SetDisplayPageMetaData(jobViewModel);
var jobApplicationViewModel = _jobProfileService.GetJobApplicationViewModelIfAny(adBaseId, GetUserId());
if (jobApplicationViewModel == null)
{
jobApplicationViewModel = new JobApplicationViewModel(adBaseId, GetUserFullName(), GetUserEmail());
}
SetViewBagContactModel(jobApplicationViewModel);
return View(jobViewModel);
}
return RedirectToHomeWithAlert(new AdWasNotFoundAlert());
}
}
</code></pre>
<p>So this is how I populate the <em>event category</em> and event label in all of the product display pages.</p>
<p>Now this is the partial view which displays a job... there is an Apply button that a candidate can click and he would be redirected to employer website...</p>
<p><strong>_JobDisplayApplyButton.cshtml</strong></p>
<pre><code>@model JobViewModel
@{
var userId = (((ClaimsPrincipal)User).Identity.GetUserId<long>());
}
@if (userId != Model.UserProfileViewModel.UserId)
{
if (string.IsNullOrEmpty(Model.ExternalApplicationUrl))
{
<div class="form-row">
<div class="form-group col-12">
<button id="openContactModalButton" class="btn btn-primary-action w-100" data-target="#contactModal">
<i class="fa fa-comments-o"></i>
<span>Apply</span>
</button>
@if (userId > 0)
{
// only logged in users can open the contact modal, those not logged in will be redirected to login page, this is done in communication.js
@Html.Partial("ContactModalComponents/_JobContactModal", Model)
}
</div>
</div>
}
else
{
<div class="form-row">
<div class="form-group col-12">
<!-- Note that I have decided that I don't want to put the onClick directly on the link,
but instead I want to put all the Google analytics events in a single .js file, so
not using the code below:
<a id="jobRedirectLinkId" href="@Model.ExternalApplicationUrl" class="btn btn-primary-action w-100" target="_blank"
onclick="gtag('event', 'job_redirect', {'event_category': '@ViewBag.GaCategory', 'event_label': '@ViewBag.GaLabel'});">
-->
<a id="jobRedirectLinkId" href="@Model.ExternalApplicationUrl" class="btn btn-primary-action w-100" target="_blank">
<i class="fa fa-external-link"></i>
<span>Apply</span>
</a>
</div>
</div>
}
}
</code></pre>
<p>So now when the <em>Apply</em> link is clicked, I want to send an event to Google Analytics, I have put all of this code in the file below:</p>
<p><strong>google-analytics-event.js</strong></p>
<pre><code>"use strict";
var isProdEnvironment = $('#isProdEnvironment').val();
var event_category = ''
var event_label = ''
function sendEvent(event) {
if (event_category != '' || event_label != '') {
gtag('event', event, {
'event_category': event_category,
'event_label': event_label
});
}
}
// events
// ------
function gaEventEmailSent() {
sendEvent('email_sent');
}
function gaEventJobRedirect() {
sendEvent('job_redirect');
}
// triggers
// --------
$("#jobRedirectLinkId").click(function () {
gaEventJobRedirect();
});
// initialization
// --------------
$(document).ready(function () {
if (isProdEnvironment == '1') {
event_category = $("head > meta[name='ga_category']").val();
event_label = $("head > meta[name='ga_label']").val();
}
}
});
</code></pre>
<p>And finally here is how I would trigger the <code>email_sent</code> event, this would happen when a message has been send successfully... I have a file called communication.js, in this file <code>displaySendingMessageSpinner()</code> is called when an email is being sent:</p>
<p><strong>communication.js</strong></p>
<pre><code>function displaySendingMessageSpinner() {
// in case of job application, message is optional, so we don't need to check user has entered a message
displayModalOverlay();
$('.sending-message-spinner').show();
gaEventEmailSent(); <-- track this event in Google Analytics
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T00:34:59.457",
"Id": "257000",
"Score": "0",
"Tags": [
"c#",
"javascript",
"asp.net-mvc"
],
"Title": "Clean way for sending Google Analytics events"
}
|
257000
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/255182/231235">A Paragraph Merger with Removing Overlapped Duplicated Lines in C#</a>. I am trying to implement a tester for testing the implemented paragraph merger for removing overlapped duplicated lines. The operations of this tester are:</p>
<ul>
<li><p>Generate Expected Output Paragraph Content</p>
</li>
<li><p>Separate Output Paragraph Content into Paragraph 1 and Paragraph 2 with Partial Overlapped</p>
</li>
</ul>
<p>The structure of the tester is as follows.</p>
<ul>
<li><p>Random Number Generator: For determining #line of output paragraph content</p>
</li>
<li><p>Expected Output Paragraph Content Generator: Generate Output Paragraph Content</p>
</li>
<li><p>Paragraph Content Separator: Separate Output Paragraph Content into Paragraph 1 and Paragraph 2 with Partial Overlapped</p>
</li>
</ul>
<p><img src="https://user-images.githubusercontent.com/5549662/110730645-c396b200-825b-11eb-82da-7765cf4ca61a.png" alt="MainStructureOfTester" /></p>
<p>The structure of the usage of this tester</p>
<p><img src="https://user-images.githubusercontent.com/5549662/110730819-1a03f080-825c-11eb-9c11-b48db0c6a329.png" alt="TheUsageStructureOfTester" /></p>
<p><strong>The experimental implementation</strong></p>
<pre><code>class ParagraphMergerTester
{
private static Random random = new Random();
public ParagraphMergerTester()
{
}
/// <summary>
///
/// </summary>
/// <returns>(Paragraph1, Paragraph2), Expected Output</returns>
public Tuple<Tuple<string[], string[]>, string[]> GenerateTestCase()
{
var ExpectedOutput = ExpectedOutputParagraphContentGenerator(RandomNumberGenerator(1, 100));
return new Tuple<Tuple<string[], string[]>, string[]>(ParagraphContentSeparator(ExpectedOutput), ExpectedOutput);
}
private Tuple<string[], string[]> ParagraphContentSeparator(in string[] input)
{
int separatedPoint = RandomNumberGenerator(0, input.Length);
int overlappedLines = RandomNumberGenerator(0, separatedPoint);
string[] paragraph1 = new string[separatedPoint];
for (int i = 0; i < separatedPoint; i++)
{
paragraph1[i] = input[i];
}
string[] paragraph2 = new string[input.Length - separatedPoint + overlappedLines];
for (int i = separatedPoint - overlappedLines; i < input.Length; i++)
{
paragraph2[i - (separatedPoint - overlappedLines)] = input[i];
}
return new Tuple<string[], string[]>(paragraph1, paragraph2);
}
private string[] ExpectedOutputParagraphContentGenerator(in int outputLineCount)
{
string[] output = new string[outputLineCount];
for (int i = 0; i < outputLineCount; i++)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Index: ");
stringBuilder.Append(i.ToString());
stringBuilder.Append("\t");
int RandomNumber2 = RandomNumberGenerator(1, 100);
stringBuilder.Append(RandomString(RandomNumber2));
output[i] = stringBuilder.ToString();
}
return output;
}
private int RandomNumberGenerator(in int lowerBound, in int UpperBound)
{
return random.Next(lowerBound, UpperBound);
}
/// <summary>
/// https://stackoverflow.com/a/1344242/6667035
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<ul>
<li>The part of <code>ExpectedOutputParagraphContentGenerator</code></li>
</ul>
<p>One kind of output from <code>ExpectedOutputParagraphContentGenerator</code>:</p>
<pre><code>Index: 0 E8TK39C6XT2WXLTWH71CSJNUDMQ7L9ZGEW3JUU6BOT8AWEPBSMUJ03D4U8GRS
Index: 1 VY4WSBSKCXBZX9K
Index: 2 896PO9OPQKS8YVNOSJ8JF9WOSIJ6IBFEUH9HU
Index: 3 0VJPFHSTVQJ
Index: 4 GOBAH9NS6GZSHPFOOQWG4PTMA04O59W3XV51DTAA4CHT61I0BEFE4D214YARE8W
Index: 5 U64VTOL5QWL1H9QISDN13R9T3E6OST56PK996WGX3KYH2AT5I28BU5DC6L2PS6M70PM7AQL5707T3112UBF0U4LUH6DV
Index: 6 0E680RNYW42QCE47TIFT95R0VM6D10ENZBGVBVCKOE8GNJR0QWXY7B45XFMOUJ66ZP1A7J68F5F57KNL4GW
Index: 7 CQPXHK75IYZEHB
Index: 8 8SR2H0YSC688M2ATNX13J9D2WLBZQFBY53P3NOOOO7N1JMU
Index: 9 IFLQPIH8
Index: 10 YF5Z9B64JCTNHF9INPMVLTK08RL3UIXWQNZJSYO6R69
Index: 11 BZA9MHC24NDF4F1SZCKBP674Q0Z
Index: 12 APEOTAZJQLRMG41DJUON76GOW83E1GTVRM1PIZV4QSBOV74VF3U5MM2EJ02UGURK1543CM
Index: 13 U8U7O423ZDI97VXJFUXGS7BX5A1WZCBT29A71PNJR7DR8UTYDWZIPGMX77BODFDWCZG8V0R0HNZV3UYLRCSCN
Index: 14 EWWMA4N8GL3QOJNUDNF8BBR13NIZ6BWBIKUULIZWMIHN1NFO769F7O1CF5TXWXCFY2IEY3I4XSW24D9
Index: 15 H32ACRD3SSOPZCAYGCZ9EB0DXERO28IB6CP25CCHYOVGO3
Index: 16 VS8W2O9LGDYM7
Index: 17 ZBUKNTXWH3E9RLZPTY4A664LPX60JYGZFH8NB6BJR8KES36YW1T9R6C3HI4ZW6NTWO3KMMOXXVS8VZ3W0IESEGIJEFG2BLWVV1S
Index: 18 9VLKN6M6NE
Index: 19 ROH9O15OQGTGGFVVL87N4G
Index: 20 WE64FI3L597YN4MI3ZNC6PPFE1KB8P1NKYU4S70FW4YGIQH180EXQE3GY1ZN72NPHUNZJR059
Index: 21 PC1J6XTTCILE6G4OF0IMI
Index: 22 RI8YDRSR9IXJY1PP4B3NZFEDXH55L9XX9VUTKIUBBVICRXRD806GS4ELD5A5WWFAV9JDG5EWR1MD7BVAZ16V
Index: 23 QEFQJPPHY
Index: 24 OQHRRNO6DWJZ0RAOCJAG40T7F5EW7QYP2M7XZUEWL5
Index: 25 930NXP5NFGSUY6KMWI19X747NUNYRFO497UEORRGCCTIK2J0PIRNT5FC839DCG5A2XU1MG7E1V7UNVWV
Index: 26 WJJXALD1SFUROE5HSQWHSOIKMV88VYN
Index: 27 O1P6WM1MR93ANXNQBM5
Index: 28 AN3IA8KPNFF42N
Index: 29 WZ9VFZK0
Index: 30 UH7ZIR6J2IGB8G5XCM8L39I9U01C1ZP0WKX2AVG6J6BTHBXSD7D
Index: 31 LPYV98ERZ3RD2QOYTDXQFCC77Y1TCI93VCOHW
Index: 32 3CQZGP
Index: 33 711W999KWIIN1XKGVOR3YS0BHBRJVAQ6WSA7A6DJ
Index: 34 T84F35OT55KZV0PBZP7S0ZW1M0IXMGYLI4ET65NGC0ZEFHA2U6KRF0J4LC3DW1GZH8Q1V5E4B1PA9SWFZPCQ5GGRVKI3BKTLTA
Index: 35 G0JGZ1QQOKI42QYNHY03A29GLWK21HER8VPOQIMZP02HMPPNN6MW3H6O1D5CQXYGG15HAK78MBNKA136H7P44RX1ZAX
Index: 36 NKI2BVBUTIMD8NK24WO9J95TI4MYDESAWUVB
Index: 37 UIP0JM9UL5RH57CWXDOPZUHJMQOZMQO2I9JO9I9W59684RIHPN9QHWCAAFN27JH5RZ85YYXOD1T0YJ
Index: 38 5IHJ9Q7VV7IN34HZV1AQFSMS10UMPDLM11STZ9IO
Index: 39 DM8PL3T6C78X2IN6YSI6UFSV5VCMX9VTW7BFNDP6BQNGNZ9SEXAR9S
Index: 40 84MTZ1GJDLPB4GHSVCM4E2MIGWTHA8EUD8DLAT0E4HJ47YEL7EOOXX3FSENDI9JEG576D6SCMHA7SRKSSHK5T06PE736FX6
Index: 41 8FXC0HIAWMBPW6XA35UAYNVQ8R1FCV6ZLF9N3H1K9JJHYR3IK3CKC5GUTHEIQC7APMDQ6JGWDKBOEN1QYS5JTW
Index: 42 Q9P3WDS37LI2MOMLAWQH242QGPYU8GYQ3ZXRRPUSUQDC5VPCMG4XDP4VG9XGP850
Index: 43 29X044VC7WL0ZUUAVI1MANO4BLS2NDWVNODW2LRMJUG2S5QOCG30DOWPV2ZSL2Z3A0
Index: 44 KR8HK0PCQGVLF4EZGK5R91XB9W9AR5M11SF
Index: 45 E9TAXLGI9QTYHCSTFJNT36HX1PVU34UXYGVH053XVPCTCK2OM3WSFWDH15JI0VOF669ARL2JPZ7O4YVQWHI9HBRBDNQ5
Index: 46 U79A6WGK16ABMDQZZMCK2WTNP74P87D57X418O7CPG4KH848BMOBNV38OVV91
Index: 47 M42FEZIY0LOA4W2IGQD6NVTCRM46NM28KY39SC4F0MVCWN0GFFPE65M0KZX24MKOSQZG220DW7G
Index: 48 9QQE
Index: 49 X0H6YCPLCZ2OCKNCHUFXUNNPLS8YL14JSGHVCR4NK40D7ZUW2916KQBJM2VF
Index: 50 09L4T55D2900
Index: 51 NZXKRW8L6M988CE7JK6YJT5OIO3YTAAAFSCMVCK8H24XM6V30FSY4BS43JBD3J25M82PA2MGA7RRZI
Index: 52 M397OR
Index: 53 GDAISMAGE7A8KNEF383MX7UBEVHZK3MNO
Index: 54 2Y
Index: 55 1J9F43TQ07YIXG9UFYJT8D7FL5KVWUJVP0BY4G3DAUO
Index: 56 SRXXM3JMSFQYM448S84GXC26FL084FSOZJW3IXJ2L7CJJMM9M4VC0HAQY0RACLRNXC
Index: 57 CHA04ZB509SW290VAUPXRJFERGI09QZWHNJ2ME0MYMKQGDZBMZR3HOS3B5IYRL5KK6PO08J53C9F8Z8NQGNK85P35P0Q5C5NQA
Index: 58 JYKLNQVAEPM5M64HK7
Index: 59 LOQVTLI2A0HVY8SYZG4A4N5KOSTNUA4VP5Z13C0AFXUJ73X64HFBP707TF
Index: 60 A15I96VF3J05WP44G2VNU4
Index: 61 TM53FSE1IX50JKPVNLX4XDLTVVCTE72WGDL5EDQXYRSI1ZUU1HIC7AAPALHUPUXK4
Index: 62 UF8TRJ49GFUD26AS27Y0ZFD
Index: 63 4266ID4HNSFPWHZ9H74457TKT72ZVESOCCYZN81CLMZJ1V6UHZS2LIA7JVMKLEWIA1NTTAVIF1TSHJT8BHS6W0C3
Index: 64 0P1VQ0G
Index: 65 RJ9IMBHDJWTZR09COJDWZWJYTR2U4XZBN20AT0YGK2MESEUAQYHGWTA4ALY5IWJW6SLZA8SXV7
Index: 66 7KEGP61DFPSO315AIB37YSZHA25ASFUVZ
Index: 67 DU5EJ8RSEHODS8E8KV19XO
Index: 68 6FWB1V956ZVYKED24QFOS36K65U584ZUY989W707EMSO6K33G27SSACDJ
Index: 69 E5BD6C9B9LFEG70HJGLSNWB0YF6GBX75ZJ24
Index: 70 APPO5KSXCW92L06219S3KP1F29LNKO7F5LI05DRLTDWT7O07AD8JJBVVYKW58EMXZ469RF6XSGKH3IHNJOMHQX540
Index: 71 CURVMO083DS1P5GK1D0N2QCIWU1FHB8BI4DLG636R4OE5S8RAF62DM4WSI92WU02
Index: 72 QSU24D4J467B7M
Index: 73 VKFCFF85AQ3
Index: 74 6BK6DW9PANZFBBSIQ6UU65GLPYW9RWULBG8IU94P86DIU9AEXZPD6JBB48RP9A7O2OE5DKYRCEW9181PXSL2GRO1E6NWR
Index: 75 P79ZPG5FAMB7A1XBJ6GC1RYFHL9M0G6BAYYYACSU
Index: 76 SR90JQXEDXQPPW8I4SEGSO4Q97MC8BGNVSJ9ZO84MIXTPVUB0QFUOOCD
Index: 77 S1LEUGBQC47N8SPUJ4J0LAOMLMR5W9HPFMGXW01CWCN1XX180AFT2NMSM92IYF3D
Index: 78 RIWL27TCHEIXWYXUTFW3XX2AYKX7TNQJJEGPEW7CVRUID50KFXE9HJ93QWXSKVS
Index: 79 Y9NRSHP7ITHFCT62UM16JQB9FN9S9P2A81UERI18HH1YB306Z4774WUH7OMFH7731HGL92LLU3YBZN7MWD
Index: 80 ER4FMHNGC6W0KJ863WP67TVMA7SRUR9TEE3L7C4EWVIP8DO11QD0GG5U5RFOY5VV6DWGQW911LKLLGO7T
Index: 81 0ENJM7IIQP7PQ0AWS4QILEQL846UJZCH56FQHX0Y8HGT4M5TLYXTQLQVXCKRBY81MZTTVTO4D2KD
Index: 82 7QW9MIUBS0UQT3FNIXJIOGE2M82K2PYAMW0VYSYPOZ399CBZJR5FA4U0M3WOPKIDCTD7CUY0844YMF3J6CALUSASCAJ45K9D
Index: 83 06P9EXY2EHG95NGANRNJ7STSV4CL34X41HWJNK1PMSQL4SGWC
Index: 84 S3W3UIM6OKUN8KUMIY16XCZ77OCIYCXPI9M4H7WN6Q6R49TF0SKS5GHPDY6FGDILWFE970EKBOAGGID846SG1
Index: 85 TC160SBRG2HU4Z
Index: 86 UIAN9RRFAJ4V7KKVBURVCHB9VJUHH8VNNDKXR22XC61X67DG6HGAMD2MGA1Z6J8BXQH49WDJ24SFQNDYGOLA2
Index: 87 BKL8QQBC028ZAPZJGJD7HSVX537CTS87JBP7TBFWHZD0G1MY97HC75NSZYDX
</code></pre>
<ul>
<li>The usage of <code>ParagraphMergerTester</code> class</li>
</ul>
<pre><code>ParagraphMergerTester paragraphMergerTester = new ParagraphMergerTester();
for (int testCaseCount = 0; testCaseCount < 10; testCaseCount++)
{
var TestContents = paragraphMergerTester.GenerateTestCase();
Console.WriteLine("Paragraph 1:");
Console.WriteLine();
for (int i = 0; i < TestContents.Item1.Item1.Length; i++)
{
Console.WriteLine(TestContents.Item1.Item1[i]);
}
Console.WriteLine();
Console.WriteLine("Paragraph 2:");
Console.WriteLine();
for (int i = 0; i < TestContents.Item1.Item2.Length; i++)
{
Console.WriteLine(TestContents.Item1.Item2[i]);
}
Console.WriteLine();
Console.WriteLine("Expect Output:");
Console.WriteLine();
for (int i = 0; i < TestContents.Item2.Length; i++)
{
Console.WriteLine(TestContents.Item2[i]);
}
Console.WriteLine();
}
</code></pre>
<p>A kind of output of the above test code.</p>
<pre><code>Paragraph 1:
Index: 0 XW6CKDX9LGIE9HPWBHSX0ANLWJSOVIOWBTN
Index: 1 GTR51CCG23AOA239GWVXIVPBVIOC2VCP31PS0X5Y7HS3IDO2OOQO80OVDQJTYAOH0
Index: 2 UIMLJT07ZBCV2R4VXNFXRDM4OKOMA72LCWTFPDF6XAANSRX1YCMABCER5S78
Index: 3 O72I0TF8YGUHIA
Index: 4 C9L6WWX7U1KASBJ6GH2JDIE18R296232CXP6HBLR0AHQQS
Index: 5 6PJOAQ0N34T7E4YA28R75WMZE5KTCAXLQ56UXO2LMKVBXDGXB9PS8U1KCTJEGGK
Index: 6 HIRJ8DNNGGVVALCBYWRDUFM5DVRDEXEG924PW6Z8WBL29GJ1RIQUYHIB6VGMVJISBPVIRXO16TRS3T67L
Index: 7 W6HUR2T2TB0NMM330TUBK43YXEZZHMZIA5WMLR73YYDNBTHFZA3MMKQ2CT6MC4VHLRMQZQSIW1
Index: 8 W0QWE7U9HSN60P4J1UU04D6BTH0PIRU0V84
Index: 9 W62PS5N
Index: 10 8VWB5H0YBAST3PD7GE0Z8WK1U1X52FI8ZID7UYUB06ZUPLIG25JNEX0LK4RDU5562T3
Index: 11 MFMRUZ8B70MJTQC6654BS1X0HRR5A226RX4XT13OYYNUSHUD39A6Y1CUSWK
Index: 12 IDBE7P15
Index: 13 PNFCPN4NCI97NCA26H0UJE7Q0GVWIXCQYRNW54JOIHPNKF4BAMBIBKLKQYLJ1
Index: 14 EPFTI5YO7B8LMCZTFULUV6
Index: 15 3PNFDGGT9WBC9H169MVO9KZ8JU6S17HVI3LE40UI0S8YLAZLOXMH9SWTZP6SJY
Index: 16 CPP4G6XBI2NXRLAXI4VEDU9V0H2OP3B8C05J5GTP1WDPW4EIY1YYYUYRP3D9EIWP0OU1P11BLFMQRU
Index: 17 5CT0XFNKSBO3CCULT9YZHJM27AWNSHIA53I6UR8KMEC0B8Z9043R251V013XTA1L2O8I4Y1BBOMDHV19KWWYO0H9CWF3YK0MM0
Index: 18 W9QFCD1POTYNE94M6ND6BG8GHS8M0X90QXE93RUUWL3QNIB34748I45QAK8TFPZ0T77Q54TP3SK0NS28RER23BRW1Y8TTA
Index: 19 GVC7PLU79OPF0TFCSR9CA777SPKZG5953CDFLVNW7GRN
Index: 20 51DWVQBT7PJYEO9B50EPTMXPA07EMF3PTTWYGCV
Index: 21 7M5X4QHGNVBQN84TEXW5T7H1W3FU2L42FYRHQAUTT01
Index: 22 DNCVYDUSPZ6AFDABLWOB0JKZRXCDCDL2GPXJ1T5Z1LNQ2QCM9TI7MZB4DMDBAQQMOE4ZP1J10ZKO6
Paragraph 2:
Index: 16 CPP4G6XBI2NXRLAXI4VEDU9V0H2OP3B8C05J5GTP1WDPW4EIY1YYYUYRP3D9EIWP0OU1P11BLFMQRU
Index: 17 5CT0XFNKSBO3CCULT9YZHJM27AWNSHIA53I6UR8KMEC0B8Z9043R251V013XTA1L2O8I4Y1BBOMDHV19KWWYO0H9CWF3YK0MM0
Index: 18 W9QFCD1POTYNE94M6ND6BG8GHS8M0X90QXE93RUUWL3QNIB34748I45QAK8TFPZ0T77Q54TP3SK0NS28RER23BRW1Y8TTA
Index: 19 GVC7PLU79OPF0TFCSR9CA777SPKZG5953CDFLVNW7GRN
Index: 20 51DWVQBT7PJYEO9B50EPTMXPA07EMF3PTTWYGCV
Index: 21 7M5X4QHGNVBQN84TEXW5T7H1W3FU2L42FYRHQAUTT01
Index: 22 DNCVYDUSPZ6AFDABLWOB0JKZRXCDCDL2GPXJ1T5Z1LNQ2QCM9TI7MZB4DMDBAQQMOE4ZP1J10ZKO6
Index: 23 7AVZET4NPQN3FOQ4YL5ABXWM7HJRHXPX8JPDPKL7RAZNLWV5L5A9S52JOJ27JNG1B0468MON98SB8IAKVOF
Index: 24 XQFCQGYGSOXE37MV1Z68QW9TN1KGIRL5
Index: 25 5DUV1P2YI5VKOHA5PT6RH
Index: 26 AQVZZ5S8AC2684199JEJI1OI8UJL38PN9ADEAC06GK5SSRIGDPTXM7WJBM0FWHFBXO680X97SID8560RLDHNP
Index: 27 ACN3CXLUK9E35DUJPQQVEE4XNFWJ3S91W4N4U7UMW78E3BAW7BX173X6HZP6BB019MHAZZZS5E8GF0
Expect Output:
Index: 0 XW6CKDX9LGIE9HPWBHSX0ANLWJSOVIOWBTN
Index: 1 GTR51CCG23AOA239GWVXIVPBVIOC2VCP31PS0X5Y7HS3IDO2OOQO80OVDQJTYAOH0
Index: 2 UIMLJT07ZBCV2R4VXNFXRDM4OKOMA72LCWTFPDF6XAANSRX1YCMABCER5S78
Index: 3 O72I0TF8YGUHIA
Index: 4 C9L6WWX7U1KASBJ6GH2JDIE18R296232CXP6HBLR0AHQQS
Index: 5 6PJOAQ0N34T7E4YA28R75WMZE5KTCAXLQ56UXO2LMKVBXDGXB9PS8U1KCTJEGGK
Index: 6 HIRJ8DNNGGVVALCBYWRDUFM5DVRDEXEG924PW6Z8WBL29GJ1RIQUYHIB6VGMVJISBPVIRXO16TRS3T67L
Index: 7 W6HUR2T2TB0NMM330TUBK43YXEZZHMZIA5WMLR73YYDNBTHFZA3MMKQ2CT6MC4VHLRMQZQSIW1
Index: 8 W0QWE7U9HSN60P4J1UU04D6BTH0PIRU0V84
Index: 9 W62PS5N
Index: 10 8VWB5H0YBAST3PD7GE0Z8WK1U1X52FI8ZID7UYUB06ZUPLIG25JNEX0LK4RDU5562T3
Index: 11 MFMRUZ8B70MJTQC6654BS1X0HRR5A226RX4XT13OYYNUSHUD39A6Y1CUSWK
Index: 12 IDBE7P15
Index: 13 PNFCPN4NCI97NCA26H0UJE7Q0GVWIXCQYRNW54JOIHPNKF4BAMBIBKLKQYLJ1
Index: 14 EPFTI5YO7B8LMCZTFULUV6
Index: 15 3PNFDGGT9WBC9H169MVO9KZ8JU6S17HVI3LE40UI0S8YLAZLOXMH9SWTZP6SJY
Index: 16 CPP4G6XBI2NXRLAXI4VEDU9V0H2OP3B8C05J5GTP1WDPW4EIY1YYYUYRP3D9EIWP0OU1P11BLFMQRU
Index: 17 5CT0XFNKSBO3CCULT9YZHJM27AWNSHIA53I6UR8KMEC0B8Z9043R251V013XTA1L2O8I4Y1BBOMDHV19KWWYO0H9CWF3YK0MM0
Index: 18 W9QFCD1POTYNE94M6ND6BG8GHS8M0X90QXE93RUUWL3QNIB34748I45QAK8TFPZ0T77Q54TP3SK0NS28RER23BRW1Y8TTA
Index: 19 GVC7PLU79OPF0TFCSR9CA777SPKZG5953CDFLVNW7GRN
Index: 20 51DWVQBT7PJYEO9B50EPTMXPA07EMF3PTTWYGCV
Index: 21 7M5X4QHGNVBQN84TEXW5T7H1W3FU2L42FYRHQAUTT01
Index: 22 DNCVYDUSPZ6AFDABLWOB0JKZRXCDCDL2GPXJ1T5Z1LNQ2QCM9TI7MZB4DMDBAQQMOE4ZP1J10ZKO6
Index: 23 7AVZET4NPQN3FOQ4YL5ABXWM7HJRHXPX8JPDPKL7RAZNLWV5L5A9S52JOJ27JNG1B0468MON98SB8IAKVOF
Index: 24 XQFCQGYGSOXE37MV1Z68QW9TN1KGIRL5
Index: 25 5DUV1P2YI5VKOHA5PT6RH
Index: 26 AQVZZ5S8AC2684199JEJI1OI8UJL38PN9ADEAC06GK5SSRIGDPTXM7WJBM0FWHFBXO680X97SID8560RLDHNP
Index: 27 ACN3CXLUK9E35DUJPQQVEE4XNFWJ3S91W4N4U7UMW78E3BAW7BX173X6HZP6BB019MHAZZZS5E8GF0
Paragraph 1:
Index: 0 M25I42GRW4RYKUGHEQ4A7HME534R0R5D1CZ851SP3IC4BH3O98WNSFCEP1MB7Z0F9N6I4ILN8OGYESCY9QR15SVW9VSEOQRDR7
Index: 1 XKUT1XIPD8NA7YYBQI9KQ2KIJZH9R6CHHWPOP7ZEWCRXWUVPZPA5SWO4AMJCPJ7G6F2KJJWTT4YOKWVZE1JC6H
Index: 2 UIUOCYXYMFL1R2KGP2RMX8ATN0U8XA5KYQICY5T56FLJ94E63V3JP5BVIAAMDYALJACAUI
Index: 3 UIVQSX1USVXECHW53OW3Y5H1HE9982EMVDJA3OT8RQR1QU8EX
Index: 4 IV8O3YB4JNX1V0RK
Index: 5 98VCO5XLINPKWG5M3TSOGKU88FFL041JFB8FBD30KCVLWTWH2O2H
Index: 6 6LZOWDJZMVNWFEUHZKZZ1DEZIMPT8SLCUKJ0J1OAUA8RHZQOB9CDCRH2HAFKXZ13KKB554786ZF1FWRT6AS9QH9CDRSJVEM5I
Index: 7 G7XVTGBEHNMPXUS
Index: 8 OWH2NCL81NMXM1MJS9PU6KRL7MAW0X470A0ZXQ2EVY3G4N1PAC7XE8ZDF64A
Index: 9 ZIETP7M
Index: 10 XWCHL8
Index: 11 QLRTUUVY0H22KWT1V1C6QZ
Index: 12 PQPNNP4P3ARW4PLPRDTNMWEBPD5QQJB11YBCFHHI519129ZLKLU26LK2LN8KUO9U
Paragraph 2:
Index: 12 PQPNNP4P3ARW4PLPRDTNMWEBPD5QQJB11YBCFHHI519129ZLKLU26LK2LN8KUO9U
Index: 13 04GNIKK6LSUXNJPOTGEYI4QNJ12J7YR1O2CET8BBK6V20F8ES6AH4505O3ERRB8XB2IUHK5UECNMJXWD2Y0BXJ6SBG004UTJ7
Index: 14 176N7HBQC2SOW1GAY3K7915ZSAUE0TSEOL5ZGO1TAGGEAXU8T4609A8ACH46W6ZTJN9K5Q3JB072U0Y5QVV6X1FON5X9U5
Expect Output:
Index: 0 M25I42GRW4RYKUGHEQ4A7HME534R0R5D1CZ851SP3IC4BH3O98WNSFCEP1MB7Z0F9N6I4ILN8OGYESCY9QR15SVW9VSEOQRDR7
Index: 1 XKUT1XIPD8NA7YYBQI9KQ2KIJZH9R6CHHWPOP7ZEWCRXWUVPZPA5SWO4AMJCPJ7G6F2KJJWTT4YOKWVZE1JC6H
Index: 2 UIUOCYXYMFL1R2KGP2RMX8ATN0U8XA5KYQICY5T56FLJ94E63V3JP5BVIAAMDYALJACAUI
Index: 3 UIVQSX1USVXECHW53OW3Y5H1HE9982EMVDJA3OT8RQR1QU8EX
Index: 4 IV8O3YB4JNX1V0RK
Index: 5 98VCO5XLINPKWG5M3TSOGKU88FFL041JFB8FBD30KCVLWTWH2O2H
Index: 6 6LZOWDJZMVNWFEUHZKZZ1DEZIMPT8SLCUKJ0J1OAUA8RHZQOB9CDCRH2HAFKXZ13KKB554786ZF1FWRT6AS9QH9CDRSJVEM5I
Index: 7 G7XVTGBEHNMPXUS
Index: 8 OWH2NCL81NMXM1MJS9PU6KRL7MAW0X470A0ZXQ2EVY3G4N1PAC7XE8ZDF64A
Index: 9 ZIETP7M
Index: 10 XWCHL8
Index: 11 QLRTUUVY0H22KWT1V1C6QZ
Index: 12 PQPNNP4P3ARW4PLPRDTNMWEBPD5QQJB11YBCFHHI519129ZLKLU26LK2LN8KUO9U
Index: 13 04GNIKK6LSUXNJPOTGEYI4QNJ12J7YR1O2CET8BBK6V20F8ES6AH4505O3ERRB8XB2IUHK5UECNMJXWD2Y0BXJ6SBG004UTJ7
Index: 14 176N7HBQC2SOW1GAY3K7915ZSAUE0TSEOL5ZGO1TAGGEAXU8T4609A8ACH46W6ZTJN9K5Q3JB072U0Y5QVV6X1FON5X9U5
Paragraph 1:
Index: 0 5XXJDCAWZIDFQLS9QAL35RIV7A33ZG32L64BHGSS5BC6LIOLRUO63X2OPCMDJG6TOK
Index: 1 TQQ1JS373OLKZVRME179YEQWE4PIZETSBP55A2FOAZ8AD2XR1411RKEPA4XPCUIZ42JK0WMMWT99FPSMG
Index: 2 R5M2B0KP5FFZLPQJFKTN1ERPE7LFJULKJECNMC1S9K1GG7HTS6KI23GMN7XDPFFK44QHNC7CSANQNLJH01WNJDRP70AOPY
Index: 3 4EQMLQAGQ9
Index: 4 Z2P08BXPMXS2B0NAJWCSW47
Index: 5 L79800VGOBOZAH1819LQLMPV8Q1TNQV445OBCZYWCMO9MX9B4D1WSQ
Index: 6 9ROAJ9B27PT4E306BLZO97
Index: 7 JKRZYKZ8LNYOUYZOXATQT224IEGZL3CIBBEZ2JMSHRIQ
Index: 8 OFIM6BNPQ5RSWQTDAWSKPNSTAWNYBJCTLO498MP1Z2UFXG
Index: 9 32OG4ZFABXZMJYZOH2
Index: 10 GIWUFXH0VX2M53QU5XCI4FN3LIAFDAONM0A7HHITW9UNIL3S3D30FUDA52J6XBXUIP9F3SNXPTV4VAUAPSL9HXI2X9CO
Index: 11 L6VM9E3LYZL0FLV8IP4HJRFZXNVGGR3P8ZDXASV50Y02AIBMW4OUHGY415YWTWFG551PH88039QV0MZOLIUMDJH1BJ6E38
Index: 12 DSU6EQWEY5Y0IZDDOGKLKC2DWYAO8C475WN
Index: 13 GPV7ZD6
Index: 14 OS9C8FR7SXBB0QKQQHGVB15WMA79VMVHGLYDY7Q2U6OHULM
Index: 15 FEQR7KPXXMZ7ISMFB44O2G1T1NBFMYBAYI3Q6EJ56BQMITUCUIF0Q769N7ZTJJK9LYI9Y5
Index: 16 7U8S0ZPKI38VESLU0L4D8O0WW0
Index: 17 AUKUNY9IFSPGJ8WR0KYFQ9ERY31KS4M59IO07JV6FJGBLFVF
Index: 18 7AL7VABP25T6Y0LFUGAT6TRZ2AH3CGSIW8
Index: 19 3A7OIMLFNB9QT5619UVPNTVFU3INWNLJ0FREW12HVODY2TY7GPTXBSGKP2
Paragraph 2:
Index: 7 JKRZYKZ8LNYOUYZOXATQT224IEGZL3CIBBEZ2JMSHRIQ
Index: 8 OFIM6BNPQ5RSWQTDAWSKPNSTAWNYBJCTLO498MP1Z2UFXG
Index: 9 32OG4ZFABXZMJYZOH2
Index: 10 GIWUFXH0VX2M53QU5XCI4FN3LIAFDAONM0A7HHITW9UNIL3S3D30FUDA52J6XBXUIP9F3SNXPTV4VAUAPSL9HXI2X9CO
Index: 11 L6VM9E3LYZL0FLV8IP4HJRFZXNVGGR3P8ZDXASV50Y02AIBMW4OUHGY415YWTWFG551PH88039QV0MZOLIUMDJH1BJ6E38
Index: 12 DSU6EQWEY5Y0IZDDOGKLKC2DWYAO8C475WN
Index: 13 GPV7ZD6
Index: 14 OS9C8FR7SXBB0QKQQHGVB15WMA79VMVHGLYDY7Q2U6OHULM
Index: 15 FEQR7KPXXMZ7ISMFB44O2G1T1NBFMYBAYI3Q6EJ56BQMITUCUIF0Q769N7ZTJJK9LYI9Y5
Index: 16 7U8S0ZPKI38VESLU0L4D8O0WW0
Index: 17 AUKUNY9IFSPGJ8WR0KYFQ9ERY31KS4M59IO07JV6FJGBLFVF
Index: 18 7AL7VABP25T6Y0LFUGAT6TRZ2AH3CGSIW8
Index: 19 3A7OIMLFNB9QT5619UVPNTVFU3INWNLJ0FREW12HVODY2TY7GPTXBSGKP2
Index: 20 PE7SA0Z0NN1EH1O49P7NAEKGG3XIH8GZ46NCX5D8C3KUOKL5WYH5SP3K31LGCRTPGCKKOLHEL8KH4026R1VT
Index: 21 LHPDDI6T75VK4NMAARLQDTTEWPD8PYL59Y544HKCLUNCY79MQ5RJKCY1YKRYF7DIU0KGRRF2HIF
Index: 22 FQQYP0SUHBU79DGU0V7NQFS8W2580YCC6FVH42IOOTBTGNGNLUC
Index: 23 K2BA8SBW5U4T9RA4S808NT86E81JVRXFVQ2EDVJM0WT4ZSTYNM5M4EI13E69
Index: 24 2AO6Y7SZ506ZOI0ADHVPD6JVLKRIAL8YJV7VE7AUA9SW8WQ5R1Z7KUX612VOPKZT1IP2KE5GG
Index: 25 OENX
Index: 26 Y4V0JVANZ8B4LMWF0K840GXVM6T1JFTSEG6U3UP80404JKT3T6Y3P25SGANMCJ
Index: 27 TOS0FPBLG4AD6Q
Index: 28 MCMZHMRZDLKOO3GD6RZGP0UONRUR9OY9CMYL9MB1BZPO4BXS90EWGJOVS8MZ29ZYXLMBE5DTQ7EZLFTM4
Index: 29 SIKC228C
Index: 30 B9L9CA01TZWNDXUGIFYJNP95ZRQNVSTCCDCTE7CZVNAWIZOV05TWK3PVAPKUTMGAFTLAVABLD8Y9ONX
Index: 31 C
Index: 32 XZ872IXQTZXRFIH9RYOO9Z4ITLEQHX2KSYZQCI1CNFQMXV2Q1P58WX575ZNQEHJ66N8RT07J7LB4JRV7SYY114
Index: 33 431VM4K8F5TQKXL6ARWAKWAYOEQ7PSRFCYDY1FUOWN58ZBKKH1YKE3NH2CHIOMSXOON
Index: 34 TXF56HN71B8M3F0X4HAJK55Y8MAJ4IULXZ1TW2N7PQQ0E4OIW52HNEKX1Q6U
Index: 35 ECSRXYEOGBB3D44PEUD7
Index: 36 X9PM8TOD1F630LN7IQGK4P30NJJQIX62WPQDDEZEZKP5FANTQR6E7X7HFY9YK75EJDGK4K4D1BUTA
Index: 37 VM60900248RI8OFB41PKWB3CYGW2N6COHHDW2T7ENRJI3VLQ8ZG2DZLUS3C3D8P86CB0LSIL3K6F2VIC4G3XZJKS6SE8RE
Index: 38 PCK
Index: 39 1UVFPQ5832G26U997E1IW1T42OK4ZJRDR
Index: 40 RSJBOG4LRZ00HNRFDKKCZAB1MBGB
Index: 41 UKCKWDRZ60VOLJ3DCG6MUFH2PU
Index: 42 QSYM92B7OXPUKAPHTYYO0IXK4KYYODJ5BWBHHNWVJMPQXVW
Index: 43 E7XE0G0I4OSZDMSLNTSX9HAGBCFN3GXIXM
Index: 44 QPFF552M256R63DDDC8M67RCYBMPY1JB02C5IOX2G4HKEVIUZDTFZAXT
Index: 45 CQ4TNYAV50D1H5ZPGGCZH7C22ZVIDL0FS8F73I2GGYJ4F2RI40T3V30FOB0YD2RT98IJZ1W7O6SSYHX9HNNN27UZHAT1S
Index: 46 COGZ5GTISCEV
Expect Output:
Index: 0 5XXJDCAWZIDFQLS9QAL35RIV7A33ZG32L64BHGSS5BC6LIOLRUO63X2OPCMDJG6TOK
Index: 1 TQQ1JS373OLKZVRME179YEQWE4PIZETSBP55A2FOAZ8AD2XR1411RKEPA4XPCUIZ42JK0WMMWT99FPSMG
Index: 2 R5M2B0KP5FFZLPQJFKTN1ERPE7LFJULKJECNMC1S9K1GG7HTS6KI23GMN7XDPFFK44QHNC7CSANQNLJH01WNJDRP70AOPY
Index: 3 4EQMLQAGQ9
Index: 4 Z2P08BXPMXS2B0NAJWCSW47
Index: 5 L79800VGOBOZAH1819LQLMPV8Q1TNQV445OBCZYWCMO9MX9B4D1WSQ
Index: 6 9ROAJ9B27PT4E306BLZO97
Index: 7 JKRZYKZ8LNYOUYZOXATQT224IEGZL3CIBBEZ2JMSHRIQ
Index: 8 OFIM6BNPQ5RSWQTDAWSKPNSTAWNYBJCTLO498MP1Z2UFXG
Index: 9 32OG4ZFABXZMJYZOH2
Index: 10 GIWUFXH0VX2M53QU5XCI4FN3LIAFDAONM0A7HHITW9UNIL3S3D30FUDA52J6XBXUIP9F3SNXPTV4VAUAPSL9HXI2X9CO
Index: 11 L6VM9E3LYZL0FLV8IP4HJRFZXNVGGR3P8ZDXASV50Y02AIBMW4OUHGY415YWTWFG551PH88039QV0MZOLIUMDJH1BJ6E38
Index: 12 DSU6EQWEY5Y0IZDDOGKLKC2DWYAO8C475WN
Index: 13 GPV7ZD6
Index: 14 OS9C8FR7SXBB0QKQQHGVB15WMA79VMVHGLYDY7Q2U6OHULM
Index: 15 FEQR7KPXXMZ7ISMFB44O2G1T1NBFMYBAYI3Q6EJ56BQMITUCUIF0Q769N7ZTJJK9LYI9Y5
Index: 16 7U8S0ZPKI38VESLU0L4D8O0WW0
Index: 17 AUKUNY9IFSPGJ8WR0KYFQ9ERY31KS4M59IO07JV6FJGBLFVF
Index: 18 7AL7VABP25T6Y0LFUGAT6TRZ2AH3CGSIW8
Index: 19 3A7OIMLFNB9QT5619UVPNTVFU3INWNLJ0FREW12HVODY2TY7GPTXBSGKP2
Index: 20 PE7SA0Z0NN1EH1O49P7NAEKGG3XIH8GZ46NCX5D8C3KUOKL5WYH5SP3K31LGCRTPGCKKOLHEL8KH4026R1VT
Index: 21 LHPDDI6T75VK4NMAARLQDTTEWPD8PYL59Y544HKCLUNCY79MQ5RJKCY1YKRYF7DIU0KGRRF2HIF
Index: 22 FQQYP0SUHBU79DGU0V7NQFS8W2580YCC6FVH42IOOTBTGNGNLUC
Index: 23 K2BA8SBW5U4T9RA4S808NT86E81JVRXFVQ2EDVJM0WT4ZSTYNM5M4EI13E69
Index: 24 2AO6Y7SZ506ZOI0ADHVPD6JVLKRIAL8YJV7VE7AUA9SW8WQ5R1Z7KUX612VOPKZT1IP2KE5GG
Index: 25 OENX
Index: 26 Y4V0JVANZ8B4LMWF0K840GXVM6T1JFTSEG6U3UP80404JKT3T6Y3P25SGANMCJ
Index: 27 TOS0FPBLG4AD6Q
Index: 28 MCMZHMRZDLKOO3GD6RZGP0UONRUR9OY9CMYL9MB1BZPO4BXS90EWGJOVS8MZ29ZYXLMBE5DTQ7EZLFTM4
Index: 29 SIKC228C
Index: 30 B9L9CA01TZWNDXUGIFYJNP95ZRQNVSTCCDCTE7CZVNAWIZOV05TWK3PVAPKUTMGAFTLAVABLD8Y9ONX
Index: 31 C
Index: 32 XZ872IXQTZXRFIH9RYOO9Z4ITLEQHX2KSYZQCI1CNFQMXV2Q1P58WX575ZNQEHJ66N8RT07J7LB4JRV7SYY114
Index: 33 431VM4K8F5TQKXL6ARWAKWAYOEQ7PSRFCYDY1FUOWN58ZBKKH1YKE3NH2CHIOMSXOON
Index: 34 TXF56HN71B8M3F0X4HAJK55Y8MAJ4IULXZ1TW2N7PQQ0E4OIW52HNEKX1Q6U
Index: 35 ECSRXYEOGBB3D44PEUD7
Index: 36 X9PM8TOD1F630LN7IQGK4P30NJJQIX62WPQDDEZEZKP5FANTQR6E7X7HFY9YK75EJDGK4K4D1BUTA
Index: 37 VM60900248RI8OFB41PKWB3CYGW2N6COHHDW2T7ENRJI3VLQ8ZG2DZLUS3C3D8P86CB0LSIL3K6F2VIC4G3XZJKS6SE8RE
Index: 38 PCK
Index: 39 1UVFPQ5832G26U997E1IW1T42OK4ZJRDR
Index: 40 RSJBOG4LRZ00HNRFDKKCZAB1MBGB
Index: 41 UKCKWDRZ60VOLJ3DCG6MUFH2PU
Index: 42 QSYM92B7OXPUKAPHTYYO0IXK4KYYODJ5BWBHHNWVJMPQXVW
Index: 43 E7XE0G0I4OSZDMSLNTSX9HAGBCFN3GXIXM
Index: 44 QPFF552M256R63DDDC8M67RCYBMPY1JB02C5IOX2G4HKEVIUZDTFZAXT
Index: 45 CQ4TNYAV50D1H5ZPGGCZH7C22ZVIDL0FS8F73I2GGYJ4F2RI40T3V30FOB0YD2RT98IJZ1W7O6SSYHX9HNNN27UZHAT1S
Index: 46 COGZ5GTISCEV
Paragraph 1:
Paragraph 2:
Index: 0 QGO0Q0OE1COTBZI4PJ3EL8M
Index: 1 Q85LJGR5N9TNN1XM9C8229G24JGF5G6S37KR5D4UUTGCG5
Index: 2 YWQFIATXQ2CR9AL9HCATPQFR5INIJ3EV82RTPBYSJJ3Z2W4
Index: 3 IT8AFLBHQ9JAWLOXXQSHS2UFOSJGXPYJN39Z4EQX1KCQ1X585GCLDXBQ
Index: 4 2VWB4UBKAW2MY2TA5PH0EO0WLKQNNF02S0CS3V60BF1BDVGOSLII305O5A0UDX746A380AGKSRY8WZTZEC4B7R824XW34MWNI6
Index: 5 C2IXRE8ZLB71G
Index: 6 APA257OCBDCONPF5KZ0UQ75OM691W075QM46VVN9ZA0EVD1
Index: 7 UQ0HBVACTWP88XPKGG8AVIJZM05PH13JEQHGAZ44M1M9FOBCVQ8
Index: 8 F17LGA5L0U523G3RPJKQMDY36KU7Z3412ODNT699
Index: 9 SD16UG9UUWLFSBBCDP6Q8V70E9OCP7TKKW4A67LEUMFGTVKNBKPQDS56FB2U16EWDB55HBGGD15VQ1GSYAB
Index: 10 SCH20745E1MYISC
Index: 11 0PFAEINLWKPO4J5159EB3CEKGLCMPHN8YY2J4AAJY5FQRQA55V3
Index: 12 OBYXK543GB6P7R0GQW6495M8
Index: 13 Y20KGQ3NETWAF89GHCX9ZS904PJY8JTZ0ZWCDSAUCC27DFKX7Y22Y8HF3AQ1GEO5A6KPM6CYCC6XZBWYEW1JR0B1RQJDC
Index: 14 O7X76G54KAWD0VBUP1N1WUNFNK
Index: 15 S86W8V2Y9A2FP2JM0XN9QZ7ASZLW4USUWLM6NOXS76CTXW88MHWSAKP3A5EJKG4PSHSEPN8M94BTXON61MJW8A
Index: 16 L6T6RKOI1BXBPD3S9JJSFJ5GWSHR76IQSXHH6RQCUWKR9M7374KNYROC
Index: 17 NJ9C
Index: 18 L43GS15WWS2H8S8NGJVOUCW42BIFGSHR9XLPY33F7LI1VRS6DXG9NYMIH8ORT0PDLKHKHSZNQQQJ45JKSMBSLHEKLCH
Index: 19 PLWG5EQKKIYU83T7ICOMZD9GZ61DG68FKA7E3JNZP9AKYQURXGCIY5ALMPR8NMENJTJ86P
Index: 20 8ZY70DZSJMJ
Index: 21 A30RP9V1N2PMC5WAFGWVHCET97KIX7IWD5DTSB48KY0FJM
Index: 22 4QYMCZYI7YGRRZNEPU2IG1CRDLYLTM9JXDP28VF7PWG5LUMI7TKURDXDNGJ0BMZVZ73OKUG4P53TUHFS9PNAC
Index: 23 1UPLO1LO6C7VFO088MNPEWKDSFB01V9ZSKFJ98GOSA
Index: 24 0W9B12BRBWWKFJL2I0VXKDIC5IQ89G86EXTRTDJ80D7C5999YG7Y7NYXN7GSLCS5Y0GS03JEQX7GFGG6IQK2IJ9085EW71WXV
Index: 25 NF3RJ462
Index: 26 JQRSH0KJ42ZWP0PT5ZXHYAJ
Index: 27 C3AC1HP6QBZKQN75XS255Q8OO8OFJVTJH6PNZHSWM3FNBFCR11TGINZW4WY
Index: 28 3KW5RPCU8TGPAFTCKUNI56NSBMB3H2TDTY3CGK6VCSTIVDGC4XLKIP866E4FOJNGAC6LMR5AY1GMNE67F
Index: 29 9TQI4D06FCP1H2FMITH50M1LWRJVT1I79PJ3Z1H3UPL3U7TNHA6N0KIW2FWN4FNO4S12TLXRLNKKB70Z75NS54GYGWAUF48PC
Index: 30 9CF145NPBM98V5O7P814S9LDV6LCMRO5IE7XTGBRFP24YHBFFHO9XHOA0BF7UKDU7E0Q71NJ7KZCGRON4G7ECOHAZ77S
Expect Output:
Index: 0 QGO0Q0OE1COTBZI4PJ3EL8M
Index: 1 Q85LJGR5N9TNN1XM9C8229G24JGF5G6S37KR5D4UUTGCG5
Index: 2 YWQFIATXQ2CR9AL9HCATPQFR5INIJ3EV82RTPBYSJJ3Z2W4
Index: 3 IT8AFLBHQ9JAWLOXXQSHS2UFOSJGXPYJN39Z4EQX1KCQ1X585GCLDXBQ
Index: 4 2VWB4UBKAW2MY2TA5PH0EO0WLKQNNF02S0CS3V60BF1BDVGOSLII305O5A0UDX746A380AGKSRY8WZTZEC4B7R824XW34MWNI6
Index: 5 C2IXRE8ZLB71G
Index: 6 APA257OCBDCONPF5KZ0UQ75OM691W075QM46VVN9ZA0EVD1
Index: 7 UQ0HBVACTWP88XPKGG8AVIJZM05PH13JEQHGAZ44M1M9FOBCVQ8
Index: 8 F17LGA5L0U523G3RPJKQMDY36KU7Z3412ODNT699
Index: 9 SD16UG9UUWLFSBBCDP6Q8V70E9OCP7TKKW4A67LEUMFGTVKNBKPQDS56FB2U16EWDB55HBGGD15VQ1GSYAB
Index: 10 SCH20745E1MYISC
Index: 11 0PFAEINLWKPO4J5159EB3CEKGLCMPHN8YY2J4AAJY5FQRQA55V3
Index: 12 OBYXK543GB6P7R0GQW6495M8
Index: 13 Y20KGQ3NETWAF89GHCX9ZS904PJY8JTZ0ZWCDSAUCC27DFKX7Y22Y8HF3AQ1GEO5A6KPM6CYCC6XZBWYEW1JR0B1RQJDC
Index: 14 O7X76G54KAWD0VBUP1N1WUNFNK
Index: 15 S86W8V2Y9A2FP2JM0XN9QZ7ASZLW4USUWLM6NOXS76CTXW88MHWSAKP3A5EJKG4PSHSEPN8M94BTXON61MJW8A
Index: 16 L6T6RKOI1BXBPD3S9JJSFJ5GWSHR76IQSXHH6RQCUWKR9M7374KNYROC
Index: 17 NJ9C
Index: 18 L43GS15WWS2H8S8NGJVOUCW42BIFGSHR9XLPY33F7LI1VRS6DXG9NYMIH8ORT0PDLKHKHSZNQQQJ45JKSMBSLHEKLCH
Index: 19 PLWG5EQKKIYU83T7ICOMZD9GZ61DG68FKA7E3JNZP9AKYQURXGCIY5ALMPR8NMENJTJ86P
Index: 20 8ZY70DZSJMJ
Index: 21 A30RP9V1N2PMC5WAFGWVHCET97KIX7IWD5DTSB48KY0FJM
Index: 22 4QYMCZYI7YGRRZNEPU2IG1CRDLYLTM9JXDP28VF7PWG5LUMI7TKURDXDNGJ0BMZVZ73OKUG4P53TUHFS9PNAC
Index: 23 1UPLO1LO6C7VFO088MNPEWKDSFB01V9ZSKFJ98GOSA
Index: 24 0W9B12BRBWWKFJL2I0VXKDIC5IQ89G86EXTRTDJ80D7C5999YG7Y7NYXN7GSLCS5Y0GS03JEQX7GFGG6IQK2IJ9085EW71WXV
Index: 25 NF3RJ462
Index: 26 JQRSH0KJ42ZWP0PT5ZXHYAJ
Index: 27 C3AC1HP6QBZKQN75XS255Q8OO8OFJVTJH6PNZHSWM3FNBFCR11TGINZW4WY
Index: 28 3KW5RPCU8TGPAFTCKUNI56NSBMB3H2TDTY3CGK6VCSTIVDGC4XLKIP866E4FOJNGAC6LMR5AY1GMNE67F
Index: 29 9TQI4D06FCP1H2FMITH50M1LWRJVT1I79PJ3Z1H3UPL3U7TNHA6N0KIW2FWN4FNO4S12TLXRLNKKB70Z75NS54GYGWAUF48PC
Index: 30 9CF145NPBM98V5O7P814S9LDV6LCMRO5IE7XTGBRFP24YHBFFHO9XHOA0BF7UKDU7E0Q71NJ7KZCGRON4G7ECOHAZ77S
Paragraph 1:
Index: 0 MH6URVHO4FCNRL3JX1DOM8SS6Z0A35I4M409U36J8TK7M4SOEY4IASSNZNX14HU86HAWV4Y353P3YVGCGM6FAA
Index: 1 4MMJHFEP18LAE363J9ANGCYZEHVURLP76NGKIURX0OY5NUBJKTWFAWX1YXE9UU7QTND1WVUZSMX2O3LTGLJ
Index: 2 YJ7J0OWUQRDGQIMAQKWZ87XX95N5LU3IK91KP4BI99IAJRLFQLD6ZUA1VJK4B1I5Y45RQBUWIOZ8YWORTHOAR6TZ99YGTGG
Index: 3 0NLOV4ZP1QXK4BD852L3NIO
Index: 4 KGRRNODCHRHLL96YS8JAJI4750L04N4S8UDPMHBMNUCN32X56XKO8NSCLUVXDMH4WZM05RLL76XYF
Index: 5 DDCP4HCQTVCBD2WOJANI0EQ69PL9RCZ364QSUXSA1FF0Y4NT
Index: 6 SWXL709WFQP6D9R5IFJLD4WSMRV8ZHFB2K8PCS9ER5OGCDYGY5QYEHVYAE8QFA77LNE2B
Index: 7 3ZGE4I
Index: 8 PPI2OK31Q7UZKO7TS9Q7Q5Y95FWC0R9MNIUYZX00DG4Q
Index: 9 D0X5GXFOK9T0J7JX1A87IMC4I45IZ4KBIQ1O9HU447CJA8Q0QDMF5T
Index: 10 1Y2WL16ZQYSS2F5XUQEDKJ33KNF2WRE
Index: 11 ZFA0GUIC7IWUSPXU
Index: 12 P1Y1QAS49L8WEC8UN2XEER9HBFBXJK50VHG0POJES5GJKQ3FX9FW9PQ81QZ
Index: 13 94VZQIB66HE8TTWIK07VL59JFI0F0H
Index: 14 9Y8FXJR2CP6JQ5GDQ3HYBTE9D5MTIS5GYJFKUO98275FOWTN9EJLST7PU9C178UTT0UG06SC4J5EX8UQM9TDIUXFLZZVMHB4
Index: 15 LWYBMXDWGRJX32VPVO8OQL9CP5AG70WHB1MM
Index: 16 OALQRBCORS7DG02DP5AWVWRW6YQ4BWCPJSGOW79J6Y8MDC194EV5LZL2TZT3VHM4QR4XUNQS61Z6XES47QA7AGETHN
Index: 17 7NGXZLD6WHDPQYD8UAOEOGZ5EGP4JNLPGSTE0DAVUI6W3BUJ7HTT3JR0XKTS6JWI6XJ7E8IR93UFJDCDWG6B31W
Index: 18 B3QPUSZKWYZF1WE89CT9YLQUIP5ZNUPEAM6LS26REJTVN6MAB7C0IWIZM5HEW97CIUEOZ3QHFB5P25HMD5XPRY6NEH9
Index: 19 U25ELRN217KIQ5VG127RY5B0MSUUY0KS34WNG1DKROUGVO9WDZWLJS7Z0E237
Paragraph 2:
Index: 11 ZFA0GUIC7IWUSPXU
Index: 12 P1Y1QAS49L8WEC8UN2XEER9HBFBXJK50VHG0POJES5GJKQ3FX9FW9PQ81QZ
Index: 13 94VZQIB66HE8TTWIK07VL59JFI0F0H
Index: 14 9Y8FXJR2CP6JQ5GDQ3HYBTE9D5MTIS5GYJFKUO98275FOWTN9EJLST7PU9C178UTT0UG06SC4J5EX8UQM9TDIUXFLZZVMHB4
Index: 15 LWYBMXDWGRJX32VPVO8OQL9CP5AG70WHB1MM
Index: 16 OALQRBCORS7DG02DP5AWVWRW6YQ4BWCPJSGOW79J6Y8MDC194EV5LZL2TZT3VHM4QR4XUNQS61Z6XES47QA7AGETHN
Index: 17 7NGXZLD6WHDPQYD8UAOEOGZ5EGP4JNLPGSTE0DAVUI6W3BUJ7HTT3JR0XKTS6JWI6XJ7E8IR93UFJDCDWG6B31W
Index: 18 B3QPUSZKWYZF1WE89CT9YLQUIP5ZNUPEAM6LS26REJTVN6MAB7C0IWIZM5HEW97CIUEOZ3QHFB5P25HMD5XPRY6NEH9
Index: 19 U25ELRN217KIQ5VG127RY5B0MSUUY0KS34WNG1DKROUGVO9WDZWLJS7Z0E237
Index: 20 DAW1PVJHA9ZW9KL5F7S7R9E8JL76XB8JNZKTT39NN5YXVWSXO495K9LE6XSDYMU9AQJK91MM7FUVKQNW
Index: 21 KS2BD8NNFX5K6ZBKZWFMIXWSW7FPZ4PK6KO3277R564EQCBQTLV4HJTW6KOG28XLHUOVLHS1ZXRL3SBU
Index: 22 Z5OJVDW017RS0Z6JS76XPFL23FU2I3NJ4KDDICWR25UKAI88UCKVF7QUTVPPS3S7TIYQV3BQLO5UVB2UGVHFS2E63
Index: 23 TWWG88MW02TSM1B3K0B59S34J7WMP1E1WCKO4EQ7I8L9BYJQEYRN5
Index: 24 TB316BM9H8X25JRW9FKDXAG33UXFH0J06YSJUCHOVI1MMI298RZMD1JT498MNG2QZ65G1IC775SPI4RU1YGZB7XEO9PVD5
Index: 25 O
Index: 26 KXPNWI0P1OHI4K9RNUZ9CP2J0113Q3B5D98HCHFQQJJS
Index: 27 6UZPEZLKPN45GW4Q797MLE4M2PGOJS2GJ34GCNMD0VYWD
Index: 28 6UK9TKLFE10MWZT6A6UYVM2XNTW4W0QHI
Index: 29 SWEK9S4EZDQZ1XU4U1CO0T2XV9XRTNKTDGG6206C4QXZHX
Index: 30 9J2GZF4083QYA4NVL26WUQXB34AUJ6DP7HYH1GVOJPHDLB6HQ5M6KBHSV0N4FJQC0B03GF4EHSMEJU0
Index: 31 82DOTGF59FWA30I99FMKKDALBHZ1ZCJA9V5MGCST653AS3LQJMFEIQQ511MMRNG76VBI5637W2OP
Index: 32 92H6JRN7F2TEAUOZGCSZ6E72DVNS
Index: 33 RPBAV29FQI53912RD4LPHQ05
Index: 34 N55P3XE4YXNSEP2OUZ3X56NEL91BCABYGKH6DZXU08LDP98OTAX07I4RS0E36C1XWYL3I5L4CI
Index: 35 7UJYLAMSBNK18PZOMV4YXHXR1XFFXZ3YYL76IB22TUZKL6NOSR8IIUI0727Y5H4MUWCWR2FL2BEDRNF4K0WF1UQECH
Index: 36 QEE6MZN0Z4060LXPGQFIUXDOFUZU9G8UK3ZHYF1NDXPAT464EEJY78P2A011A20T5GW6VP1BY1F7HD4KY4Q56KWLO7G8NANK66
Index: 37 NIAIYNI9G3RV
Index: 38 5QDFM5XVTKRYJ3XXN4AL9RCYV2RYKQS6LIC77H8BJS37SUOUVM28RK8ONPUTN8LD1UMB0Z0G58CQXFFBN7D7YTPBJXURX
Index: 39 YKG0F7HN35VWDSIS1HJSGQ5NOIFL1CFISRK2J79I3
Index: 40 DH
Index: 41 CQ6216MIEIIO3L725V0ZNDVIQI3IBYFMYB
Index: 42 1JS9G3ANIBNQVCQ8PNR984XMTCDHPD6Z28FS
Index: 43 VU6NZNHC2IFV009GCO7VGQDZ28EFXXW67V3
Index: 44 UVIQQK148VYN6T0UI7GEQHU1IBOEWJYF6GVQFQF5ZJ1HJ1IE7BYAOYLNBRIO6WHY7TQ07JP11KPHQNS
Index: 45 2JGUUY0H4IOXI09CBCJZLSGYW6IEJE6Y81WWQXEJ3I5Z51T
Index: 46 LMF
Index: 47 D3FJCS8XPW80LZYREMWO796CXR24NH279SVFVMT
Index: 48 ZR3HKFOFDC68Z1QD7DWVZDKI3A12ES622YYQGZ1RDW1KK3HHCRIRZ8IVGVNJOVBUGEGBCA7HLESDM97A3T0WKOC4PDJVLS
Index: 49 RVHEGXGFCU
Index: 50 FUP
Index: 51 IHXMQ44OJ1BLV80
Index: 52 63BASF41NXOYCJIROK5B79BIWG7NFLUGLH
Index: 53 MTPXDN693QGMAS
Index: 54 6KDYO612NLIRWBCIM4E689X2YB9I2Q474VPJCW3HU1BL56K80I3R5V
Index: 55 7XLAM7S97RKWAV3F0B6MG7M721BSUWNBIASW1VQKB1E4UJJM7CDQ8JO9LOI
Index: 56 6APKEJOADGNEUVKP3RMSRYVRT7C8VTKMN5OBL3ZK4JJ0Z95M99F3BZDHP81H
Index: 57 POU6B1ZHJDA1CYIO42UB
Index: 58 9WNRLX1GWNBSDO4Z4XHFF05EB9B43UGHFRQ1GOZD8AW08J9JOZAEM6TJ1IPMV6NCG4NV8CT
Index: 59 8DHFDEG292QDTC5J7HA79NSBWUTE5NKLGUFIYOFWCXM
Index: 60 QJSE8DY1BVQVVFSSUB6WRF796WUTBN4MAZVNCPF1ZTJUEUWS6WBB0ZLLMTILTE0Y1EU6UFQF5E775N4LA
Index: 61 WOM2VLN
Index: 62 ATH4IU3V3AA080G6GV2NP9Y6LQRLM
Index: 63 SJSKE78B6NEJU4LKE6HPWASA4B5KS1CRJ4R0HXWJ7FZPJFP3UBMVD6MS0SPCCXSEKWAZNUCQJ8RRKD1YWBZQPQNNR9AYITHK
Index: 64 VEWFZQA86MFO5HW10PA7CY4JWHOUOHZ1H4Z9ET7VZRTEI9W2N6SEGMU6KMSRBQ
Index: 65 YWNGARXWHSOIUFZAXUWGRZVU5K3Y2APTJ64R42WK0KKV2E91UM46PJD8A2
Index: 66 ZY84GC48XKHF58LQHOA20LCEPFSE936
Index: 67 CR6W1PDS7FLQMG98E36TAAUOW4OBT084O0DOBZY1LR4U9V1
Index: 68 GU9G7MQB6S97AC9HHRBVCV6OEE
Index: 69 TF9PACF49017CKBRTZ11ISXN
Index: 70 TFGVXUC2D667C945I9QPU9LBDNZNNABSV7Q78JLGZE8NFUQ06
Index: 71 9SG76U4FRK5ZPD5NLFS769YK0PA75T69QRATMYA6C31AKAZ5S2ILI89A36HRT6J8N6I7CLAXEV5CIX900FODKV0R
Index: 72 AZQQTNFU2XO123H1VHWD62F6R1OSFX2F0PCWUGUIZSPAU87MHM
Index: 73 OEOVHUT929XOF5JBM0VGOWOOONFLS3BL37NBM34BAH1ICDJFL7VVWFL1Z9H4OHQ97MUHRIY
Index: 74 6TFG5FMKD9AVIQYYWWLMWAX212LZTCYCICYD9F6TX60PG41QX6V5
Index: 75 M565NOC4W1BL8MF1VYQZ2Z0JHV6A4CWQ2G6G2HW03YAFZDIRVYBHEFEXFWY1RB9UEUS2Q99OC06DYUUENPPGAOMXCI
Index: 76 FT
Index: 77 I1ZQAEUQAVZXEOIA9UCTNCW3TZI40I934HREOHUPT6O3QMK8PBJPD9RGF57K6002W6276DW1AXARY2MGPJPY8T
Index: 78 50K9SKJS3GVHUTMBLORPP9ASMT04WKB4CG7HVEER0FGLCV2WDIEJQEK6Z2X9TO5TE0ENWFPH
Index: 79 9YK2ZP00D1OG2N86BR2RF8LJXGLROA
Index: 80 279RP9DAN6IPXQMMNFRUXWZFBNAESDJLD3WI36T68QPU6TY3K48L7PKFH3PC98SKW7L33ETQWUWGHEISYH3XE8NYSRB9QQ7
Index: 81 8F89H49GLRZM2E7CV7N2F4FYTXLMCTAFXXHBGJK3HXMWIB5NT8NTDF3DAKPTTWD1RUZF656LWUURSSPS273EGQCR3EB531KUT
Index: 82 FYL0RXCB6TUMVR570V39VASHL24AS5JA87N1GCQFBEUT7RSTA5AZ0U9EGE
Index: 83 Z3BTAJUOXED1YFY7RQ9K3JK9W4UJN8JVBX1M9UUJM
Index: 84 4P6EMTCWRX
Index: 85 4VPSC7FZLAZ4SZAOL776
Index: 86 70O4CRSAG0QVOGCL37XOTBDEUOOLF1ZU1R74AY9PXZEJJJET8CR9JSG6XKJYDH4PB536JHL
Index: 87 8H04634LJ5MDJZL
Index: 88 LAH0OKMQ5ZIOQHJ01MAB1LA3P8PH
Index: 89 0FLTTVI9U0Y5K8GVQ4BWWM6YJS9AOLP4EWET646WA0GVMGRN3I8DOVIOJXKBWIVJL40Y4WZV8PV5FKMCBWG
Index: 90 MLPTO0KIU591F7KRP
Index: 91 THSNF99MJ8KIAACP69OHKDMQBDP30H94WIC9X8GQTBQL7M58ZZBLDISP5BMCTFWB8QV17D2737XIXASY
Expect Output:
Index: 0 MH6URVHO4FCNRL3JX1DOM8SS6Z0A35I4M409U36J8TK7M4SOEY4IASSNZNX14HU86HAWV4Y353P3YVGCGM6FAA
Index: 1 4MMJHFEP18LAE363J9ANGCYZEHVURLP76NGKIURX0OY5NUBJKTWFAWX1YXE9UU7QTND1WVUZSMX2O3LTGLJ
Index: 2 YJ7J0OWUQRDGQIMAQKWZ87XX95N5LU3IK91KP4BI99IAJRLFQLD6ZUA1VJK4B1I5Y45RQBUWIOZ8YWORTHOAR6TZ99YGTGG
Index: 3 0NLOV4ZP1QXK4BD852L3NIO
Index: 4 KGRRNODCHRHLL96YS8JAJI4750L04N4S8UDPMHBMNUCN32X56XKO8NSCLUVXDMH4WZM05RLL76XYF
Index: 5 DDCP4HCQTVCBD2WOJANI0EQ69PL9RCZ364QSUXSA1FF0Y4NT
Index: 6 SWXL709WFQP6D9R5IFJLD4WSMRV8ZHFB2K8PCS9ER5OGCDYGY5QYEHVYAE8QFA77LNE2B
Index: 7 3ZGE4I
Index: 8 PPI2OK31Q7UZKO7TS9Q7Q5Y95FWC0R9MNIUYZX00DG4Q
Index: 9 D0X5GXFOK9T0J7JX1A87IMC4I45IZ4KBIQ1O9HU447CJA8Q0QDMF5T
Index: 10 1Y2WL16ZQYSS2F5XUQEDKJ33KNF2WRE
Index: 11 ZFA0GUIC7IWUSPXU
Index: 12 P1Y1QAS49L8WEC8UN2XEER9HBFBXJK50VHG0POJES5GJKQ3FX9FW9PQ81QZ
Index: 13 94VZQIB66HE8TTWIK07VL59JFI0F0H
Index: 14 9Y8FXJR2CP6JQ5GDQ3HYBTE9D5MTIS5GYJFKUO98275FOWTN9EJLST7PU9C178UTT0UG06SC4J5EX8UQM9TDIUXFLZZVMHB4
Index: 15 LWYBMXDWGRJX32VPVO8OQL9CP5AG70WHB1MM
Index: 16 OALQRBCORS7DG02DP5AWVWRW6YQ4BWCPJSGOW79J6Y8MDC194EV5LZL2TZT3VHM4QR4XUNQS61Z6XES47QA7AGETHN
Index: 17 7NGXZLD6WHDPQYD8UAOEOGZ5EGP4JNLPGSTE0DAVUI6W3BUJ7HTT3JR0XKTS6JWI6XJ7E8IR93UFJDCDWG6B31W
Index: 18 B3QPUSZKWYZF1WE89CT9YLQUIP5ZNUPEAM6LS26REJTVN6MAB7C0IWIZM5HEW97CIUEOZ3QHFB5P25HMD5XPRY6NEH9
Index: 19 U25ELRN217KIQ5VG127RY5B0MSUUY0KS34WNG1DKROUGVO9WDZWLJS7Z0E237
Index: 20 DAW1PVJHA9ZW9KL5F7S7R9E8JL76XB8JNZKTT39NN5YXVWSXO495K9LE6XSDYMU9AQJK91MM7FUVKQNW
Index: 21 KS2BD8NNFX5K6ZBKZWFMIXWSW7FPZ4PK6KO3277R564EQCBQTLV4HJTW6KOG28XLHUOVLHS1ZXRL3SBU
Index: 22 Z5OJVDW017RS0Z6JS76XPFL23FU2I3NJ4KDDICWR25UKAI88UCKVF7QUTVPPS3S7TIYQV3BQLO5UVB2UGVHFS2E63
Index: 23 TWWG88MW02TSM1B3K0B59S34J7WMP1E1WCKO4EQ7I8L9BYJQEYRN5
Index: 24 TB316BM9H8X25JRW9FKDXAG33UXFH0J06YSJUCHOVI1MMI298RZMD1JT498MNG2QZ65G1IC775SPI4RU1YGZB7XEO9PVD5
Index: 25 O
Index: 26 KXPNWI0P1OHI4K9RNUZ9CP2J0113Q3B5D98HCHFQQJJS
Index: 27 6UZPEZLKPN45GW4Q797MLE4M2PGOJS2GJ34GCNMD0VYWD
Index: 28 6UK9TKLFE10MWZT6A6UYVM2XNTW4W0QHI
Index: 29 SWEK9S4EZDQZ1XU4U1CO0T2XV9XRTNKTDGG6206C4QXZHX
Index: 30 9J2GZF4083QYA4NVL26WUQXB34AUJ6DP7HYH1GVOJPHDLB6HQ5M6KBHSV0N4FJQC0B03GF4EHSMEJU0
Index: 31 82DOTGF59FWA30I99FMKKDALBHZ1ZCJA9V5MGCST653AS3LQJMFEIQQ511MMRNG76VBI5637W2OP
Index: 32 92H6JRN7F2TEAUOZGCSZ6E72DVNS
Index: 33 RPBAV29FQI53912RD4LPHQ05
Index: 34 N55P3XE4YXNSEP2OUZ3X56NEL91BCABYGKH6DZXU08LDP98OTAX07I4RS0E36C1XWYL3I5L4CI
Index: 35 7UJYLAMSBNK18PZOMV4YXHXR1XFFXZ3YYL76IB22TUZKL6NOSR8IIUI0727Y5H4MUWCWR2FL2BEDRNF4K0WF1UQECH
Index: 36 QEE6MZN0Z4060LXPGQFIUXDOFUZU9G8UK3ZHYF1NDXPAT464EEJY78P2A011A20T5GW6VP1BY1F7HD4KY4Q56KWLO7G8NANK66
Index: 37 NIAIYNI9G3RV
Index: 38 5QDFM5XVTKRYJ3XXN4AL9RCYV2RYKQS6LIC77H8BJS37SUOUVM28RK8ONPUTN8LD1UMB0Z0G58CQXFFBN7D7YTPBJXURX
Index: 39 YKG0F7HN35VWDSIS1HJSGQ5NOIFL1CFISRK2J79I3
Index: 40 DH
Index: 41 CQ6216MIEIIO3L725V0ZNDVIQI3IBYFMYB
Index: 42 1JS9G3ANIBNQVCQ8PNR984XMTCDHPD6Z28FS
Index: 43 VU6NZNHC2IFV009GCO7VGQDZ28EFXXW67V3
Index: 44 UVIQQK148VYN6T0UI7GEQHU1IBOEWJYF6GVQFQF5ZJ1HJ1IE7BYAOYLNBRIO6WHY7TQ07JP11KPHQNS
Index: 45 2JGUUY0H4IOXI09CBCJZLSGYW6IEJE6Y81WWQXEJ3I5Z51T
Index: 46 LMF
Index: 47 D3FJCS8XPW80LZYREMWO796CXR24NH279SVFVMT
Index: 48 ZR3HKFOFDC68Z1QD7DWVZDKI3A12ES622YYQGZ1RDW1KK3HHCRIRZ8IVGVNJOVBUGEGBCA7HLESDM97A3T0WKOC4PDJVLS
Index: 49 RVHEGXGFCU
Index: 50 FUP
Index: 51 IHXMQ44OJ1BLV80
Index: 52 63BASF41NXOYCJIROK5B79BIWG7NFLUGLH
Index: 53 MTPXDN693QGMAS
Index: 54 6KDYO612NLIRWBCIM4E689X2YB9I2Q474VPJCW3HU1BL56K80I3R5V
Index: 55 7XLAM7S97RKWAV3F0B6MG7M721BSUWNBIASW1VQKB1E4UJJM7CDQ8JO9LOI
Index: 56 6APKEJOADGNEUVKP3RMSRYVRT7C8VTKMN5OBL3ZK4JJ0Z95M99F3BZDHP81H
Index: 57 POU6B1ZHJDA1CYIO42UB
Index: 58 9WNRLX1GWNBSDO4Z4XHFF05EB9B43UGHFRQ1GOZD8AW08J9JOZAEM6TJ1IPMV6NCG4NV8CT
Index: 59 8DHFDEG292QDTC5J7HA79NSBWUTE5NKLGUFIYOFWCXM
Index: 60 QJSE8DY1BVQVVFSSUB6WRF796WUTBN4MAZVNCPF1ZTJUEUWS6WBB0ZLLMTILTE0Y1EU6UFQF5E775N4LA
Index: 61 WOM2VLN
Index: 62 ATH4IU3V3AA080G6GV2NP9Y6LQRLM
Index: 63 SJSKE78B6NEJU4LKE6HPWASA4B5KS1CRJ4R0HXWJ7FZPJFP3UBMVD6MS0SPCCXSEKWAZNUCQJ8RRKD1YWBZQPQNNR9AYITHK
Index: 64 VEWFZQA86MFO5HW10PA7CY4JWHOUOHZ1H4Z9ET7VZRTEI9W2N6SEGMU6KMSRBQ
Index: 65 YWNGARXWHSOIUFZAXUWGRZVU5K3Y2APTJ64R42WK0KKV2E91UM46PJD8A2
Index: 66 ZY84GC48XKHF58LQHOA20LCEPFSE936
Index: 67 CR6W1PDS7FLQMG98E36TAAUOW4OBT084O0DOBZY1LR4U9V1
Index: 68 GU9G7MQB6S97AC9HHRBVCV6OEE
Index: 69 TF9PACF49017CKBRTZ11ISXN
Index: 70 TFGVXUC2D667C945I9QPU9LBDNZNNABSV7Q78JLGZE8NFUQ06
Index: 71 9SG76U4FRK5ZPD5NLFS769YK0PA75T69QRATMYA6C31AKAZ5S2ILI89A36HRT6J8N6I7CLAXEV5CIX900FODKV0R
Index: 72 AZQQTNFU2XO123H1VHWD62F6R1OSFX2F0PCWUGUIZSPAU87MHM
Index: 73 OEOVHUT929XOF5JBM0VGOWOOONFLS3BL37NBM34BAH1ICDJFL7VVWFL1Z9H4OHQ97MUHRIY
Index: 74 6TFG5FMKD9AVIQYYWWLMWAX212LZTCYCICYD9F6TX60PG41QX6V5
Index: 75 M565NOC4W1BL8MF1VYQZ2Z0JHV6A4CWQ2G6G2HW03YAFZDIRVYBHEFEXFWY1RB9UEUS2Q99OC06DYUUENPPGAOMXCI
Index: 76 FT
Index: 77 I1ZQAEUQAVZXEOIA9UCTNCW3TZI40I934HREOHUPT6O3QMK8PBJPD9RGF57K6002W6276DW1AXARY2MGPJPY8T
Index: 78 50K9SKJS3GVHUTMBLORPP9ASMT04WKB4CG7HVEER0FGLCV2WDIEJQEK6Z2X9TO5TE0ENWFPH
Index: 79 9YK2ZP00D1OG2N86BR2RF8LJXGLROA
Index: 80 279RP9DAN6IPXQMMNFRUXWZFBNAESDJLD3WI36T68QPU6TY3K48L7PKFH3PC98SKW7L33ETQWUWGHEISYH3XE8NYSRB9QQ7
Index: 81 8F89H49GLRZM2E7CV7N2F4FYTXLMCTAFXXHBGJK3HXMWIB5NT8NTDF3DAKPTTWD1RUZF656LWUURSSPS273EGQCR3EB531KUT
Index: 82 FYL0RXCB6TUMVR570V39VASHL24AS5JA87N1GCQFBEUT7RSTA5AZ0U9EGE
Index: 83 Z3BTAJUOXED1YFY7RQ9K3JK9W4UJN8JVBX1M9UUJM
Index: 84 4P6EMTCWRX
Index: 85 4VPSC7FZLAZ4SZAOL776
Index: 86 70O4CRSAG0QVOGCL37XOTBDEUOOLF1ZU1R74AY9PXZEJJJET8CR9JSG6XKJYDH4PB536JHL
Index: 87 8H04634LJ5MDJZL
Index: 88 LAH0OKMQ5ZIOQHJ01MAB1LA3P8PH
Index: 89 0FLTTVI9U0Y5K8GVQ4BWWM6YJS9AOLP4EWET646WA0GVMGRN3I8DOVIOJXKBWIVJL40Y4WZV8PV5FKMCBWG
Index: 90 MLPTO0KIU591F7KRP
Index: 91 THSNF99MJ8KIAACP69OHKDMQBDP30H94WIC9X8GQTBQL7M58ZZBLDISP5BMCTFWB8QV17D2737XIXASY
Paragraph 1:
Index: 0 GY0O
Index: 1 XDVWD6NOONR0DBW6DRFVK14TX4CBV5JZHCJ9HLZAJ4IXB7EPRECGU2O5IC8J4M3TD1TA1X
Index: 2 22FMQTHRZZXUQ3DFOXO0EMQG7AZTKODX4PJOPQ8MBUJTG1MZAWFNN7UQL8PP4XHLV90BUY
Index: 3 8YBZUD6AFY9TXJ0K643CRATRNN77GAKFL6GYLHANP8J04ETC5Z3G1VI7FULHF83EO4I1CC9
Index: 4 4PXS12WJ35CRHDO0YIS162HQEEMA62920EML7ZGN7CNK6L7KQRC4TH2BIHNWPVNB5J1C1
Index: 5 28BF33P7U
Index: 6 GBUOZFJSLKD0LU7LZLPWT4TNYE2NO8WLXUPNB8MZAJ0Q9CWRIREDR7JMSHZVN5DMY2D1ETK090VKECNWRK
Index: 7 74S3ZKD53J0LFGN
Paragraph 2:
Index: 2 22FMQTHRZZXUQ3DFOXO0EMQG7AZTKODX4PJOPQ8MBUJTG1MZAWFNN7UQL8PP4XHLV90BUY
Index: 3 8YBZUD6AFY9TXJ0K643CRATRNN77GAKFL6GYLHANP8J04ETC5Z3G1VI7FULHF83EO4I1CC9
Index: 4 4PXS12WJ35CRHDO0YIS162HQEEMA62920EML7ZGN7CNK6L7KQRC4TH2BIHNWPVNB5J1C1
Index: 5 28BF33P7U
Index: 6 GBUOZFJSLKD0LU7LZLPWT4TNYE2NO8WLXUPNB8MZAJ0Q9CWRIREDR7JMSHZVN5DMY2D1ETK090VKECNWRK
Index: 7 74S3ZKD53J0LFGN
Index: 8 H85NZGOE1M9IP4CDC0FSG8OQAXQQJOQD0KFXW7Q1PNBNK5P9GWJPA5VJUOMBZ75N56RFYORFJOC26A
Index: 9 FIQJWFBC4Y6DHUOBR
Index: 10 YRONKK2EDFW23MTIH2IYII43XQ2LKV5NVJIT118GRRB5QC5TT9MV
Expect Output:
Index: 0 GY0O
Index: 1 XDVWD6NOONR0DBW6DRFVK14TX4CBV5JZHCJ9HLZAJ4IXB7EPRECGU2O5IC8J4M3TD1TA1X
Index: 2 22FMQTHRZZXUQ3DFOXO0EMQG7AZTKODX4PJOPQ8MBUJTG1MZAWFNN7UQL8PP4XHLV90BUY
Index: 3 8YBZUD6AFY9TXJ0K643CRATRNN77GAKFL6GYLHANP8J04ETC5Z3G1VI7FULHF83EO4I1CC9
Index: 4 4PXS12WJ35CRHDO0YIS162HQEEMA62920EML7ZGN7CNK6L7KQRC4TH2BIHNWPVNB5J1C1
Index: 5 28BF33P7U
Index: 6 GBUOZFJSLKD0LU7LZLPWT4TNYE2NO8WLXUPNB8MZAJ0Q9CWRIREDR7JMSHZVN5DMY2D1ETK090VKECNWRK
Index: 7 74S3ZKD53J0LFGN
Index: 8 H85NZGOE1M9IP4CDC0FSG8OQAXQQJOQD0KFXW7Q1PNBNK5P9GWJPA5VJUOMBZ75N56RFYORFJOC26A
Index: 9 FIQJWFBC4Y6DHUOBR
Index: 10 YRONKK2EDFW23MTIH2IYII43XQ2LKV5NVJIT118GRRB5QC5TT9MV
Paragraph 1:
Index: 0 XV03SQ4RJIHTDAQQ4CG1G8MUVI1KIJV1A26GBFXAWTVH5
Index: 1 QTS61ZWSJYIFHJYUJAXPTLEKOZPGEWMFZJ
Index: 2 I1LS5FRSH757NLCKVUQ2EPIRBKQOXMDQ8RQ27S1KB36NT2B4BL0UJQX3T4QVYC454P865JND3F1LS58
Index: 3 IVMLVSHR3WJDBFV98BSE3E928X1
Index: 4 ZMLY5HMCZT
Index: 5 LHQCIAKCXU1MQM3QDWUN81D2QLU
Index: 6 42SJP2H6MC11YVET7A5M
Index: 7 0IQEFLU
Index: 8 YV6PCH4BS7YF
Index: 9 EB53YMXU5QQIEDUBEJQW2YQ4MVNJRPCGGFWHVLR86T3FQH7EK9NXHSEQVARD9NCQNJB9QMQ22S0I4LNEXI9SBP9YAGVV
Index: 10 N8TRN1HF8X7TV5Y26VKXMP0OUO8JN9K057OTG1RUG9ZVB8QUK6DVL7S7IE682728MGYXQFVFD0QM0FMV8O8R6
Index: 11 O7PQLB4T1JH1I5J2DFK8SVRGHC2K9N8LCX11I93TLU8GF96RMFK3G8G3PIJIJTTNL6YVD
Index: 12 UEL1W8XKAIGK83DFEEQ8M90VJ2AV5JKLO3VGRPLIFEHAB9UZKF1
Index: 13 EEFUN0R47CP1856EI6XZ2H2H1ZTKIKKZRZHJXA218RLDZQCGDPQNSB26L8
Index: 14 YGGWW1ZKIYWQID61L6ZSLXNH236HP6K7ZGEU15YMAF3RQ8IKWKR9WQRB39324R4LNZ1B9M9PHNRF3614VW
Index: 15 FPLKJZD01B6RSLRD1HHKKKB1J8MH7I9HH6Z6CORM6VHNL593M29WNLL4NTB
Index: 16 M53TCYJVWVBMZ5OYCXQO8S5EIM46V4SS
Index: 17 G9A1YLWWNH00X7R7W1ZDXM4AYL04NA1CS9T6O
Index: 18 OM31VLEOVPM89D2P03FADNU1INPYIXNVSZMMJ50S5KZLSOAYJDJZ0O3B2CTI6QF7B0PJ0PG4CWE2XJJ4M1OEOX4E6LU
Index: 19 MSWPE2J180737OXEJAN
Index: 20 3Y5EBBSO6LNP59STAZY4AR5V3UH9A0557CNXXRNDJ45XNS875DDU
Index: 21 TSL3KLQ3TOGPRR3V56SLVVFWIILWJE6WK
Index: 22 OTB4MG7J0QYH5AFLAGUJ08MZUC94UORTF8CJTBUMNM4Z7AMLQ7D0BB3
Index: 23 HMJKGCZL9FC77619WI5ODX1UZYNWL1SDEWBH1JFLWS027P
Index: 24 UFED3FOMUVZVSYDAIX82L4UHMCU1U79WKL3QG
Index: 25 Y80JRVCYXWTSRF8WC0V610VX1XWCLG5X3V8ACBN9FYO8HCP3XXIC5K58MCR399NQ
Index: 26 6Z6H8TBMV0CLXPZI2PX822SZ9Y9TT9GL7HLNSWZDHZJU3WZX2VHTZS7EGHHKUR3VT1OPDM0FZ
Paragraph 2:
Index: 1 QTS61ZWSJYIFHJYUJAXPTLEKOZPGEWMFZJ
Index: 2 I1LS5FRSH757NLCKVUQ2EPIRBKQOXMDQ8RQ27S1KB36NT2B4BL0UJQX3T4QVYC454P865JND3F1LS58
Index: 3 IVMLVSHR3WJDBFV98BSE3E928X1
Index: 4 ZMLY5HMCZT
Index: 5 LHQCIAKCXU1MQM3QDWUN81D2QLU
Index: 6 42SJP2H6MC11YVET7A5M
Index: 7 0IQEFLU
Index: 8 YV6PCH4BS7YF
Index: 9 EB53YMXU5QQIEDUBEJQW2YQ4MVNJRPCGGFWHVLR86T3FQH7EK9NXHSEQVARD9NCQNJB9QMQ22S0I4LNEXI9SBP9YAGVV
Index: 10 N8TRN1HF8X7TV5Y26VKXMP0OUO8JN9K057OTG1RUG9ZVB8QUK6DVL7S7IE682728MGYXQFVFD0QM0FMV8O8R6
Index: 11 O7PQLB4T1JH1I5J2DFK8SVRGHC2K9N8LCX11I93TLU8GF96RMFK3G8G3PIJIJTTNL6YVD
Index: 12 UEL1W8XKAIGK83DFEEQ8M90VJ2AV5JKLO3VGRPLIFEHAB9UZKF1
Index: 13 EEFUN0R47CP1856EI6XZ2H2H1ZTKIKKZRZHJXA218RLDZQCGDPQNSB26L8
Index: 14 YGGWW1ZKIYWQID61L6ZSLXNH236HP6K7ZGEU15YMAF3RQ8IKWKR9WQRB39324R4LNZ1B9M9PHNRF3614VW
Index: 15 FPLKJZD01B6RSLRD1HHKKKB1J8MH7I9HH6Z6CORM6VHNL593M29WNLL4NTB
Index: 16 M53TCYJVWVBMZ5OYCXQO8S5EIM46V4SS
Index: 17 G9A1YLWWNH00X7R7W1ZDXM4AYL04NA1CS9T6O
Index: 18 OM31VLEOVPM89D2P03FADNU1INPYIXNVSZMMJ50S5KZLSOAYJDJZ0O3B2CTI6QF7B0PJ0PG4CWE2XJJ4M1OEOX4E6LU
Index: 19 MSWPE2J180737OXEJAN
Index: 20 3Y5EBBSO6LNP59STAZY4AR5V3UH9A0557CNXXRNDJ45XNS875DDU
Index: 21 TSL3KLQ3TOGPRR3V56SLVVFWIILWJE6WK
Index: 22 OTB4MG7J0QYH5AFLAGUJ08MZUC94UORTF8CJTBUMNM4Z7AMLQ7D0BB3
Index: 23 HMJKGCZL9FC77619WI5ODX1UZYNWL1SDEWBH1JFLWS027P
Index: 24 UFED3FOMUVZVSYDAIX82L4UHMCU1U79WKL3QG
Index: 25 Y80JRVCYXWTSRF8WC0V610VX1XWCLG5X3V8ACBN9FYO8HCP3XXIC5K58MCR399NQ
Index: 26 6Z6H8TBMV0CLXPZI2PX822SZ9Y9TT9GL7HLNSWZDHZJU3WZX2VHTZS7EGHHKUR3VT1OPDM0FZ
Index: 27 0CS85N8L182WVPJGGKPPT06XACIKUP5B3G24VHM3LI0537F8F7FPZK
Expect Output:
Index: 0 XV03SQ4RJIHTDAQQ4CG1G8MUVI1KIJV1A26GBFXAWTVH5
Index: 1 QTS61ZWSJYIFHJYUJAXPTLEKOZPGEWMFZJ
Index: 2 I1LS5FRSH757NLCKVUQ2EPIRBKQOXMDQ8RQ27S1KB36NT2B4BL0UJQX3T4QVYC454P865JND3F1LS58
Index: 3 IVMLVSHR3WJDBFV98BSE3E928X1
Index: 4 ZMLY5HMCZT
Index: 5 LHQCIAKCXU1MQM3QDWUN81D2QLU
Index: 6 42SJP2H6MC11YVET7A5M
Index: 7 0IQEFLU
Index: 8 YV6PCH4BS7YF
Index: 9 EB53YMXU5QQIEDUBEJQW2YQ4MVNJRPCGGFWHVLR86T3FQH7EK9NXHSEQVARD9NCQNJB9QMQ22S0I4LNEXI9SBP9YAGVV
Index: 10 N8TRN1HF8X7TV5Y26VKXMP0OUO8JN9K057OTG1RUG9ZVB8QUK6DVL7S7IE682728MGYXQFVFD0QM0FMV8O8R6
Index: 11 O7PQLB4T1JH1I5J2DFK8SVRGHC2K9N8LCX11I93TLU8GF96RMFK3G8G3PIJIJTTNL6YVD
Index: 12 UEL1W8XKAIGK83DFEEQ8M90VJ2AV5JKLO3VGRPLIFEHAB9UZKF1
Index: 13 EEFUN0R47CP1856EI6XZ2H2H1ZTKIKKZRZHJXA218RLDZQCGDPQNSB26L8
Index: 14 YGGWW1ZKIYWQID61L6ZSLXNH236HP6K7ZGEU15YMAF3RQ8IKWKR9WQRB39324R4LNZ1B9M9PHNRF3614VW
Index: 15 FPLKJZD01B6RSLRD1HHKKKB1J8MH7I9HH6Z6CORM6VHNL593M29WNLL4NTB
Index: 16 M53TCYJVWVBMZ5OYCXQO8S5EIM46V4SS
Index: 17 G9A1YLWWNH00X7R7W1ZDXM4AYL04NA1CS9T6O
Index: 18 OM31VLEOVPM89D2P03FADNU1INPYIXNVSZMMJ50S5KZLSOAYJDJZ0O3B2CTI6QF7B0PJ0PG4CWE2XJJ4M1OEOX4E6LU
Index: 19 MSWPE2J180737OXEJAN
Index: 20 3Y5EBBSO6LNP59STAZY4AR5V3UH9A0557CNXXRNDJ45XNS875DDU
Index: 21 TSL3KLQ3TOGPRR3V56SLVVFWIILWJE6WK
Index: 22 OTB4MG7J0QYH5AFLAGUJ08MZUC94UORTF8CJTBUMNM4Z7AMLQ7D0BB3
Index: 23 HMJKGCZL9FC77619WI5ODX1UZYNWL1SDEWBH1JFLWS027P
Index: 24 UFED3FOMUVZVSYDAIX82L4UHMCU1U79WKL3QG
Index: 25 Y80JRVCYXWTSRF8WC0V610VX1XWCLG5X3V8ACBN9FYO8HCP3XXIC5K58MCR399NQ
Index: 26 6Z6H8TBMV0CLXPZI2PX822SZ9Y9TT9GL7HLNSWZDHZJU3WZX2VHTZS7EGHHKUR3VT1OPDM0FZ
Index: 27 0CS85N8L182WVPJGGKPPT06XACIKUP5B3G24VHM3LI0537F8F7FPZK
Paragraph 1:
Index: 0 83FY1LC12PWPU98WDL9B4C6JEWJPLTG2Y0ISYXQO2BE0L0MGRDHYAFB665TECWPJI4040P7P4VI28G7OKC8HMS2
Index: 1 ZMW2ELMFV4SR9SQBG13O6I708F49YI7ZBHEN3FLTJDGDXPO1W7BUZ
Index: 2 WQO649QMRN72P1NCIAPJF3C4CS0CM1GMAYVY8
Index: 3 LMC6V2F5AXOUYBEPH3OU3LIOA0HU21FYDLYDHJHJZHSCY1CFHUQ2KOD9DY54VUCIRZRNMBH7VF4W3G0IYBMIKNOYHYAT
Index: 4 MXEEJV8KY3GMTHETRG68WGTI48DK3FXBYTIR0RT
Index: 5 189IG51GKE0SDV1GD5KKRYRSFFY98X39XLGYHLB8H7AYPF8C2CN4HIEDRQC
Index: 6 H1H
Index: 7 L151OC824MDTX2DAHVH6J82OHDH1IA1QZNNYJGXZDVA4FUPYMB3VUKNM8QTL5HU
Index: 8 VX4JOP1A7R3Y77JXXSOGGF6OAAZ2WM45BHJRZGJ7K3XCRYPBH6YM3NWP1PJO08NVX7X0X17RIQ5NR37LV
Index: 9 U0YRCXU30K65HMQCOTBZNQ8GEMRJ87S73CNW7G59F4BXUMJS7OONJ5KE2RNZFL5219
Index: 10 F93EIYCT
Index: 11 PKV1D8MTTFX71I4P2F338I6VKDTDKFYHM0ZR5VWG9LJVLFN09YPTI0
Index: 12 GOAR9PIJNRQVATMUHTW4X9KJE02EVZF8VGSD5EW10B6E5UMHWEI9W56HD
Paragraph 2:
Index: 5 189IG51GKE0SDV1GD5KKRYRSFFY98X39XLGYHLB8H7AYPF8C2CN4HIEDRQC
Index: 6 H1H
Index: 7 L151OC824MDTX2DAHVH6J82OHDH1IA1QZNNYJGXZDVA4FUPYMB3VUKNM8QTL5HU
Index: 8 VX4JOP1A7R3Y77JXXSOGGF6OAAZ2WM45BHJRZGJ7K3XCRYPBH6YM3NWP1PJO08NVX7X0X17RIQ5NR37LV
Index: 9 U0YRCXU30K65HMQCOTBZNQ8GEMRJ87S73CNW7G59F4BXUMJS7OONJ5KE2RNZFL5219
Index: 10 F93EIYCT
Index: 11 PKV1D8MTTFX71I4P2F338I6VKDTDKFYHM0ZR5VWG9LJVLFN09YPTI0
Index: 12 GOAR9PIJNRQVATMUHTW4X9KJE02EVZF8VGSD5EW10B6E5UMHWEI9W56HD
Index: 13 MJXEYXLR94BIZD65DVDFOUNVRQRFM0JK9E1NEWNI2OVSFOPFC02LE8M26BWHFGEJV0JVLT0QH4
Index: 14 A95PDBMDV77GB19QCAGDWJL6PE43S9LDJVM2
Index: 15 WTF
Index: 16 CTLXTH3MCYQB000X8A8HSUVW46QPGPQQBJT0AJ57ARPL4CT4VFCVU7KS7Z2X0OGXI99QGAXZFAHBEK12N
Index: 17 3AN46D9B2LQIGWL2D5CCYUSNQT0INX7AJFUFJND6RFILJ64V0MH6ZL7JSAOMM
Expect Output:
Index: 0 83FY1LC12PWPU98WDL9B4C6JEWJPLTG2Y0ISYXQO2BE0L0MGRDHYAFB665TECWPJI4040P7P4VI28G7OKC8HMS2
Index: 1 ZMW2ELMFV4SR9SQBG13O6I708F49YI7ZBHEN3FLTJDGDXPO1W7BUZ
Index: 2 WQO649QMRN72P1NCIAPJF3C4CS0CM1GMAYVY8
Index: 3 LMC6V2F5AXOUYBEPH3OU3LIOA0HU21FYDLYDHJHJZHSCY1CFHUQ2KOD9DY54VUCIRZRNMBH7VF4W3G0IYBMIKNOYHYAT
Index: 4 MXEEJV8KY3GMTHETRG68WGTI48DK3FXBYTIR0RT
Index: 5 189IG51GKE0SDV1GD5KKRYRSFFY98X39XLGYHLB8H7AYPF8C2CN4HIEDRQC
Index: 6 H1H
Index: 7 L151OC824MDTX2DAHVH6J82OHDH1IA1QZNNYJGXZDVA4FUPYMB3VUKNM8QTL5HU
Index: 8 VX4JOP1A7R3Y77JXXSOGGF6OAAZ2WM45BHJRZGJ7K3XCRYPBH6YM3NWP1PJO08NVX7X0X17RIQ5NR37LV
Index: 9 U0YRCXU30K65HMQCOTBZNQ8GEMRJ87S73CNW7G59F4BXUMJS7OONJ5KE2RNZFL5219
Index: 10 F93EIYCT
Index: 11 PKV1D8MTTFX71I4P2F338I6VKDTDKFYHM0ZR5VWG9LJVLFN09YPTI0
Index: 12 GOAR9PIJNRQVATMUHTW4X9KJE02EVZF8VGSD5EW10B6E5UMHWEI9W56HD
Index: 13 MJXEYXLR94BIZD65DVDFOUNVRQRFM0JK9E1NEWNI2OVSFOPFC02LE8M26BWHFGEJV0JVLT0QH4
Index: 14 A95PDBMDV77GB19QCAGDWJL6PE43S9LDJVM2
Index: 15 WTF
Index: 16 CTLXTH3MCYQB000X8A8HSUVW46QPGPQQBJT0AJ57ARPL4CT4VFCVU7KS7Z2X0OGXI99QGAXZFAHBEK12N
Index: 17 3AN46D9B2LQIGWL2D5CCYUSNQT0INX7AJFUFJND6RFILJ64V0MH6ZL7JSAOMM
Paragraph 1:
Index: 0 P8BBFTZ1FUSMGETZFRBQBK7HLWJ91T0RC7382TU
Index: 1 REU0O6M64WHJWZMFA4ZTJ0AW4BJIKV6V6H860G2PKNEEMQ4NUY784BT0E76MWDVJ0VMP0QO3BKJ6W5JNH
Index: 2 YWX715YI12KP2H15O1EPWEJD6U2WEJXSF0P8V24R0SZVTVSCF0RSJ2KTNUBHDCESF1KB23JV7WYEOXUKB0RN1EJMP5
Index: 3 B1XOXOHQ1LQJLQ6VWDGFZA0FNV00AS8V6II4KIBZHH29VQF65TWIJZ5ABRA
Index: 4 XQQJN4MD
Index: 5 BLOCQ8SH0T7P35Q6ZMHMI3
Index: 6 H8C01TW1DBY3HHF31N3K8DW3U9NXSF19ITGEOH0YE24OECJYUTQ8OS3DLIG1F9J7KZUXABPTWEGGJI
Index: 7 RZZD8Z2V00D2FB9TET6DPSVXSD7LKLX3DTYCQ6KIRE377IJRXVBXNEJ9EBU52QKOCJZVN
Paragraph 2:
Index: 5 BLOCQ8SH0T7P35Q6ZMHMI3
Index: 6 H8C01TW1DBY3HHF31N3K8DW3U9NXSF19ITGEOH0YE24OECJYUTQ8OS3DLIG1F9J7KZUXABPTWEGGJI
Index: 7 RZZD8Z2V00D2FB9TET6DPSVXSD7LKLX3DTYCQ6KIRE377IJRXVBXNEJ9EBU52QKOCJZVN
Index: 8 CIIYWLYXZK4PYYJAQ8KY7OMPPA3O5YTXE0T3OYS7KQMJAM2VFC20LY9X63IVSJ2A1GL7FQV1QNORCCODHHJ262MP156
Index: 9 Q6OBXLS4B5PYRAK8KRU4PFOK9AE945FKTALU8N41TTBL1UL5RNFKKCFLSE
Index: 10 XGTA
Index: 11 0FFQZ0A7X3K5DCTPZ
Index: 12 RQ059Q4AB4LHVAT5VWP4G1NHW
Index: 13 2KHQUW77BTP5GYVYYGVQIJLIQ694CZDSIRYU3VJZJX89Q0Q0I
Index: 14 DHWGJS989YWD4MQ6WYAB5C65HUKL20QJVVV66BHFU4WVDF2WT
Index: 15 D1ZGWBK09ZIXGJHMRJ0UAVQ4QAPL1B1X2IWZTO8UWFBS77YMN1YS69
Expect Output:
Index: 0 P8BBFTZ1FUSMGETZFRBQBK7HLWJ91T0RC7382TU
Index: 1 REU0O6M64WHJWZMFA4ZTJ0AW4BJIKV6V6H860G2PKNEEMQ4NUY784BT0E76MWDVJ0VMP0QO3BKJ6W5JNH
Index: 2 YWX715YI12KP2H15O1EPWEJD6U2WEJXSF0P8V24R0SZVTVSCF0RSJ2KTNUBHDCESF1KB23JV7WYEOXUKB0RN1EJMP5
Index: 3 B1XOXOHQ1LQJLQ6VWDGFZA0FNV00AS8V6II4KIBZHH29VQF65TWIJZ5ABRA
Index: 4 XQQJN4MD
Index: 5 BLOCQ8SH0T7P35Q6ZMHMI3
Index: 6 H8C01TW1DBY3HHF31N3K8DW3U9NXSF19ITGEOH0YE24OECJYUTQ8OS3DLIG1F9J7KZUXABPTWEGGJI
Index: 7 RZZD8Z2V00D2FB9TET6DPSVXSD7LKLX3DTYCQ6KIRE377IJRXVBXNEJ9EBU52QKOCJZVN
Index: 8 CIIYWLYXZK4PYYJAQ8KY7OMPPA3O5YTXE0T3OYS7KQMJAM2VFC20LY9X63IVSJ2A1GL7FQV1QNORCCODHHJ262MP156
Index: 9 Q6OBXLS4B5PYRAK8KRU4PFOK9AE945FKTALU8N41TTBL1UL5RNFKKCFLSE
Index: 10 XGTA
Index: 11 0FFQZ0A7X3K5DCTPZ
Index: 12 RQ059Q4AB4LHVAT5VWP4G1NHW
Index: 13 2KHQUW77BTP5GYVYYGVQIJLIQ694CZDSIRYU3VJZJX89Q0Q0I
Index: 14 DHWGJS989YWD4MQ6WYAB5C65HUKL20QJVVV66BHFU4WVDF2WT
Index: 15 D1ZGWBK09ZIXGJHMRJ0UAVQ4QAPL1B1X2IWZTO8UWFBS77YMN1YS69
Paragraph 1:
Index: 0 ZVV8987U47XS3CKF85T76TMD8ANJ130EOYYN9YFDVNC0Z58VH0AW8N8GIS98VY2BHSEFN7GKZQMTQWNDC1BA2DG
Index: 1 ZSF
Index: 2 YHR7UATH03HKU06RAP0WE653X2JDMDP52ZVS8P8PCGMJU0P
Index: 3 GYAJ
Index: 4 SM1LYJ11P5WNLS5EOSVRKT8TWJ6MI7XDGDJN3GKFGYXLZ6IIU62FP2R9NIZONPTSHTHHISLHIPKW5
Index: 5 3ZAY2LERXNWK9VR521EFDGZA9CVU79S4DZO9NZWHNZ53V8SZZMXTS0UXA9Y00UUY51
Index: 6 JHSSDE62NK5PBT64VM9MM
Index: 7 08OA6R2FH830ISH4
Index: 8 OV8GNFUXG4Z9L6P4EQTDCIO9IC7WKKNW02U1O8N34M0XDG6CO6ECY0RG
Index: 9 98LI7N5QCITLYQFCZJ0
Index: 10 15CG4HOGL8AKOUOACV694HA7N00P898Q1YPD6EN09YEEII7DBE
Index: 11 DN
Index: 12 XT4E2ER8HM9TTZELE7IGAFC6ZE3WN394DAB5I1LIIAR2EYYH90AC5G0RR8PYL4VNNEPTYICNV9
Index: 13 9YJ2AQVXW3696JTOKLX7OPDPAJFS0XXR5J12HGPHZH8UQFTJF32B7CTUV321KC69GODXS0GE6PHHRS8506N65VT30HHO
Index: 14 Y7WK8OCB50OXYER4LDD46AOZAEU5K6LT20ISU7S
Index: 15 634F9JGQB8OD
Index: 16 TRXT7K44H19
Index: 17 44869KOV88DGIZ07D3LRHQJIU9XWXJZC40FOIUCY9S
Index: 18 VNQKHT60OPRHOV
Index: 19 M9X17YJBMRULZT0WRYLY5EYPD0TLWNS13SICBIVPMME2XHHHX39SD74HLHYGF7O993SHLX
Index: 20 JD5MS9516TLX3NAY5YA13TOKO7F34ZA6AIZPHVLIPQ2X4KVV8FWSL510YV7
Index: 21 4B7HTOXVXVQKM1MN11PDMT4YCRVEQ90WX0ONSVDQWA8NZMFTTN87F3IKHI
Index: 22 B2TEX43XWN94G
Index: 23 9RLVR90LCUCB2Q3RDGKQBXD6KS5ZTFUT1JGM7ZZJOZ08BWCM3EK2U0WLNPL8DB26AT
Index: 24 TKRUOQACL6F4XQT5P518BX48RN
Index: 25 FM737SNSCMT5MTXKPIVXRUFNBJUH6PSDAY5ZOCHLK8QT59POOMPZ60KVHU2Y7GWW3Q5XY86MBJNTD
Index: 26 RB4F3TA2GKOJR4JTODL30PE1ZPQCYXM1RVC141MCWAJUJOQCCS5JHJ5B6CQND
Paragraph 2:
Index: 24 TKRUOQACL6F4XQT5P518BX48RN
Index: 25 FM737SNSCMT5MTXKPIVXRUFNBJUH6PSDAY5ZOCHLK8QT59POOMPZ60KVHU2Y7GWW3Q5XY86MBJNTD
Index: 26 RB4F3TA2GKOJR4JTODL30PE1ZPQCYXM1RVC141MCWAJUJOQCCS5JHJ5B6CQND
Index: 27 ET8X261SYW1IHZGUSL8O9G1CTHZA41L89Z5ZWWWTKU3IS8CG5MUEOZ7815DUH1X7K2JR3Q76YODPMTUUFSFSHGTJ1770S
Index: 28 MT667Z
Index: 29 UMOOYQAVRVILSPYWFZDIA06SHNWCUTQV45UG0ET0TXJLZP9WY60G4RY4Q5HK47B8FXRX4
Index: 30 5BGNYMQU31O9NX2J1MG0Z46I6WWLGC8M2GBZAQ2MN6CP64UNF5
Expect Output:
Index: 0 ZVV8987U47XS3CKF85T76TMD8ANJ130EOYYN9YFDVNC0Z58VH0AW8N8GIS98VY2BHSEFN7GKZQMTQWNDC1BA2DG
Index: 1 ZSF
Index: 2 YHR7UATH03HKU06RAP0WE653X2JDMDP52ZVS8P8PCGMJU0P
Index: 3 GYAJ
Index: 4 SM1LYJ11P5WNLS5EOSVRKT8TWJ6MI7XDGDJN3GKFGYXLZ6IIU62FP2R9NIZONPTSHTHHISLHIPKW5
Index: 5 3ZAY2LERXNWK9VR521EFDGZA9CVU79S4DZO9NZWHNZ53V8SZZMXTS0UXA9Y00UUY51
Index: 6 JHSSDE62NK5PBT64VM9MM
Index: 7 08OA6R2FH830ISH4
Index: 8 OV8GNFUXG4Z9L6P4EQTDCIO9IC7WKKNW02U1O8N34M0XDG6CO6ECY0RG
Index: 9 98LI7N5QCITLYQFCZJ0
Index: 10 15CG4HOGL8AKOUOACV694HA7N00P898Q1YPD6EN09YEEII7DBE
Index: 11 DN
Index: 12 XT4E2ER8HM9TTZELE7IGAFC6ZE3WN394DAB5I1LIIAR2EYYH90AC5G0RR8PYL4VNNEPTYICNV9
Index: 13 9YJ2AQVXW3696JTOKLX7OPDPAJFS0XXR5J12HGPHZH8UQFTJF32B7CTUV321KC69GODXS0GE6PHHRS8506N65VT30HHO
Index: 14 Y7WK8OCB50OXYER4LDD46AOZAEU5K6LT20ISU7S
Index: 15 634F9JGQB8OD
Index: 16 TRXT7K44H19
Index: 17 44869KOV88DGIZ07D3LRHQJIU9XWXJZC40FOIUCY9S
Index: 18 VNQKHT60OPRHOV
Index: 19 M9X17YJBMRULZT0WRYLY5EYPD0TLWNS13SICBIVPMME2XHHHX39SD74HLHYGF7O993SHLX
Index: 20 JD5MS9516TLX3NAY5YA13TOKO7F34ZA6AIZPHVLIPQ2X4KVV8FWSL510YV7
Index: 21 4B7HTOXVXVQKM1MN11PDMT4YCRVEQ90WX0ONSVDQWA8NZMFTTN87F3IKHI
Index: 22 B2TEX43XWN94G
Index: 23 9RLVR90LCUCB2Q3RDGKQBXD6KS5ZTFUT1JGM7ZZJOZ08BWCM3EK2U0WLNPL8DB26AT
Index: 24 TKRUOQACL6F4XQT5P518BX48RN
Index: 25 FM737SNSCMT5MTXKPIVXRUFNBJUH6PSDAY5ZOCHLK8QT59POOMPZ60KVHU2Y7GWW3Q5XY86MBJNTD
Index: 26 RB4F3TA2GKOJR4JTODL30PE1ZPQCYXM1RVC141MCWAJUJOQCCS5JHJ5B6CQND
Index: 27 ET8X261SYW1IHZGUSL8O9G1CTHZA41L89Z5ZWWWTKU3IS8CG5MUEOZ7815DUH1X7K2JR3Q76YODPMTUUFSFSHGTJ1770S
Index: 28 MT667Z
Index: 29 UMOOYQAVRVILSPYWFZDIA06SHNWCUTQV45UG0ET0TXJLZP9WY60G4RY4Q5HK47B8FXRX4
Index: 30 5BGNYMQU31O9NX2J1MG0Z46I6WWLGC8M2GBZAQ2MN6CP64UNF5
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/255182/231235">A Paragraph Merger with Removing Overlapped Duplicated Lines in C#</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The implementation of <code>ParagraphMergerTester</code> class is the main idea here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T03:42:56.107",
"Id": "257004",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"strings",
"array",
"random"
],
"Title": "A Tester of Paragraph Merger for Removing Overlapped Duplicated Lines in C#"
}
|
257004
|
<p>I'm programming a multithreaded application (server-client UNIX socket) implemented for the server-side. I have two thread <code>check_cmd_thr</code> and <code>server_thr</code>.</p>
<p>I use <code>check_cmd_thr</code> to check data input from keyboard, if the input is <code>start</code> then the server is allowed to receive messages, if the input is <code>stop</code> then the server is not allowed to receive messages.</p>
<p>The purpose of this code is show the reliability of the UNIX datagram socket.</p>
<p>The code is working well 90%, it's just about the performance of the code.</p>
<ul>
<li>When the user sends <code>stop</code>, the server doesn't stop receiving messages immediately.</li>
<li>After the server stop receiving message, the client still sends successfully 11 messages before stopping to wait for the server. The point is, at that moment, the server doesn't show those 11 messages to the console log.</li>
<li>When the user sends <code>start</code>, the server "pop up" those 11 messages and continues receiving new messages from the client.</li>
</ul>
<p>What I expect is</p>
<ul>
<li>When the user sends <code>stop</code>, the server stop receiving messages immediately, and the client can not sends any messages to the server after that.</li>
</ul>
<p>I think that the design of the code implemented for the server-side is not good. Please show me some suggestions to improve. Thank you.</p>
<hr />
<p><strong>Server's code</strong></p>
<pre><code>#include "urd_hdr.h"
#include <pthread.h>
#define SERVER_LOCK() pthread_mutex_lock(&mtx)
#define SERVER_UNLOCK() pthread_mutex_unlock(&mtx);
static u_int8_t rx_is_allowed = 0;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static int init_server(char *svr_path);
static void *check_cmd_thr(void *arg);
static void *server_thr(void *arg);
/**
* @brief Initialize server
* @param svr_path socket pathname of server
* @return Bound socket of server, -1 for errors
*/
static int init_server(char *svr_path)
{
SOCK_ADDR_UN_t svr_addr;
int sfd;
// Create socket:
sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sfd == -1) {
printf("Error line[%d]: %s\n", __LINE__, strerror(errno));
return -1;
}
// Verify socket's namepath:
if (strlen(svr_path) > (sizeof(svr_addr.sun_path) - 1)) {
printf("Error line[%d]: invalid socket name\n", __LINE__);
return -1;
}
// Remove any exitsting file having the same namepath with server's:
if ((remove(svr_path) == -1) && (errno != ENOENT)) {
printf("Error line[%d]: %s\n", __LINE__, strerror(errno));
return -1;
}
// Bind the socket to desired addr:
memset(&svr_addr, 0, sizeof(SOCK_ADDR_UN_t));
svr_addr.sun_family = AF_UNIX;
strncpy(svr_addr.sun_path, svr_path, sizeof(svr_addr.sun_path) - 1);
if (bind(sfd, (SOCK_ADDR_t *)&svr_addr, sizeof(SOCK_ADDR_UN_t)) == -1) {
printf("Error line[%d]: %s\n", __LINE__, strerror(errno));
return -1;
}
return sfd;
}
static void *check_cmd_thr(void *arg)
{
char in_buf[10];
int8_t len;
printf ("Start %s\n", __func__);
while (1) {
len = read(STDIN_FILENO, in_buf, sizeof(in_buf));
if (len == -1) {
printf("Error line[%d]: fails to read from stdin, %s\n", __LINE__, strerror(errno));
continue;
}
if (len > sizeof(in_buf)) {
printf("The length of input buffer is too long\n");
continue;
}
in_buf[len - 1] = 0x0;
SERVER_LOCK();
if (strcmp(in_buf, "start") == 0) {
printf("=> Start receiving packets\n");
rx_is_allowed = 1;
} else if (strcmp(in_buf, "stop") == 0) {
printf("=> Stop receiving packets\n");
rx_is_allowed = 0;
} else {
printf("Invalid input buffer\n");
}
SERVER_UNLOCK();
}
return 0;
}
static void *server_thr(void *arg)
{
int16_t sfd;
int8_t buf[SOCKET_BUF_SIZE];
ssize_t num_rw;
printf ("Start %s\n", __func__);
sfd = init_server(SOCKET_SV_PATH);
if (sfd == -1) {
printf("Failed to initialize server\n");
} else {
printf("Initialize server successfully\n");
}
while (1) {
SERVER_LOCK();
if (rx_is_allowed) {
// Receive data from client:
memset(buf, 0, sizeof(buf));
num_rw = recvfrom(sfd, buf, SOCKET_BUF_SIZE, 0, NULL, NULL);
if (num_rw == -1) {
printf("Error line[%d]: %s\n", __LINE__, strerror(errno));
SERVER_UNLOCK();
continue;
}
printf("Server received %ld bytes, ret_buf=[%.*s]\n", (long)num_rw, (int)num_rw, buf);
}
SERVER_UNLOCK();
usleep(100);
}
return 0;
}
int main(int argc, char **argv)
{
pthread_t tid_1, tid_2;
int ret;
rx_is_allowed = 1;
ret = pthread_create(&tid_1, NULL, server_thr, NULL);
if (ret != 0) {
printf("Fail to create server_thr\n");
} else {
printf("Create server_thr succesfully\n");
}
ret = pthread_create(&tid_2, NULL, check_cmd_thr, NULL);
if (ret != 0) {
printf("Fail to create check_cmd_thr\n");
} else {
printf("Create check_cmd_thr succesfully\n");
}
ret = pthread_join(tid_1, NULL);
if (ret != 0) {
printf("Fail to join server_thr\n");
} else {
printf("Join server_thr succesfully\n");
}
ret = pthread_join(tid_2, NULL);
if (ret != 0) {
printf("Fail to join check_cmd_thr\n");
} else {
printf("Join check_cmd_thr succesfully\n");
}
return 0;
}
</code></pre>
<hr />
<p><strong>Header file</strong></p>
<pre><code>#ifndef _URD_HDR_H_
#define _URD_HDR_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <unistd.h>
#define SOCKET_SV_PATH "/tmp/dxduc/ud_reliable"
#define SOCKET_BUF_SIZE 20
typedef struct sockaddr SOCK_ADDR_t;
typedef struct sockaddr_un SOCK_ADDR_UN_t;
typedef socklen_t SOCKLEN_t;
#endif
</code></pre>
<hr />
<p><strong>Client's code</strong></p>
<pre><code>#include "urd_hdr.h"
#define MAX_MSG_SIZE 200
static void send_msg(int sd, const SOCK_ADDR_UN_t *addr, SOCKLEN_t addr_len);
int main(int argc, char **argv)
{
SOCK_ADDR_UN_t svr_addr;
int sfd;
SOCKLEN_t svr_addr_len;
// Create socket:
sfd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (sfd == -1) {
printf("%s, %s-line %d\n", strerror(errno), __func__, __LINE__);
exit(EXIT_FAILURE);
}
// Construct server's address:
memset(&svr_addr, 0, sizeof(SOCK_ADDR_UN_t));
svr_addr.sun_family = AF_UNIX;
strncpy(svr_addr.sun_path, SOCKET_SV_PATH, sizeof(svr_addr.sun_path) - 1);
svr_addr_len = sizeof(SOCK_ADDR_UN_t);
printf("Client is ready to run\n");
while (1) {
send_msg(sfd, &svr_addr, svr_addr_len);
sleep(1);
}
}
static void send_msg(int sd, const SOCK_ADDR_UN_t *addr, SOCKLEN_t addr_len)
{
static int idx = 0;
static char str[] = "message ";
static char msg[MAX_MSG_SIZE];
// Format message before sending:
memset(&msg, 0, sizeof(msg));
sprintf(msg, "%s%d", str, idx++);
// Send msg to server:
if (sendto(sd, msg, strlen(msg), 0, (SOCK_ADDR_t *)addr, addr_len) != strlen(msg)) {
printf("%s, %s-line %d\n", strerror(errno), __func__, __LINE__);
exit(EXIT_FAILURE);
} else {
printf("Message is sent successfully: [%s]\n", msg);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T12:29:09.060",
"Id": "507589",
"Score": "0",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>First of all, get rid of your secret macro language so that other programmers who don't know your what your secret names mean can read the code. This means replace the mysterious, unreadable <code>SERVER_LOCK</code> with the super-readable <code>pthread_mutex_lock(&mtx)</code> and so on.</p>\n<p>Second, grabbing a mutex and holding on to it while the program does I/O or unrelated string comparisons etc is very bad for performance. You do this all over, so it's a massive performance killer.</p>\n<p>What you should do is this:</p>\n<pre><code> if (strcmp(in_buf, "start") == 0) {\n printf("=> Start receiving packets\\n");\n\n pthread_mutex_lock(&mtx)\n rx_is_allowed = 1;\n pthread_mutex_unlock(&mtx);\n } \n else if (strcmp(in_buf, "stop") == 0) {\n printf("=> Stop receiving packets\\n");\n \n pthread_mutex_lock(&mtx)\n rx_is_allowed = 0;\n pthread_mutex_unlock(&mtx);\n } \n else {\n printf("Invalid input buffer\\n");\n }\n</code></pre>\n<p>That is, hold on to the mutex as short a time as possible and only for the purpose of protecting variables shared between threads. In this case <em>only</em> when you modify the <code>rx_is_allowed</code> variable (or any such variable shared between threads). Fix this and I'm pretty certain all the mentioned problems will disappear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T09:14:47.800",
"Id": "507567",
"Score": "0",
"body": "I tried but the client still sends 11 messages succesfully after the server stops receiving messages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T10:06:03.760",
"Id": "507575",
"Score": "0",
"body": "@xuanduc611 Did you make changes on _all_ places where you use the secret macro? The one in my answer is just to illustrate, you need to do this everywhere when you grab a mutex."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T08:54:15.043",
"Id": "257013",
"ParentId": "257005",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code>#define SERVER_LOCK() pthread_mutex_lock(&mtx)\n#define SERVER_UNLOCK() pthread_mutex_unlock(&mtx);\n</code></pre>\n</blockquote>\n<p>I'm not sure why you're defining macros for these simple calls (it mainly just serves to obfuscate your code), but that second one (with a <code>;</code>) is liable to give surprises when it's expanded.</p>\n<blockquote>\n<pre><code>static u_int8_t rx_is_allowed = 0;\n</code></pre>\n</blockquote>\n<p>I don't see where that type gets defined. Did you mean <code>uint8_t</code> (from <code><stdint.h></code>)? For a variable with <code>_is_</code> in the name like that, I would expect to see a <code>bool</code>.</p>\n<blockquote>\n<pre><code>typedef struct sockaddr SOCK_ADDR_t;\ntypedef struct sockaddr_un SOCK_ADDR_UN_t;\ntypedef socklen_t SOCKLEN_t;\n</code></pre>\n</blockquote>\n<p>Careful there - POSIX lays claim to type names ending in <code>_t</code>! Again, I don't see any value in these definitions, compared to using the type name that's better known to your readers.</p>\n<blockquote>\n<pre><code>sfd = socket(AF_UNIX, SOCK_DGRAM, 0);\nif (sfd == -1) {\n printf("Error line[%d]: %s\\n", __LINE__, strerror(errno));\n return -1;\n}\n</code></pre>\n</blockquote>\n<p>Good! I like to see errors properly checked. To make this even better, write the message to <code>stderr</code> rather than <code>stdout</code> (consider <code>perror()</code> for that), and return a <em>positive</em> value, preferably <code>EXIT_FAILURE</code>.</p>\n<blockquote>\n<pre><code>memset(&svr_addr, 0, sizeof(SOCK_ADDR_UN_t));\n</code></pre>\n</blockquote>\n<p>While not wrong, the correctness of this would be more obvious if we used <code>sizeof svr_addr</code>, so we didn't need to check if the type name agrees with the variable.</p>\n<hr />\n<p>Sorry, that's as far as I got before I had to yield to other demands on my time. I hope the partial review is useful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T13:34:37.090",
"Id": "257023",
"ParentId": "257005",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T03:46:52.747",
"Id": "257005",
"Score": "2",
"Tags": [
"c",
"multithreading"
],
"Title": "Multi-threaded application performance in C"
}
|
257005
|
<p>Trying to generate fractals image with given <a href="https://en.wikipedia.org/wiki/Iterated_function_system" rel="nofollow noreferrer">IFS equations</a>. I have two classes:</p>
<ul>
<li><code>Shape</code> - Gives co-ordinate to form a shape.</li>
<li><code>Ifs</code> - Takes the given <a href="https://en.wikipedia.org/wiki/Iterated_function_system" rel="nofollow noreferrer">IFS equations</a> and generates a fractal image.</li>
</ul>
<p><strong>Code</strong>:</p>
<p><strong><code>ifs.py</code></strong></p>
<pre><code>class Shape:
@staticmethod
def square():
x1 = np.concatenate(
(
np.linspace(0, 1, 100),
np.ones(100),
np.linspace(0, 1, 100),
np.zeros(100),
)
)
y1 = np.concatenate(
(
np.zeros(100),
np.linspace(0, 1, 100),
np.ones(100),
np.linspace(0, 1, 100),
)
)
return x1, y1
@staticmethod
def triangle():
x1 = np.concatenate(
(
np.linspace(0, 1, 100),
np.linspace(1, 0.5, 100),
np.linspace(0.5, 0, 100),
)
)
y1 = np.concatenate(
(np.zeros(100), np.linspace(0, 1, 100), np.linspace(1, 0, 100))
)
return x1, y1
@staticmethod
def line():
x1 = np.linspace(0, 1, 100)
y1 = np.zeros(100)
return x1, y1
class Ifs:
def __init__(self):
self._equationList = []
def AddEquations(self, EqnLst):
for eqn in EqnLst:
*coef, e, f = eqn
self._equationList.append((np.array(coef), np.array([e, f])))
def __str__(self):
out = ""
for idx, (coef, intercept) in enumerate(self._equationList, 1):
a, b, c, d = coef
e, f = intercept
out = (
out
+ f"""equation = {idx}: [[a = {a} b = {b}] [e = {e}
[c = {c} d = {d}]] f = {f}]\n\n"""
)
return out
def deterministic(self, shape=Shape.square(), iterations=6):
arr = np.column_stack(shape)
for i in range(iterations):
allEquations = []
for coef, intercept in self._equationList:
coef_ = coef.reshape(-1, 2)
transformed_arr = (coef_ * arr[:, None]).sum(
axis=2
) + intercept[None, :]
allEquations.append(transformed_arr)
arr = np.vstack(allEquations)
self.Values = arr
return arr
def plot(self):
x, y = zip(*self.Values)
plt.scatter(x, y, 1)
plt.show()
</code></pre>
<p><strong>Sample run</strong>:
I have given equations of <a href="http://larryriddle.agnesscott.org/ifs/siertri/siertri.htm" rel="nofollow noreferrer">Sierpinski Gasket</a></p>
<ul>
<li><code>python3 ifs.py</code> for what it's worth, this is how I run my code.</li>
</ul>
<pre><code>i = Ifs()
# There are 6 values in each equation a, b, c, d, e and f.
# where [a, b, c, d] is called coef
#[e, f] is called intercept
lst = [
[ 0.5, 0, 0, 0.5, 0, 0],
[0.5, 0, 0, 0.5, 0.5, 0],
[0.5, 0, 0, 0.5, 0, 0.5]
]
i.AddEquations(lst)
i.deterministic(Shape.triangle())
i.plot()
print(i)
</code></pre>
<p>Output to console:</p>
<pre><code>equation = 1: [[a = 0.5 b = 0.0] [e = 0
[c = 0.0 d = 0.5]] f = 0]
equation = 2: [[a = 0.5 b = 0.0] [e = 0.5
[c = 0.0 d = 0.5]] f = 0.0]
equation = 3: [[a = 0.5 b = 0.0] [e = 0.0
[c = 0.0 d = 0.5]] f = 0.5]
</code></pre>
<p><strong>Image of fractal generated:</strong></p>
<p><a href="https://i.stack.imgur.com/WMeMR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WMeMR.png" alt="enter image description here" /></a></p>
<hr />
<p>I feel there's a lot of room to improve this code. I looking for suggestions to improve the <code>Ifs</code> class be it a way of storing equations or improving <code>deterministic</code> function. <code>Shape</code> is written by another user I might not have the power to change it but I can put forward your valuable suggestions to the author.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T06:58:38.427",
"Id": "257010",
"Score": "3",
"Tags": [
"python",
"numpy"
],
"Title": "Generating basic Fractals"
}
|
257010
|
<p>I made my own custom OpenGL shader loader for C++. Please tell me is I'm doing anything incorrectly or anything to improve on. I've tested this and it works perfectly fine.</p>
<p>main.cc</p>
<pre><code>std::vector<ShaderInfo> shader_info {
{GL_VERTEX_SHADER, "shader.vert"},
{GL_FRAGMENT_SHADER, "shader.frag"}
};
GLuint shader_program {LoadShaders(shader_info)};
glUseProgram(shader_program);
</code></pre>
<p>shader-loader.hh</p>
<pre><code>struct ShaderInfo {
GLenum type;
std::string file;
};
GLuint LoadShaders(const std::vector<ShaderInfo>&);
</code></pre>
<p>shader-loader.cc</p>
<pre><code>GLuint LoadShaders(const std::vector<ShaderInfo>& shader_info) {
GLuint program {glCreateProgram()};
std::vector<GLuint> detach;
for (auto info : shader_info) {
std::ifstream file {info.file, std::ios_base::in};
file.seekg(0, std::ios_base::end);
std::string source(file.tellg(), '\0');
file.seekg(0, std::ios_base::beg);
file.read(&source[0], source.size());
file.close();
GLuint shader {glCreateShader(info.type)};
GLchar* source_ptr {&source[0]};
glShaderSource(shader, 1, &source_ptr, nullptr);
glCompileShader(shader);
glAttachShader(program, shader);
glDeleteShader(shader);
detach.push_back(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLint length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
std::string log(length, '\0');
glGetShaderInfoLog(shader, length, nullptr, &log[0]);
glDeleteProgram(program);
throw std::runtime_error(log);
}
}
glLinkProgram(program);
for (auto shader : detach)
glDetachShader(program, shader);
GLint status;
glGetProgramiv(program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLint length;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length);
std::string log(length, '\0');
glGetProgramInfoLog(program, length, nullptr, &log[0]);
glDeleteProgram(program);
throw std::runtime_error(log);
}
return program;
}
<span class="math-container">`````</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T17:57:08.993",
"Id": "507621",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)."
}
] |
[
{
"body": "<ul>\n<li><p><code>for (auto info : shader_info)</code> -> <code>for (auto const& info : shader_info)</code> to avoid a string copy.</p>\n</li>\n<li><p>Reading the source file into a string should probably be a separate function.</p>\n</li>\n<li><p>We should throw an error if the file fails to open. (<code>tellg</code> will return <code>-1</code> in that case).</p>\n</li>\n<li><p>I find it's often helpful to output more than one shader object log before stopping compilation (for example, if we have a minor error in the vertex shader, and another one in the fragment shader, we can see and fix both at once, rather than only having the vertex shader error in the log).</p>\n</li>\n</ul>\n<p>e.g.:</p>\n<pre><code>GLuint LoadShaders(const std::vector<ShaderInfo>& shader_info) {\n // ...\n bool compiled = true; // flag to indicate overall compile status\n\n for (auto const& info : shader_info) {\n // ... read file and compile shader\n\n GLint status;\n glGetShaderiv(shader, GL_COMPILE_STATUS, &status);\n\n if (status == GL_FALSE) {\n // ... get log string\n \n // log the error (if you have an existing logging system, or print to std::cerr)\n LogError("glCompileShader() failed for shader object: " + info.file);\n LogError(log);\n \n compiled = false; // set the overall flag to false\n }\n }\n \n // and now we throw!\n if (!compiled) {\n glDeleteProgram(program);\n throw std::runtime_error("Shader compilation failed!");\n }\n\n // ... link program etc. as before\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T13:34:25.097",
"Id": "507592",
"Score": "0",
"body": "How can I combine the logs from 2 shaders compilation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T16:46:10.997",
"Id": "507611",
"Score": "0",
"body": "Edited to show what I mean. It depends how you're logging things. It's really just moving the `throw` a bit later."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T10:12:27.073",
"Id": "257015",
"ParentId": "257012",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "257015",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T07:52:01.640",
"Id": "257012",
"Score": "1",
"Tags": [
"c++",
"opengl",
"glsl"
],
"Title": "OpenGL Shader Loader in C++"
}
|
257012
|
<p>So I created a wrapper class to authenticate user via POST HTTP request.</p>
<pre class="lang-php prettyprint-override"><code> class Nucleolus
{
public const AUTHEN_USER_URL = "localhost:8000/authen/user";
protected $ch;
public function __construct(string $token)
{
$this->ch = curl_init();
curl_setopt($this->ch, CURLOPT_URL, self::AUTHEN_USER_URL);
curl_setopt($this->ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
"Authorization: Bearer " . $token,
]);
curl_setopt($this->ch, CURLOPT_POST, 1);
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
}
public function authenticate(string $username, string $password, string $serverUrl = null)
{
$url = $serverUrl ? $serverUrl : $_SERVER['SERVER_NAME'];
curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode(compact('url', 'username', 'password')));
return json_decode(curl_exec($this->ch), true);
}
public function __destruct()
{
curl_close($this->ch);
}
}
</code></pre>
<p>Then the other developers can do the following.</p>
<pre class="lang-php prettyprint-override"><code> $nucleolus = new Nucleolus($token);
$result = $nucleolus->authenticate($username, $password);
</code></pre>
<p>and retrieve result as a PHP array.<br />
Please review.</p>
|
[] |
[
{
"body": "<p>Let me be frank: this code is just a Frankenstein sewn from different unrelated parts. Basically here are two main problems:</p>\n<ul>\n<li>sending HTTP requests is a distinct task and should be performed by another wrapper</li>\n<li>splitting the main functionality between two methods just makes no sense. I do understand that you probably wanted to make use of constructor, but that's not how it is done</li>\n</ul>\n<h2>The HTTP request class</h2>\n<p>Basically there must be a class that does HTTP requests with methods to set particular settings, such as</p>\n<ul>\n<li><code>setAuth(new BearerAuth($token))</code></li>\n<li><code>setContentType()</code></li>\n<li><code>setUrl()</code></li>\n<li>etc</li>\n</ul>\n<h2>The error checking</h2>\n<p>Also, in this class, it is important to check for errors. Right now your code returns whatever is sent by the other party. But it is not necessarily would be JSON of a particular format. It could be HTML, JSON that contains some different data, an empty string, etc.</p>\n<ul>\n<li>First of all the code must check for the curl_error. In case there is, it must throw an Exception</li>\n<li>Then it must try to decode JSON. If it fails it must throw an Exception</li>\n<li>Then it must check if the decoded data contains expected information. If it doesn't, it must throw an Exception</li>\n<li>only then it must return the data</li>\n</ul>\n<h2>The actual class</h2>\n<p>And then there could be a class to interact with a particular API, something like this</p>\n<pre><code>class Nucleolus\n{\n protected $transport;\n protected $host;\n\n public function __construct(string $host, string $token)\n {\n $this->transport = new HTTPTransport;\n $this->transport->setAuth(new BearerAuth($token));\n $this->transport->setContentType('application/json');\n }\n\n public function authenticate(string $username, string $password, string $serverUrl = null)\n {\n $this->transport->setUrl($this->host."/authen/user");\n $result = $this->transport->post([\n 'url' => $serverUrl ? $serverUrl : $_SERVER['SERVER_NAME'], \n 'username' => $username, \n 'password' => $password,\n ]);\n $data = JSON::decode($result);\n if ($data === true)\n return true;\n } else {\n throw new NucleolusException("Incorrect data from auth: $result");\n }\n }\n}\n</code></pre>\n<p>Destructor is not really needed as PHP will destruct everything itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:31:50.800",
"Id": "507579",
"Score": "0",
"body": "thanks for your comment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:35:12.933",
"Id": "507580",
"Score": "0",
"body": "is there a way to do it in one file so that it's easy to distribute?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:37:52.667",
"Id": "507581",
"Score": "0",
"body": "What do you mean, \"easily distribute\"? Distribution is usually done through composer packages"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:42:42.763",
"Id": "507583",
"Score": "0",
"body": "there are still people who don't use composer in the organization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:45:43.233",
"Id": "507584",
"Score": "0",
"body": "Inside the organization a Concurrent Versions System such as git must be used for the code distribution"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:24:59.877",
"Id": "257019",
"ParentId": "257014",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T09:28:39.253",
"Id": "257014",
"Score": "0",
"Tags": [
"php",
"authentication",
"curl"
],
"Title": "A wrapper for user authentication using cURL in PHP"
}
|
257014
|
<p>The following code creates a simple tree structure and then walks through the tree looking for node with the value 9 that appears after we have seen a node with the value 1 and a node with the value 4 (order of the 1 and 4 don't matter).</p>
<pre><code>type N = Value of int | Children of N list
type S = {oneFound:bool; fourFound:bool}
let walk () =
let mutable state = {oneFound = false; fourFound = false}
let rec walkImpl curNode =
match curNode with
| Value n -> match n with
| 1 -> state <- {state with oneFound = true }
| 4 -> state <- {state with fourFound = true }
| 9 -> if state.oneFound && state.fourFound then
printfn "Found a good 9"
else
printfn "Found a bad 9"
| _ -> ()
printfn "Node value %d" n
| Children c -> c |> List.iter (fun n -> walkImpl n)
walkImpl (Children [Value 1; Value 2 ; Children [Value 9; Children [Value 4; Value 5]; Value 9]])
walk ()
</code></pre>
<p>When I run it produces the correct output:</p>
<pre><code>Node value 1
Node value 2
Found a bad 9
Node value 9
Node value 4
Node value 5
Found a good 9
Node value 9
</code></pre>
<p>Is there a method to do this that threads the state through the recursive function calls rather than making it a mutable variable? The mutability is confined to my function but I keep thinking there must be a way to structure this that makes it unnecessary.</p>
<p>In real life the tree structure will be much larger, several thousand nodes and 10 levels deep, while the code has not run into any recursion limits yet are there improvements that would make this less likely?</p>
|
[] |
[
{
"body": "<p>At first step I've removed hardcoded into function input data, so it's become testable.</p>\n<pre><code> ...\n walkImpl (Children [Value 1; Value 2 ; Children [Value 9; Children [Value 4; Value 5]; Value 9]])\n \nwalk ()\n</code></pre>\n<pre><code>\nlet walk n =\n ...\n walkImpl n\n\nwalk (Children ...)\n</code></pre>\n<p>Than get rid of type which exists only for one function and replaced it with <a href=\"https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/anonymous-records\" rel=\"nofollow noreferrer\">anonymous record</a>.</p>\n<pre><code> let initialState = {| oneFound = false; fourFound = false |}\n</code></pre>\n<p>Afterwards comes hardest part of refactoring: remove mutability. In order to use <em>mutable</em> state in functional way we have to use recursion and pass state as parameter to function which must return updated state, so signature should be <code>State -> State</code> instead of <code>() -> ()</code> (<code>curNode</code> omitted for clarity).</p>\n<pre><code> | Value n ->\n let patched =\n match n with\n | 1 -> {| state with oneFound = true |}\n | 4 -> {| state with fourFound = true |}\n | 9 ->\n if state.oneFound && state.fourFound then\n printfn "Found a good 9"\n else\n printfn "Found a bad 9"\n state\n | _ -> state\n printfn "Node value %d" n\n patched\n</code></pre>\n<p>Now we have part of function that matches over <code>curNode</code> and transforms <code>state</code> if <code>Value</code> branch is evaluated. We also must transfer <code>state</code> when walking across different children while iterating list. <a href=\"https://fsharp.github.io/fsharp-core-docs/reference/fsharp-collections-listmodule.html#fold\" rel=\"nofollow noreferrer\"><code>List.fold</code></a> is function that iterates over list while keep tracking of state changes. All list function may be implemented with fold, such a powerful abstraction.</p>\n<pre><code> | Children c -> c |> List.fold walkImpl state\n</code></pre>\n<p>Now we have complete working example without mutations</p>\n<pre><code>type N = Value of int | Children of N list\n\nlet walk n =\n let rec walkImpl (state : {| oneFound: bool; fourFound: bool |}) curNode = // explicit type required here\n match curNode with\n | Value n ->\n let patched =\n match n with\n | 1 -> {| state with oneFound = true |}\n | 4 -> {| state with fourFound = true |}\n | 9 ->\n if state.oneFound && state.fourFound then\n printfn "Found a good 9"\n else\n printfn "Found a bad 9"\n state\n | _ -> state\n printfn "Node value %d" n\n patched\n | Children c ->\n c |> List.fold walkImpl state\n\n let initialState = {| oneFound = false; fourFound = false |}\n walkImpl initialState n\n |> ignore // don't care about state, because it's for internal use only\n\n[<EntryPoint>]\nlet main argv =\n walk (Children [Value 1; Value 2 ; Children [Value 9; Children [Value 4; Value 5]; Value 9]])\n 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T12:25:22.963",
"Id": "507676",
"Score": "0",
"body": "Yes, the key insight is replacing the List.iter with List.fold to allow the state to be tracked down into the Value nodes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T06:31:21.327",
"Id": "257050",
"ParentId": "257017",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257050",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:03:29.073",
"Id": "257017",
"Score": "1",
"Tags": [
"recursion",
"f#"
],
"Title": "Maintaining state while walking a tree structure"
}
|
257017
|
<p>Use-case in a nutshell: Interpolate fixed-sized data (a lookup table) that provides output values for combinations of a (fixed) number of inputs. The appropriate scaling is done externally, each axis starts at 0 and increments by 1. The output is a floating point value regardless of the table data type, the idea being that the user of this class can determine if rounding/casting is needed.</p>
<p>This function attempts to generalise <a href="https://en.wikipedia.org/wiki/Bilinear_interpolation" rel="nofollow noreferrer">(bi|tri|etc)linear interpolation</a> in a way that's efficient on a microcontroller (with hardware FPU).</p>
<p>A working example that can be copy-pasted:</p>
<pre><code>#include <cmath>
#include <array>
#include <cstddef>
#include <cstdint>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
namespace interpolate {
/**
* @brief Linear interpolation for N-dimensional data. Saturates / clamps search values to dataset range.
*
* This function is mainly meant to interpolate singleton values -such as lookup tables-, not entire images.
*
* @tparam DIMS Size of each dimension in supplied data array, excluding the last. For example 7 for a table with 7 columns and 3 rows.
* @tparam Td Type of data
* @tparam N Count of data
* @tparam Ts Type of search values / indices
* @param search... Search indices, the amount equal to the amount of dimensions.
* @return Td Interpolated value
*/
template <std::size_t... DIMS,
typename Td = decltype(0.0),
std::size_t N,
typename... Ts>
constexpr auto linear(const Td(&data)[N], const Ts& ...search) {
using index_t = std::size_t;
using fp_t = decltype(0.0); // Use the system default literal floating point type
using result_t = std::conditional_t<std::is_floating_point_v<Td> && (sizeof(Td) >= sizeof(fp_t)), Td, fp_t>; // Ensure we're always working in precise and reasonably performant floating point
constexpr index_t D {sizeof...(Ts)};
using search_set = std::array<std::common_type_t<Ts...>, D>;
if constexpr (sizeof...(Ts) > 1) {
constexpr index_t LAST_S { N / (DIMS * ...) };
constexpr std::size_t SIZES[D] { DIMS..., LAST_S };
constexpr std::size_t MAX[D] { (DIMS - 1u)..., LAST_S - 1 };
constexpr std::size_t L = 0;
constexpr std::size_t H = 1;
static_assert(sizeof...(DIMS) + 1 == sizeof...(Ts), "Amount of dimension sizes doesn't match search parameter count");
static_assert((DIMS * ...) != 0 && LAST_S != 0, "Can't interpolate singularities");
static_assert(N == (LAST_S * (DIMS * ...)), "Data size doesn't match provided dimension sizes");
index_t i[D][2] {{0}}; // High & low indices
fp_t w[D][2] {{0}}; // Associated weights
result_t result {0};
for (index_t j = 0; j < D; ++j) {
const auto searchval = search_set{{search...}}[j];
// Perform input clamping
if (searchval <= 0) {
// Keeping the indices one apart should do better in vectorisation
i[j][L] = 0;
i[j][H] = 1;
w[j][L] = 1;
w[j][H] = 0;
} else if (searchval >= MAX[j]) {
i[j][L] = MAX[j]-1;
i[j][H] = MAX[j];
w[j][L] = 0;
w[j][H] = 1;
} else {
i[j][L] = static_cast<index_t>(searchval);
if constexpr (false) {
// Sinus curve based fitting. TODO: Find an elegant way to toggle this
i[j][H] = i[j][L] + ((search_set{{search...}}[j] - i[j][L]) > 0);
w[j][H] = std::sin((i[j][L] + 0.5 - searchval) * M_PI) / -2.0 + 0.5;
} else {
// Linear
w[j][H] = searchval - static_cast<index_t>(searchval);
i[j][H] = i[j][L] + 1;
}
w[j][L] = 1 - w[j][H];
}
}
// Accumulate 2^D weighed results
for (index_t j = 0; j < (0b1 << D); ++j) {
fp_t weight { w[0][j & 0b1] };
index_t offset { 1 };
index_t idx { i[0][j & 0b1] };
for (index_t k = 1; k < D; ++k) {
const bool n = (j >> k) & 0b1;
weight *= w[k][n];
offset *= SIZES[k-1];
idx += i[k][n] * offset;
}
result += weight * data[idx];
}
return result;
} else {
const auto searchval = search_set{{search...}}[0];
if (searchval <= 0) {
return static_cast<result_t>(data[0]);
} else if (searchval >= N) {
return static_cast<result_t>(data[N-1]);
} else {
const auto i = static_cast<index_t>(searchval);
const auto w = searchval - i;
if (w == 0) {
return static_cast<result_t>(data[i]);
} else {
return static_cast<result_t>(data[i] * (1 - w) + data[i + 1] * w);
}
}
}
}
}
</code></pre>
<pre><code>// volatile
constexpr
float
// unsigned
data[] {
// 0 1 2 3
/* 0 */ 1000, 2000, 3000, 4000,
/* 1 */ 5000, 6000, 7000, 8000,
/* 2 */ 9000, 10000, 11000, 12000,
/* 3 */ 1000, 2000, 3000, 4000,
/* 4 */ 5000, 6000, 7000, 8000,
/* 5 */ 9000, 10000, 11000, 12000,
/* 6 */ 1000, 2000, 3000, 4000,
/* 7 */ 5000, 6000, 7000, 8000,
/* 8 */ 9000, 10000, 11000, 12000
};
int main() {
volatile unsigned interpolated1 __attribute__((unused)) = interpolate::linear(data, 2.5);
volatile unsigned interpolated2 __attribute__((unused)) = interpolate::linear<4>(data, 2.5, 1.5);
volatile unsigned interpolated3 __attribute__((unused)) = interpolate::linear<4,3>(data, 2.25, 1.25, 0.5);
}
</code></pre>
<p>I'd love to hear comments & critiques!</p>
|
[] |
[
{
"body": "<p>First, the input type is rather strange <code>const Td(&data)[N]</code> - normally one would want a <code>std::span</code> or equivalent and I don't think that fixing values of all dimensions as a template parameter is helpful. Number of dimensions indeed should be a template as otherwise implementation would be somewhat more problematic with requirements of dynamic memory usage.</p>\n<p>Second, <code>const Ts& ...search</code> you should wrap it as <code>std::array<floating_type, dims></code> or something of the sort instead of a sequence of arbitrary parameters.</p>\n<p>Perhaps, this is an oddness of programming for a micro controller, but generally I'd advice to wrap it all in a class and store important parameters like <code>SIZES[D]</code>, <code>MAX[D]</code>, and more importantly steps sizes as members of the class. And hopefully make the whole class <code>constexpr</code>. I am not certain which C++ version do you use and thus not entire certain that it is feasible.</p>\n<p>Lastly, the interpolation algorithm is inefficient. What you do is for each vertex of the <code>n</code> dimensional cube compute product of weights and sum it all together. Which is inefficient as you make <code>O(n)</code> products for each vertex with a bunch of rather random memory access.</p>\n<p>A faster approach is to interpolate according to a single dimension and get <code>n-1</code> dimensional cube of values - and repeat. This way you'll make <code>O(1)</code> products for each vertex. I suppose it is confusing what I mean without example.</p>\n<p>Let me give you one: you have <code>2x2x2</code> block <code>{{{1,2}{3,4}},{{5,6}{7,8}}}</code> and you want to compute interpolation at point <code>(0.3, 0.4, 0.8)</code>. So first you interpolate along first dimension and get 2x2 block:</p>\n<pre><code>{{1.3, 3.3}, {5.3, 7.3}} // here 1*(1-0.3) + 2*0.3 = 1.3, 3*(1-0.3) + 4*0.3 = 3.3 etc...\n</code></pre>\n<p>Then you interpolate along second dimension (interp value = 0.4) to get block of size 2 <code>{2.1, 6.1}</code> and finally, along the last dimension (interp value = 0.8) and get <code>2.1*(1-0.8)+6.1*0.8 = 5.3</code>.</p>\n<p>Here, as you can see it is a rather simple double loop that just applies <code>a[k] = a[2k]*(1-p)+a[2k+1]*p</code> for the majority of operations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T11:06:21.493",
"Id": "257061",
"ParentId": "257018",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T11:09:08.913",
"Id": "257018",
"Score": "2",
"Tags": [
"c++",
"template-meta-programming",
"embedded",
"interpolation"
],
"Title": "C++ generic, multi-dimensional linear interpolation template"
}
|
257018
|
<p><strong>Summary</strong></p>
<p>I have finished creating a secure login functionality. I have used 1 resource to help me with the security. The security section was copy and pasted but implemented into a class to suit it in my own way, but all the logic and properties, commands etc.. is all my work. <a href="https://medium.com/@mehanix/lets-talk-security-salted-password-hashing-in-c-5460be5c3aae" rel="nofollow noreferrer">https://medium.com/@mehanix/lets-talk-security-salted-password-hashing-in-c-5460be5c3aae</a></p>
<p>Would appreciate any helpful review to my current code I have, from the community in areas where I can improve.</p>
<p><strong>Current Code</strong></p>
<p><strong>SecurePasswordHasher.cs</strong></p>
<p>At the moment I do not use <code>public static string Hash(string password)</code> anywhere, the focus is at the verification.</p>
<pre><code>public static class SecurePasswordHasher
{
public static string Hash(string password)
{
// Create salt
byte[] salt;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);
// Create hash
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
byte[] hashBytes = new byte[36];
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);
return Convert.ToBase64String(hashBytes);
}
public static bool Verify(string savedPassword, string givenPassword)
{
byte[] hashBytes = Convert.FromBase64String(savedPassword);
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
var pbkdf2 = new Rfc2898DeriveBytes(givenPassword, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
int ok = 1;
for (int i = 0; i < 20; i++)
{
if (hashBytes[i + 16] != hash[i])
{
ok = 0;
}
}
if (ok == 1)
{
return true;
}
else
{
return false;
}
}
}
</code></pre>
<p><strong>LoginViewModel</strong></p>
<pre><code>public class LoginViewModel : BaseViewModel
{
// User Properties
private UserModel _User;
public UserModel User
{
get { return _User; }
set
{
_User = value;
OnPropertyChanged(nameof(User));
}
}
private string _FirstName;
public string FirstName
{
get { return _FirstName; }
set
{
_FirstName = value;
User = new UserModel
{
FirstName = _FirstName,
LastName = this.LastName,
Password = this.Password
};
OnPropertyChanged(nameof(FirstName));
}
}
private string _LastName;
public string LastName
{
get { return _LastName; }
set
{
_LastName = value;
User = new UserModel
{
LastName = _LastName,
FirstName = this.FirstName,
Password = this.Password
};
OnPropertyChanged(nameof(LastName));
}
}
private string _Password;
public string Password
{
get { return _Password; }
set
{
_Password = value;
User = new UserModel
{
FirstName = this.FirstName,
LastName = this.LastName,
Password = _Password
};
OnPropertyChanged(nameof(Password));
}
}
// Login Command
public ICommand LoginCommand { get; set; }
// Function
private bool LoginFunction(object param)
{
// Get user credentials
UserModel user = param as UserModel;
// Veryify credentials have data to work with
// Also, reason this method return a bool, because it prevents NullReferenceException.
if (user == null)
{
MessageBox.ShowMessageBox("Credentials not specified");
return false;
}
else if (user.FirstName == null || string.IsNullOrEmpty(user.FirstName))
{
MessageBox.ShowMessageBox("Firstname cannot be empty");
return false;
}
else if (user.LastName == null || string.IsNullOrEmpty(user.LastName))
{
MessageBox.ShowMessageBox("Surname field cannot be empty");
return false;
}
else if (user.Password == null || string.IsNullOrEmpty(user.Password))
{
MessageBox.ShowMessageBox("Password field cannot be empty");
return false;
}
// Find Firstname and Surename in the database
else
{
using (var conn = new MySqlConnection(ConnectionString.ConnString))
{
conn.Open();
string query = @"SELECT
*
FROM USERS u
JOIN DEPARTMENT d
on d.id = u.departmentid
JOIN usergroup ug
ON ug.id = u.UserGroupID
WHERE FirstName = @Firstname AND Lastname = @LastName";
var userDetails = conn.Query<UserModel>(query, new { FirstName = user.FirstName, LastName = user.LastName}).ToList();
// If user is found, proceed to verification
if(userDetails.Count() == 1)
{
// Get password from the user
string savedPasswordHash = userDetails.First().Password;
bool verification = SecurePasswordHasher.Verify(savedPasswordHash, Password);
if (verification == true)
{
// Store Username
UserData.FullName = $"{user.FirstName} {user.LastName}";
ShowDashboard.ShowDashboard();
return true;
}
// Password is incorrect
else
{
MessageBox.ShowMessageBox("User not found");
return false;
}
}
// User with the given Firstname and surename is not found
else
{
MessageBox.ShowMessageBox("User not found");
return false;
}
}
}
}
// Messagebox Interface
public IMessageBoxService MessageBox { get; set; }
// Open Dashboard Interface
public IShowDashboardService ShowDashboard { get; set; }
public LoginViewModel(IMessageBoxService messageBox, IShowDashboardService showDashboard)
{
this.MessageBox = messageBox;
this.ShowDashboard = showDashboard;
LoginCommand = new RelayCommand(param => LoginFunction(param));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T12:24:44.753",
"Id": "507587",
"Score": "1",
"body": "If *Most of it was just copy and paste* then what should be reviewed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T14:55:59.940",
"Id": "507600",
"Score": "0",
"body": "@BCdotWEB Altered."
}
] |
[
{
"body": "<h3>Storing password in <code>string</code> is totally insecure.</h3>\n<p>Because <code>string</code> is immutable object and can be kept in memory for undefined period of time. This makes easy to get clean password through not complicated reverse engineering operation.</p>\n<p>By the way</p>\n<blockquote>\n<p>The focus is at the verification.</p>\n</blockquote>\n<p>Ok</p>\n<p>Renamed <code>savedPassword</code> because it's a hash not clean password.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static bool Verify(string savedPasswordHash, string givenPassword)\n{\n byte[] hashBytes = Convert.FromBase64String(savedPasswordHash);\n byte[] salt = hashBytes.Take(16).ToArray();\n byte[] hash = new Rfc2898DeriveBytes(givenPassword, salt, 10000).GetBytes(20);\n \n return hashBytes.Skip(16).SequenceEqual(hash);\n}\n</code></pre>\n<p>That's it. Easy Linq query.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T16:56:44.690",
"Id": "507612",
"Score": "0",
"body": "@LV98 Here's my detailed [Russian StackOverflow answer](https://ru.stackoverflow.com/a/1245131/373567) how to securely use `PasswordBox` in WPF."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T17:03:11.803",
"Id": "507613",
"Score": "0",
"body": "I'm just wondering.. is it worth to have the security if the application is only used internally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T17:04:11.333",
"Id": "507614",
"Score": "0",
"body": "@LV98 at least it's worth to learn security."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:00:27.340",
"Id": "507622",
"Score": "0",
"body": "Agreed.. Any suggestions where I can start?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T16:51:40.093",
"Id": "257033",
"ParentId": "257022",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257033",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T12:02:48.887",
"Id": "257022",
"Score": "0",
"Tags": [
"c#",
"mysql"
],
"Title": "First-name, Last-name and Password logging in functionality using C#"
}
|
257022
|
<p>I have an array of object and I want to group/order some inner properties in a map according to a key.
I did this code but I would like to know if there was a way to optimize the code ?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const myArray = [{
getValue: () => {
return {
country: 'France',
city: 'Toulouse',
};
},
},
{
getValue: () => {
return {
country: 'England',
city: 'London',
};
},
},
{
getValue: () => {
return {
country: 'France',
city: 'Paris',
};
},
},
];
const myMap = new Map();
myArray.forEach(item => {
const key = item.getValue().country;
const value = item.getValue().city;
if (myMap.has(key)) {
myMap.get(key).push(value);
} else {
myMap.set(key, [value]);
}
});
for (const [key, value] of myMap) {
console.log(`${key} = ${value}`);
}</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>The code looks okay as is, but I would destructure the return value of the function rather than calling twice and also remove the brackets from the conditionals since they’re both one-liners</p>\n<pre><code>const myMap = new Map();\nmyArray.forEach(item => {\n const {key, value} = item.getValue();\n \n if (myMap.has(key)) myMap.get(key).push(value);\n else myMap.set(key, [value]);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T09:20:51.203",
"Id": "507728",
"Score": "2",
"body": "Never skimp on `{}` for code blocks. Missing `{}` after modifying code is an extremely common (non syntax error) hard to spot bug that can be completely eliminated if you always delimit code blocks with `{}`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T06:35:31.880",
"Id": "257091",
"ParentId": "257024",
"Score": "1"
}
},
{
"body": "<h2>Too complex</h2>\n<p>Don't make code more complicated than needed.</p>\n<p>The <code>getValue</code> function for each data item is entirely unnecessary. You can move the function out and reduce the data input complexity a great deal. See 1st rewrite.</p>\n<p>For each data item property you call <code>getValue</code> (once for <code>country</code> and once for <code>city</code>) which creates a new object each time it is called. This is a huge overhead, the items should be created only once (When code is parsed) and to process you should not need to make copies just to read properties.</p>\n<p>If you need the data items to be functions, don't write the function for each item, write the function once and return it using a second function. See 2nd rewrite.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Template literals\">Template_literals</a> can sometimes add a lot of noise to the construction of a string. Maybe <code>${key} = ${value}</code> can be better as <code>key + " = " + value</code>. Template literals do not make for better code just by using them.</p>\n<h2>Names</h2>\n<p>The naming is very poor. You should never get lazy with naming, even if its example code.</p>\n<ul>\n<li><code>key</code> and <code>value</code> should be <code>country</code> and <code>city</code></li>\n<li><code>myMap</code> Yes we know its a map, but what does it represent. <code>citesByCountry</code></li>\n</ul>\n<p>Code should never stand alone. Always write code as a <em>named</em> function, even when its just example code. See rewrite.</p>\n<h2>General points</h2>\n<p>Always code in <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Strict mode\">Strict_mode</a>.</p>\n<p>Prefer <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for...of\">for...of</a> loops over <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array\">Array</a> iterators when possible.</p>\n<p>You do two map look-ups with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Map has\">Map.has</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Map get\">Map.get</a> if an index exists. You can avoid one of the look-ups and use only <code>Map.get</code>. Check the result to determine if the map has the index you are looking for. See rewrite.</p>\n<p>Learn to use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. ?\">Conditional Operator <code>?</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. Nullish coalescing operator\">Nullish coalescing operator <code>??</code></a> and / or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. Optional chaining ?.\">Optional chaining <code>?.</code></a> to simplify statement combinations.</p>\n<h2>Rewrites</h2>\n<p>First without the overhead of the <code>getValue</code> call per item.</p>\n<pre><code>"use strict";\nfunction dataTest() {\n const addCountry = (country, city) => ({country, city});\n const data = [\n addCountry("France", "Toulouse"),\n addCountry("England", "London"),\n addCountry("France", "Paris"),\n ];\n function joinByCountry(data) {\n const countries = new Map();\n for (const {country, city} of data) {\n countries.get(country)?.push(city) ?? countries.set(country, [city]);\n }\n return countries;\n }\n\n for (const [country, cites] of joinByCountry(data)) { \n console.log(country + " = " + cites);\n }\n}\n</code></pre>\n<p>If <code>getValue</code> is required then write the <code>getValue</code> function once rather than for each item.</p>\n<p>This rewrite uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. ?\">Conditional Operator <code>?</code></a> to replace the if else statements.</p>\n<pre><code>"use strict";\nfunction dataTest() {\n const addCountry = (country) => ({ getValue() { return country} });\n const data = [\n addCountry({country: "France", city: "Toulouse"}),\n addCountry({country: "England", city: "London"}),\n addCountry({country: "France", city: "Paris"}),\n ];\n function joinByCountry(data) {\n const countries = new Map();\n for (const location of data) {\n const {country, city} = location.getValue(); \n const cites = countries.get(country);\n cites ? cites.push(city) : countries.set(country, [city]);\n }\n return countries;\n }\n\n for (const [country, cites] of joinByCountry(data)) { \n console.log(country + " = " + cites);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T09:15:48.217",
"Id": "257093",
"ParentId": "257024",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257093",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T13:43:06.273",
"Id": "257024",
"Score": "1",
"Tags": [
"javascript",
"typescript"
],
"Title": "Group inner properties from an array of objects to a map"
}
|
257024
|
<p>In an attempt to create a function that returns <code>x</code> with the <code>n</code> bits that begin at position <code>p</code> inverted, leaving the others unchanged - following the exercise in K&R - I've come up with the following piece of code.</p>
<p>Still, I find it unclear where to start counting, i.e. the result would be different if starting from the right. I am starting from the left - bit one is the first bit from the left.</p>
<pre class="lang-c prettyprint-override"><code>unsigned invert(unsigned x, unsigned p, unsigned n)
{
return x ^ ((~0U >> (p - 1 + (sizeof(int) * CHAR_BIT - p + 1 - n))) << (sizeof(int) * CHAR_BIT - p + 1 - n));
}
</code></pre>
<p>Which I'd then simplify to:</p>
<pre class="lang-c prettyprint-override"><code>unsigned invert(unsigned x, unsigned p, unsigned n)
{
return x ^ ((~0U >> (sizeof(int) * CHAR_BIT - n)) << (sizeof(int) * CHAR_BIT - p + 1 - n));
}
</code></pre>
<p>I'm not performing any boundary checks.</p>
<p>Is this good practice? Is there a cleaner solution?</p>
|
[] |
[
{
"body": "<p>When you find it "<em>unclear where to start counting</em>" you have encountered one of the greatest problems in software development: extracting useful specifications from your stakeholders! In these situations, when we can't just ask, then we need to choose an interpretation that seems most useful and reasonable, and (this is the important bit), be very clear that we had to make a choice, and what we chose.</p>\n<p>In this case, I would probably make a somewhat more specific name, and also add an explanatory comment:</p>\n<pre><code>/*\n * Returns x with n bits inverted starting at bit p\n * (counting from the left)\n * E.g. invert_bits(0x0000, 4, 2) == 0x0c00 for 16-bit unsigned\n */\nunsigned invert_bits(unsigned x, unsigned p, unsigned n)\n</code></pre>\n<p>That example in the comment would normally become one of the tests I use to verify the function.</p>\n<p>I find it odd that we're working with <code>unsigned</code> yet we use <code>sizeof (int)</code> to calculate the width. Although we know that <code>int</code> and <code>unsigned int</code> have the same size, it's clearer to be consistent. Actually, I would just use <code>sizeof x</code>, which then makes it easier to re-use the code - e.g. if we write a version for <code>unsigned long</code>.</p>\n<p>I think the arithmetic could be simplified if we consider that a mask with the leftmost <code>p</code> bits unset is <code>~0u >> p</code>. Using <code>invert_bits(0x0000, 4, 2)</code> again, as in the comment, we can visualise what we're doing:</p>\n<pre><code> 0000111111111111 mask_p = ~0u >> p;\n 0000001111111111 mask_n = mask_p >> n;\n 0000110000000000 mask_p ^ mask_n\n</code></pre>\n<p>As a completed function, we can reuse a single <code>mask</code> variable for this:</p>\n<pre><code>unsigned invert_bits(unsigned x, unsigned p, unsigned n)\n{\n unsigned mask = ~0u >> p;\n mask ^= mask >> n;\n return x ^ mask;\n}\n</code></pre>\n<p>The nice thing about this is that it adapts automatically to the type's size, without needing any <code>sizeof</code> at all in the computation.</p>\n<hr />\n<p>In case I've provided too much spoiler here, I provide some follow-up exercises:</p>\n<ol>\n<li>Write the same function, but with the assumption that you count bits from the <em>rightmost</em> (least significant) bit.</li>\n<li>Write a version for <code>unsigned long</code>.</li>\n<li>Write versions that unconditionally set and reset the specified group of bits.</li>\n<li>Write a <code>main()</code> that tests whether the above functions work as advertise. Remember to return <code>EXIT_SUCCESS</code> or <code>EXIT_FAILURE</code> as appropriate.</li>\n</ol>\n<p>Which code can be shared in the answers to these questions?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T20:05:32.647",
"Id": "507641",
"Score": "0",
"body": "You seem very modest, thanks for the kind and very clear review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:01:14.440",
"Id": "257037",
"ParentId": "257025",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257037",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T15:04:10.367",
"Id": "257025",
"Score": "3",
"Tags": [
"c",
"bitwise"
],
"Title": "Invert n bits beginning at position p of an unsigned integer"
}
|
257025
|
<p>I implemented <a href="https://github.com/tugrul512bit/VirtualMultiArray" rel="nofollow noreferrer">virtual array</a> using OpenCL and graphics cards as backing store, with caching some of data on RAM using a LRU algorithm and accessing data through some simple setters/getters. Accession of an array element goes through a page lock (using array of mutexes for all independent pages), then LRU cache, then pcie data transmission in case of eviction and returning with data (or editing page data if its a write).</p>
<pre><code>#include "GraphicsCardSupplyDepot.h"
#include "VirtualMultiArray.h"
#include "PcieBandwidthBenchmarker.h"
#include "CpuBenchmarker.h"
// testing
#include <random>
#include <iostream>
#include "omp.h"
constexpr bool TEST_BANDWIDTH=true;
constexpr bool TEST_LATENCY=false;
constexpr bool testType = TEST_BANDWIDTH;
// a test object for virtual array
// testing bandwidth: 512kB size
// testing latency: 8byte size
class Object
{
public:
Object():id(-1){}
Object(int p):id(p){}
const int getId() const {return id;}
private:
char data[testType?(1024*512 - 4):(4)];
int id;
};
int main()
{
// number of elements per cache page
const long long pageSize = 1;
// number of elements of array
const long long n = pageSize*(testType?1000:100000);
// number of benchmark runs
const int numTestsPerThread = 25;
// virtual array of objects in video memory
VirtualMultiArray<Object> test(n,GraphicsCardSupplyDepot().requestGpus(),pageSize,3,PcieBandwidthBenchmarker().bestBandwidth(10));
// heating cpu to get precise benchmark results
#pragma omp parallel for
for(long long j=0;j<n;j++)
{
test.set(j,Object(j));
}
// test for single thread, 2 threads, .. 64 threads
for(int i=1;i<=64;i++)
{
// benchmark set method
{
CpuBenchmarker bench(i*numTestsPerThread*sizeof(Object),std::string("scalar set, ")+std::to_string(i)+std::string("threads"),i*numTestsPerThread);
#pragma omp parallel for num_threads(i)
for(long long j=0;j<i;j++)
{
// random-access to data
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_real_distribution<float> rnd(0,n-1);
for(int k=0;k<numTestsPerThread;k++)
{
int rndv = rnd(rng);
test.set(rndv,Object(rndv));
}
}
}
// benchmark get method
{
CpuBenchmarker bench(i*numTestsPerThread*sizeof(Object),std::string("scalar get, ")+std::to_string(i)+std::string("threads"),i*numTestsPerThread);
#pragma omp parallel for num_threads(i)
for(long long j=0;j<i;j++)
{
// random-access to data
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_real_distribution<float> rnd(0,n-1);
for(int k=0;k<numTestsPerThread;k++)
{
int rndv = rnd(rng);
const auto obj = test.get(rndv);
if(obj.getId()!=rndv)
{
throw std::invalid_argument("Error: set/get");
}
}
}
}
std::cout<<"==================================================================="<<std::endl;
}
return 0;
}
</code></pre>
<p>When I test it on Ubuntu 18.04, it uses up to 3/4 of the combined pcie bandwidth of system but on Windows 10, it uses mostly 1/4 (which is only 2GB/s) of peak.</p>
<p>My system has this specs:</p>
<ul>
<li>fx8150</li>
<li>4 GB single channel ddr3 RAM (10.6 GB/s hardware peak)</li>
<li>3 low end graphics cards (gt1030, 2xk420) that support OpenCL (8GB/s hardware peak)</li>
<li>
<ul>
<li>TCC driver mode enabled for 2 of cards, but first card cant do TCC mode</li>
</ul>
</li>
<li>g++-10 for Ubuntu C++17</li>
<li>MSVC 2019 for Windows C++17</li>
</ul>
<p>I tried to make it as platform-independent as possible but at one part I had to branch some code for aligned-allocations. <strong>What am I doing wrong with Windows-side?</strong> (besides the aligned allocations)</p>
<p>For example, in Ubuntu, I get this output:</p>
<pre><code>scalar set, 1threads: 12182103 nanoseconds (bandwidth = 1075.94 MB/s) (throughput = 487284.12 nanoseconds per iteration)
scalar get, 1threads: 10874521 nanoseconds (bandwidth = 1205.31 MB/s) (throughput = 434980.84 nanoseconds per iteration)
===================================================================
scalar set, 2threads: 15642385 nanoseconds (bandwidth = 1675.86 MB/s) (throughput = 312847.70 nanoseconds per iteration)
scalar get, 2threads: 16902450 nanoseconds (bandwidth = 1550.92 MB/s) (throughput = 338049.00 nanoseconds per iteration)
===================================================================
scalar set, 3threads: 15004388 nanoseconds (bandwidth = 2620.67 MB/s) (throughput = 200058.51 nanoseconds per iteration)
scalar get, 3threads: 16687201 nanoseconds (bandwidth = 2356.39 MB/s) (throughput = 222496.01 nanoseconds per iteration)
...
...
===================================================================
scalar set, 63threads: 212283324 nanoseconds (bandwidth = 3889.87 MB/s) (throughput = 134783.06 nanoseconds per iteration)
scalar get, 63threads: 136367146 nanoseconds (bandwidth = 6055.37 MB/s) (throughput = 86582.31 nanoseconds per iteration)
===================================================================
scalar set, 64threads: 229655008 nanoseconds (bandwidth = 3652.70 MB/s) (throughput = 143534.38 nanoseconds per iteration)
scalar get, 64threads: 149184573 nanoseconds (bandwidth = 5622.97 MB/s) (throughput = 93240.36 nanoseconds per iteration)
===================================================================
</code></pre>
<p>but in Windows it tops out at 2GB/s with much less number of threads. Tested it without LRU caching (simply direct-mapping of pages to vram) too but same performance difference happened.</p>
<p><strong>Edit:</strong></p>
<p>According to performance profiler of Visual Studio, the random-number generator is not bottleneck:</p>
<p><a href="https://i.stack.imgur.com/7b2n0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7b2n0.png" alt="enter image description here" /></a></p>
<p>When I follow hot path, it ends at an OpenCL command that queries an event:</p>
<pre><code> clGetEventInfo(evt, evtInf,sizeof(cl_int), &evtStatus0, nullptr)
</code></pre>
<p>in the PageCache header, line 248.</p>
<p><a href="https://i.stack.imgur.com/J4wOc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J4wOc.png" alt="enter image description here" /></a></p>
<p>This is out of project, maybe related to my system being old? Or maybe its about some wrong api usage elsewhere, such as some wrong flags in opencl buffer construction?</p>
<p><strong>Edit 2:</strong></p>
<p>For Windows, I removed clGetEventInfo() and used blocking-version of read/write opencl commands:</p>
<pre><code>clEnqueueReadBuffer(q->getQueue(), gpu->getMem(), CL_TRUE
</code></pre>
<p>this gave +25% performance (2.5GB/s instead of 2.0GB/s) for the benchmark on Windows but there is another bottleneck now:</p>
<p><a href="https://i.stack.imgur.com/gTCXa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gTCXa.png" alt="enter image description here" /></a></p>
<p>kernel-related overhead is nearly as high as pcie-i/o overhead! When I follow hot path, again, the i/o part is the most bottlenecking part:</p>
<p><a href="https://i.stack.imgur.com/LxCaq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LxCaq.png" alt="enter image description here" /></a></p>
<p>Does this mean, these OpenCL buffer read/write operations also go through kernel of Windows? I guess they have busy-wait inside with some mutex lock which is slow? When I click "include external code" it adds "nvopencl64.dll" to list of hot path with "kernel" tag on its line. Does this mean, nvidia driver uses some spin-wait in OpenCL synchronization which reduces threading i/o scalability because of Windows-related lock-contention? In Ubuntu, it is 2x fast with same nvidia gpus and extra 25% faster with explicit idle-wait loop using events. So, (I guess) its more related to Windows-based issue rather than Nvidia. But not sure.</p>
<p>When I don't use all 3 graphics cards at the same time, I get these results:</p>
<ul>
<li>GT1030: 1GB/s</li>
<li>K420 at 8x slot: 2GB/s</li>
<li>K420 at 4x slot: 1GB/s</li>
</ul>
<p>but when I use all 3 with many threads, I get 2.5GB/s total. Thats not same with Ubuntu which reaches 6GB/s total. If there was a way to tell OpenCL to use idle-wait loop instead of busy-wait loop, then threads would actually overlap i/o efficiently. But in Windows they not only stop scaling at 8 threads, but also decrease after more threads. In Ubuntu, it continuously increases until 64 threads. Maybe page-locking contention inside OpenCL driver causes this scalability issue?</p>
<p><strong>Edit-3:</strong></p>
<p>When I test a simple mutex example:</p>
<pre><code>int main()
{
std::mutex m;
for (int i = 0; i < 100; i++)
{
CpuBenchmarker bench;
for (int j = 0; j < 1000; j++)
{
std::unique_lock<std::mutex> l(m);
}
}
return 0;
}
</code></pre>
<p>profiler says 97% of overhead is from kernel space and benchmarker outputs ~70 nanoseconds per lock duration. CPU is FX8150 at 2.1 GHz.</p>
<p>Lastly, does the code structure look ok?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T20:12:43.367",
"Id": "507642",
"Score": "0",
"body": "I am not familiar with `omp` so not sure how it parallelizes it loops. But the`std::random_device` is very expensive to create. Could you not do this outside the loop (in an array)? Then your code in the loop will be the only thing you test (and you can access the random device via the array and each loop iteration can look up its own random device."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:14:44.263",
"Id": "507651",
"Score": "0",
"body": "If I measure only random number generation, it is much less overhead than 25 iterations of copying 512kB objects. Every omp thread creates only 1 random device. Then 25 iterations are run."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T15:32:12.547",
"Id": "257027",
"Score": "0",
"Tags": [
"c++",
"cache",
"benchmarking",
"portability",
"opencl"
],
"Title": "Performance discrepancy between Windows and Ubuntu for a video-memory-based virtual array implementation"
}
|
257027
|
<p>I've been toying with Haskell again and implementing a simple text replacement program that replaces all consonants <em>c</em> in a text by <em>c</em>o<em>c</em>, i.e., inserting an 'o' in between:</p>
<pre><code>> robber_simple "abcdef"
"abobcocdodefof"
</code></pre>
<p>This is rather simple to implement:</p>
<pre class="lang-hs prettyprint-override"><code>robber_simple :: [Char] -> [Char]
robber_simple [] = []
robber_simple (x:xs)
| x `elem` monophthongs = x:(robber_simple xs)
| otherwise = x:'o':x:(robber_simple xs)
where -- vowels represented by one character, or monograph
monophthongs :: [Char]
monophthongs = "aeiouy"
</code></pre>
<p>However, in many languages, such as German, we have multigraphs which can act as vowels or consonants, such as "uh" ("uhr") or "sch" ("schokolade").</p>
<p>So I implemented a more complicated program which does a basic lookahead to figure out, whether the, say 's', we currently read is actually part of a "sch". I'm not happy with it, though :)</p>
<pre class="lang-hs prettyprint-override"><code>import Data.List
robber :: [Char] -> [Char]
robber xs = robber' xs [] where
robber' :: [Char] -> [Char] -> [Char]
-- Read first character into backlog
robber' (x:xs) [] = robber' xs [x]
-- Nonempty prefix, new input can either form a multigraph prefix or end one.
robber' (x:xs) (p:ps)
-- Current character with existing prefix forms a prefix of a multigraph
| token `elem` (prefixes multigraph_consonant) = robber' xs token
| token `elem` (prefixes multigraph_vowel) = robber' xs token
-- The current token makes it clear that we aren't reading a multigraph
| otherwise = (robber' [] (p:ps)) ++ (robber' (x:xs) [])
where token = (p:ps) ++ [x]
-- No input, consume characters in backlog.
robber' [] pref
-- Either this forms a multigraph...
| pref `elem` multigraph_consonant = pref ++ 'o':pref
| pref `elem` multigraph_vowel = pref
-- ... or not.
| otherwise = robber_simple pref
-- consonant phoneme made up of multiple characters
multigraph_consonant :: [[Char]]
multigraph_consonant = ["sch", "ch", "sc"]
-- same for vowels
multigraph_vowel :: [[Char]]
multigraph_vowel = ["ei", "uh"]
prefixes :: [[a]] -> [[a]]
prefixes xs = concat $ map prefix xs
prefix :: [a] -> [[a]]
prefix = inits
</code></pre>
<p>The parsing/tokenizing strategy I use, is to read characters and store them into the backlog until a character (or end of input) comes that determines that the current backlog can be treated as one unit. That is, it either is a complete monograph (e.g., "sch") or definitely not a prefix of a monograph ("c").</p>
<p>In that case, I replace the backlog <em>x</em> with either <code>x++'o':x</code> or leave it, depending on whether it is a consonant or a vowel.</p>
<p>Finally, I carry on parsing the rest of the string.</p>
<p>Any suggestions welcome!</p>
|
[] |
[
{
"body": "<p>I probably would reach directly for Parsec or another parsing library writing this from scratch, but I think even with a more direct recursive solution you've drastically overcomplicated this!</p>\n<p>Separate your problem into constituent pieces which you find easier to handle on their own terms. In this case, I would start by writing a function <code>phoneme :: [Multigraph] -> String -> (Phoneme, String)</code> to consume only a single n-graph off of a given word.</p>\n<pre><code>import Data.List (isPrefixOf, stripPrefix)\n\ntype Phoneme = String\ntype Multigraph = Phoneme\n\nphoneme :: [Multigraph] -> String -> Maybe (Phoneme, String)\nphoneme multigraphs word@(letter:rest) = -- The use of @ is an example of an 'as-pattern'\n case filter (`isPrefixOf` word) multigraphs of\n (multigraph:_) -> Just (multigraph, fromJust $ stripPrefix multigraph word)\n [] -> Just ([letter], rest)\nphoneme _multigraphs [] = Nothing -- Prefixing an arg with _ says to the compiler\n -- that you meant not to use it in the definition\n -- i.e. you won't get a warning when compiling\n -- with -Wall (specifically --Wunused-matches)\n</code></pre>\n<p>This version achieves multigraph detection by testing the passed multigraphs against the remaining portion of the string, <span class=\"math-container\">\\$O(m)\\$</span> in the number of multigraphs. Your original version tests every multigraph against every prefix of the string, making it <span class=\"math-container\">\\$O(mn)\\$</span>.</p>\n<p>Now the next obvious step is to use this function in breaking an entire string into its constituent phonemes.</p>\n<pre><code>import Data.List (unfoldr)\n\nphonemes :: [Multigraph] -> String -> [Phoneme]\nphonemes multigraphs = unfoldr (phoneme multigraphs)\n</code></pre>\n<p>Sometimes you either know about a common Haskell concept or you don't. In this case, if you're unfamiliar, <code>unfoldr :: (b -> Maybe (a, b)) -> b -> [a]</code> repeatedly applies a function that returns a desired output and some state to itself, collecting the output into a list and terminating once the function reaches the “end” and has returned <code>Nothing</code>.</p>\n<p>Now before anything else we have to be able to robber an individual phoneme.</p>\n<pre><code>robberPhoneme :: [Multigraph] -> [Multigraph] -> Phoneme -> String\nrobberPhoneme _mconsonants mvowels p\n | p `elem` mvowels = p\n | p `elem` vowels = p\n | otherwise = p ++ "o" ++ p\n where vowels = map pure "aeiouy"\n</code></pre>\n<p>You could obviously leave out the consonants argument, but I think it's helpful to remind callers not to just pass all of the multigraphs they have on hand, vowels being treated differently from consonants.</p>\n<p>And now we're ready to tie it together.</p>\n<pre><code>robber :: [Multigraph] -> [Multigraph] -> String -> String\nrobber mconsonants mvowels = concatMap (robberPhoneme mconsonants mvowels)\n . phonemes (mconsonants ++ mvowels)\n</code></pre>\n<p>And there you go! Much less bookkeeping, parsed strictly left to right, and by relying entirely on standard functions for all of the recursion anyone reading my code (including me, later) can quickly understand how control flows through the program without having to mentally grapple with primitive recursion.</p>\n<p>This doesn't sit wholly perfectly with me (I'd probably create a datatype to represent all the different kinds of phonemes in a language and pass that around instead, I didn't feel good just throwing the monophthongs in there but it was expedient, couple other nits) but it's enough of a solution that I'd ship it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T17:13:19.930",
"Id": "507760",
"Score": "1",
"body": "TYVM! I thought about basically tokenizing into phonemes first, then replacing, but I tried to use the `splitOn` family and failed :)\nI definitely learned a few things today, especially the `phoneme` function is wonderful. It took some time and delving into Applicatives in order to understand that `map pure` on a list is basically mapping `(:[])`, but this lead me to reading up on Functors etc. which was much fun. People like you make this website so great!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T17:03:09.557",
"Id": "507860",
"Score": "0",
"body": "You’re more than welcome!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T00:29:42.603",
"Id": "257089",
"ParentId": "257028",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257089",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T15:43:22.260",
"Id": "257028",
"Score": "3",
"Tags": [
"strings",
"parsing",
"haskell"
],
"Title": "Text replacement with Räubersprache (\"Røversprog\")"
}
|
257028
|
<p>I have a function that I've been trying to make faster that computes <span class="math-container">\$XA + B\$</span>, where <span class="math-container">\$A \in \mathbb{R}^{n \times n}\$</span> is a tridiagonal matrix, and <span class="math-container">\$X, B \in \mathbb{R}^{m \times n}\$</span>. In the code, the lower, main, and upper diagonals are represented by <code>dl, dm, du</code>. The naive implementation of this is,</p>
<pre><code>/* Compute BA + X where A is tridiagonal shape (n, n), B, X are matrices shape (m, n) */
void dgtaxmt(const double *dl, const double *dm, const double *du,
const double *x, const double *b, double *out,
const unsigned int n, const unsigned int m, double *temp)
{
int i, j, ii;
for (i = 0; i < m; i++){
ii = i * n;
temp[ii] = (x[ii] * dm[0]) + (x[ii + 1] * dl[0]) + b[ii];
for (j = 1; j < n - 1; j++){
temp[ii + j] = ((x[ii + j - 1] * du[j - 1]) + ((x[ii + j] * dm[j]) + ((x[ii + j + 1] * dl[j]) + b[ii + j])));
}
temp[ii + j] = (x[ii + j] * dm[j]) + (x[ii + j - 1] * du[j - 1]) + b[ii + j];
}
// store the transpose of temp into out
// otrans(temp, out, m, n, 16);
}
</code></pre>
<p>Note that all of the pointers use the <code>restrict</code> keyword, but I left them out for readability. My attempts at increasing performance include tiling and using AVX intrinsics in hopes that not having to reload <code>dl, dm, du</code> would speed up the code, but it actually made it a lot slower. Is there anyway to vectorize this function in an efficient manner? Clang doesn't report any vectorization, and the assembly code it generates is using the xmm registers, but only the first value. Could there be a different order of operations that would allow better re-usage of data that's been previously loaded?</p>
<p>EDIT Here is the attempt I made with AVX intrinsics</p>
<pre><code>void dgtaxmt_avx(const double *dl, const double *dm, const double *du,
const double *x, const double *b, double *out,
const unsigned int n, const unsigned int m, double *temp)
{
// idx is for "rolling" values in vector to left by one index
const __m256i idx = _mm256_set_epi32(1, 0, 7, 6, 5, 4, 3, 2);
__m256d dl_vec, dm_vec, du_vec, bn, xnm1, xn, xn1, tmp4;
__m128d tmp2;
unsigned int i, j, ii;
const unsigned int r = ((n - 2) & (-4)) + 1;
for (i = 0; i < m; i++){
ii = i * n;
temp[ii] = (x[ii] * dm[0]) + (x[ii + 1] * dl[0]) + b[ii];
for (j = 1; j < r; j += 4){
dl_vec = _mm256_loadu_pd(&dl[j - 1]);
dm_vec = _mm256_loadu_pd(&dm[j]);
du_vec = _mm256_loadu_pd(&du[j]);
bn = _mm256_loadu_pd(&b[ii + j]);
xnm1 = _mm256_loadu_pd(&x[ii + j - 1]);
tmp2 = _mm_loadu_pd(&x[ii + j + 3]);
xn1 = _mm256_set_m128d(tmp2, _mm256_extractf128_pd(xnm1, 1));
// use permutations to avoid doing extra loads
xn = (__m256d)_mm256_permutevar8x32_ps((__m256)xnm1, idx);
tmp4 = (__m256d)_mm256_permutevar8x32_ps((__m256)xn1, idx);
tmp2 = _mm256_extractf128_pd(tmp4, 0);
xn = _mm256_insertf128_pd(xn, tmp2, 1);
tmp4 = _mm256_fmadd_pd(du_vec, xn1, bn);
tmp4 = _mm256_fmadd_pd(dm_vec, xn, tmp4);
tmp4 = _mm256_fmadd_pd(dl_vec, xnm1, tmp4);
_mm256_storeu_pd(&out[ii + j], tmp4);
}
for (j = r; j < n - 1; j++){
temp[ii + j] = ((x[ii + j - 1] * du[j - 1]) + ((x[ii + j] * dm[j]) + ((x[ii + j + 1] * dl[j]) + b[ii + j])));
}
temp[ii + j] = (x[ii + j] * dm[j]) + (x[ii + j - 1] * du[j - 1]) + b[ii + j];
}
otrans(temp, out, m, n, 16);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:10:43.327",
"Id": "507623",
"Score": "0",
"body": "Can you show the attempted AVX code as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:44:02.100",
"Id": "507627",
"Score": "0",
"body": "@harold I edited the question to include the AVX code. Sorry it's a littles messy since it was \"experimental\" code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:15:20.950",
"Id": "507652",
"Score": "0",
"body": "I actually did not measure a serious performance issue in the AVX code. Are you running this on an AMD processor? `_mm256_permutevar8x32_ps` is a bigger problem for AMD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:16:45.580",
"Id": "507653",
"Score": "0",
"body": "1. How large are \\$n\\$ and \\$m\\$, and 2. Did you try computing the result column-wise (rather than row-wise)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:26:20.523",
"Id": "507654",
"Score": "0",
"body": "@harold I'm on a macbook running an intel i5-5257U CPU @ 2.70GHz and I'm not entirely sure why I'm seeing the difference. In the intel documentation for broadwell, it says the efficiency of these instructions aren't too bad"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:29:04.917",
"Id": "507655",
"Score": "0",
"body": "@vnp My data is stored in row major form, so if I were to compute it column wise, wouldn't that cause a bunch of cache misses when accessing the data in `x`, and `b`? \\$n, m\\$ range from 100 to only 5000 since I have limited memory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:36:53.680",
"Id": "507656",
"Score": "0",
"body": "That's exactly where I was driving to. I don't know the rest of your code, but exploring column-major layout _could_ be beneficial. And of course CUDA..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:52:53.810",
"Id": "507657",
"Score": "0",
"body": "@vnp hmmm I hadn't thought of switching to column-major. It would be a lot of changes to convert everything over. Is there any immediate benefit to using column-major? I was always told that they are roughly the same in terms of performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:56:14.363",
"Id": "507658",
"Score": "0",
"body": "The benefit I am thinking about is that you will naturally avoid reloading diagonals. A tricky part is that \\$A\\$ still needs to be row-major. Perhaps just transposing \\$A\\$ into column-major is a way to go. But as I said I don't know the rest of your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T23:01:42.570",
"Id": "507660",
"Score": "0",
"body": "@vnp I'll give it a try. This code is apart of my personal library for numerically solving PDEs so I'll have to benchmark everything in order to really know if it provides any significant improvements"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T17:54:15.387",
"Id": "257036",
"Score": "1",
"Tags": [
"performance",
"c",
"vectorization"
],
"Title": "Faster Tridiagonal Matrix Multiplication"
}
|
257036
|
<p>The problem is basically this: Return the permutation of the set of the first <em>n</em> natural numbers which satisfies the following property:</p>
<p>|pos(i) - i| = k<br />
∀ i ∈ (1,n)<br />
where pos(i) is the <em>i</em>th number in the permutation</p>
<p>If no such permutation exists, return -1.</p>
<p>Note: the input is the integer n.</p>
<p>The full problem is <a href="https://www.hackerrank.com/challenges/absolute-permutation/problem" rel="nofollow noreferrer">on HackerRank</a>.</p>
<p>The code for the main algorithm:</p>
<pre><code>try:
for y in g.keys():
g[y] = [y-k,y+k]
if y - k <=0:
g[y].remove(y-k)
if y + k > n:
g[y].remove(y+k)
d = []
for y in range(1,n+1):
if len(g[y]) == 1:
if g[y][0] not in d:
d.append(g[y][0])
if len(g[y]) == 2:
if g[y][0] not in d:
d.append(g[y][0])
if len(set(d)) == len(d) and len(d) == n:
return d
else:
return [-1]
except:
return [-1]
</code></pre>
<p><code>g</code> is a previously defined dictionary containing the first n natural numbers as keys with each key initially being assigned a value of 0</p>
<p>the first block changes the value of the key <code>y</code> to the possible numbers that could be at position <code>y</code> in the permutation, namely, <code>y - k</code> or <code>y + k</code></p>
<p><code>d</code> is the list that will contain the final permutation. If the value for <code>i</code> in <code>g</code> has only one number, then that number is added to <code>d</code>. If it contains 2 numbers, the first number is added by default. If the first number is already in <code>d</code>, the second number is added. <code>d</code> is printed if, finally, <code>d</code> contains n elements and there are no repeating elements.</p>
<p>On hackerrank, 9 of the 13 test cases are successful, but the last 4 return a timeout error. I've run through the code step by step and it's clear that the second block is taking way too long for larger numbers. I know using list comprehension would make it faster, but I have no idea how to convert that into list comprehension.</p>
<p>How do I make this code more efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:33:43.093",
"Id": "507626",
"Score": "0",
"body": "There are 2 \"if\" that are doing same thing. Why don't you use only 1 \"if\"? if len<=2 then add once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:46:58.333",
"Id": "507628",
"Score": "0",
"body": "If I don't include the if len == 1 statement then I get an index error when checking if g[y][1] is in d."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T19:03:22.213",
"Id": "507631",
"Score": "0",
"body": "Where are you checking if g[y][1] is in d?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T21:03:21.650",
"Id": "507644",
"Score": "0",
"body": "Why do you say \"the input is the integer n\" when in reality it's n and k? And better show the whole `absolutePermutation(n, k)` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T23:29:32.117",
"Id": "507662",
"Score": "0",
"body": "*\"On hackerrank, 9 of the 13 test cases are successful\"* - I tried it and got \"Wrong Answer\" for 6 of the test cases."
}
] |
[
{
"body": "<p>Many programming puzzles of this sort can be solved without brute-force\ncomputations if you can figure out the pattern. Rather than trying to implement\na solution to the puzzle, it's often helpful to write some temporary code just\nto explore. The small script below does that. For each list size from 1 through\nmax_n, we find the permutations having valid solutions, along with the\ncorresponding k values.</p>\n<p>Some patterns jump about pretty quickly. Odd-sized lists appear\nto support only k=0. Even-sized lists are interesting: take a close\nlook, for example, at sizes 6 and 8.</p>\n<pre><code>import sys\nfrom itertools import permutations\n\ndef main():\n max_n = int(sys.argv[1])\n fmt = '{:<6} {:<4} {}'\n div = '-' * 40\n print(fmt.format('SIZE', 'K', 'PERM'))\n for size in range(1, max_n + 1):\n print(div)\n for tup in permutations(range(1, size + 1)):\n diffs = [abs(j + 1 - x) for j, x in enumerate(tup)]\n ds = sorted(set(diffs))\n if len(ds) == 1:\n k = ds[0]\n print(fmt.format(size, k, tup))\n\nmain()\n</code></pre>\n<p>Output for max_n=9:</p>\n<pre><code>SIZE K PERM\n----------------------------------------\n1 0 (1,)\n----------------------------------------\n2 0 (1, 2)\n2 1 (2, 1)\n----------------------------------------\n3 0 (1, 2, 3)\n----------------------------------------\n4 0 (1, 2, 3, 4)\n4 1 (2, 1, 4, 3)\n4 2 (3, 4, 1, 2)\n----------------------------------------\n5 0 (1, 2, 3, 4, 5)\n----------------------------------------\n6 0 (1, 2, 3, 4, 5, 6)\n6 1 (2, 1, 4, 3, 6, 5)\n6 3 (4, 5, 6, 1, 2, 3)\n----------------------------------------\n7 0 (1, 2, 3, 4, 5, 6, 7)\n----------------------------------------\n8 0 (1, 2, 3, 4, 5, 6, 7, 8)\n8 1 (2, 1, 4, 3, 6, 5, 8, 7)\n8 2 (3, 4, 1, 2, 7, 8, 5, 6)\n8 4 (5, 6, 7, 8, 1, 2, 3, 4)\n----------------------------------------\n9 0 (1, 2, 3, 4, 5, 6, 7, 8, 9)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:14:34.223",
"Id": "257043",
"ParentId": "257039",
"Score": "0"
}
},
{
"body": "<p>You test <code>not in d</code>, where <code>d</code> is a list. That's slow. Use an additional <em>set</em> for those membership tests.</p>\n<p>Simpler way: Note that the number 1 must go to position 1+k. It has nowhere else to go. Also, the only number that can go to position 1 is the number 1+k. So numbers 1 and 1+k must switch places. Similarly, the numbers 2 and 2+k must switch places (unless k<2). And so on. The entire first k numbers must switch with the next k numbers.</p>\n<p>After that, the reasoning repeats, numbers (2k+1) and (2k+1)+k must switch. The entire third chunk of k numbers must switch with the fourth chunk of k numbers. And so on.</p>\n<p>In other words, numbers in the first, third, fifth, etc chunk of k numbers must move k positions to the right and numbers in the other chunks of k numbers must move k positions to the left. In yet other words, add k to the odd-numbered chunks and subtract k from the even-numbered chunks.</p>\n<p>A solution that tries to build it and discards it if it's invalid:</p>\n<pre><code>def absolutePermutation(n, k):\n p = [i+1 + (-k if k and i//k%2 else k) for i in range(n)]\n return p if max(p) == n else [-1]\n</code></pre>\n<p>Shorter but slower (still accepted):</p>\n<pre><code>def absolutePermutation(n, k):\n p = [i+1 + k*(-1)**(k and i//k) for i in range(n)]\n return p if max(p) == n else [-1]\n</code></pre>\n<p>Alternatively, check whether it'll work and build it only if it will. It will iff there's an even number of complete k-chunks, i.e., if n is divisible by 2k:</p>\n<pre><code>def absolutePermutation(n, k):\n if k == 0:\n return range(1, n+1)\n if n % (2*k):\n return [-1]\n return [i+1 + k*(-1)**(k and i//k) for i in range(n)]\n\n</code></pre>\n<p>Yet another, starting with the identity permutation and then swapping slices:</p>\n<pre><code>def absolutePermutation(n, k):\n K = 2 * k\n if k and n % K:\n return [-1]\n p = list(range(1, n+1))\n for i in range(k):\n p[i::K], p[i+k::K] = p[i+k::K], p[i::K]\n return p\n</code></pre>\n<p>A longer but quite nice version using the <code>grouper</code> <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\">recipe</a> to give us the chunks:</p>\n<pre><code>def absolutePermutation(n, k):\n numbers = range(1, n+1)\n if k == 0:\n yield from numbers\n elif n % (2*k):\n yield -1\n else:\n chunks = grouper(numbers, k)\n for chunk in chunks:\n yield from next(chunks)\n yield from chunk\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T22:55:05.543",
"Id": "257045",
"ParentId": "257039",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257045",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T18:22:16.170",
"Id": "257039",
"Score": "-2",
"Tags": [
"python",
"algorithm",
"time-limit-exceeded"
],
"Title": "Hackerrank: Absolute Permutation - How do I make this code more efficient"
}
|
257039
|
<p>I am a beginner in C# and trying to learn how to program with OOP in mind. I am 100% that the code is not OOP-friendly at all, but the game is running and working, so if anyone could look throw the code and give me feedback on how to improve it, that would be helpful.</p>
<p>The game is a simple snake game with three players option. I have done two players part, but the code seems to be ugly and messy, so I didn't want to add anything more to the garbage, and I am completely ok if I have to redo everything I am doing this to learn anyways</p>
<p><strong>Form1.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace snakeGame3players
{
public partial class Form1 : Form
{
private readonly List<Square> SnakeBoddy = new List<Square>();
private readonly List<Square> SnakeBoddy2 = new List<Square>();
private readonly List<Square> SnakeFoods1 = new List<Square>();
private readonly List<Square> SnakeFoods2 = new List<Square>();
private readonly List<Square> SnakeFoods3 = new List<Square>();
private readonly List<Square> SnakeFoods4 = new List<Square>();
System.Windows.Forms.Timer eventTimer = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer foodTimer = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer foodTimer2 = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer foodTimer3 = new System.Windows.Forms.Timer();
System.Windows.Forms.Timer foodTimer4 = new System.Windows.Forms.Timer();
Random random = new Random();
bool exitFlag = false;
public Form1()
{
InitializeComponent();
choice1.Appearance = System.Windows.Forms.Appearance.Button;
choice2.Appearance = System.Windows.Forms.Appearance.Button;
choice3.Appearance = System.Windows.Forms.Appearance.Button;
choice1.Size = new Size(154, 56);
choice2.Size = new Size(154, 56);
choice3.Size = new Size(154, 56);
new Player1setting();
new Player2setting();
new FoodSetting();
GameTimer.Interval = 100;
this.KeyPreview = true;
GameTimer.Tick += UpdateScreen;
GameTimer.Start();
label3.Visible = false;
label2.Visible = false;
}
private void UpdateScreen(object sender, EventArgs e)
{
if (label1.Visible == true)
{
if (KeyInput.KeyInputs(Keys.Q))
{
Application.Restart();
Environment.Exit(0);
}
}
if (choice2.Checked && Player1setting.Gameover ==false)
{
if (KeyInput.KeyInputs(Keys.Right) && Player1setting.Movment != SnakeMovment.Left)
{
Player1setting.Movment = SnakeMovment.Right;
}
else if (KeyInput.KeyInputs(Keys.Left) && Player1setting.Movment != SnakeMovment.Right)
{
Player1setting.Movment = SnakeMovment.Left;
}
else if (KeyInput.KeyInputs(Keys.Up) && Player1setting.Movment != SnakeMovment.Down)
{
Player1setting.Movment = SnakeMovment.Up;
}
else if (KeyInput.KeyInputs(Keys.Down) && Player1setting.Movment != SnakeMovment.Up)
{
Player1setting.Movment = SnakeMovment.Down;
}
PlayerMovment();
}
pictureBox1.Invalidate();
if (choice1.Checked && Player2setting.Gameover2 == false)
{
if (KeyInput.KeyInputs(Keys.D) && Player2setting.Movment2 != SnakeMovment2.A)
{
Player2setting.Movment2 = SnakeMovment2.D;
}
else if (KeyInput.KeyInputs(Keys.A) && Player2setting.Movment2 != SnakeMovment2.D)
{
Player2setting.Movment2 = SnakeMovment2.A;
}
else if (KeyInput.KeyInputs(Keys.W) && Player2setting.Movment2 != SnakeMovment2.S)
{
Player2setting.Movment2 = SnakeMovment2.W;
}
else if (KeyInput.KeyInputs(Keys.S) && Player2setting.Movment2 != SnakeMovment2.W)
{
Player2setting.Movment2 = SnakeMovment2.S;
}
PlayerMovment2();
}
pictureBox1.Invalidate();
}
private void PlayerMovment()
{
if (choice2.Checked) {
for (int i = SnakeBoddy.Count - 1; i >= 0; i--)
{
if (i == 0)
{
switch (Player1setting.Movment)
{
case SnakeMovment.Right:
SnakeBoddy[i].X++;
break;
case SnakeMovment.Left:
SnakeBoddy[i].X--;
break;
case SnakeMovment.Up:
SnakeBoddy[i].Y--;
break;
case SnakeMovment.Down:
SnakeBoddy[i].Y++;
break;
}
int maxXPosition = pictureBox1.Size.Width / Player1setting.Width;
int maxYPosition = pictureBox1.Size.Height / Player1setting.Height;
if (
SnakeBoddy[i].X < 0 || SnakeBoddy[i].Y < 0 ||
SnakeBoddy[i].X > maxXPosition || SnakeBoddy[i].Y >= maxYPosition
)
{
Die();
}
for (int J = 1; J < SnakeBoddy.Count; J++)
{
if (SnakeBoddy[i].X == SnakeBoddy[J].X && SnakeBoddy[i].Y == SnakeBoddy[J].Y)
{
Die();
}
}
for (int g = 0; g < SnakeBoddy2.Count; g++)
{
if (SnakeBoddy[0].X == SnakeBoddy2[g].X && SnakeBoddy[0].Y == SnakeBoddy2[g].Y)
{
Player1setting.GameScore += FoodSetting.food2;
label3.Text = Player1setting.GameScore.ToString();
Die();
}
}
if (SnakeFoods1.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
EatFood();
}
if (SnakeFoods2.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
EatFood2();
}
if (SnakeFoods3.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
EatFood3();
}
if (SnakeFoods4.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
EatFood4();
}
}
else
{
SnakeBoddy[i].X = SnakeBoddy[i - 1].X;
SnakeBoddy[i].Y = SnakeBoddy[i - 1].Y;
}
}
}
}
private void PlayerMovment2()
{
if (choice1.Checked)
{
for (int x = SnakeBoddy2.Count - 1; x >= 0; x--)
{
if (x == 0)
{
switch (Player2setting.Movment2)
{
case SnakeMovment2.D:
SnakeBoddy2[x].X++;
break;
case SnakeMovment2.A:
SnakeBoddy2[x].X--;
break;
case SnakeMovment2.W:
SnakeBoddy2[x].Y--;
break;
case SnakeMovment2.S:
SnakeBoddy2[x].Y++;
break;
}
int maxXPosition2 = pictureBox1.Size.Width / Player2setting.Width2;
int maxYPosition2 = pictureBox1.Size.Height / Player2setting.Height2;
if (
SnakeBoddy2[x].X < 0 || SnakeBoddy2[x].Y < 0 ||
SnakeBoddy2[x].X > maxXPosition2 || SnakeBoddy2[x].Y >= maxYPosition2
)
{
Die2();
}
for (int h = 1; h < SnakeBoddy2.Count; h++)
{
if (SnakeBoddy2[x].X == SnakeBoddy2[h].X && SnakeBoddy2[x].Y == SnakeBoddy2[h].Y)
{
Die2();
}
}
for (int g = 0; g < SnakeBoddy.Count; g++)
{
if (SnakeBoddy2[0].X == SnakeBoddy[g].X && SnakeBoddy2[0].Y == SnakeBoddy[g].Y)
{
Player1setting.GameScore += FoodSetting.food2;
label2.Text = Player1setting.GameScore.ToString();
Die2();
}
}
if (SnakeFoods1.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
EatFood();
}
if (SnakeFoods2.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
EatFood2();
}
if (SnakeFoods3.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
EatFood3();
}
if (SnakeFoods4.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
EatFood4();
}
}
else
{
SnakeBoddy2[x].X = SnakeBoddy2[x - 1].X;
SnakeBoddy2[x].Y = SnakeBoddy2[x - 1].Y;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Keyisup(object sender, KeyEventArgs e)
{
KeyInput.SnakeDirections(e.KeyCode, false);
}
private void Keyisdown(object sender, KeyEventArgs e)
{
KeyInput.SnakeDirections(e.KeyCode, true);
}
private void UpdateGame(object sender, PaintEventArgs e)
{
Graphics canvas = e.Graphics;
if (label1.Visible==false && Information.Visible==false)
{
foreach (Square SnakeFood in SnakeFoods1) {
canvas.FillRectangle(Brushes.Red,
new Rectangle(
SnakeFood.X * Player2setting.Width2,
SnakeFood.Y * Player2setting.Width2,
Player2setting.Width2, Player2setting.Height2
));
}
foreach (Square SnakeFoods2 in SnakeFoods2) {
canvas.FillRectangle(Brushes.Orange,
new Rectangle(
SnakeFoods2.X * Player1setting.Width,
SnakeFoods2.Y * Player1setting.Width,
Player1setting.Width, Player1setting.Height
));
}
foreach (Square SnakeFoods3 in SnakeFoods3) {
canvas.FillRectangle(Brushes.Purple,
new Rectangle(
SnakeFoods3.X * Player1setting.Width,
SnakeFoods3.Y * Player1setting.Width,
Player1setting.Width, Player1setting.Height
));
}
foreach (Square SnakeFoods4 in SnakeFoods4) {
canvas.FillRectangle(Brushes.Green,
new Rectangle(
SnakeFoods4.X * Player1setting.Width,
SnakeFoods4.Y * Player1setting.Width,
Player1setting.Width, Player1setting.Height
));
}
}
if (choice2.Checked)
{
if (Player1setting.Gameover == false)
{
Brush SnakeBoddyColor;
for (int i = 0; i < SnakeBoddy.Count; i++)
{
if (i == 0)
{
SnakeBoddyColor = Brushes.Black;
canvas.FillRectangle(SnakeBoddyColor,
new Rectangle(
SnakeBoddy[i].X * Player1setting.Width,
SnakeBoddy[i].Y * Player1setting.Width,
Player1setting.Width, Player1setting.Height
));
}
else
{
SnakeBoddyColor = Brushes.Red;
canvas.FillRectangle(SnakeBoddyColor,
new Rectangle(
SnakeBoddy[i].X * Player1setting.Width,
SnakeBoddy[i].Y * Player1setting.Width,
Player1setting.Width, Player1setting.Height
));
}
}
}
}
if (choice1.Checked)
{
if (Player2setting.Gameover2 == false)
{
Brush SnakeBoddyColor2;
for (int x = 0; x < SnakeBoddy2.Count; x++)
{
if (x == 0)
{
SnakeBoddyColor2 = Brushes.Black;
canvas.FillRectangle(SnakeBoddyColor2,
new Rectangle(
SnakeBoddy2[x].X * Player2setting.Width2,
SnakeBoddy2[x].Y * Player2setting.Width2,
Player2setting.Width2, Player2setting.Height2
));
}
else
{
SnakeBoddyColor2 = Brushes.Blue;
canvas.FillRectangle(SnakeBoddyColor2,
new Rectangle(
SnakeBoddy2[x].X * Player2setting.Width2,
SnakeBoddy2[x].Y * Player2setting.Width2,
Player2setting.Width2, Player2setting.Height2
));
}
}
}
}
if (Player2setting.GameScore2 > Player1setting.GameScore && Player2setting.Gameover2 == true)
{
string gameEnd = "Player 1 \n" + "With the score of " + Player2setting.GameScore2 + "\nPress Q to play again \n";
label1.Text = gameEnd;
label3.Visible = false;
label2.Visible = false;
label1.Visible = true;
}
if (Player2setting.GameScore2 < Player1setting.GameScore && Player1setting.Gameover == true)
{
string gameEnd = "Player 2 \n" + "With the score of " + Player1setting.GameScore + "\nPress Q to play again\n";
label1.Text = gameEnd;
label3.Visible = false;
label2.Visible = false;
label1.Visible = true;
}
if (Player2setting.GameScore2 == Player1setting.GameScore && Player1setting.Gameover == true && Player2setting.Gameover2 == true)
{
string gameEnd = "Draw \nPress Q to play again\n";
label1.Text = gameEnd;
label3.Visible = false;
label2.Visible = false;
label1.Visible = true;
}
}
private void StartGame()
{
pictureBox1.Visible = false;
Information.Visible = false;
Player1Information.Visible = false;
Player2Information.Visible = false;
Player3Information.Visible = false;
choice1.Visible = false;
choice2.Visible = false;
choice3.Visible = false;
GameStart.Visible = false;
pictureBox3.Visible = false;
pictureBox1.Visible = true;
label1.Visible = false;
new FoodSetting();
new Player1setting();
new Player2setting();
if (choice2.Checked)
{
label2.Visible = true;
SnakeBoddy.Clear();
Square SneakHead = new Square { X = 35, Y = 5 };
SnakeBoddy.Add(SneakHead);
if (choice2.Checked && !choice1.Checked)
{
Square SneakHead2 = new Square { X = 35, Y = 5 };
Player2setting.GameScore2 = -1;
SnakeBoddy2.Add(SneakHead2);
}
}
if (choice1.Checked)
{
label3.Visible = true;
SnakeBoddy2.Clear();
Square SneakHead2 = new Square { X = 10, Y = 5 };
SnakeBoddy2.Add(SneakHead2);
if (choice1.Checked && !choice2.Checked)
{
Square SneakHead = new Square { X = 10, Y = 5 };
Player1setting.GameScore = -1;
SnakeBoddy.Add(SneakHead);
}
}
label2.Text = Player1setting.GameScore.ToString();
label3.Text = Player2setting.GameScore2.ToString();
FoodEvent();
}
private void GenerateSnakeFood()
{
Square newFood = GenerateRandomFood();
while (SnakeFoods1.Any(snakeFood => snakeFood.X == newFood.X && snakeFood.Y == newFood.Y))
{
newFood = GenerateRandomFood();
}
SnakeFoods1.Add(newFood);
}
private void GenerateSnakeFood2()
{
Square newFood = GenerateRandomFood();
while (SnakeFoods2.Any(snakeFood => snakeFood.X == newFood.X && snakeFood.Y == newFood.Y))
{
newFood = GenerateRandomFood();
}
SnakeFoods2.Add(newFood);
}
private void GenerateSnakeFood3()
{
Square newFood = GenerateRandomFood();
while (SnakeFoods3.Any(snakeFood => snakeFood.X == newFood.X && snakeFood.Y == newFood.Y))
{
newFood = GenerateRandomFood();
}
SnakeFoods3.Add(newFood);
}
private void GenerateSnakeFood4()
{
Square newFood = GenerateRandomFood();
while (SnakeFoods4.Any(snakeFood => snakeFood.X == newFood.X && snakeFood.Y == newFood.Y))
{
newFood = GenerateRandomFood();
}
SnakeFoods4.Add(newFood);
}
private Square GenerateRandomFood()
{
int maxXPosition = pictureBox1.Size.Width / Player1setting.Width;
int maxYPosition = pictureBox1.Size.Height / Player1setting.Height;
return new Square { X = random.Next(0, maxXPosition), Y = random.Next(0, maxYPosition) };
}
private void EatFood()
{
if (SnakeFoods1.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
Square foodBody = new Square
{
X = SnakeBoddy[SnakeBoddy.Count - 1].X,
Y = SnakeBoddy[SnakeBoddy.Count - 1].Y
};
SnakeBoddy.Add(foodBody);
Player1setting.GameScore += FoodSetting.food1;
label2.Text = Player1setting.GameScore.ToString();
var snakePosition = SnakeBoddy[0];
SnakeFoods1.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
}
if (SnakeFoods1.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
Square foodBody2 = new Square
{
X = SnakeBoddy2[SnakeBoddy2.Count - 1].X,
Y = SnakeBoddy2[SnakeBoddy2.Count - 1].Y
};
SnakeBoddy2.Add(foodBody2);
Player2setting.GameScore2 += FoodSetting.food1;
label3.Text = Player2setting.GameScore2.ToString();
var snakePosition = SnakeBoddy2[0];
SnakeFoods1.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
}
}
private void EatFood2()
{
if (SnakeFoods2.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
Square foodBody3 = new Square
{
X = SnakeBoddy[SnakeBoddy.Count - 1].X,
Y = SnakeBoddy[SnakeBoddy.Count - 1].Y
};
SnakeBoddy.Add(foodBody3);
Square foodBody35 = new Square
{
X = SnakeBoddy[SnakeBoddy.Count - 1].X,
Y = SnakeBoddy[SnakeBoddy.Count - 1].Y
};
SnakeBoddy.Add(foodBody35);
Player1setting.GameScore += FoodSetting.food2;
label2.Text = Player1setting.GameScore.ToString();
var snakePosition = SnakeBoddy[0];
SnakeFoods2.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
}
if (SnakeFoods2.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
Square foodBody4 = new Square
{
X = SnakeBoddy2[SnakeBoddy2.Count - 1].X,
Y = SnakeBoddy2[SnakeBoddy2.Count - 1].Y
};
SnakeBoddy2.Add(foodBody4);
Square foodBody45 = new Square
{
X = SnakeBoddy2[SnakeBoddy2.Count - 1].X,
Y = SnakeBoddy2[SnakeBoddy2.Count - 1].Y
};
SnakeBoddy2.Add(foodBody45);
Player2setting.GameScore2 += FoodSetting.food2;
label3.Text = Player2setting.GameScore2.ToString();
var snakePosition = SnakeBoddy2[0];
SnakeFoods2.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
}
}
private void EatFood3()
{
if (SnakeFoods3.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
if (SnakeBoddy.Count > 1)
{
SnakeBoddy.RemoveAt(SnakeBoddy.Count - 1);
}
Player1setting.GameScore += FoodSetting.food3;
label2.Text = Player1setting.GameScore.ToString();
var snakePosition = SnakeBoddy[0];
SnakeFoods3.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
}
if (SnakeFoods3.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
if (SnakeBoddy2.Count > 1)
{
SnakeBoddy2.RemoveAt(SnakeBoddy2.Count - 1);
}
Player2setting.GameScore2 += FoodSetting.food3;
label3.Text = Player2setting.GameScore2.ToString();
var snakePosition = SnakeBoddy2[0];
SnakeFoods3.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
}
}
private void EatFood4()
{
if (SnakeFoods4.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))
{
Player1setting.GameScore += FoodSetting.food4;
label2.Text = Player1setting.GameScore.ToString();
var snakePosition = SnakeBoddy[0];
SnakeFoods4.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
RandomEevent();
}
if (SnakeFoods4.Any(s => s.X == SnakeBoddy2[0].X && s.Y == SnakeBoddy2[0].Y))
{
Player2setting.GameScore2 += FoodSetting.food4;
label3.Text = Player2setting.GameScore2.ToString();
var snakePosition = SnakeBoddy2[0];
SnakeFoods4.RemoveAll(s => s.X == snakePosition.X && s.Y == snakePosition.Y);
RandomEevent();
}
}
private void RandomEevent()
{
var time = DateTime.Now;
eventTimer.Tick += new EventHandler(TimerEventProcessor);
eventTimer.Interval = 3000;
eventTimer.Start();
while (exitFlag == false)
{
//Application.DoEvents();
if ((DateTime.Now - time).TotalSeconds > 30)
{
eventTimer.Stop();
exitFlag = true;
}
}
}
private void TimerEventProcessor(Object sender, EventArgs e)
{
eventTimer.Enabled = true;
Player2setting.Movment2 = (SnakeMovment2)random.Next(4);
}
private void FoodEvent()
{
foodTimer.Tick += new EventHandler(FoodGenerator);
foodTimer.Interval = random.Next(1000,4000);
foodTimer.Start();
foodTimer2.Tick += new EventHandler(FoodGenerator2);
foodTimer2.Interval = random.Next(4000, 7000);
foodTimer2.Start();
foodTimer3.Tick += new EventHandler(FoodGenerator3);
foodTimer3.Interval = random.Next(5000, 10000);
foodTimer3.Start();
foodTimer4.Tick += new EventHandler(FoodGenerator4);
foodTimer4.Interval = random.Next(3000, 6000);
foodTimer4.Start();
}
private void FoodGenerator(object sender, EventArgs e)
{
foodTimer.Enabled = true;
GenerateSnakeFood();
}
private void FoodGenerator2(object sender, EventArgs e)
{
foodTimer2.Enabled = true;
GenerateSnakeFood2();
}
private void FoodGenerator3(object sender, EventArgs e)
{
foodTimer3.Enabled = true;
GenerateSnakeFood3();
}
private void FoodGenerator4(object sender, EventArgs e)
{
foodTimer4.Enabled = true;
GenerateSnakeFood4();
}
private void Die()
{
Player1setting.Gameover = true;
}
private void Die2()
{
Player2setting.Gameover2 = true;
}
private void GameStart_Click(object sender, EventArgs e)
{
if (choice1.Checked || choice2.Checked || choice3.Checked) {
StartGame();
}
}
}
}
</code></pre>
<p><strong>KeyInput.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Windows.Forms;
namespace snakeGame3players
{
class KeyInput
{
private static Hashtable keyTable = new Hashtable();
public static bool KeyInputs(Keys key)
{
if (keyTable[key] == null)
{
return false;
}
return (bool)keyTable[key];
}
public static void SnakeDirections(Keys key, bool direction)
{
keyTable[key] = direction;
}
}
}
</code></pre>
<p><strong>Player1setting.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace snakeGame3players
{
public enum SnakeMovment
{
Right,
Left,
Down,
Up
};
public enum SnakeMovment2
{
W,
S,
D,
A
};
class Player1setting
{
public static int Width { get; set; }
public static int Height { get; set; }
public static int GameScore { get; set; }
public static bool Gameover { get; set; }
public static SnakeMovment Movment { get; set; }
public Player1setting()
{
Height = 16;
Width = 16;
Gameover = false;
Movment = SnakeMovment.Down;
GameScore = 0;
}
}
class Player2setting
{
public static int Width2 { get; set; }
public static int Height2 { get; set; }
public static int GameScore2 { get; set; }
public static bool Gameover2 { get; set; }
public static SnakeMovment2 Movment2 { get; set; }
public Player2setting()
{
Height2 = 16;
Width2 = 16;
Gameover2 = false;
Movment2 = SnakeMovment2.S;
GameScore2 = 0;
}
}
class FoodSetting
{
public static int food1 { get; set; }
public static int food2 { get; set; }
public static int food3 { get; set; }
public static int food4 { get; set; }
public FoodSetting()
{
food1 = 1;
food2 = 5;
food3 = 1;
food4 = 1;
}
}
}
</code></pre>
<p><strong>Square.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace snakeGame3players
{
class Square
{
public int X { get; set; }
public int Y { get; set; }
public Square()
{
X = 0;
Y = 0;
}
}
}
</code></pre>
<p><strong>Program.cs</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace snakeGame3players
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T07:49:47.110",
"Id": "507668",
"Score": "3",
"body": "Are you sure that you understand the OOP principles? 700+ lines of `Form1` class says you don't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T07:19:53.440",
"Id": "508158",
"Score": "0",
"body": "From what aspect are you looking for a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T14:39:46.907",
"Id": "508215",
"Score": "0",
"body": "I just want to improve it, it can be just one function `private void UpdateScreen(object sender, EventArgs e)` for an example to how I would do it if I was following OOP standards"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T17:21:37.130",
"Id": "508237",
"Score": "1",
"body": "I've left a quite lengthy answer. Please check it. I hope it helps you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-25T21:07:27.537",
"Id": "509001",
"Score": "0",
"body": "To mark the answer as accepted please check the label to the left from the answer. In case it was helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-26T13:03:56.520",
"Id": "509061",
"Score": "0",
"body": "ops maybe I double clicked it sry"
}
] |
[
{
"body": "<p>OP has stated that (s)he is interested mainly about the <code>UpdateScreen</code>.<br />\nSo, in this review I try to focus only on that part of the application.</p>\n<p>First, let me show you the end result and then let me iterate through the changes one-by-one:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private void UpdateScreen(object sender, EventArgs e)\n{\n if (label1.Visible)\n {\n if (KeyInput.IsKeyDown(Keys.Q))\n {\n Application.Restart();\n Environment.Exit(0);\n }\n }\n if (choice2.Checked)\n {\n playerOne.UpdateMovement();\n UpdateSnakeBoddy();\n }\n\n pictureBox1.Invalidate();\n\n\n if (choice1.Checked)\n {\n playerTwo.UpdateMovement();\n UpdateSnakeBoddy2();\n }\n\n pictureBox1.Invalidate();\n}\n</code></pre>\n<h3>Use instances</h3>\n<ul>\n<li>In your original solution you have a <code>Player1setting</code> class with <code>static</code> properties.</li>\n<li>In case of OOP you should work on a particular instance not on a global one.</li>\n</ul>\n<p>So, lets get rid of the <code>static</code> keywords:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Player1setting\n{\n public int Width { get; set; }\n public int Height { get; set; }\n public int GameScore { get; set; }\n public bool Gameover { get; set; }\n public SnakeMovment Movment { get; set; }\n\n public Player1setting()\n {\n Height = 16;\n Width = 16;\n Gameover = false;\n Movment = SnakeMovment.Down;\n GameScore = 0;\n }\n}\n</code></pre>\n<p>Then create instances:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>//Class-wide private members\nprivate readonly Player1setting playerOne;\nprivate readonly Player2setting playerTwo;\n\npublic Form1()\n{\n InitializeComponent();\n playerOne = new Player1setting();\n playerTwo = new Player2setting();\n ...\n}\n</code></pre>\n<p>And use them. So, we have to change all <code>Player1setting.</code> and <code>Player2setting.</code> to <code>playerOne.</code> and <code>playerTwo.</code>. For example:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (KeyInput.KeyInputs(Keys.Right) && playerOne.Movment != SnakeMovment.Left)\n{\n playerOne.Movment = SnakeMovment.Right;\n}\n</code></pre>\n<h3>Use better naming</h3>\n<p><em>In the comments you can find the original</em></p>\n<pre class=\"lang-cs prettyprint-override\"><code>class PlayerOneSettings //Orig: Player1setting\n{\n public int Width { get; set; }\n public int Height { get; set; }\n public int GameScore { get; set; }\n public bool IsGameOver { get; set; } //Orig: Gameover\n public SnakeMovement Movement { get; set; } //Orig: SnakeMovment Movment\n ...\n}\n</code></pre>\n<p>Please also rename the following methods:</p>\n<ul>\n<li><code>PlayerMovment</code> to <code>UpdateSnakeBoddy</code></li>\n<li><code>PlayerMovment2</code> to <code>UpdateSnakeBoddy2</code></li>\n</ul>\n<p>In my opinion these names are more expressive because in those methods you are changing mainly those collections.</p>\n<h3>Encapsulate logic</h3>\n<p>The change of the <code>Movement</code> should reside inside the <code>Player{XYZ}Settings</code> classes.<br />\nSo, let's introduce an <code>UpdateMovement</code> method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class PlayerOneSettings\n{\n ...\n public void UpdateMovement()\n {\n if (Player1setting.Gameover == false)\n {\n if (KeyInput.KeyInputs(Keys.Right) && Movement != SnakeMovement.Left)\n {\n Movement = SnakeMovement.Right;\n }\n\n else if (KeyInput.KeyInputs(Keys.Left) && Movement != SnakeMovement.Right)\n {\n Movement = SnakeMovement.Left;\n }\n\n else if (KeyInput.KeyInputs(Keys.Up) && Movement != SnakeMovement.Down)\n {\n Movement = SnakeMovement.Up;\n }\n\n else if (KeyInput.KeyInputs(Keys.Down) && Movement != SnakeMovement.Up)\n {\n Movement = SnakeMovement.Down;\n }\n }\n }\n}\n</code></pre>\n<p>Here I can access the class members (like <code>Movement</code>) so I don't need to use <code>player1</code> prefix.<br />\nWe can also restrict the access of the <code>Movement</code>'s setter:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public SnakeMovement Movement { get; private set; }\n</code></pre>\n<p>Now the <code>UpdateScreen</code> should look like as it is was stated above.</p>\n<h3>Reuse available components</h3>\n<p>The <code>SnakeMovement</code> contains a subset of the <code>Keys</code> enumeration.<br />\nDo not reinvent the wheel, try to re-use existing components.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class PlayerOneSettings\n{\n ...\n private readonly Keys[] ValidKeys = new[] { Keys.Right, Keys.Left, Keys.Up, Keys.Down };\n}\n</code></pre>\n<p>Also we can define counterparts for each key:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class PlayerOneSettings\n{\n ...\n private readonly Keys[] ValidKeys = new[] { Keys.Right, Keys.Left, Keys.Up, Keys.Down };\n private readonly Dictionary<Keys, Keys> KeyCounterpartMapping = new Dictionary<Keys, Keys>\n {\n { Keys.Up, Keys.Down },\n { Keys.Down, Keys.Up },\n { Keys.Right, Keys.Left },\n { Keys.Left, Keys.Right },\n };\n}\n</code></pre>\n<p>With these in our hand we can greatly simplify the <code>UpdateMovement</code>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class PlayerOneSettings\n{\n ...\n public void UpdateMovement()\n {\n if (IsGameOver) return;\n\n foreach (var key in ValidKeys)\n {\n var counterpart = KeyCounterpartMapping[key];\n if (KeyInput.KeyInputs(key) && Movement != counterpart)\n {\n Movement = key;\n break;\n }\n }\n }\n}\n</code></pre>\n<p>With this modification the data and the operation is separated cleanly.</p>\n<h3>Use inheritance</h3>\n<p>The <code>PlayerOneSettings</code> and <code>PlayerTwoSettings</code> have a huge resembles, which is not a coincidence.<br />\nSo, it would be wise to define a base class and inherit from it:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>abstract class PlayerSettings\n{\n public int Width { get; set; }\n public int Height { get; set; }\n public int GameScore { get; set; }\n public bool IsGameOver { get; set; }\n public Keys Movement { get; protected set; } //Orig: private\n\n protected abstract Keys[] ValidKeys { get; }\n protected abstract Dictionary<Keys, Keys> KeyCounterpartMapping { get; }\n\n public void UpdateMovement()\n {\n if (IsGameOver) return;\n\n foreach (var key in ValidKeys)\n {\n var counterpart = KeyCounterpartMapping[key];\n if (KeyInput.IsKeyDown(key) && Movement != counterpart)\n {\n Movement = key;\n break;\n }\n }\n }\n}\n</code></pre>\n<ul>\n<li>I've changed the <code>Movement</code>'s setter's accessibility from <code>private</code> to <code>protected</code> to be able to set it in the constructors of the derived classes.</li>\n<li>Because fields can't be <code>virtual</code> or <code>abstract</code> that's why I used properties for <code>ValidKeys</code> and <code>KeyCounterpartMapping</code>.</li>\n<li>I used <code>abstract</code> to enforce override in the derived classes:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>class PlayerOneSettings: PlayerSettings\n{\n public PlayerOneSettings()\n {\n Height = 16;\n Width = 16;\n IsGameOver = false;\n Movement = Keys.Down;\n GameScore = 0;\n }\n\n protected override Keys[] ValidKeys { get; } = new[] { Keys.Right, Keys.Left, Keys.Up, Keys.Down };\n\n protected override Dictionary<Keys, Keys> KeyCounterpartMapping { get; } = new Dictionary<Keys, Keys>\n {\n { Keys.Up, Keys.Down },\n { Keys.Down, Keys.Up },\n { Keys.Right, Keys.Left },\n { Keys.Left, Keys.Right },\n };\n}\n</code></pre>\n<pre class=\"lang-cs prettyprint-override\"><code>class PlayerTwoSettings: PlayerSettings\n{\n public PlayerTwoSettings()\n {\n Height = 16;\n Width = 16;\n IsGameOver = false;\n Movement = Keys.S;\n GameScore = 0;\n }\n\n protected override Keys[] ValidKeys { get; } = new[] { Keys.W, Keys.S, Keys.D, Keys.A };\n\n protected override Dictionary<Keys, Keys> KeyCounterpartMapping { get; } = new Dictionary<Keys, Keys>\n {\n { Keys.D, Keys.A },\n { Keys.A, Keys.D },\n { Keys.W, Keys.S },\n { Keys.S, Keys.W },\n };\n}\n</code></pre>\n<p>With these the derived classes only contains the deviations.<br />\nAll the common stuff are inherited.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T19:06:31.663",
"Id": "508241",
"Score": "0",
"body": "Sorry it was a copy-paste issue. Thanks I fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T07:52:51.340",
"Id": "510319",
"Score": "0",
"body": "@zellez Health should be your number one priority. Everything else could wait. After you are better, feel free to contact me and I'll try to help here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T09:18:42.803",
"Id": "511124",
"Score": "0",
"body": "@zellez I'm glad that you are better. As I stated in the review I've focused on the `UpdateScreen` method, not on the `PlayerMovment`. In my opinion the `PlayerMovment` has too much responsibility. If you want to move some part of this into a separate class then you have to remember **data and behaviour should stick together**. So, `SnakeBoddy` and related part of the `PlayerMovment` method should reside inside the same class. Food related updates should belong to another separate class. Does it make sense to you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T09:45:50.053",
"Id": "511131",
"Score": "0",
"body": "The collision detection could belong to the same class as the movement handling, because it operates on the same data. The reaction part could be separated into its on class if it operates on other data as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:02:14.720",
"Id": "511621",
"Score": "0",
"body": "I know it is shameless, but I can't seem to get it to work. I know it has been a while since you have viewed the code, but if could you show me the proper way it doesn't need to be explained, in detail, or anything like that. I could sit and study the code and try to figure out why on my own. I just lack the basic logic to do it, and if you don't want to help me further, it is understandable, and I wish you a nice day."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:51:57.990",
"Id": "511625",
"Score": "0",
"body": "@zellez Can you please share with me where do you have difficulties? What sort of information do you need?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T11:03:13.403",
"Id": "511627",
"Score": "0",
"body": "In the function I have `for (int i = SnakeBoddy.Count - 1; i >= 0; i--)` followed by a Switch statement how would I implement it in the class ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T07:24:21.203",
"Id": "511732",
"Score": "0",
"body": "@zellez I will leave another post where I will try to demonstrate how can you refactor that code. I can't promise that it will happen today but for sure it will happen this week."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T17:19:54.163",
"Id": "257311",
"ParentId": "257042",
"Score": "2"
}
},
{
"body": "<p>In this post I'll focus on the <code>PlayerMovment</code>. Before I try to guide you through the OOP related transformations, let me show you a couple of refactoring techniques which will help you to dramatically reduce the complexity of this method.</p>\n<h2>Guard expression vs Early exit</h2>\n<h3>Before</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private void PlayerMovment()\n{\n if (choice2.Checked)\n {\n for (...)\n {\n ...\n }\n }\n}\n</code></pre>\n<h3>After</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>private void PlayerMovment()\n{\n if (!choice2.Checked) return;\n \n for (...)\n {\n ...\n }\n}\n</code></pre>\n<ul>\n<li>Instead of guarding the whole operation, do some preliminary checks and if they fail then early exit</li>\n<li>This will help you streamline your code and reduce the indentation</li>\n</ul>\n<h2>Splitting logic</h2>\n<h3>Before</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>for (int i = SnakeBoddy.Count - 1; i >= 0; i--)\n{\n if (i == 0)\n {\n //DO a lots of stuff\n }\n else\n { \n //DO a simple stuff\n }\n}\n\n</code></pre>\n<h3>After</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>//Move each part of the snake body forward (without head) \nfor (int i = SnakeBoddy.Count - 1; i > 0; i--)\n{\n //DO a simple stuff\n}\n\n//DO a lots of stuff\n</code></pre>\n<ul>\n<li>In your reverse iteration I changed the exit condition from <code>i >= 0</code> to <code>i > 0</code>\n<ul>\n<li>With this modification I could eliminate the branching logic</li>\n</ul>\n</li>\n<li>So, the <code>for</code> loop now has that code which was inside the <code>else</code> block\n<ul>\n<li>In other words <em>we move each part of the snake body forward (without head)</em></li>\n</ul>\n</li>\n</ul>\n<h2>Don't repeat yourself #1</h2>\n<h3>Before</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>switch (Player1setting.Movment)\n{\n case SnakeMovment.Right:\n SnakeBoddy[i].X++;\n break;\n\n case SnakeMovment.Left:\n SnakeBoddy[i].X--;\n break;\n\n case SnakeMovment.Up:\n SnakeBoddy[i].Y--;\n break;\n\n case SnakeMovment.Down:\n SnakeBoddy[i].Y++;\n break;\n}\n</code></pre>\n<h3>After</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>//Adjust head\nvar head = SnakeBoddy[0];\nhead.X += Player1setting.Movment == SnakeMovment.Right ? 1\n : Player1setting.Movment == SnakeMovment.Left ? -1 : 0;\n\nhead.Y += Player1setting.Movment == SnakeMovment.Down ? 1\n : Player1setting.Movment == SnakeMovment.Up ? -1 : 0;\n</code></pre>\n<ul>\n<li>One can argue with this modification that it does not improve legibility\n<ul>\n<li>I can agree with them because using two nested conditional operators (<code>?:</code>) might not be easily readable</li>\n<li>But logic is quite simple\n<ul>\n<li>Increase <code>X</code> with <code>1</code> if user pressed <code>Right</code></li>\n<li>Increase <code>X</code> with <code>-1</code> if user pressed <code>Left</code></li>\n<li>Increase <code>X</code> with <code>0</code> otherwise</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>I've also introduced a variable <code>head</code> because you have referred to the same element as <code>SnakeBoddy[0]</code> and sometimes as <code>SnakeBoddy[i]</code> where <code>i</code> is guaranteed to be 0</li>\n</ul>\n<h2>Don't repeat yourself #2</h2>\n<h3>Before</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>for (int J = 1; J < SnakeBoddy.Count; J++)\n{\n if (SnakeBoddy[i].X == SnakeBoddy[J].X && SnakeBoddy[i].Y == SnakeBoddy[J].Y)\n {\n Die();\n }\n}\nfor (int g = 0; g < SnakeBoddy2.Count; g++)\n{\n if (SnakeBoddy[0].X == SnakeBoddy2[g].X && SnakeBoddy[0].Y == SnakeBoddy2[g].Y)\n {\n Player1setting.GameScore += FoodSetting.food2;\n label3.Text = Player1setting.GameScore.ToString();\n Die();\n }\n}\n</code></pre>\n<h3>After</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>//Check whether the snake has collided with itself or with the other snake\nforeach (var body in SnakeBoddy.Union(SnakeBoddy2))\n{\n if (head.X == body.X && head.Y == body.Y)\n {\n Die();\n break;\n }\n}\n</code></pre>\n<ul>\n<li>Here you can make use of the <code>foreach</code>, you don't have to use <code>for</code></li>\n<li>You have done the same operation against <code>SnakeBoddy</code> and <code>SnakeBoddy2</code>\n<ul>\n<li>With LINQ's <code>Union</code> you can easily merge these two iterations</li>\n</ul>\n</li>\n<li>Once you have detected collision then you do not need to iterate through the rest of the items that's why you can <code>break</code> out from the loop\n<ul>\n<li>Or even <code>return</code> from the <code>PlayerMovment</code></li>\n</ul>\n</li>\n<li>I do believe that <code>GameScore</code> and <code>label3</code> updates should not belong here that's why I removed from my code\n<ul>\n<li>This should be handled on the caller side</li>\n</ul>\n</li>\n</ul>\n<h2>Separate data and operation</h2>\n<h3>Before</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>if (SnakeFoods1.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))\n{\n EatFood();\n}\n\nif (SnakeFoods2.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))\n{\n EatFood2();\n}\n\nif (SnakeFoods3.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))\n{\n EatFood3();\n}\n\nif (SnakeFoods4.Any(s => s.X == SnakeBoddy[0].X && s.Y == SnakeBoddy[0].Y))\n{\n EatFood4();\n}\n</code></pre>\n<h3>After</h3>\n<pre class=\"lang-cs prettyprint-override\"><code>//Eat all food which was in its way\nvar allFood = new Dictionary<List<Square>, Action> {\n { SnakeFoods1, EatFood },\n { SnakeFoods2, EatFood2 },\n { SnakeFoods3, EatFood3 },\n { SnakeFoods4, EatFood4 }\n};\nforeach(var foodsAndEatMapping in allFood)\n{\n if (foodsAndEatMapping.Key.Any(s => s.X == head.X && s.Y == head.Y))\n {\n foodsAndEatMapping.Value();\n }\n}\n</code></pre>\n<ul>\n<li>Yet again you have performed the same operation against different datasets\n<ul>\n<li>By separating operation from data you can avoid repetition</li>\n</ul>\n</li>\n<li>Here I've created a mapping (called <code>allFood</code>) where I have mapped the food source collection to the related <code>EatFood</code> function\n<ul>\n<li>I did not want to spent time to generalize the <code>EatFood{XYZ}</code> methods but that should your homework</li>\n</ul>\n</li>\n</ul>\n<h2>The refactored <code>PlayerMovment</code></h2>\n<pre class=\"lang-cs prettyprint-override\"><code>private void PlayerMovment()\n{\n if (!choice2.Checked) return;\n\n //Move each part of the snake body forward (without head) \n for (int i = SnakeBoddy.Count - 1; i > 0; i--)\n {\n SnakeBoddy[i].X = SnakeBoddy[i - 1].X;\n SnakeBoddy[i].Y = SnakeBoddy[i - 1].Y;\n }\n\n //Adjust head\n var head = SnakeBoddy[0];\n head.X += Player1setting.Movment == SnakeMovment.Right ? 1\n : Player1setting.Movment == SnakeMovment.Left ? -1 : 0;\n\n head.Y += Player1setting.Movment == SnakeMovment.Down ? 1\n : Player1setting.Movment == SnakeMovment.Up ? -1 : 0;\n\n //Check whether the snake has moved out of the arena\n int maxXPosition = pictureBox1.Size.Width / Player1setting.Width;\n int maxYPosition = pictureBox1.Size.Height / Player1setting.Height;\n\n if (head.X < 0 || head.X > maxXPosition ||\n head.Y < 0 || head.Y >= maxYPosition)\n Die();\n\n //Check whether the snake has collided with itself or with the other snake\n foreach (var body in SnakeBoddy.Union(SnakeBoddy2))\n {\n if (head.X == body.X && head.Y == body.Y)\n {\n Die();\n break;\n }\n }\n\n //Eat all food which was in its way\n var allFood = new Dictionary<List<Square>, Action> {\n { SnakeFoods1, EatFood },\n { SnakeFoods2, EatFood2 },\n { SnakeFoods3, EatFood3 },\n { SnakeFoods4, EatFood4}\n };\n foreach(var foodsAndEatMapping in allFood)\n {\n if (foodsAndEatMapping.Key.Any(s => s.X == head.X && s.Y == head.Y))\n {\n foodsAndEatMapping.Value();\n }\n }\n}\n</code></pre>\n<ul>\n<li>The same transformation should be applied to <code>PlayerMovment2</code></li>\n</ul>\n<hr />\n<p>Now let's start to focus on the OOP stuff.</p>\n<h3>Basics</h3>\n<p>First we have to identify what sort of components do we have.<br />\nThen we have to identify what can we do with them.</p>\n<p>Now, let's just list the comments here (which I have placed in the refactored version):</p>\n<pre class=\"lang-cs prettyprint-override\"><code>//Move each part of the snake body forward (without head) \n\n//Adjust head\n\n//Check whether the snake has moved out of the arena\n\n//Check whether the snake has collided with itself or with the other snake\n\n//Eat all food which was in its way\n</code></pre>\n<h3>Nouns</h3>\n<p>To identify object let's focus on the nouns:</p>\n<ul>\n<li>Snake\n<ul>\n<li>Body</li>\n<li>Head</li>\n</ul>\n</li>\n<li>Arena</li>\n<li>Food</li>\n</ul>\n<p>As you can see our primary object could be the <code>Snake</code>, which encapsulates <code>Body</code> and <code>Head</code>. Depending on the operations <code>Body</code> and <code>Head</code> may or may not be public</p>\n<ul>\n<li>If we want to perform operations on <code>Body</code> and <code>Head</code> at same time then most probably we don't need to expose them. They can become implementation details from the consumer point of view.</li>\n<li>If we want to allow separate query operations against <code>Body</code> and <code>Head</code> then we should expose only <em>readonly</em> access. In other words the modification methods remain private to the object.</li>\n</ul>\n<p>The <code>Arena</code> is related to <code>pictureBox1</code> and <code>Player1setting</code>. If they are not changing over time then the <code>Arena</code> should not depend on them, just initialize it with the related values. Yet again exposing its members depends on the exposed behaviours. We will talk about this in the <strong>verbs</strong> section.</p>\n<p>And finally the <code>Food</code>, which is more precisely a set of food. So, here the object could be <code>Foods</code> or <code>FoodManager</code> or what so ever.</p>\n<h3>Verbs</h3>\n<p>To identify behaviours let's focus on the verbs:</p>\n<ul>\n<li>Snake\n<ul>\n<li>Body\n<ul>\n<li><em>Move</em></li>\n</ul>\n</li>\n<li>Head\n<ul>\n<li><em>Adjust</em></li>\n<li><em>Check</em> collision</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>Arena\n<ul>\n<li><em>Check</em> boundary</li>\n</ul>\n</li>\n<li>Food\n<ul>\n<li><em>Eat</em></li>\n</ul>\n</li>\n</ul>\n<p>As you can the <code>Move</code> and <code>Adjust</code> operates on the snake's body and head. If we want to perform them together then we should not separate them.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Snake\n{\n private List<Square> WholeBody {get; set;}\n private Square Head => WholeBody[0];\n private IEnumerable<Square> Body => WholeBody.Skip(1);\n \n public Snake(...)\n {\n //TODO: Initialize snake's internals\n }\n\n public void MoveForward(int verticalMove, int horizontalMove)\n {\n AdjustHead(verticalMove, horizontalMove);\n MoveBody();\n }\n\n private void MoveBody()\n {\n //TODO: perform operation against Body\n }\n\n private AdjustHead(int verticalMove, int horizontalMove)\n {\n //TODO: perform operation against Head\n }\n}\n</code></pre>\n<p>The <code>CheckCollision</code> can be performed against the <code>Snake</code> instance itself or against any other instance. So we can create two separate methods to cover both cases:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Snake\n{\n ...\n public bool HaveIBittenMyself()\n {\n //TODO: Check whether head is collided with any part of the body\n }\n\n public bool HasOtherBittenMe(Square headOfOtherSnake)\n {\n //TODO: Check whether the other's head is collided with any part of the wholeBody\n }\n}\n</code></pre>\n<ul>\n<li>As you can see the Snake itself does not know about the rest of the world. <strong>It can perform operations on its own data.</strong> This is crucial in case of OOP.</li>\n</ul>\n<hr />\n<p>I think now you have the flavour so I'll leave <code>Arena</code> and <code>Foods</code> as an exercise for yourself. I hope this lengthy post helped you a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-16T10:48:27.313",
"Id": "259613",
"ParentId": "257042",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "257311",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T19:42:07.280",
"Id": "257042",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"snake-game"
],
"Title": "Simple Snake Game With OOP in Mind"
}
|
257042
|
<p>The original Javascript slider is on W3 schools. I modified it to work as a slider for my homepage. The goal is to call it into <code>index.js</code> (which works) and use it at the top of the page (which works) and if I want to swap out an image, I could load <code>slideshow.js</code>, add a new static image or remove an old one (also works).</p>
<p>But I bet it isn't really "React ready" as many tutorials have multiple components and GraphQL calls in them.</p>
<p>How can I make this better?</p>
<p>Oh yeah, Gatsby version 3.0.0 and <code>gatsby-starter-default</code> is the base.</p>
<pre><code>import * as React from "react";
import { slideshow_wrapper } from "./slideshow.module.css";
import { StaticImage } from "gatsby-plugin-image";
const SlideShow = () => {
let myIndex = 0;
const showNextSlide = () => {
let i;
let x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {
myIndex = 1;
}
x[myIndex - 1].style.display = "block";
};
React.useEffect(() => {
showNextSlide()
const i = setInterval(showNextSlide, 4000);
return () => clearInterval(i)
}, [])
return (
<div className={slideshow_wrapper}>
<StaticImage
src="../../images/slides/home_slider_1.jpg"
width={1920}
quality={100}
formats={["AUTO", "WEBP", "AVIF"]}
alt="A Gatsby astronaut"
className="mySlides"
/>
<StaticImage
src="../../images/slides/home_slider_2.jpg"
width={1920}
quality={100}
formats={["AUTO", "WEBP", "AVIF"]}
alt="A Gatsby astronaut"
className="mySlides"
/>
</div>
);
};
export default SlideShow;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T20:20:08.830",
"Id": "507713",
"Score": "0",
"body": "Welcome to Code Review! Your post looks good, I wonder though if you couldn't include a link to a fully working version to check out, since it's impossible to actually run it like this. Otherwise, hope you get some good answers anyway!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T02:29:21.193",
"Id": "257047",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"react.js"
],
"Title": "W3 automatic slideshow converted to React (gatsbyjs)"
}
|
257047
|
<p>I am trying to stay ahead of my Year 12 Software class. Starting to work with records and arrays. I have answered the question, but the solution feels very clunky. I am hoping someone has suggestions/links for completing this task in a more efficient way.</p>
<p>The task: read in lines from a text file and into a structure, and then loop through that, populating four list boxes if an animal hasn't been vaccinated.</p>
<pre><code>Imports System.IO
Public Class Form1
'Set up the variables - customer record, total pets not vaccinated, total records in the file, and a streamreader for the file.
Structure PetsRecord
Dim custName As String
Dim address As String
Dim petType As String
Dim vacced As String
End Structure
Dim totNotVac As Integer
Dim totalRecCount As Integer
Dim PetFile As IO.StreamReader
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
'set an array of records to store each record as it comes in. Limitation: you need to know how many records in the file. Set the array at 15 to allow for adding more in later.
Dim PetArray(15) As PetsRecord
'variables that let me read in a line and split it into sections.
Dim lineoftext As String
Dim i As Integer
Dim arytextfile() As String
'tell them what text file to read
PetFile = New IO.StreamReader("patients.txt")
totNotVac = 0
Try
totalRecCount = 0
' read each line in and split the lines into fields for the records. Then assign the fields from the array. Finally, reset the array and loop.
Do Until PetFile.Peek = -1
'read in a line of text
lineoftext = PetFile.ReadLine()
'split that line into bits separated by commas. these will go into the array.
arytextfile = lineoftext.Split(",")
'dunno whether this is the best way to do it, but stick the array bits into the record, and then clear the array to start again.
PetArray(totalRecCount).custName = arytextfile(0)
PetArray(totalRecCount).address = arytextfile(1)
PetArray(totalRecCount).petType = arytextfile(2)
PetArray(totalRecCount).vacced = arytextfile(3)
totalRecCount += 1
Array.Clear(arytextfile, 0, arytextfile.Length)
Loop
For i = 0 To PetArray.GetUpperBound(0)
If PetArray(i).vacced = "No" Then
lstVaccinated.Items.Add(PetArray(i).vacced)
lstCustomer.Items.Add(PetArray(i).custName)
lstAddress.Items.Add(PetArray(i).address)
lstPetType.Items.Add(PetArray(i).petType)
totNotVac += 1
lblVacTotal.Text = "The total number of unvaccinated animals is " & CStr(totNotVac)
End If
Next
Catch ex As Exception
MsgBox("Something went wrong with the file")
End Try
PetFile.Close()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
End Class
</code></pre>
<p>And one line from the patient.txt file:</p>
<pre><code> Richard Gere,16 Sunset Blvd,Gerbil,No
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T07:08:32.027",
"Id": "513006",
"Score": "0",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T08:26:53.003",
"Id": "513111",
"Score": "0",
"body": "I went to delete the post so that it could not be used by my students and the system told me that if I needed to make changes I could. Changing the variables doesn't change the validity of the answers."
}
] |
[
{
"body": "<p>Opinion: there is no benefit to building an array like this. I agree it is a clunky use of arrays which I think is unnecessary (and old-school). For instance you don't even need to know in advance how many records, nor do you need to dimension the array to a predetermined size. There are more flexible data types available than arrays for the job.</p>\n<p>When adding items to controls like a ListView or ListBox using <code>.Items.Add</code> you can use <code>BeginUpdate</code> at the beginning of your loop and <code>EndUpdate</code> at the end as you are populating the items from a loop.</p>\n<p>The aim is to make the UI more responsive - if you have a large file and you're adding lots of items, the interface may freeze while the loop is running.</p>\n<p>Although I would probably bind the list to a datatable instead, or another structure. Just append items to the datatable and let the control update itself.</p>\n<p>So here is a refactored example: I have converted your structure to a class and I use <code>List Of</code> instead of an array (note the addition of a binding source). For this to work I need to use <strong>properties</strong> to expose class members (so I think), which is why I am using a class instead of a structure, but there should be a way to retain a structure if you wish.</p>\n<p>There are several ways of reading a file, in this example I am using <code>StreamReader</code>. Note the use of a context manager (the <code>Using</code> block), which means I don't have to worry about closing the file, including in case of an exception. This happens automatically past the <code>End Using</code> statement.</p>\n<p>In your code <code>PetFile.Close()</code> will not be executed if an exception occurs. Your procedure will exit after MsgBox. But what you can do is move <code>PetFile.Close()</code> to a Finally section within your Try-Catch block. But if you're attempting to close a file that isn't even open, this will raise an exception within the exception. The best solution is not to bother with it and use the context manager.</p>\n<p>Note that each line in the file has to contain at least 4 comma-separated fields or the code will crash. So it is advisable to verify for each line that <code>fields.Count</code> = 4 and skip lines that don't match this criterion.</p>\n<p>Here I am populating only one listbox, you can figure out the rest easily hopefully.</p>\n<pre><code>Imports System.IO\n\nPublic Class Form1\n\n Public Class PetsRecord\n Private m_CustomerName As String\n Private m_CustomerAddress As String\n Private m_PetType As String\n Private m_Vaccinated As String\n\n Public Property CustomerName() As String\n Get\n Return Me.m_CustomerName\n End Get\n Set(ByVal value As String)\n Me.m_CustomerName = value\n End Set\n End Property\n\n Public Property CustomerAddress() As String\n Get\n Return Me.m_CustomerAddress\n End Get\n Set(ByVal value As String)\n Me.m_CustomerAddress = value\n End Set\n End Property\n\n Public Property PetType() As String\n Get\n Return Me.m_PetType\n End Get\n Set(ByVal value As String)\n Me.m_PetType = value\n End Set\n End Property\n\n Public Property Vaccinated() As String\n Get\n Return Me.m_Vaccinated\n End Get\n Set(ByVal value As String)\n Me.m_Vaccinated = value\n End Set\n End Property\n End Class 'Structure\n\n Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoad.Click\n Dim PetArray As New List(Of PetsRecord)\n Dim bs As New BindingSource()\n Dim PetFile As String = "C:\\Users\\test\\Documents\\pets.txt"\n\n Using r As StreamReader = New StreamReader(PetFile)\n Dim line As String\n line = r.ReadLine\n Do While (Not line Is Nothing)\n\n ' split the line into fields\n Dim fields As New List(Of String)(line.Split(","c))\n If fields.Count < 4 Then\n Console.WriteLine("Skipping line (contains less than 4 fields): " & line)\n Else\n ' flag this line\n If fields(3) = "No" Then\n Dim pet As New PetsRecord\n pet.CustomerName = fields(0)\n pet.CustomerAddress = fields(1)\n pet.PetType = fields(2)\n pet.Vaccinated = fields(3)\n PetArray.Add(pet)\n End If\n End If\n\n line = r.ReadLine\n Loop\n End Using\n\n ' bind the listbox to PetArray\n bs.DataSource = PetArray\n Me.lstCustomer.DisplayMember = "CustomerName"\n Me.lstCustomer.DataSource = bs\n\n End Sub\nEnd Class\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T21:42:24.637",
"Id": "257082",
"ParentId": "257051",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257082",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T07:17:18.347",
"Id": "257051",
"Score": "2",
"Tags": [
"vb.net"
],
"Title": "Reading from a text file into a structure and posting to list boxes"
}
|
257051
|
<p>I am attempting to implement a converter which can convert two dimensional array (such as <code>string[,]</code>) into <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#Tables" rel="nofollow noreferrer">markdown table</a>.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>Converter</code> class is as below.</p>
<pre><code>public static class Converter
{
/// <summary>
/// Align formats
/// </summary>
public enum Align
{
Right,
Center,
Left,
Default
}
private static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)
{
// null check
if (ReferenceEquals(array, null))
{
throw new ArgumentNullException($"{nameof(array)} is null");
}
if (ReferenceEquals(converter, null))
{
throw new ArgumentNullException($"{nameof(converter)} is null");
}
var output = new TOutput[array.GetLongLength(0), array.GetLongLength(1)];
for (long row = 0; row < array.GetLongLength(0); row++)
{
for (long column = 0; column < array.GetLongLength(1); column++)
{
output[row, column] = converter(array[row, column]);
}
}
return output;
}
/// <summary>
/// ToMarkdownTable method with TInput type array
/// </summary>
/// <param name="input">Input array</param>
/// <param name="align">Align format of all columns</param>
/// <returns></returns>
public static string[] ToMarkdownTable<TInput>(TInput[,] input, Align align = Align.Default)
{
return ToMarkdownTable(ConvertAll(input, element => element.ToString()), align);
}
/// <summary>
/// ToMarkdownTable method with TInput type array and the parameter for assigning align format of each column
/// </summary>
/// <param name="input">Input array</param>
/// <param name="aligns">Align format of each column</param>
/// <returns></returns>
public static string[] ToMarkdownTable<TInput>(TInput[,] input, Align[] aligns)
{
return ToMarkdownTable(ConvertAll(input, element => element.ToString()), aligns);
}
/// <summary>
/// ToMarkdownTable method
/// </summary>
/// <param name="input">Input array</param>
/// <param name="align">Align format of all columns</param>
/// <returns></returns>
public static string[] ToMarkdownTable(string[,] input, Align align = Align.Default)
{
Align[] format = new Align[input.GetLongLength(1)];
Array.Fill(format, align);
return ToMarkdownTable(input, format);
}
/// <summary>
/// ToMarkdownTable method with assigning align format of each column
/// </summary>
/// <param name="input">Input array</param>
/// <param name="aligns">Align format of each column</param>
/// <returns></returns>
public static string[] ToMarkdownTable(string[,] input, Align[] aligns)
{
// Null check
if (ReferenceEquals(input, null))
{
throw new ArgumentNullException($"{nameof(input)} is null");
}
if (ReferenceEquals(input, null))
{
throw new ArgumentNullException($"{nameof(aligns)} is null");
}
long width = input.GetLongLength(1);
long height = input.GetLongLength(0);
string[] output = new string[height + 1];
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append('|');
for (int x = 0; x < width; x++)
{
stringBuilder.Append(input[0, x]);
stringBuilder.Append('|');
}
output[0] = stringBuilder.ToString();
stringBuilder.Clear();
stringBuilder.Append('|');
for (int x = 0; x < width; x++)
{
switch (aligns[x])
{
case Align.Right:
stringBuilder.Append("-:|");
break;
case Align.Center:
stringBuilder.Append(":-:|");
break;
case Align.Left:
stringBuilder.Append(":-|");
break;
case Align.Default:
stringBuilder.Append("-|");
break;
default:
stringBuilder.Append("-|");
break;
}
}
output[1] = stringBuilder.ToString();
stringBuilder.Clear();
for (int y = 1; y < height; y++)
{
stringBuilder.Append('|');
for (int x = 0; x < width; x++)
{
stringBuilder.Append(input[y, x]);
stringBuilder.Append('|');
}
output[y + 1] = stringBuilder.ToString();
stringBuilder.Clear();
}
return output;
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The test cases of <code>Converter.ToMarkdownTable</code> methods include <code>string</code>, <code>sbyte</code>, <code>byte</code>, <code>short</code>, <code>ushort</code>, <code>char</code> and <code>int</code> type two dimensional arrays input.</p>
<pre><code>// string type two dimensional array case
Console.WriteLine("string type two dimensional array case");
string[,] test_string = { { "0", "1", "1", "1" },
{ "2", "3", "1", "1" },
{ "0", "1", "1", "1" }};
var format = new Converter.Align[test_string.GetLongLength(1)];
for (int i = 0; i < test_string.GetLongLength(1); i++)
{
format[i] = Converter.Align.Center;
}
var MarkdownTable = Converter.ToMarkdownTable(test_string, Converter.Align.Center);
for (int i = 0; i < MarkdownTable.Length; i++)
{
Console.WriteLine(MarkdownTable[i]);
}
Console.WriteLine();
// sbyte type two dimensional array case
Console.WriteLine("sbyte type two dimensional array case");
sbyte[,] test_sbyte = { { 0, 1, 1, 1 },
{ 2, 3, 1, 1 },
{ 0, 1, 1, 1 }};
var MarkdownTable_sbyte = Converter.ToMarkdownTable(test_sbyte, Converter.Align.Center);
for (int i = 0; i < MarkdownTable.Length; i++)
{
Console.WriteLine(MarkdownTable[i]);
}
Console.WriteLine();
// byte type two dimensional array case
Console.WriteLine("byte type two dimensional array case");
byte[,] test_byte = { { 0, 1, 1, 1 },
{ 2, 3, 1, 1 },
{ 0, 1, 1, 1 }};
var MarkdownTable_byte = Converter.ToMarkdownTable(test_byte, Converter.Align.Center);
for (int i = 0; i < MarkdownTable.Length; i++)
{
Console.WriteLine(MarkdownTable[i]);
}
Console.WriteLine();
// short type two dimensional array case
Console.WriteLine("short type two dimensional array case");
short[,] test_short = { { 0, 1, 1, 1 },
{ 2, 3, 1, 1 },
{ 0, 1, 1, 1 }};
var MarkdownTable_short = Converter.ToMarkdownTable(test_short, Converter.Align.Center);
for (int i = 0; i < MarkdownTable.Length; i++)
{
Console.WriteLine(MarkdownTable[i]);
}
Console.WriteLine();
// ushort type two dimensional array case
Console.WriteLine("ushort type two dimensional array case");
ushort[,] test_ushort = { { 0, 1, 1, 1 },
{ 2, 3, 1, 1 },
{ 0, 1, 1, 1 }};
var MarkdownTable_ushort = Converter.ToMarkdownTable(test_ushort, Converter.Align.Center);
for (int i = 0; i < MarkdownTable.Length; i++)
{
Console.WriteLine(MarkdownTable[i]);
}
Console.WriteLine();
// char type two dimensional array case
Console.WriteLine("char type two dimensional array case");
char[,] test_char = { { '0', '1', '1', '1' },
{ '2', '3', '1', '1' },
{ '0', '1', '1', '1' }};
var MarkdownTable_char = Converter.ToMarkdownTable(test_char, Converter.Align.Center);
for (int i = 0; i < MarkdownTable.Length; i++)
{
Console.WriteLine(MarkdownTable[i]);
}
Console.WriteLine();
// int type two dimensional array case
Console.WriteLine("int type two dimensional array case");
int[,] test_int = { { 0, 1, 1, 1 },
{ 2, 3, 1, 1 },
{ 0, 1, 1, 1 }};
var MarkdownTable_int = Converter.ToMarkdownTable(test_int, Converter.Align.Center);
for (int i = 0; i < MarkdownTable.Length; i++)
{
Console.WriteLine(MarkdownTable[i]);
}
Console.WriteLine();
</code></pre>
<p>The output of the above tests:</p>
<pre><code>string type two dimensional array case
|0|1|1|1|
|:-:|:-:|:-:|:-:|
|2|3|1|1|
|0|1|1|1|
sbyte type two dimensional array case
|0|1|1|1|
|:-:|:-:|:-:|:-:|
|2|3|1|1|
|0|1|1|1|
byte type two dimensional array case
|0|1|1|1|
|:-:|:-:|:-:|:-:|
|2|3|1|1|
|0|1|1|1|
short type two dimensional array case
|0|1|1|1|
|:-:|:-:|:-:|:-:|
|2|3|1|1|
|0|1|1|1|
ushort type two dimensional array case
|0|1|1|1|
|:-:|:-:|:-:|:-:|
|2|3|1|1|
|0|1|1|1|
char type two dimensional array case
|0|1|1|1|
|:-:|:-:|:-:|:-:|
|2|3|1|1|
|0|1|1|1|
int type two dimensional array case
|0|1|1|1|
|:-:|:-:|:-:|:-:|
|2|3|1|1|
|0|1|1|1|
</code></pre>
<p>If there is any possible improvement, please let me know.</p>
|
[] |
[
{
"body": "<p>Here are my observations:</p>\n<h3><code>Align</code></h3>\n<ul>\n<li>I think <code>Alignment</code> would be a better name. (<em>Align</em> is a verb where <em>Alignment</em> is a noun)</li>\n<li>Most of the time the <code>Default</code>, <code>Unknown</code> or <code>Invalid</code> is the first element in the enum\n<ul>\n<li>If you define an enum variable without specifying its value then it will be declared as 0</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public enum Alignment { Default, Left, Center, Right }\n</code></pre>\n<h3><code>ConvertAll</code></h3>\n<ul>\n<li><code>ReferenceEquals(array, null)</code>: This can be simplified like this: <code>array is null</code></li>\n<li><code>ArgumentNullException($"{nameof(array)} is null")</code>: Here the constructor anticipates the <strong>name of the parameter</strong>, not the <em>message</em>. So the correct way would look like this:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>if (array is null) throw new ArgumentNullException(nameof(array));\n</code></pre>\n<ul>\n<li><code>array.GetLongLength(0)</code>: As you have done it in the <code>ToMarkdownTable</code> you can declare a helper variable to store this value and reuse it multiple times:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var rowCount = array.GetLongLength(0);\nvar columnCount = array.GetLongLength(1);\nvar output = new TOutput[rowCount, columnCount];\n</code></pre>\n<ul>\n<li>Nested for loops: It is minor, but you can get rid of the block operators:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>for (var row = 0; row < rowCount; row++)\n for (var column = 0; column < columnCount; column++)\n output[row, column] = converter(array[row, column]);\n</code></pre>\n<p>So the whole <code>ConvertAll</code> can be refactored like this:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static TOutput[,] ConvertAll<TInput, TOutput>(TInput[,] array, Converter<TInput, TOutput> converter)\n{\n if (array is null) throw new ArgumentNullException(nameof(array));\n if (converter is null) throw new ArgumentNullException(nameof(converter));\n\n var rowCount = array.GetLongLength(0);\n var columnCount = array.GetLongLength(1);\n var output = new TOutput[rowCount, columnCount];\n\n for (var row = 0; row < rowCount; row++)\n for (var column = 0; column < columnCount; column++)\n output[row, column] = converter(array[row, column]);\n\n return output;\n}\n</code></pre>\n<h3><code>ToMarkDownTable</code> <em>where the core logic resides</em></h3>\n<ul>\n<li>Yet again the null checks can be simplified\n<ul>\n<li>The second null check is done against <code>input</code>, please fix it to use <code>alings</code> there</li>\n</ul>\n</li>\n<li><code>width</code> and <code>height</code>: I would suggest to stick with the terms <code>row</code> and <code>column</code> because we are talking about table.</li>\n<li><code>stringBuilder.Clear()</code>: Even though it does work, it indicates that your separation of concerns is not good.\n<ul>\n<li>I do suggest to introduce several helper method and use them like this:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string[] ToMarkDownTable(string[,] input, Alignment[] aligns)\n{\n if (input is null) throw new ArgumentNullException(nameof(input));\n if (aligns is null) throw new ArgumentNullException(nameof(aligns));\n\n var rowCount = input.GetLongLength(0);\n var output = new string[rowCount + 1];\n\n output[0] = ToTableHeader(input);\n output[1] = ToTableCellAlignments(input, aligns);\n\n for (var row = 1; row < rowCount; row++)\n output[row + 1] = ToTableRow(input, row);\n\n return output;\n}\n</code></pre>\n<h3>Header</h3>\n<ul>\n<li><code>stringBuilder.Append('|');</code>: I suggest to introduce a class level constant to hold the cell separator:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>private const char CellSeparator = '|';\n</code></pre>\n<ul>\n<li>With this the header generation would be string literal free:</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string ToTableHeader(string[,] input)\n{\n var tableHeaderBuilder = new StringBuilder();\n tableHeaderBuilder.Append(CellSeparator);\n\n for (var column = 0; column < input.GetLongLength(1); column++)\n {\n tableHeaderBuilder.Append(input[0, column]);\n tableHeaderBuilder.Append(CellSeparator);\n }\n\n return tableHeaderBuilder.ToString();\n}\n</code></pre>\n<ul>\n<li>If your <code>input</code> would be a multi-dimensional array, not a jagged one then the <code>input</code> could be a single dimensional array. That would increase the separation.</li>\n</ul>\n<h3>Cell Alignments</h3>\n<ul>\n<li><code>stringBuilder.Append</code>: This has been repeated way too many times.\n<ul>\n<li>Your branching should be scoped to the data (should NOT include the operation).</li>\n<li>With that you would be able to use switch expression:</li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string ToTableCellAlignments(string[,] input, Alignment[] aligns)\n{\n var tableCellAlignmentBuilder = new StringBuilder();\n tableCellAlignmentBuilder.Append(CellSeparator);\n\n for (var column = 0; column < input.GetLongLength(1); column++)\n {\n var separator = aligns[column] switch\n {\n Alignment.Right => $"-:{CellSeparator}",\n Alignment.Center => $":-:{CellSeparator}",\n Alignment.Left => $":-{CellSeparator}",\n Alignment.Default => $"-{CellSeparator}",\n _ => $"-{CellSeparator}"\n };\n\n tableCellAlignmentBuilder.Append(separator);\n }\n\n return tableCellAlignmentBuilder.ToString();\n}\n</code></pre>\n<h3>Row</h3>\n<ul>\n<li>I've decided to extract away only a single row generation instead of all rows\n<ul>\n<li>This simplifies the row generation logic</li>\n<li><em>and can be easily altered to utilize multi dimensional array</em></li>\n</ul>\n</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string ToTableRow(string[,] input, int row)\n{\n var tableRowBuilder = new StringBuilder();\n tableRowBuilder.Append(CellSeparator);\n\n for (var column = 0; column < input.GetLongLength(1); column++)\n {\n tableRowBuilder.Append(input[row, column]);\n tableRowBuilder.Append(CellSeparator);\n }\n return tableRowBuilder.ToString();\n}\n</code></pre>\n<hr />\n<p>In case of multi-dimensional arrays the core logic would look like this:</p>\n<ul>\n<li>So, in my opinion it might make sense to convert your jagged array to multi-dimensional</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string[] ToMarkDownTable(string[][] input, Alignment[] aligns)\n{\n if (input is null) throw new ArgumentNullException(nameof(input));\n if (aligns is null) throw new ArgumentNullException(nameof(aligns));\n\n var rowCount = input.GetLongLength(0);\n var columnCount = input.GetLongLength(1);\n var output = new string[rowCount + 1];\n\n output[0] = ToTableHeader(input[0]);\n output[1] = ToTableCellAlignments(columnCount, aligns);\n\n for (var row = 1; row < rowCount; row++)\n output[row + 1] = ToTableRow(input[row]);\n\n return output;\n}\n\nprivate const char CellSeparator = '|';\nprivate static string ToTableHeader(string[] headers)\n{\n var tableHeaderBuilder = new StringBuilder();\n tableHeaderBuilder.Append(CellSeparator);\n\n foreach (var header in headers)\n {\n tableHeaderBuilder.Append(header);\n tableHeaderBuilder.Append(CellSeparator);\n }\n\n return tableHeaderBuilder.ToString();\n}\n\nprivate static string ToTableCellAlignments(long columns, Alignment[] aligns)\n{\n var tableCellAlignmentBuilder = new StringBuilder();\n tableCellAlignmentBuilder.Append(CellSeparator);\n\n for (var column = 0; column < columns; column++)\n {\n var separator = aligns[column] switch\n {\n Alignment.Right => $"-:{CellSeparator}",\n Alignment.Center => $":-:{CellSeparator}",\n Alignment.Left => $":-{CellSeparator}",\n _ => $"-{CellSeparator}"\n };\n\n tableCellAlignmentBuilder.Append(separator);\n }\n\n return tableCellAlignmentBuilder.ToString();\n}\n\nprivate static string ToTableRow(string[] cells)\n{\n var tableRowBuilder = new StringBuilder();\n tableRowBuilder.Append(CellSeparator);\n\n foreach (var cell in cells)\n {\n tableRowBuilder.Append(cell);\n tableRowBuilder.Append(CellSeparator);\n }\n return tableRowBuilder.ToString();\n}\n</code></pre>\n<hr />\n<p><strong>UPDATE</strong> Further simplification of <code>ToTableCellAlignments</code>:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string ToTableCellAlignments(Alignment[] alignments)\n{\n var tableCellAlignmentBuilder = new StringBuilder();\n tableCellAlignmentBuilder.Append(CellSeparator);\n\n for (var alignment in alignments)\n {\n var separator = alignment switch\n {\n Alignment.Right => $"-:{CellSeparator}",\n Alignment.Center => $":-:{CellSeparator}",\n Alignment.Left => $":-{CellSeparator}",\n _ => $"-{CellSeparator}"\n };\n\n tableCellAlignmentBuilder.Append(separator);\n }\n\n return tableCellAlignmentBuilder.ToString();\n}\n</code></pre>\n<p>Prerequisite: <code>ToMarkDownTable</code> has to check <code>aligns.Length</code> against <code>array.GetLongLength(1)</code> if they aren't matching then it could throw an <code>ArgumentException</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T09:14:27.013",
"Id": "257058",
"ParentId": "257052",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "257058",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T07:34:45.560",
"Id": "257052",
"Score": "2",
"Tags": [
"c#",
"strings",
"array",
"formatting",
"generics"
],
"Title": "Two Dimensional Array to Markdown Table Converter Implementation in C#"
}
|
257052
|
<p>I tried my hand at a contact-us PHP script. I came up with the following. First the markup, then a little client-side validation and then the email script. I just need to know if this is usable code.
<p>I actually got to the point where I can make some cash developing websites. I just need to know if this is valid</p></p>
<p><strong>HTML</strong></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>function validateContactForm() {
var valid = true;
$(".info").html("");
$(".input-field").css('border', '#e0dfdf 1px solid');
var userName = $("#userName").val();
var userEmail = $("#userEmail").val();
var subject = $("#subject").val();
var content = $("#content").val();
if (userName == "") {
$("#userName-info").html("Required.");
$("#userName").css('border', '#e66262 1px solid');
valid = false;
}
if (userEmail == "") {
$("#userEmail-info").html("Required.");
$("#userEmail").css('border', '#e66262 1px solid');
valid = false;
}
if (!userEmail.match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
$("#userEmail-info").html("Invalid Email Address.");
$("#userEmail").css('border', '#e66262 1px solid');
valid = false;
}
if (subject == "") {
$("#subject-info").html("Required.");
$("#subject").css('border', '#e66262 1px solid');
valid = false;
}
if (content == "") {
$("#userMessage-info").html("Required.");
$("#content").css('border', '#e66262 1px solid');
valid = false;
}
return valid;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="frmContact" id="frmContact" method="post" action="" enctype="multipart/form-data" onsubmit="return validateContactForm()">
<div class="input-row">
<label style="padding-top: 20px;">Name</label> <span id="userName-info" class="info"></span><br />
<input type="text" class="input-field" name="userName" id="userName" />
</div>
<div class="input-row">
<label>Email</label> <span id="userEmail-info" class="info"></span><br /> <input type="text" class="input-field" name="userEmail" id="userEmail" />
</div>
<div class="input-row">
<label>Subject</label> <span id="subject-info" class="info"></span><br /> <input type="text" class="input-field" name="subject" id="subject" />
</div>
<div class="input-row">
<label>Message</label> <span id="userMessage-info" class="info"></span><br />
<textarea name="content" id="content" class="input-field" cols="60" rows="6"></textarea>
</div>
<div>
<input type="submit" name="send" class="btn-submit" value="Send" />
<div id="statusMessage">
<?php if (!empty($message)) { ?>
<p class='<?php echo $type; ?>Message'>
<?php echo $message; ?>
</p>
<?php } ?>
</div>
</div>
</form></code></pre>
</div>
</div>
</p>
<p><strong>PHP</strong></p>
<pre class="lang-php prettyprint-override"><code><?php if (!empty($_POST['send'])) {
$name = $_POST['userName'];
$email = $_POST['userEmail'];
$subject = $_POST['subject'];
$content = $_POST['content'];
$toEmail = 'neilmeyermusic@gmail.com';
$mailHeaders = 'From: ' . $name . '<' . $email . ">\r\n";
if (mail($toEmail, $subject, $content, $mailHeaders)) {
$message = 'Your contact information is received successfully.';
$type = 'success';
}
}
require_once "contact-view.php";
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T09:17:47.453",
"Id": "507671",
"Score": "0",
"body": "If somebody could help me format that code to look more pretty I would appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T09:22:42.870",
"Id": "507672",
"Score": "3",
"body": "you must validate $name and $email or this script will become a spam gate that will make possible to send any email to any address due to Mail injection. Better yet, do not add the custom From: header at all"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T13:50:04.970",
"Id": "507754",
"Score": "0",
"body": "Your title doesn't need to ask for \"reviews\". Your title should endeavor to uniquely describe what your script does."
}
] |
[
{
"body": "<p>The script is extremely basic but it seems to me that it is also not secure. I have seen similar code that vulnerable to header injection, so it was possible for spammers to add a BCC header, and instead spam other people through your server (and your IP address will get blacklisted as a result).</p>\n<p>Even a seasoned class like phpmailer has suffered <a href=\"https://legalhackers.com/advisories/PHPMailer-Exploit-Remote-Code-Exec-CVE-2016-10045-Vuln-Patch-Bypass.html\" rel=\"nofollow noreferrer\">nasty security bugs</a>. Another article that touches on the issue: <a href=\"https://blog.ripstech.com/2017/why-mail-is-dangerous-in-php/\" rel=\"nofollow noreferrer\">Why mail() is dangerous in PHP</a></p>\n<p>Since $mailHeaders is injectable, I can provide an E-mail address like:</p>\n<pre>someone@attacker.com@\\r\\nBcc: someone@victim.com</pre>\n<p>and I should be able to send spam to someone@victim.com, with your unwitting assistance.</p>\n<p>Validation of form fields in Javascript is not sufficient, it has to be performed server-side as well. Javascript is useful for instant, client-side validation to avoid back and forth exchanges with the server but cannot be considered a security feature since you don't control the client and can't trust it.</p>\n<p>It is only a matter of time until your form is indexed by spambots, that will start pounding your server. The bots don't care about Javascript. Your script will not stop them. So basically everything you wrote in JS has to be implemented server-side in PHP. JS validation is nice to have but optional.</p>\n<p>Since it appears that you are using Bootstrap, you could perhaps take advantage of the <a href=\"https://getbootstrap.com/docs/5.0/forms/validation/\" rel=\"nofollow noreferrer\">validation</a> options available. Then you can also get rid of the inline CSS styling eg: <code>$("#userEmail").css('border', '#e66262 1px solid');</code>.</p>\n<p>You can also use the <code>required</code> attribute in your mandatory HTML controls. Then the browser will prompt the user if some fields are empty, and will not submit the form. It is a small extra and costs nothing.</p>\n<p>To sum up, I suggest that you read up a bit on header injection and don't reinvent the wheel. There is mature, open-source third-party code available for this kind of task. It will be more secure that your homemade attempt.</p>\n<p>I seem to remember that there is also the possibility of <strong>nullbyte injection</strong> but can't remember the details right now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T23:43:13.490",
"Id": "257087",
"ParentId": "257059",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T09:16:47.517",
"Id": "257059",
"Score": "0",
"Tags": [
"php",
"html5",
"email"
],
"Title": "Reviews on a contact-us form"
}
|
257059
|
<p>I have a code that scrapes list of URL and appends dataframe as below:</p>
<pre><code>from selenium import webdriver
import pandas as pd
from tabulate import tabulate
import os
os.chdir(r"C:\Users\harsh\Google Drive\sportsintel.shop\Files")
cwd = os.getcwd()
print(cwd)
browser = webdriver.Chrome()
browser.get("https://www.oddsportal.com/soccer/england/premier-league/results/")
df = pd.read_html(browser.page_source, header=0)[0]
dateList = []
gameList = []
scoreList = []
home_odds = []
draw_odds = []
away_odds = []
for row in df.itertuples():
if not isinstance(row[1], str):
continue
elif ':' not in row[1]:
date = row[1].split('-')[0]
continue
time = row[1]
dateList.append(date)
gameList.append(row[2])
scoreList.append(row[3])
home_odds.append(row[4])
draw_odds.append(row[5])
away_odds.append(row[6])
result_comp_1 = pd.DataFrame({'date': dateList,
'game': gameList,
'score': scoreList,
'Home': home_odds,
'Draw': draw_odds,
'Away': away_odds})
print(tabulate(result_comp_1))
browser.get("https://www.oddsportal.com/soccer/england/premier-league/results/#/page/2/")
df = pd.read_html(browser.page_source, header=0)[0]
dateList = []
gameList = []
scoreList = []
home_odds = []
draw_odds = []
away_odds = []
for row in df.itertuples():
if not isinstance(row[1], str):
continue
elif ':' not in row[1]:
date = row[1].split('-')[0]
continue
time = row[1]
dateList.append(date)
gameList.append(row[2])
scoreList.append(row[3])
home_odds.append(row[4])
draw_odds.append(row[5])
away_odds.append(row[6])
result_comp = pd.DataFrame({'date': dateList,
'game': gameList,
'score': scoreList,
'Home': home_odds,
'Draw': draw_odds,
'Away': away_odds})
new_df =result_comp_1.append(result_comp, ignore_index=True)
</code></pre>
<p>Can I make my code better to avoid redundancy?</p>
|
[] |
[
{
"body": "<p>Seems like there's one major point of redundancy, in that you're performing the same logic on the two different pages you're scraping (requesting site, parsing results, storing in dataframe).</p>\n<p>You could eliminate the redundancy with a function that takes in the site URL and performs the logic... something like <code>def get_matches_data(url)</code>...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T17:06:19.823",
"Id": "507702",
"Score": "0",
"body": "Can you pass a list of urls in the def function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T17:07:59.090",
"Id": "507703",
"Score": "0",
"body": "you can write your functions to take whatever kinds of parameters you want - it's about what makes sense for your code, I'd say here it makes sense for it to take a single url, then loop through the target urls passing each one to the function"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T17:04:57.183",
"Id": "257073",
"ParentId": "257064",
"Score": "3"
}
},
{
"body": "<p>As mentioned by lsimmons your code repeats the same logic. Therefore you could abstract this into a method and call it twice.</p>\n<p>You also have some variables overriding names in the standard library ie, <code>date</code>, <code>time</code>. Naming like this can lead to some hard to track bugs.</p>\n<p>In addition you can remove the camel cased varaible names as this is not what standard styling defined <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>The class, although not needed, groups everything and keeps it clean. Plus if you ever have to use this data in other methods you don't have to have 6 args.</p>\n<p>As your code gets more sophisticated you can decouple the parsing logic so you could use the same grouping code for multiple sites.</p>\n<p>Here's some code that attempts the changes that might be helpful:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\nfrom selenium import webdriver\n\nbrowser = webdriver.Chrome()\n\n\nclass GameData:\n\n def __init__(self):\n self.dates = []\n self.games = []\n self.scores = []\n self.home_odds = []\n self.draw_odds = []\n self.away_odds = []\n\n\ndef parse_data(url):\n browser.get(url)\n df = pd.read_html(browser.page_source, header=0)[0]\n game_data = GameData()\n game_date = None\n for row in df.itertuples():\n if not isinstance(row[1], str):\n continue\n elif ':' not in row[1]:\n game_date = row[1].split('-')[0]\n continue\n game_data.dates.append(game_date)\n game_data.games.append(row[2])\n game_data.scores.append(row[3])\n game_data.home_odds.append(row[4])\n game_data.draw_odds.append(row[5])\n game_data.away_odds.append(row[6])\n\n return game_data\n\n\nif __name__ == '__main__':\n\n urls = ["https://www.oddsportal.com/soccer/england/premier-league/results/",\n "https://www.oddsportal.com/soccer/england/premier-league/results/#/page/2/"]\n\n results = None\n\n for url in urls:\n game_data = parse_data(url)\n result = pd.DataFrame(game_data.__dict__)\n if results is None:\n results = result\n else:\n results = results.append(result, ignore_index=True)\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T20:39:01.603",
"Id": "507773",
"Score": "3",
"body": "This needs some commentary. Code - only answers are off topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:52:19.007",
"Id": "507790",
"Score": "1",
"body": "@PyNoob put in fix with the last edit!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T06:52:12.827",
"Id": "507816",
"Score": "0",
"body": "I tried the old code, I had 696 urls. I copy repeated the link and the function and run it, (I know, funny but this is before the loop solution), it takes 52s while the loop solution takes around 4 mins. Is there a reason this takes more time than the latter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T14:57:57.903",
"Id": "507851",
"Score": "1",
"body": "@PyNoob That's weird, no reason it should take longer. What I would do is put in some print statements to see what's taking so long.\n```python\n#at top\nstart = datetime.now()\n...\nprint(f'<some descriptive text>: {(datetime.now()-start).total_seconds()}')\n```\nYou are becoming a real programmer my friend! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T22:06:26.050",
"Id": "507890",
"Score": "1",
"body": "On the path to one: Yes, Have I reached there? No way! For the life of me, I am not able to figure out \"for\" loops :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T18:49:28.003",
"Id": "257108",
"ParentId": "257064",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257108",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T12:19:34.207",
"Id": "257064",
"Score": "3",
"Tags": [
"python",
"functional-programming"
],
"Title": "Scraping Premier League results"
}
|
257064
|
<p>I wrote a math vector implementation using expression templates to add a little boost to "chain operations" like:</p>
<pre class="lang-cpp prettyprint-override"><code>tnt::vector res = -v * 2 + d / 2 - 4 * c; // v, d, c are some vectors.
</code></pre>
<p>by avoiding the creation of the temporaries. The implementation uses C++20's concepts for safer and more readable code, generic lambda's explicit template parameters to avoid having "implementation/private functions" inside <code>struct vector</code> and other C++20 features like three way comparison and conditional <code>explicit</code> as well. Here's the code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <algorithm> // std::lexicographical_compare_three_way, std::ranges::equal
#include <utility> // std::index_sequence
namespace tnt
{
namespace detail
{
template <typename T>
concept arithmetic = std::integral<T> or std::floating_point<T>;
template <typename T>
concept expression = requires {
typename T::value_type;
{ T::size() } -> std::same_as<std::size_t>;
} and requires (T const& t) {
requires std::same_as<std::remove_cvref_t<decltype(t[0])>,
typename T::value_type>;
};
// vector_sum
template <detail::expression Left, detail::expression Right>
requires (Left::size() == Right::size())
struct vector_sum final
{
using value_type = decltype(std::declval<Left>()[0] + std::declval<Right>()[0]);
static constexpr std::size_t size() noexcept
{
return Left::size();
}
constexpr auto operator[](std::size_t i) const noexcept(noexcept(lhs[i] + rhs[i]))
{
return lhs[i] + rhs[i];
}
Left const& lhs;
Right const& rhs;
};
template <typename Left, typename Right>
vector_sum(Left, Right) -> vector_sum<Left, Right>;
// vector_diff
template <detail::expression Left, detail::expression Right>
requires (Left::size() == Right::size())
struct vector_diff final
{
using value_type = decltype(std::declval<Left>()[0] - std::declval<Right>()[0]);
static constexpr std::size_t size() noexcept
{
return Left::size();
}
constexpr auto operator[](std::size_t i) const noexcept(noexcept(lhs[i] - rhs[i])) { return lhs[i] - rhs[i]; }
Left const& lhs;
Right const& rhs;
};
template <typename Left, typename Right>
vector_diff(Left, Right) -> vector_diff<Left, Right>;
// vector_prod
template <detail::expression Left, detail::arithmetic Right>
struct vector_prod final
{
using value_type = decltype(std::declval<Left>()[0] * std::declval<Right>());
static constexpr std::size_t size() noexcept { return Left::size(); }
constexpr auto operator[](std::size_t i) const noexcept(noexcept(lhs[i] * rhs)) { return lhs[i] * rhs; }
Left const& lhs;
Right const& rhs;
};
template <typename Left, typename Right>
vector_prod(Left, Right) -> vector_prod<Left, Right>;
// vector_ratio
template <detail::expression Left, detail::arithmetic Right>
struct vector_ratio final
{
using value_type = decltype(std::declval<Left>()[0] / std::declval<Right>());
static constexpr std::size_t size() noexcept { return Left::size(); }
constexpr auto operator[](std::size_t i) const noexcept(noexcept(lhs[i] / rhs)) { return lhs[i] / rhs; }
Left const& lhs;
Right const& rhs;
};
template <typename Left, typename Right>
vector_ratio(Left, Right) -> vector_ratio<Left, Right>;
}
// math operators
constexpr auto operator+(detail::expression auto const& lhs, detail::expression auto const& rhs) noexcept
{
return detail::vector_sum{lhs, rhs};
}
constexpr auto operator-(detail::expression auto const& lhs, detail::expression auto const& rhs) noexcept
{
return detail::vector_diff{lhs, rhs};
}
constexpr auto operator*(detail::expression auto const& lhs, detail::arithmetic auto const& rhs) noexcept
{
return detail::vector_prod{lhs, rhs};
}
constexpr auto operator*(detail::arithmetic auto const& lhs, detail::expression auto const& rhs) noexcept
{
return detail::vector_prod{rhs, lhs};
}
constexpr auto operator/(detail::expression auto const& lhs, detail::arithmetic auto const& rhs) noexcept
{
return detail::vector_ratio{lhs, rhs};
}
// vector
template <detail::arithmetic T, std::size_t N>
requires (N > 0u)
struct vector final
{
using value_type = T;
template <std::convertible_to<T> ...Ts>
requires (sizeof...(Ts) <= N)
explicit(sizeof...(Ts) == 1) constexpr vector(Ts &&... ts) noexcept
: data{std::forward<T>(ts)...} {}
// copy stuff
template <std::convertible_to<T> U, std::size_t S>
requires (S <= N)
constexpr vector(vector<U, S> const& rhs) noexcept
{
[this, &rhs]<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] = rhs.data[I]), ...);
}(std::make_index_sequence<S>{});
}
template <std::convertible_to<T> U, std::size_t S>
requires (S <= N)
constexpr vector& operator=(vector<U, S> const& rhs) noexcept
{
[this, &rhs]<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] = rhs.data[I]), ...);
}(std::make_index_sequence<S>{});
return *this;
}
// move operators
template <std::convertible_to<T> U, std::size_t S>
requires (S <= N)
constexpr vector(vector<U, S> &&rhs) noexcept
{
[this, rhs = std::move(rhs)]<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] = std::exchange(rhs.data[I], U(0))), ...);
}(std::make_index_sequence<S>{});
}
template <std::convertible_to<T> U, std::size_t S>
requires (S <= N)
constexpr vector& operator=(vector<U, S> &&rhs) noexcept
{
if (this != &rhs)
[this, rhs = std::move(rhs)]<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] = std::exchange(rhs.data[I], U(0))), ...);
}(std::make_index_sequence<S>{});
return *this;
}
// detail::expression logic
template <detail::expression E>
requires std::convertible_to<typename E::value_type, T>
constexpr vector(E &&rhs) noexcept
{
[this, rhs = std::move(rhs)]
<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] = rhs[I]), ...);
}(std::make_index_sequence<N>{});
}
template <detail::expression E>
requires (E::size() <= N and std::convertible_to<typename E::value_type, T>)
constexpr vector& operator=(E &&rhs) noexcept
{
[this, rhs = std::move(rhs)]
<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] = rhs[I]), ...);
}(std::make_index_sequence<N>{});
return *this;
}
// math operators
template <detail::expression E>
requires (E::size() <= N and std::convertible_to<typename E::value_type, T>)
constexpr vector& operator +=(E &&rhs) noexcept
{
[this, rhs = std::move(rhs)]
<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] += rhs[I]), ...);
}(std::make_index_sequence<N>{});
return *this;
}
template <detail::expression E>
requires (E::size() <= N and std::convertible_to<typename E::value_type, T>)
constexpr vector& operator -=(E &&rhs) noexcept
{
[this, rhs = std::move(rhs)]
<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] -= rhs[I]), ...);
}(std::make_index_sequence<N>{});
return *this;
}
template <detail::arithmetic A>
constexpr vector& operator *=(A const& rhs) noexcept
{
[this, &rhs]
<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] *= rhs), ...);
}(std::make_index_sequence<N>{});
return *this;
}
template <detail::arithmetic A>
constexpr vector& operator /=(A const& rhs) noexcept
{
[this, &rhs]
<std::size_t... I>(std::index_sequence<I...>) noexcept {
((data[I] /= rhs), ...);
}(std::make_index_sequence<N>{});
return *this;
}
// operator []
constexpr T& operator[](std::size_t i) noexcept { return data[i]; }
constexpr const T& operator[](std::size_t i) const noexcept { return data[i]; }
// size
static constexpr std::size_t size() noexcept { return N; }
// operator ==, operator <=>
template <std::equality_comparable_with<T> A>
friend constexpr bool operator==(vector const& lhs, vector<A, N> const& rhs) noexcept
{
return std::ranges::equal(lhs.data, lhs.data + N, &rhs[0], &rhs[N]);
}
template <std::three_way_comparable_with<T> A>
friend constexpr auto operator <=>(vector const& lhs, vector<A, N> const& rhs) noexcept
{
return std::lexicographical_compare_three_way(lhs.data, lhs.data + N, rhs.data, rhs.data + N);
}
private:
T data[N]{};
};
// deduction guides
template <detail::arithmetic T, std::convertible_to<T>... U>
vector(T, U...) -> vector<T, sizeof...(U) + 1>;
template <detail::expression E>
vector(E) -> vector<typename E::value_type, E::size()>;
// vector constants
template <detail::arithmetic T, std::size_t N>
requires (N > 0)
inline constexpr vector<T, N> vector_zero{};
// unary operator -
template <detail::arithmetic T, std::size_t N>
requires (N > 0)
constexpr auto operator -(vector<T, N> const& vec) noexcept
{
return detail::vector_diff{vector_zero<T, N>, vec};
}
} // namespace tnt
</code></pre>
<p>And here is a small demonstration</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
int main()
{
constexpr tnt::vector v{1, 2, 3.};
constexpr tnt::vector d{2., 4, 6};
constexpr tnt::vector r = -v * 2 + d / 2; // no tnt::vector temporary created
std::cout << '{' << r[0] << ", " << r[1] << ", " << r[2] << '}'; // prints {-1, -2, -3}
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks like very good code in general, good use of C++20 features, <code>constexpr</code> all the things. There is one issue I see with this code though:</p>\n<h1>Is it worth avoiding temporary <code>tnt::vector</code>s?</h1>\n<p>Are you sure that avoiding temporary <code>tnt::vector</code>s is worth creating expression types? Because those expressions themselves are now going to be the temporaries, and each of those expression types has storage of its own: most of them store two pointers. So is trading in three doubles for two pointers worth it? Because now there is indirection involved, and expressions themselves can be complex and thus need a lot of temporary storage.</p>\n<p>Temporaries might not have any overhead at all, depending on whether the compiler can see it doesn't need to create them. So the problem you are trying to fix might not even exist in practice.</p>\n<p>Another issue is that you change the order in which data is accessed. Instead of accessing all the elements of two vectors to create a third vector, when converting a <code>detail::expression</code> to a <code>tnt::vector</code>, you first access the first element of all the vectors involved in the expression, then the second, and so on. This means you are less likely to benefit from locality of data. For small vectors and expressions, it will probably not matter as long as everything fits into the CPU's cache, but if you are working with much larger vectors this might be an issue.</p>\n<p>I would create a version that doesn't use expression types, and then look at the resulting assembler code generated by the compiler, and benchmark the code, to see if it really was worth it or not.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T08:04:55.603",
"Id": "507720",
"Score": "1",
"body": "Thank you. I will try to benchmark both approaches and check the assembly as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T20:43:44.060",
"Id": "257081",
"ParentId": "257067",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "257081",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T14:03:00.813",
"Id": "257067",
"Score": "6",
"Tags": [
"c++",
"mathematics",
"c++20"
],
"Title": "C++20 generic math vector implementation"
}
|
257067
|
<p>This is a website Question on Hackrrank called Hash Tables: Ransom Note:</p>
<p>Given the words in the magazine and the words in the ransom note, print "Yes" if we can replicate the ransom note exactly using whole words from the magazine; otherwise, print "No".</p>
<p>Here is an example input:</p>
<pre class="lang-none prettyprint-override"><code>6 4
give me one grand today night
give one grand today
</code></pre>
<p>Output: Yes</p>
<p>And another:</p>
<pre class="lang-none prettyprint-override"><code>6 5
two times three is not four
two times two is four
</code></pre>
<p>Output: No</p>
<hr />
<pre><code>def checkMagazine(magazine, note):
#Creating 2 Empty Dictionaries for the "Magazine" and the "Note" then filling them up
UniqueWordsMag = set(magazine)
UniqueCountMag = [0]*len(UniqueWordsMag)
UniqueWordDictMag = dict(zip(UniqueWordsMag, UniqueCountMag))
UniqueWordsNote= set(note)
UniqueCountNote = [0]*len(UniqueWordsNote)
UniqueWordDictNote = dict(zip(UniqueWordsNote, UniqueCountNote))
for i in magazine:
if i in list(UniqueWordDictMag.keys()):
UniqueWordDictMag[i] += 1
for i in note:
if i in list(UniqueWordDictNote.keys()):
UniqueWordDictNote[i] += 1
#Checking for existance in the magazine then checking for the correct count, print no if it does not fulfil conditions
Success = False
DesiredCount = len(note)
Count = 0
for index,i in enumerate(UniqueWordsNote):
if i in list(UniqueWordDictMag.keys()):
if UniqueWordDictNote[i] <= UniqueWordDictMag[i]:
Count += UniqueWordDictNote[i]
else:
break
else:
break
if Count == DesiredCount:
Success = True
print("Yes")
else:
print("No")
</code></pre>
<p>It's called from this <code>main</code> program, that's provided by the challenge:</p>
<blockquote>
<pre><code>def main():
mn = input().split()
m = int(mn[0])
n = int(mn[1])
magazine = input().rstrip().split()
note = input().rstrip().split()
checkMagazine(magazine, note)
if __name__ == "__main__":
main()
</code></pre>
</blockquote>
<p>My code is currently taking too long on some lists (e.g. lists of size 30,000 or more). Are there any optimisations I can make to make this a bit more legible and faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T19:44:58.757",
"Id": "507707",
"Score": "0",
"body": "Please link to the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T10:29:26.180",
"Id": "507733",
"Score": "0",
"body": "Check out [PEP 8](https://www.python.org/dev/peps/pep-0008/), the Python style guide, especially the suggestion to use `snake_case` instead of `camelCase`."
}
] |
[
{
"body": "<p>Instead of:</p>\n<pre><code>for i in magazine:\n if i in list(UniqueWordDictMag.keys()):\n UniqueWordDictMag[i] += 1\n\n for i in note:\n if i in list(UniqueWordDictNote.keys()):\n UniqueWordDictNote[i] += 1\n</code></pre>\n<p>Avoid creating a list and just iterate over the keys</p>\n<pre><code>for i in magazine:\n if i in UniqueWordDictMag.keys():\n UniqueWordDictMag[i] += 1\n\n for i in note:\n if i in UniqueWordDictNote.keys():\n UniqueWordDictNote[i] += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T19:59:20.350",
"Id": "507710",
"Score": "0",
"body": "No need for `.keys()`, either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T20:15:03.717",
"Id": "507712",
"Score": "1",
"body": "Actually the entire condition is unneeded. You *know* that `i` is in there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T16:04:06.660",
"Id": "257072",
"ParentId": "257068",
"Score": "0"
}
},
{
"body": "<p>You're making it enormously complicated. This is a job for <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>Counter</code></a>:</p>\n<pre><code>from collections import Counter\n\ndef checkMagazine(magazine, note):\n print('No' if Counter(note) - Counter(magazine) else 'Yes')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T08:56:32.417",
"Id": "507724",
"Score": "0",
"body": "I can't find where [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) is documented to evaluate false if any element is negative. Please could you enlighten me? It does seem a very useful property."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T09:46:43.860",
"Id": "507731",
"Score": "1",
"body": "@TobySpeight That's not really what happens. As the doc says about the `-` operation: *\"the output will exclude results with counts of zero or less\"*. So my difference Counter doesn't have negatives. I think a Counter is false for the standard reason: being empty. What I really check is whether there are any *positives*. That is, whether any words needed for the note remain unaccounted for after discounting by the magazine words."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T10:13:31.603",
"Id": "507732",
"Score": "0",
"body": "Thanks for the explanation; I understand it better now. I'm not so fluent in Python, so didn't recognise the idiom!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T19:58:49.190",
"Id": "257078",
"ParentId": "257068",
"Score": "4"
}
},
{
"body": "<p>General (non-performance) review:</p>\n<p>There are several variables assigned but never used. For example:</p>\n<blockquote>\n<pre><code> mn = input().split()\n m = int(mn[0])\n n = int(mn[1])\n</code></pre>\n</blockquote>\n<p>We never use <code>m</code> or <code>n</code>, so this can just be replaced by</p>\n<blockquote>\n<pre><code> input()\n</code></pre>\n</blockquote>\n<p>(I later discovered that <code>main()</code> was provided by the challenge, so you're not to blame for this. OTOH, there's nothing to stop you improving the boilerplate you were given!)</p>\n<p>Similarly:</p>\n<blockquote>\n<pre><code> Success = True\n print("Yes")\n</code></pre>\n</blockquote>\n<p><code>Success</code> is never used; just remove it.</p>\n<p>As noted elsewhere,</p>\n<blockquote>\n<pre><code>#Creating 2 Empty Dictionaries for the "Magazine" and the "Note" then filling them up\nUniqueWordsMag = set(magazine)\nUniqueCountMag = [0]*len(UniqueWordsMag)\nUniqueWordDictMag = dict(zip(UniqueWordsMag, UniqueCountMag))\n\nUniqueWordsNote= set(note)\nUniqueCountNote = [0]*len(UniqueWordsNote)\nUniqueWordDictNote = dict(zip(UniqueWordsNote, UniqueCountNote))\n\nfor i in magazine:\n if i in list(UniqueWordDictMag.keys()):\n UniqueWordDictMag[i] += 1\n\nfor i in note:\n if i in list(UniqueWordDictNote.keys()):\n UniqueWordDictNote[i] += 1\n</code></pre>\n</blockquote>\n<p>is much simpler using a Counter:</p>\n<pre><code>import collections\nmagazine_words = collections.Counter(magazine)\nnote_words = collections.Counter(note)\n</code></pre>\n<p>And the test</p>\n<blockquote>\n<pre><code>#Checking for existance in the magazine then checking for the correct count, print no if it does not fulfil conditions\nSuccess = False\nDesiredCount = len(note)\nCount = 0\n\nfor index,i in enumerate(UniqueWordsNote):\n if i in list(UniqueWordDictMag.keys()):\n if UniqueWordDictNote[i] <= UniqueWordDictMag[i]:\n Count += UniqueWordDictNote[i]\n else:\n break\n else:\n break\n\nif Count == DesiredCount:\n</code></pre>\n</blockquote>\n<p>reduces to just</p>\n<pre><code>if magazine_words & note_words == note_words:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T20:35:13.680",
"Id": "507714",
"Score": "0",
"body": "That `m`/`n` part is kinda not their fault, you're reviewing the site's code there, not the OP's."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T08:22:37.477",
"Id": "507721",
"Score": "0",
"body": "Ah, that wasn't clear in the question (and I don't follow links to read specs, as questions should be self-contained). And I was going to praise the correct use of a `main` guard, too! Is everything from `def main:` onwards not OP code then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T08:26:45.533",
"Id": "507722",
"Score": "0",
"body": "Ha, that praise would've been funny. Yes, only the body of the `checkMagazine` function is the OP's (the `def`-line is provided by the site, too)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T09:19:03.947",
"Id": "507727",
"Score": "0",
"body": "Oops actually I *might* be slightly wrong there. At least at [the URL I found](https://www.hackerrank.com/challenges/ctci-ransom-note/problem) (you can close the login dialog by clicking the X or pressing escape), the given code is not in a main *function* but just inside a guard. I wish the people would just link to the sources, sigh. Anyway, I think your edit is alright."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T20:23:26.523",
"Id": "257080",
"ParentId": "257068",
"Score": "0"
}
},
{
"body": "<p>You should use <code>Counter</code>, but even for not using <code>Counter</code> you made it very complicated. Doing it with <code>dict</code> and keeping your structure, you could do this:</p>\n<pre><code>def checkMagazine(magazine, note):\n \n mag_ctr = dict.fromkeys(magazine, 0)\n note_ctr = dict.fromkeys(note, 0)\n \n for word in magazine:\n mag_ctr[word] += 1\n \n for word in note:\n note_ctr[word] += 1\n \n for word in note_ctr:\n if note_ctr[word] > mag_ctr.get(word, 0):\n print('No')\n break\n else:\n print('Yes')\n</code></pre>\n<p>Just for fun, while I'm here... this trivial solution also got accepted despite being slow:</p>\n<pre><code>def checkMagazine(magazine, note):\n try:\n for word in note:\n magazine.remove(word)\n print('Yes')\n except:\n print('No')\n</code></pre>\n<p>I like it because it's simple. We can do a similar but fast one by using a Counter for the magazine (none needed for the note, saving memory compared to two Counters):</p>\n<pre><code>def checkMagazine(magazine, note):\n available = Counter(magazine)\n for word in note:\n if not available[word]:\n print('No')\n break\n available[word] -= 1\n else:\n print('Yes')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T23:42:18.623",
"Id": "257086",
"ParentId": "257068",
"Score": "2"
}
},
{
"body": "<p>Counting the number of occurrences of an item already exists in the <code>list.count(item)</code> function.\nTo continue with the approach of jumping out of code as soon as possible with your break out of a for loop, we can use a generator inside an <code>any</code> evaluation like so:</p>\n<pre><code>def check_magazine(magazine, note):\n print("No" if any(note.count(word) > magazine.count(word) for word in set(note)) else "Yes")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T09:31:42.740",
"Id": "257223",
"ParentId": "257068",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T14:26:09.130",
"Id": "257068",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Determine whether a magazine contains the words needed for a ransom note"
}
|
257068
|
<p>I am currently learning C++, so I made this basic password wallet for Ubuntu.</p>
<p>Its source code is in the <code>/opt</code> directory and it has a symlink so i can launch it from any directory using <code>pw</code> in the terminal.</p>
<p><strong>Here is what it does:</strong><br />
It asks for a password (pass) and a site (which is related to the pass). It decrypts the file (test.enc) that contains the passwords to another file (text.txt), writes the pass and site to test.txt, encrypt it back to test.enc and delete it (test.txt).</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
char pass[30];
string site;
getline(cin, site);
cin >> pass;
system("cd /opt/PW/ && openssl enc -aes-256-ecb -d -iter 100000 -in test.enc -out test.txt");
ofstream MyFile("/opt/PW/test.txt", ios::app);
MyFile << pass << ":" << site << endl;
MyFile.close();
system("cd /opt/PW/ && openssl enc -aes-256-ecb -iter 100000 -in test.txt -out test.enc && rm -rf test.txt");
}
</code></pre>
<p>It's for personal use only.<br />
I am curious to know how it can be exploited.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T15:28:31.663",
"Id": "507699",
"Score": "3",
"body": "This looks very similar to your earlier, closed question. The right thing to do is to edit that question, which will automatically nominate it for re-opening - you don't need to post a new question. (Just for future reference - don't mess with it now; we can answer this question and delete the closed one)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T23:20:07.007",
"Id": "507782",
"Score": "0",
"body": "Not related to the code itself but if you're looking for a secure command line password manager, you might be interested in [pass](https://www.passwordstore.org/) ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T11:14:14.143",
"Id": "507837",
"Score": "0",
"body": "There is one rudimentary vulnerability in the process - if you are saving the decrypted file somewhere, there is a window (however small) for a malicious program to open and lock the file, gaining access to your plaintext password and associated site"
}
] |
[
{
"body": "<p>There's quite a few beginner problems here:</p>\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>This is a really bad idea. It means we no longer have any control over the names in the global namespace as the Standard Library evolves. If this is a habit you have, it's wise to escape it as soon as possible.</p>\n<blockquote>\n<pre><code> char pass[30];\n string site;\n getline(cin, site);\n cin >> pass;\n</code></pre>\n</blockquote>\n<p>We have no idea whether any of this was successful, because we never checked the status of <code>std::cin</code> afterwards.</p>\n<blockquote>\n<pre><code> system("cd /opt/PW/ && openssl enc -aes-256-ecb -d -iter 100000 -in test.enc -out test.txt");\n</code></pre>\n</blockquote>\n<p>Don't ignore the return value from <code>system()</code>! How do we know whether the command was successful?</p>\n<p>And there are no measures preventing an adversary leaving a symlink in that location, thus redirecting your output to a file of their choosing.</p>\n<blockquote>\n<pre><code> ofstream MyFile("/opt/PW/test.txt", ios::app);\n MyFile << pass << ":" << site << endl;\n</code></pre>\n</blockquote>\n<p>We haven't taken measures to set the appropriate permissions on the file, so it's entirely dependent on the process umask value whether others can read it. That's very lax.</p>\n<p>Both of these problems would have been avoided if we'd used the <code>mktemp()</code> library function to give us a unique temporary named file.</p>\n<blockquote>\n<pre><code> MyFile.close();\n</code></pre>\n</blockquote>\n<p>There's no point calling <code>close()</code> if we're going to ignore its return value! Again, this is important, because there are many factors that can prevent writing a file.</p>\n<blockquote>\n<pre><code> system("cd /opt/PW/ && openssl enc -aes-256-ecb -iter 100000 -in test.txt -out test.enc && rm -rf test.txt");\n</code></pre>\n</blockquote>\n<p>Another <code>system()</code> invocation that should have its return value tested.</p>\n<p>Why do we not remove the file if the command was unsuccessful? I don't think it's good to leave it lying around when that happens.</p>\n<hr />\n<p>For the larger view, I think a shell would be a better choice than C++ for writing a program such as this, since it's mostly about coordinating other processes. I don't think we'd need any temporary files at all if we used pipes appropriately to pass data from one command to another, entirely eliminating the file-handling problems we have.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T15:36:13.087",
"Id": "257071",
"ParentId": "257069",
"Score": "10"
}
},
{
"body": "<h1>Avoid calling <code>system()</code></h1>\n<p>If possible, avoid calling <code>system()</code>. There are almost always issues doing this:</p>\n<ul>\n<li>It is slow: <code>system()</code> will spawn another shell, which has to parse the command line you give it, and then it will spawn the actual commands you want to run).</li>\n<li>Constructing a command line itself has all kinds of issues. For example, are you sure <code>openssl</code> is in your <code>$PATH</code>? And what if the search path finds a different version of openssl than the one you expected (<code>/usr/bin/openssl</code>)?</li>\n<li>There is no easy way to send and receive data to the commands you start, so you have to redirect the input/output to files.</li>\n</ul>\n<p>Especially the latter issue is important: what if someone reads <code>/opt/PW/test.txt</code> between the two calls to <code>system()</code>?</p>\n<p>It would be much better to use a crypto library. <a href=\"https://www.openssl.org/\" rel=\"noreferrer\">OpenSSL</a> is not just a program, it's also a library that you can call directly from C. However, I would say it is not the easiest to work with. There are other libraries out there that make encrypting and decrypting files easier and safer, for example <a href=\"https://nacl.cr.yp.to/\" rel=\"noreferrer\">NaCL</a>.</p>\n<h1>Cryptography is hard to get right</h1>\n<p>Trying to learn about cryptography is great! However, be aware that it is not easy to get cryptography right. You are using AES-256 in <a href=\"https://crypto.stackexchange.com/questions/20941/why-shouldnt-i-use-ecb-encryption\">ECB mode, which is bad</a>. Furthermore, you are not using any form of <a href=\"https://en.wikipedia.org/wiki/Message_authentication_code\" rel=\"noreferrer\">message authentication</a>, so if someone tampers with the encrypted file, then even if they cannot decrypt it properly, when you try to decrypt it you will not get the same data back as you put it. Sometimes it will be obviously garbage, but it sometimes is possible to change the data in more subtle ways (especially with ECB mode, but other modes also have issues if not combined with a MAC).</p>\n<p>Go ahead and try to improve your program, learn more about cryptography, but I strongly suggest you do not use your cryptographic code for anything serious until you get a much better understanding of cryptography.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T19:49:22.420",
"Id": "257077",
"ParentId": "257069",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "257071",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T14:44:30.407",
"Id": "257069",
"Score": "4",
"Tags": [
"c++",
"security",
"linux",
"openssl"
],
"Title": "Securing my password wallet"
}
|
257069
|
<p>I had to populate the fields of a <code>Service</code> object using a <code>Set</code> (HashSet) with any configuration parameters -> <code>ConfigurationMap</code> (Class with 2 attributes: key and value).
The problem is that the attribute <code>quantity</code> of <code>Service</code> object can be set from two distinct parameters ("service_quantity" or "publications_amount") based on the value of another parameter("type").</p>
<p>I've gotten it to work with the code below, but I think it's pretty messy and inefficient.
Is there any way to make it more readable considering that the methods signatures are invariable?</p>
<pre><code>@Override
protected void populateServiceConfigurationData(Service theService, Set<ConfigurationMap> configurationParams) {
boolean publishService = false;
for (ConfigurationMap configParam : configurationParams) {
String paramValue = configParam.getValue();
String paramKey = configParam.getKey();
setFieldValue(theService, paramKey, paramValue);
if("type".equals(paramKey) && paramValue.equals("20")) {
publishService = true;
}
}
if(publishService) {
for (ConfigurationMap configParam : configurationParams) {
String paramKey = configParam.getKey();
if(paramKey.equals("publications_amount")) {
String paramValue = configParam.getValue();
setFieldValue(theService, paramKey, paramValue);
}
}
}
}
@Override
public void setFieldValue(Service service, String paramKey, String paramValue) {
if ("type".equals(paramKey)) {
service.setType(Integer.valueOf(paramValue));
}
if ("service_quantity".equals(paramKey) || "publications_amount".equals(paramKey)) {
service.setQuantity(Integer.valueOf(paramValue));
}
if ("gateway_id".equals(paramKey)) {
service.setGatewayId(paramValue);
}
if ("comissions".equals(paramKey)) {
service.setCommissions(paramValue);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T19:57:11.410",
"Id": "507708",
"Score": "0",
"body": "Tough one, hard to gain anything from introducing functions. I thought about introducing a `Set<String, Function>` or similar which maps from parameter names to setters on the service, but even that would add quite some overhead which is hardly worth the effort. I mean, if you're handling only these field names. If you have a hundred or so field names, I think the gains might be worth it to introduce such an infrastructure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T19:58:45.627",
"Id": "507709",
"Score": "0",
"body": "What you could do is find and store the value of \"publications_amount\" in the first loop, alongside \"publish_service\" and then set it inside the \"publish\"-loop directly. Then you don't need to do a second loop and the logic becomes a little bit easier to read, you can immediately see that \"publications_amount\" wins over \"service_quantity\" (or anything else) when publishing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:29:10.993",
"Id": "507737",
"Score": "1",
"body": "Doesn't the first loop already set `\"publications_amount\"` - and if so what is it for then (it's redundant)??"
}
] |
[
{
"body": "<blockquote>\n<p>I think it's pretty messy and inefficient</p>\n</blockquote>\n<p>Let's say that it is getting messy, especially if the number of parameters (and hidden rules) keeps growing.</p>\n<p>About being inefficient, I am not sure. Even if the input is very large, the method <code>populateServiceConfigurationData</code> runs in <span class=\"math-container\">\\$O(N)\\$</span>, so I don't think it will be a big problem.</p>\n<p>My suggestions:</p>\n<ul>\n<li><strong>Readability</strong>: setting the quantity of the service depends on more than one parameter. So the "rule" to set <code>quantity</code> would be more evident if included in a single function, like <code>setServiceQuantity</code>.</li>\n<li><strong>Performance</strong>: the input set can be converted to a map, to easily access the parameters. The performance gain is minimal, but it should help to make the code more clear.</li>\n<li><strong>Design</strong>: using <code>setFieldValue</code> in <code>populateServiceConfigurationData</code> seems unnecessary. The method <code>populateServiceConfigurationData</code> can be completely independent to <code>setFieldValue</code>. More on this later.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>public void populateServiceConfigurationData(Service service, Set<ConfigurationMap> configurationParams) {\n // Convert the input set to a map\n Map<String, String> params = configurationParams.stream()\n .collect(Collectors.toMap(ConfigurationMap::getKey, ConfigurationMap::getValue));\n\n if (params.containsKey("type")) {\n service.setType(Integer.valueOf(params.get("type")));\n }\n\n if (params.containsKey("gateway_id")) {\n service.setGatewayId(params.get("gateway_id"));\n }\n\n if (params.containsKey("comissions")) {\n service.setCommissions(params.get("comissions"));\n }\n\n setServiceQuantity(service, params);\n}\n\nprivate void setServiceQuantity(Service service, Map<String, String> params){\n boolean isPublishService = params.get("type").equals("20");\n String quantity = isPublishService ? params.get("publications_amount") : params.get("service_quantity");\n service.setQuantity(Integer.valueOf(quantity));\n}\n</code></pre>\n<p>(<strong>Note</strong>: not tested, it's just to give an idea)</p>\n<p>Now the logic for setting each property of the service is clear and can be easily extracted into functions like <code>setServiceQuantity</code>.</p>\n<p>One issue is that <code>populateServiceConfigurationData</code> needs to know how to set the properties into the service (for example, parsing <code>type</code> to <code>Integer</code>). If you don't like this approach, the setters can be replaced with <code>setFieldValue</code> (as before) or let <code>service</code> do the parsing in its own methods.</p>\n<p>The method <code>setFieldValue</code> looks fine, the only thing I can suggest is to use <code>else if</code> since only one condition will match per invocation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T07:38:01.530",
"Id": "507902",
"Score": "0",
"body": "I like your approach but what if the number of parameters was higher in the future. Suppose there are 20 parameters, how this solution would scale?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T09:22:53.083",
"Id": "507907",
"Score": "1",
"body": "It's still possible to loop over the map and set the fields of the service on the way, then calling `setServiceQuantity` at the end. Or I would look at [ModelMapper](http://modelmapper.org/) that allows the mapping between a map and a bean. Anyway, if the sole purpose of this class is to configure the service, it is ok to be a bit longer, as long as it is simple and easy to change."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T08:53:05.390",
"Id": "257092",
"ParentId": "257070",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257092",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T15:09:07.540",
"Id": "257070",
"Score": "3",
"Tags": [
"java",
"collections",
"set"
],
"Title": "Take element of a Set collection depending on the value of another element"
}
|
257070
|
<p>I finished my first real C project and it was Conways Game of Life. The code is working fine and the game runs. Since this was my first project though I don't know any of the real code conventions for writing C. I wanted to implement some tests so I had to split up the functionality from the main file into a new one.</p>
<p>I couldn't really figure out though how to write the tests to maybe refactor the code in the future and just for educational purposes since this is my first time also writing any real tests. Since I implemented many functions that work together with the ones from SDL I have no clue how to test these. This is the file containing all functions:</p>
<pre><code>#include "./main.h"
multi_arr Field = {0,};
multi_arr nextState = {0,};
SDL_Color blue = {0,0,255,255};
SDL_Color black = {0,0,0,255};
SDL_Color white = {244,244,244,50};
int getLastMultiple(int number){
int multiple = RECT_SIZE;
float remainder;
if ((remainder = (number % multiple)) == 0)
return number;
else{
number -= remainder;
}
return number;
}
void colorRect(SDL_Renderer *renderer, SDL_Rect r,SDL_Color color){
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b ,255);
// Render rect
SDL_RenderFillRect(renderer, &r);
}
void drawGrid(SDL_Renderer *renderer,SDL_Color color){
SDL_SetRenderDrawColor(renderer, color.r,color.g,color.b,color.a);
for (int i = 20; i < SCREEN_WIDTH; i += 20){
SDL_RenderDrawLine(renderer, i,0,i,SCREEN_HEIGHT);
}
for (int i = 20; i < SCREEN_HEIGHT;i += 20){
SDL_RenderDrawLine(renderer, 0,i,SCREEN_WIDTH,i);
}
}
void displayImg(SDL_Renderer *renderer,char* path){
SDL_Surface *image = SDL_LoadBMP(path);
if (image == NULL){
printf("cant load image\n");
}
SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, image);
SDL_Rect image_pos = { 6,SCREEN_HEIGHT-55, 50, 50 };
SDL_Rect rect = {0,SCREEN_HEIGHT-59,60,60};
colorRect(renderer, rect, white);
SDL_RenderCopy(renderer, texture, NULL,&image_pos);
}
void updateGame(SDL_Window *window,SDL_Renderer *renderer, SDL_Rect r,bool paused){
//Loop through field-array and show rectangles if cell alive
char *path;
if (paused){
path = "./assets/start.bmp";
} else{
path = "./assets/pause.bmp";
}
for (int i = 0; i < WIDTH;i++){
for (int j = 0; j < HEIGHT;j++){
if (Field[i][j] == true){
r.x = i * 20;
r.y = j * 20;
colorRect(renderer, r, blue);
} else {
r.x = i * 20;
r.y = j * 20;
colorRect(renderer, r, white);
}
}
}
drawGrid(renderer,black);
displayImg(renderer, path);
SDL_RenderPresent(renderer);
}
int countAliveNeighbors(int x, int y){
int count = 0;
for (int rows = -1; rows < 2; rows++){
for (int columns = -1; columns < 2;columns++){
if ((x+columns) >= 0 && (x+columns) < WIDTH && (y+rows) >= 0 && (y+rows) < HEIGHT){
if (Field[x+columns][y+rows] == true){
count++;
}
}
}
}
if (Field[x][y] == true){
return count -1;
}
return count;
}
void copyArray(multi_arr arr1,multi_arr arr2){
for (int i = 0; i < WIDTH;i++){
for (int j = 0; j < HEIGHT;j++){
arr1[i][j] = arr2[i][j];
}
}
}
void nextEpoch(){
for (int i = 0; i < WIDTH;i++){
for (int j = 0; j < HEIGHT;j++){
if (Field[i][j] == true && (countAliveNeighbors(i, j) == 3 || countAliveNeighbors(i, j) == 2)){
nextState[i][j] = true;
} else if (Field[i][j] == false && countAliveNeighbors(i, j) == 3){
nextState[i][j] = true;
} else {
nextState[i][j] = false;
}
}
}
copyArray(Field, nextState);
}
bool buttonPress(int x,int y){
if (x <= 2 && x >= 0 && y >= (HEIGHT - 3) && y <= HEIGHT){
return true;
}
return false;
}
Uint32 my_callbackfunc( Uint32 interval, void *param ){
SDL_Event e;
e.user.type = SDL_USEREVENT;
e.user.code = 0;
e.user.data1 = NULL;
e.user.data2 = NULL;
SDL_PushEvent(&e);
return interval;
}
</code></pre>
<p>These are the tests I have written so far:</p>
<pre><code>#include "./include/criterion/criterion.h"
#include "include/criterion/assert.h"
#include "include/criterion/internal/test.h"
#include "main.h"
extern multi_arr Field;
Test(getLastMultiple,test_getLastMultiple_if_multiple_20){
cr_assert(getLastMultiple(58) == 40);
cr_assert(getLastMultiple(29) == 20);
cr_assert(getLastMultiple(640) == 640);
}
Test(aliveNeighbors,test_count_alive_neighbors_if_cell_active){
Field[20][10] = true;
Field[19][10] = true;
Field[21][11] = true;
cr_assert(countAliveNeighbors(20, 10) == 2);
}
Test(aliveNeighbors,test_count_alive_neighbors_if_cell__not_active){
Field[20][10] = true;
Field[19][10] = true;
Field[21][11] = true;
cr_assert(countAliveNeighbors(20, 11) == 3);
}
Test(buttonPress,test_button_press_detected){
cr_assert(buttonPress(2, HEIGHT) == true);
cr_assert(buttonPress(5, HEIGHT) == false);
}
Test(copyArray,test_array_copied){
Field[20][10] = true;
Field[19][10] = true;
Field[21][11] = true;
multi_arr copied = {0,};
copyArray(copied,Field);
/*cr_assert_arrays_eq_cmp(copied,Field);*/
}
Test(nextEpoch,test_if_next_epoch_cells_correct_pos){
int active_cells = 0;
multi_arr nextState = {0,};
Field[20][10] = true;
Field[19][10] = true;
Field[21][11] = true;
nextEpoch();
for (int i = 0;i < WIDTH;i++){
for (int j = 0; j < HEIGHT;j++){
active_cells += (Field[i][j] == true) ? 1 : 0;
}
}
cr_assert(active_cells == 2);
cr_assert(Field[20][10] == true && Field[20][11] == true);
}
</code></pre>
<p>Thanks for the help and sorry if I didn't use the community in the correct way. Any help is appreciated. This is all the code: <a href="https://github.com/PhilippRados/GameOfLife" rel="nofollow noreferrer">https://github.com/PhilippRados/GameOfLife</a></p>
<p><strong>Any tips for improving this code are highly appreciated</strong></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T17:33:29.493",
"Id": "257075",
"Score": "4",
"Tags": [
"c",
"unit-testing",
"sdl"
],
"Title": "Testing and coding conventions for testing C with SDL"
}
|
257075
|
<p><strong>dlfcn.h</strong> is a library of C functions to work with dynamic dependencies (shared objects). I've been experimenting with wrapping them in a C++ API, mostly as practice in making a C++ wrapper.</p>
<p>This is an excerpt of my process of wrapping the <code>Dl_serinfo</code> parts of <a href="https://man7.org/linux/man-pages/man3/dlinfo.3.html" rel="nofollow noreferrer"><code>dlinfo(...)</code></a> in the C library. For reference:</p>
<blockquote>
<pre><code>typedef struct {
size_t dls_size; /* Size in bytes of
the whole buffer */
unsigned int dls_cnt; /* Number of elements
in 'dls_serpath' */
Dl_serpath dls_serpath[1]; /* Actually longer,
'dls_cnt' elements */
} Dl_serinfo;
</code></pre>
</blockquote>
<p>And <code>Dl_serpath</code>:</p>
<blockquote>
<pre><code>typedef struct {
char *dls_name; /* Name of library search
path directory */
unsigned int dls_flags; /* Indicates where this
directory came from */
} Dl_serpath;
</code></pre>
</blockquote>
<p>Note that the <code>dls_serpath</code> member of <code>Dl_serinfo</code> is a "flexible array member" and the entire <code>Dl_serinfo</code> struct is supposed to be allocated with enough space for <code>dls_cnt</code> entries in the array.</p>
<hr />
<p>My wrapper:</p>
<pre><code>#include <dlfcn.h>
#include <cstddef>
#include <memory>
#include <stdexcept>
#include <string_view>
namespace dl {
class dl_error : public std::runtime_error {
public:
using std::runtime_error::runtime_error;
};
class serinfo;
class serpath {
friend class serinfo;
private:
std::string_view name_;
unsigned int flags_;
explicit serpath(::Dl_serpath path)
: name_(path.dls_name)
, flags_(path.dls_flags)
{}
public:
std::string_view name() const { return name_; }
unsigned int flags() const { return flags_; }
};
class serinfo {
private:
std::unique_ptr<std::byte[]> bytes;
public:
explicit serinfo(void* dlhandle) {
::Dl_serinfo size;
if (::dlinfo(dlhandle, RTLD_DI_SERINFOSIZE, &size)) {
throw dl_error(::dlerror());
}
bytes = std::make_unique<std::byte[]>(size.dls_size);
if (::dlinfo(dlhandle, RTLD_DI_SERINFOSIZE, bytes.get())) {
throw dl_error(::dlerror());
}
if (::dlinfo(dlhandle, RTLD_DI_SERINFO, bytes.get())) {
throw dl_error(::dlerror());
}
}
unsigned int cnt() const {
return reinterpret_cast<::Dl_serinfo const*>(bytes.get())->dls_cnt;
}
dl::serpath serpath(unsigned int index) const {
return dl::serpath(
reinterpret_cast<::Dl_serinfo const*>(bytes.get())->dls_serpath[index]);
}
};
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>class dl_error : public std::runtime_error {\npublic:\n using std::runtime_error::runtime_error;\n};\n</code></pre>\n<p>Given the purpose of this class, it seems logical to have it get the most recent error automatically. Especially since there is a gotcha involved, where <code>dlerror()</code> will return <code>NULL</code> if called a second time (so if some coder checks <code>dlerror()</code> to print or log the error message, and then does <code>dl_error{::dlerror()}</code>… boom). Plus it just makes it so much easier to use: <code>throw dl_error{};</code> is just so much more ergonomic than <code>throw dl_error{::dlerror()};</code>.</p>\n<p>Also, given that this class is already in namespace <code>dl</code>, it seems superfluous to have a prefix. <code>dl::error</code> is much nicer than <code>dl::dl_error</code>.</p>\n<pre><code>class serpath\n</code></pre>\n<p>Eh, I mean, is it really that much more painful to type out <code>search_path</code> (or <code>search_path_info</code>, given that it’s actually a path and some (in theory) flags)?</p>\n<p>If you’re doing a thin wrapper around a C library, then it’s okay to recreate the C library’s shitty names. But that doesn’t look like what you’re doing, so why not use human-readable names? For someone whose first language isn’t English, the following is damn-near illegible:</p>\n<pre><code>auto const paths = dl::serinfo{dlhandle};\n\nauto const path = paths.serpath(paths.cnt() - 1);\n</code></pre>\n<p>Compare that to:</p>\n<pre><code>auto const paths = dl::get_search_paths_for(dlhandle);\n\nauto const path = paths[paths.size() - 1];\n</code></pre>\n<p>Every semi-competent C++ programmer will understand what <code>size()</code> and <code>operator[]</code> mean, and the function name is pretty much self-documenting. Meanwhile, <code>ser</code> isn’t even short for <code>search</code> (“serch” path?), and <code>cnt</code> just sounds rude.</p>\n<p>Coders shouldn’t need to keep a translation guide open at hand to be able to read code, stopping every two lines to translate <code>dl_serinfopathxyzagiuasgtha</code> to something human-legible. 90% of the verbiage in good C++ code disappears into <code>auto</code> and the like anyway (and the fact that you need way fewer function calls than in C code), so take advantage of that and spell things out clearly.</p>\n<pre><code>class serpath {\n // ... [snip] ...\n\n std::string_view name_;\n</code></pre>\n<p>This is <em>extremely</em> unwise. I get that you’re trying to avoid unnecessary allocations, and you <em>assume</em> that the string <code>name_</code> references will be owned by a <code>serinfo</code> object which will outlive the <code>serpath</code> object. But there’s nothing in the interface of either class that suggests that, let alone requires it. What’s to stop someone from doing:</p>\n<pre><code>auto get_particular_library_search_path(void* dlhandle)\n{\n auto const info = dl::serinfo{dlhandle};\n\n for (auto i = 0u; i < info.cnt(); ++i)\n {\n auto const sp = info.serpath(i);\n \n if (satisfies_some_condition(sp))\n return sp;\n }\n\n throw std::runtime_error{"not found"};\n}\n</code></pre>\n<p>If you’re going to keep this interface, then it might be wise to use a <code>shared_ptr</code> rather than a <code>unique_ptr</code> in <code>serinfo</code>, and pass a copy of that to every <code>serpath</code> you create. Copying <code>shared_ptr</code> is cheap (it’s actually <em>destroying</em> shared pointers that is fairly costly, but not really that much). That way, even if the original <code>serinfo</code> is destroyed, the <code>serpath</code>s won’t dangle.</p>\n<p>Alternately, perhaps, you could make <code>serpath</code> non-copyable and non-movable, then create an array of them at construction time, and return references to them. Or, even simpler, just return a reference to the <code>Dl_serpath</code> <code>struct</code> directly. Because why not? All you’re doing with <code>serpath</code> is converting the <code>char*</code> to a <code>string_view</code>… and you don’t really gain all that much by that. (In fact, you <em>lose</em> info, because it’s very likely the user might want to use the returned path(s) with some system call or other, but you can’t use <code>string_view</code> because it isn’t <code>NUL</code>-terminated. You’d need to convert the <code>string_view</code> to a <code>string</code> to do pretty much anything useful with it anyway.)</p>\n<p>Frankly, I’d just use a <code>string</code> (or possibly a <code>std::filesystem::path</code>!) in <code>serpath</code>, and all of this risk and hassle vanishes. Yeah, sure, you’re paying for the cost of a string allocation… but compared to all the costs involved in the allocation for <code>serinfo</code>, all those system calls, and so on… meh. The safety and ease of use is so much more worth it compared to avoiding a single, likely small allocation on what is certainly never going to be a hot path.</p>\n<pre><code>class serpath {\n\n // ... [snip] ...\n\n std::string_view name_;\n unsigned int flags_;\n\n // ... [snip] ...\n\npublic:\n std::string_view name() const { return name_; }\n unsigned int flags() const { return flags_; }\n</code></pre>\n<p>Are getters really necessary? Why couldn’t you just do:</p>\n<pre><code>class serpath\n{\n friend class serinfo;\n\n explicit serpath(::Dl_serpath path)\n : name(path.dls_name)\n , flags(path.dls_flags)\n {}\n\npublic:\n std::string name; // perhaps better: std::filesystem::path path;\n unsigned int flags;\n};\n</code></pre>\n<p>There doesn’t seem to be any gain from using getter functions for this simple return-value <code>struct</code>.</p>\n<pre><code>class serinfo\n</code></pre>\n<p>The thing that strikes me most about this class is that it’s actually a container of <code>serpath</code>s. All of the gymnastics you do in the constructor is really just to get that array of <code>Dl_serpath</code>, then dole it out safely. In theory, the class could be this:</p>\n<pre><code>class serinfo\n{\n std::vector<serpath> _paths; // assuming serpath uses string, not string_view\n\npublic:\n \n explicit serinfo(void* dlhandle)\n {\n // everything the same as your current constructor, except `bytes` is\n // a local variable\n\n // then:\n\n _paths.reserve(bytes->dls_cnt);\n for (auto i = 0u; i < bytes->dls_cnt; ++i)\n _paths.push_back(serpath{bytes->dls_serpath[i]});\n }\n\n auto size() const noexcept { return _paths.size(); }\n\n // same for all the other useful const vector functions:\n // begin, end, operator[], etc.\n};\n</code></pre>\n<p>I’m not suggesting it <em>should</em> be like this; there’s no point in allocating the <code>Dl_serinfo</code> structure, then just duplicating that allocation in the vector to copy all the data over. I’m just illustrating that it <em>could</em> be like this to make the point that <code>serinfo</code> is basically an immutable container of <code>serpath</code>s… so its interface should reflect that.</p>\n<p>If you did implement a container interface, you could do stuff like:</p>\n<pre><code>// printing all the search paths\nfor (auto const& [path, _] : dl::get_search_paths_for(dlhandle))\n std::cout << path << '\\n';\n</code></pre>\n<p>Note that you don’t need the <em>entire</em> container interface. All you need are <code>const</code> versions of <code>begin()</code>, <code>end()</code>, <code>size()</code>, and maybe <code>empty()</code>. If you wanted, you could add <code>operator[]</code> for convenience, but that’s pretty much it.</p>\n<pre><code>bytes = std::make_unique<std::byte[]>(size.dls_size);\n</code></pre>\n<p>This <em>might</em> work… if <code>alignof(::Dl_serinfo) >= __STDCPP_DEFAULT_NEW_ALIGNMENT__</code>.</p>\n<p>See, <code>std::malloc()</code> always allocates with alignment <code>alignof(std::max_align_t)</code>. Presumably <code>::Dl_serinfo</code> doesn’t have any special alignment requirements (you don’t need to use <code>std::aligned_alloc()</code> to allocate it), so <code>std::malloc()</code> will never allocate <em>under</em>-aligned memory for <code>::Dl_serinfo</code>, though it may allocate <em>over</em>-aligned memory, but that’s not a problem (other than a tiny amount of wasted memory, I suppose).</p>\n<p>But <code>new</code> uses <code>__STDCPP_DEFAULT_NEW_ALIGNMENT__</code>… which may be more <em>or less</em> than <code>alignof(std::max_align_t)</code>. If you did <code>new ::Dl_serinfo</code> directly, there would be no problem; if <code>alignof(::Dl_serinfo) > __STDCPP_DEFAULT_NEW_ALIGNMENT__</code>, then <code>new</code> would automatically fix the alignment for you.</p>\n<p>But you’re doing <code>new std::byte[sizeof(::Dl_serinfo)]</code> (basically). You’re not allocating a <code>::Dl_serinfo</code>, you’re allocating bytes (which have an alignment of 1, though <code>new</code> will naturally use <code>__STDCPP_DEFAULT_NEW_ALIGNMENT__</code>). So you need to be sure that the memory is properly aligned.</p>\n<p>You could just use a static assert like:</p>\n<pre><code>static_assert(__STDCPP_DEFAULT_NEW_ALIGNMENT__ >= alignof(::Dl_serinfo));\n</code></pre>\n<p>That will just kill the compilation if there is a danger of alignment problems.</p>\n<p>A better solution is to make sure the alignment is correct:</p>\n<pre><code>// in constructor:\nconstexpr auto alignment = std::align_val_t{alignof(::Dl_serinfo)};\n\nbytes.reset(new (alignment) std::byte[size.dls_size]);\n// note: can't use make_unique(), but doesn’t really matter\n</code></pre>\n<p>All the calls to <code>::dlinfo()</code> look like this:</p>\n<pre><code>if (::dlinfo(/*...*/)) {\n throw dl_error(::dlerror());\n}\n</code></pre>\n<p>For starters, I think you should make the error class more ergonomic:</p>\n<pre><code>if (::dlinfo(/*...*/)) {\n throw error{};\n}\n</code></pre>\n<p>But also, simply converting the result of the <code>::dlinfo()</code> call to <code>bool</code> doesn’t really give the best sense of what is actually going on here. I have no way of knowing whether maybe <code>::dlinfo()</code> actually returns <code>bool</code> or something, or who knows what else, or what it means. <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#es87-dont-add-redundant--or--to-conditions\" rel=\"nofollow noreferrer\">You should generally not add redundant <code>!=</code> or <code>==</code> to conditions</a>… but the guideline is actually more subtle; it says adding redundant tests is unwise when there are only two meaningful values (like a valid pointer value and <code>nullptr</code>). With integers, there are often several meaningful values. It would be more clear to explain that you’re explicitly testing for “not zero” like this:</p>\n<pre><code>if (::dlinfo(/*...*/) != 0) {\n throw error{};\n}\n</code></pre>\n<p>When I read that, even without looking up the <code>::dlinfo()</code> API, I immediately understand, okay, this function returns zero on success.</p>\n<p>One final thing: I’m not a fan of constructors that do more than <em>just</em> construct objects. <code>serinfo</code>’s constructor is more than just a constructor of <code>serinfo</code> objects. It’s actually doing a series of queries first, <em>and then using the results</em> to construct the object. That’s a violation of the single-responsibility principle.</p>\n<p>Besides, you’re “doing a thing”… not “making a thing”. You’re “getting the search paths for a shared object”… you’re not “making a <code>serinfo</code> object”. The latter only happens as a side-effect of the former, but it’s not <em>really</em> the <code>serinfo</code> object you want… it’s the paths.</p>\n<p>“Doing a thing” usually means you want a function, not a constructor. I think that’s especially important when you’re doing a thing that might fail, because then you can give the user the option of avoiding exceptions in cases where they can’t afford them. In other words, you could do:</p>\n<pre><code>class serinfo\n{\nprivate:\n explicit serinfo(std::unique_ptr<std::byte[]> data) :\n _data{std::move(data)}\n {}\n\n std::unique_ptr<std::byte[]> _data;\n\n friend auto get_search_paths_for(handle h) -> expected<serinfo>;\n\n // ... [snip] ...\n};\n\n// using something similar to the proposed std::expected:\nauto get_search_paths_for(handle h) -> expected<serinfo>\n{\n auto size = ::Dl_serinfo{};\n\n if (::dlinfo(h, RTLD_DI_SERINFOSIZE, &size) != 0)\n return make_unexpected(dl_error{});\n\n auto buffer = std::unique_ptr<std::byte[]>{};\n try\n {\n auto p = new (std::align_val_t{alignof(::Dl_serinfo)}) std::byte[size.dls_size];\n\n buffer.reset(p);\n }\n catch (...)\n {\n return make_unexpected(std::current_exception());\n }\n\n if (::dlinfo(h, RTLD_DI_SERINFOSIZE, buffer.get()) != 0)\n return make_unexpected(dl_error{});\n\n if (::dlinfo(h, RTLD_DI_SERINFO, buffer.get()) != 0)\n return make_unexpected(dl_error{});\n\n return serinfo{std::move(buffer)};\n}\n</code></pre>\n<p>With usage like:</p>\n<pre><code>// I absolutely cannot tolerate an exception here:\nif (auto const search_paths = dl::get_search_paths_for(dlhandle); search_paths)\n{\n // do something with *search_paths\n}\nelse\n{\n // report error somehow\n}\n\n// Exceptions are okay here:\nauto const search_paths = *dl::get_search_paths_for(dlhandle);\n// if there was an error, it will be automatically rethrown\n</code></pre>\n<p>Once you do this, you open the door to allowing no-fail default-constructed <code>serinfo</code> objects, which internally just have a null pointer, but externally present as an empty list of search paths. And once you have that, you can trivially implement no-fail moving and swapping, which are <em>very</em> handy in general. Plus, being able to default construct things is handy in a lot of ways (like reading stuff from streams, for example).</p>\n<p>Even if you don’t use something like <code>expected<T></code> and just throw exceptions from the function, I think it’s still a better interface than doing all the work in the constructor on top of actually constructing the object.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T21:54:34.587",
"Id": "508463",
"Score": "0",
"body": "You've given me lots to think about. A few comments on your comments: `dl::dl_error` was because I like names to be unambiguous even sans-namespace. `serinfo`/`serpath`/`cnt` were named specifically to recreate the C library's names without C \"namespacing\" (`Dl_serinfo`/`Dl_serpath`/`dls_cnt`). The getters were to have the same interface between `serinfo` and `serpath` (if one had to be getters, I figured uniformity was nicer). W.r.t. your superior design, idk how I feel, since I prefer C library wrappers to mimic the library rather than improve on the design. Perhaps another layer on-top."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T01:33:16.933",
"Id": "508470",
"Score": "0",
"body": "Yeah, there are basically 2 strategies to wrapping a C library: an interface that is basically identical, so migrating is mostly trivial (and sometimes free!)… or make an actual, true C++ interface that might look very different, but is more natural to C++ programmers. There are pros and cons to either option. I obviously lean to the latter generally, but meh, that’s a matter of personal preference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T18:34:48.727",
"Id": "257408",
"ParentId": "257083",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "257408",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-12T22:47:02.073",
"Id": "257083",
"Score": "0",
"Tags": [
"c++"
],
"Title": "dlinfo(... SERPATH ...) C++ wrapper"
}
|
257083
|
<p>I have a C# application which needs to encrypt string and save the key as a hash. The key is saved as a hash to check the right key has been input before trying to decrypt the message.</p>
<p>First, I have these method to generate the hash string - hopefully "off the shelf" and ready to go</p>
<pre><code> public static byte[] GetHash(string inputString)
{
using (HashAlgorithm algorithm = SHA256.Create())
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}
public static string GetHashString(string inputString)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in GetHash(inputString))
sb.Append(b.ToString("X2"));
return sb.ToString();
}
</code></pre>
<p>Then my encryption extension method:</p>
<pre><code>private const int Keysize = 256;
private const int DerivationIterations = 1000;
public static string Encrypt(this string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate256BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
var engine = new RijndaelEngine(256);
var blockCipher = new CbcBlockCipher(engine);
var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding());
var keyParam = new KeyParameter(keyBytes);
var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32);
cipher.Init(true, keyParamWithIV);
var comparisonBytes = new byte[cipher.GetOutputSize(plainTextBytes.Length)];
var length = cipher.ProcessBytes(plainTextBytes, comparisonBytes, 0);
cipher.DoFinal(comparisonBytes, length);
// return Convert.ToBase64String(comparisonBytes);
return Convert.ToBase64String(saltStringBytes.Concat(ivStringBytes).Concat(comparisonBytes).ToArray());
}
}
private static byte[] Generate256BitsOfRandomEntropy()
{
var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
</code></pre>
<p>Which is then called to a input string:</p>
<p><code>var encryptedString = inputString.Encrypt(_appSettings.EncryptionSecret + passPhrase);</code></p>
<p>The passphrase is a random set of characters, prepended with an application string.</p>
<p>My concern is that the passphrase is 4 sets of "diceware" words (like here: <a href="https://diceware.dmuth.org/" rel="nofollow noreferrer">https://diceware.dmuth.org/</a>) and therefore could be brute forced. Would adding more to the <code>passphrase</code>, such as as hash of <code>DateTime.UtcNow.ToString("yyyyMMdd")</code> or <code>GetHashString(random-string)</code> for example add any additional security or is it just theatre and the "diceware" passphrase is practicably unbreakable?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:12:12.620",
"Id": "507734",
"Score": "1",
"body": "If you add a date into the pass-phrase - how does the other end know what it is ??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:15:49.147",
"Id": "507735",
"Score": "0",
"body": "The point of a SALT is to not include it - thus reducing the likelihood of BFing with pre-computed hashes [aka. rainbow attack](https://en.wikipedia.org/wiki/Salt_(cryptography))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:32:56.850",
"Id": "507738",
"Score": "0",
"body": "@MrR The date would be in the stored row as well, so could be retrieved as part of the record, and hashed and added back to the key to decrypt. This would then mean an attacker has the basis of that salt so not sure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:35:09.410",
"Id": "507739",
"Score": "0",
"body": "@MrR the rainbow attack is what I'm looking to mitigate - however Microsoft themselves include the salt in the password hashes stored in the same column in the ASP.NET identity framework. So you have the password `password`, which you hash and then get a load of `password` hashes. Adding the salt `randomstuff+password` and saving as `randomstuff + hash(randomstuff+password)` mitigates the rainbow attack right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:35:53.727",
"Id": "507740",
"Score": "0",
"body": "So answering my own q, we'd need to add some random stuff to the diceware to prevent rainbow attacks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:40:01.080",
"Id": "507741",
"Score": "0",
"body": "if this is all on the same secure machine - then sure ignore my comments ... for some reason I was thinking the hash was being transmitted somewhere (in which case SALT/Date would need to be communicated out of band)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:42:19.557",
"Id": "507742",
"Score": "1",
"body": "And I'd be willing to guess a Date is not good for a salt - because it is not really a random number - if you were concerned go for a wider salt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T11:46:27.423",
"Id": "507743",
"Score": "0",
"body": "Thanks - yes, they `passphrase` will need to be communicated out of band but the encryption is all internal. So perhaps a hash string of the date down to the millisecond, which would then be 64 characters? The input would be unique per row unless multiple rows were written within the same millisecond and the hash would widen the salt?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T15:46:30.590",
"Id": "511468",
"Score": "0",
"body": "@MrR A salt is not supposed to be kept secret. A secret \"salt\" may be used as a \"key\" - a piece of data that can be retrieved from a secure location and that is needed in addition to the password, but we generally call that a \"pepper\"."
}
] |
[
{
"body": "<blockquote>\n<p>My concern is that the passphrase is 4 sets of "diceware" words (like here: <a href=\"https://diceware.dmuth.org/\" rel=\"nofollow noreferrer\">https://diceware.dmuth.org/</a>) and therefore could be brute forced.</p>\n</blockquote>\n<p>The diceware password is about 51 bits in strength, so it should indeed be run through a password based key derivation function, <strong>especially</strong> if you use it to encrypt messages - because encryption can be broken offline (i.e. on the computer of an attacker).</p>\n<blockquote>\n<p>Would adding more to the passphrase, such as as hash of <code>DateTime.UtcNow.ToString("yyyyMMdd")</code> or <code>GetHashString(random-string)</code> for example add any additional security or is it just theatre and the "diceware" passphrase is practicably unbreakable?</p>\n</blockquote>\n<p>No, the passphrase is not big enough to be unbreakable. Adding more information could help, but only if it is not available to an attacker, which is very questionable for a date / time.</p>\n<hr />\n<pre><code>private const int Keysize = 256;\n</code></pre>\n<p>This is good because we generally use key sizes in bits (and "size" is better than "length" in my opinion).</p>\n<pre><code>private const int DerivationIterations = 1000;\n</code></pre>\n<p>This is not a good idea at all. First of all, you should use about a million as iteration count <em>at the moment</em>. It would also be a big boon if you could upgrade it to a higher count later on. The amount of operations that an attacker has to perform is the same as the number of iterations, and an attacker may use a very fast implementation. Currently it adds about log_2(1000) =~ 10 bits of security.</p>\n<pre><code>public static byte[] GetHash(string inputString)\n</code></pre>\n<p>Especially if this is a public method (<em>why?</em>) then the hash function and encoding performed on the input string should be documented. It is not clear why the input needs to be a string in the first place though.</p>\n<pre><code>public static string GetHashString(string inputString)\n</code></pre>\n<p>Same for the output encoding of course.</p>\n<pre><code>StringBuilder sb = new StringBuilder();\nforeach (byte b in GetHash(inputString))\n sb.Append(b.ToString("X2"));\n</code></pre>\n<p>Reprogramming a hex encoder doesn't make sense, and why not use a generic hex encoding function? In the end you want to have something like: <code>hex(hash(utf8(text)))</code> in your code...</p>\n<pre><code>var saltStringBytes = Generate256BitsOfRandomEntropy();\n</code></pre>\n<p>No, that's 256 bits of randomness you generate, the entropy is <em>gathered</em> by the operating system in the end. Why not just call it a <code>salt</code>? A <code>StringByte</code> is not a structure I've ever heard of.</p>\n<pre><code> using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))\n</code></pre>\n<p>This badly named class of Microsoft implements PBKDF2, which is defined <strong>in</strong> the Password Based Encryption standard. So what about <code>var pbkdf2 = </code> because the returned object certainly is not a password.</p>\n<p>Note that PBKDF2 is inefficient if you ask more than the configured hash output size. That defaults to SHA-1. If you'd use SHA-512 instead then you could retrieve a key, and IV and a check value all from a 512 bit / 64 byte output (32 bytes for the key, 16 bytes for the IV and check value each, for instance).</p>\n<pre><code>var engine = new RijndaelEngine(256);\n</code></pre>\n<p>Why would you use Bouncy Castle, a software only provider for bog-standard AES functionality? Do you hate the AES-NI instruction set?</p>\n<pre><code>var keyParamWithIV = new ParametersWithIV(keyParam, ivStringBytes, 0, 32);\n</code></pre>\n<p>I'm not sure, but I'm pretty confident that <code>ivStringBytes</code> is already the correct size, so the offset and length should not be needed.</p>\n<pre><code>var comparisonBytes = new byte[cipher.GetOutputSize(plainTextBytes.Length)];\n</code></pre>\n<p>Comparison to what? You have encrypted a message, right? If you just want to check if a password is correct then just use the password hash (PBKDF2).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T19:53:35.303",
"Id": "511487",
"Score": "0",
"body": "Quick question before I digest the rest of the review (thanks BTW) - the 51 bits for a diceware, is that 4 times diceware? i.e. `fish-sock-cheese-river` as 4 separate rolls to create the 4 words? Or is it 51 bits of entropy per roll? And so 51 bits of entropy multiplied by 4?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T19:58:04.523",
"Id": "511490",
"Score": "0",
"body": "Heh, no, it is the total of 4 rolls. I simply asked for a 4 word roll on the site, got the answer back + the number of possibilities. Then it is simply a question of taking the $\\log_2$ of that number. Or counting the number of digits, and divide by 3 and multiply by 10 to get an approximation (and you're welcome :) )."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T20:15:52.497",
"Id": "511494",
"Score": "0",
"body": "From 4 rolls, and your sums I get: (3,656,158,440,062,976 / 3) * 10 = 1.2187195e+16\n... Is that right? 4 rolls gives over 3.5 trillion (??? Quadrillion??) combinations right? Or are my maths way off? On my phone, hence a bit gammy with the numbers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T10:28:28.467",
"Id": "511623",
"Score": "0",
"body": "Hi @maarten-bodewes, I've put a few 4 word passwords into KeePass and always get over 110 bits of entropy? Not sure how to get an absolute on this"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T13:41:29.313",
"Id": "511640",
"Score": "0",
"body": "One more thing - I've had a look at the AES-NI in C# and it only supports smaller key sizes, and the key and IV is only 32 and 16 bytes. It \"feels\" safer to use the Bouncy Castle with the full width key and IV...??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T14:08:56.053",
"Id": "511643",
"Score": "1",
"body": "@RemarkLima No, the calculations are over the *number of digits*. So if e+16 then you have slightly over 16 digits, then (16 / 3) x 10 = 53 bits and cryptographers do use caution so we guess to the low end. KeePass doesn't know that they are diceware rolls so it's guess is way too high, this kind of knowledge should be included. A key size of 32 bytes is 256 bit, which gives you enough protection even against quantum computers. And as you may notice, the 51 bit password is what you need to protect - not the 256 bit key."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-12T21:11:45.297",
"Id": "511692",
"Score": "0",
"body": "Unrelated, I seem to have a problem with a word today, unable to spell \"its\". Ni!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-13T07:48:53.893",
"Id": "511737",
"Score": "0",
"body": "Is that a reference to the knights who say... Ni!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-10T15:42:47.553",
"Id": "259314",
"ParentId": "257095",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259314",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T10:38:30.680",
"Id": "257095",
"Score": "1",
"Tags": [
"c#",
"cryptography",
"encryption"
],
"Title": "Encrypted text - C# SHA256, implementation"
}
|
257095
|
<p>My code doesn't actually do that per se, but rather it find every possible edge that can be added without creating a cycle. The return value of the function <code>FindNodesToConnect</code> is a map, where the key is a node and the value is a list of all the nodes we can direct an edge to from the key without introducing cycles.</p>
<p>Another quirk is that this is not a stand-alone function, but part of a bigger neuro-evolution project, so the input is not a graph but a genome that has a graph encoded in it, however the genome is immediately translated to a other data structures so no prior knowledge is necessary (but I'd be glad to clarify further as needed).</p>
<p>My main worry is <strong>performance</strong>, this function could be called hundreds of times every generation for hundreds or thousands of generations, but it contains nested loops and a recursive function. Is there any way to optimize this? or maybe a completely different way of doing this?</p>
<p>Another minor point is <strong>readability</strong> which is something I'm always trying to improve.</p>
<p>The code:</p>
<pre><code>'use strict';
if (!window.Neat) window.Neat = {};
Neat.GenomeGraph = (function () {
const genomeToNodeMap = genome => {
// return value is a map that maps every node to its direct predecessors
const result = new Map()
for (let nodeGene of genome.nodeGenes)
result.set(nodeGene.id, [])
for (let connectionGene of genome.connectionGenes)
result.get(connectionGene.outId).push(connectionGene.inId)
return result
}
const getDependencies = (nodeMap, nodeId) => {
// return value is all the predecessors of a node (found recursively)
return [].concat.apply(nodeMap.get(nodeId), nodeMap.get(nodeId).map(nextNodeId => getDependencies(nodeMap, nextNodeId)))
}
const setDifference = (A, B) => A.filter(x => !B.includes(x))
return {
FindNodesToConnect: genome => {
const nodeMap = genomeToNodeMap(genome)
const graphNodes = genome.nodeGenes.map(nodeGene => nodeGene.id)
const result = new Map()
for (let currentNodeId of graphNodes) {
const cannotConnectTo = getDependencies(nodeMap, currentNodeId);
cannotConnectTo.push(currentNodeId)
for (let [nodeId, dep] of nodeMap)
if (dep.includes(currentNodeId))
cannotConnectTo.push(nodeId)
const canConnectTo = setDifference(graphNodes, cannotConnectTo)
if (canConnectTo.length > 0)
result.set(currentNodeId, canConnectTo)
}
return result;
}
}
})()
</code></pre>
<p>Example function call:</p>
<pre><code>Neat.GenomeGraph.FindNodesToConnect({
nodeGenes: [1, 2, 3, 4, 5, 6, 7].map(x => ({ id: x })),
connectionGenes: [
{ inId: 1, outId: 2},
{ inId: 2, outId: 3},
{ inId: 3, outId: 6},
{ inId: 5, outId: 6},
{ inId: 4, outId: 3},
{ inId: 4, outId: 7},
]
})
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T12:09:09.690",
"Id": "257096",
"Score": "0",
"Tags": [
"javascript",
"graph",
"genetic-algorithm"
],
"Title": "Add an edge to a directed acyclic graph such that it stay acyclic"
}
|
257096
|
<p>I have written a class that acts like a stopwatch using C++11's <code>std::chrono</code> library. I wrote this because I find it difficult to benchmark my cpp code properly, this class just combines chrono's functionality and gives it a nice interface</p>
<p>I have two classes, <code>stopwatch.h</code> and <code>lapwatch.h</code>. The second one has the functionality of a stop watch but also has a lap function which you can use to multiple intervals</p>
<h2><code>stopwatch.h</code></h2>
<pre class="lang-cpp prettyprint-override"><code>#ifndef STOPWATCH_H_
#define STOPWATCH_H_
#include <chrono>
template<typename duration = std::chrono::milliseconds>
class StopWatch
{
public:
using clock = std::chrono::steady_clock;
using time_point = std::chrono::time_point<clock, duration>;
StopWatch() = default;
protected:
enum class State : unsigned char;
static constexpr time_point current_time() noexcept
{
return std::chrono::time_point_cast<duration>(clock::now());
}
public:
virtual void reset() noexcept
{
clock_state = State::idle;
}
time_point go() noexcept
{
if (clock_state != State::stopped)
start_point = current_time();
clock_state = State::running;
return start_point;
}
void stop() noexcept
{
if (clock_state == State::running)
{
stop_point = current_time();
clock_state = State::stopped;
}
}
duration elapsed_time() const noexcept
{
switch (clock_state)
{
case State::idle:
return std::chrono::duration_cast<duration>(clock::duration::zero());
case State::running:
return std::chrono::duration_cast<duration>(current_time() - start_point);
case State::stopped:
return std::chrono::duration_cast<duration>(stop_point - start_point);
default:
return std::chrono::duration_cast<duration>(clock::duration::zero());
break;
}
}
protected:
enum class State : unsigned char { idle, running, stopped };
time_point start_point;
time_point stop_point;
State clock_state = State::idle;
};
</code></pre>
<hr />
<h2><code>lapwatch.h</code></h2>
<pre class="lang-cpp prettyprint-override"><code>
#ifndef LAPWATCH_H_
#define LAPWATCH_H_
#include "stopwatch.h"
#include <vector>
template<typename duration = std::chrono::milliseconds>
class LapWatch : public StopWatch<duration>
{
using clock = typename StopWatch<duration>::clock;
using time_point = typename StopWatch<duration>::clock;
using StopWatch<duration>::State;
public:
LapWatch() = default;
struct Lap
{
duration total_time;
duration split_time;
};
void lap()
{
if (this->clock_state != StopWatch<duration>::State::running)
return;
Lap current;
if (laps.size() == 0)
current.total_time = current.split_time = StopWatch<duration>::elapsed_time();
else
{
current.total_time = StopWatch<duration>::elapsed_time();
current.split_time = (current.total_time - laps[laps.size() - 1].total_time);
}
laps.push_back(static_cast<Lap&&>(current));
}
void reset() noexcept
{
laps.clear();
}
std::vector<Lap> laps;
};
#endif // !LAPWATCH_H_
</code></pre>
<hr />
<h2>usage example</h2>
<pre class="lang-cpp prettyprint-override"><code>#include "lapwatch.h"
int main()
{
LapWatch<> watch;
watch.go() // start the timer
// Some time passes
watch.lap() // Adds the total and split time, but doesn't stop it
// Some more time passes
watch.lap() // Adds another lap
watch.stop() // stop the watch now
// Laps are added to a vector in watch.laps
for(auto const& lap : watch.laps) {
lap.total_time // Total time passed since the start
lap.split_time // Total time passed since the previous lap
}
}
</code></pre>
<h2>Concerns</h2>
<ul>
<li><p>Is this a good idea? Would you use it?</p>
</li>
<li><p>Is this a nice design?</p>
</li>
</ul>
<hr />
<p>I have a github <a href="https://github.com/Aryan1508/StopWatch-cpp" rel="nofollow noreferrer">repository</a> for it too, if anyone prefers reading code that way.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T20:18:08.977",
"Id": "507772",
"Score": "0",
"body": "Calling `LapWatch::reset` does not reset the `clock_state` in the base class to `idle`. Is this intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T05:34:10.610",
"Id": "507809",
"Score": "0",
"body": "@1201ProgramAlarm no! made a mistake there"
}
] |
[
{
"body": "<h1>Use <code>clock</code>'s native resolution everywhere</h1>\n<p>If you cast time points and durations to something with a different resolution than that of <code>clock</code>, you risk losing precision. So for all internal state of your classes, I would definitely store everything as <code>clock::duration</code> and <code>clock::time_point</code> types. You might consider keeping the template parameter to ensure the return types of public member functions have the requested time resolution, but that just makes it easy for the caller to make the same mistake.</p>\n<p>To give an example of where it can go wrong, suppose I write:</p>\n<pre><code>StopWatch<std::chrono::seconds> watch;\nwatch.go(); // done at 11:59:59.999\n...\nwatch.stop(); // done at 12:00:00.000\nauto elapsed = watch.elapsed_time();\n</code></pre>\n<p>With your implementation, <code>elapsed</code> will be equal to one second, even though only one millisecond passed.</p>\n<p>If the issue is just convenience so the caller doesn't have to call <code>std::chrono::duration_cast<>()</code> themselves, I would remove the template parameter from the <code>class</code>, and make the member function <code>elapsed_time()</code> a template instead, like so:</p>\n<pre><code>template <typename duration = clock::duration>\nduration elapsed_time() const noexcept\n{\n ...\n}\n</code></pre>\n<h1><code>current_time()</code> should not be <code>constexpr</code></h1>\n<p>If you mark a function <a href=\"https://en.cppreference.com/w/cpp/language/constexpr\" rel=\"nofollow noreferrer\"><code>constexpr</code></a>, you promise that this function can be evaluated at compile-time. But that does not make sense here.</p>\n<h1>Consider not storing lap results in <code>LapWatch</code></h1>\n<p>Having <code>struct Lap</code> and a function to mark when a lap happened is good. However, by making <code>lap()</code> store the results in a member variable, you now gave <code>LapWatch</code> the responsibility to store laps. That might sometimes be exactly what you want, but maybe the caller wants to do something completely different. Maybe the previous laps don't need to be stored, or they need to be stored in a different way. I would make <code>lap()</code> return a <code>Lap</code> instead, and have the caller decide whether it wants to add those to some container. So:</p>\n<pre><code>Lap lap() {\n Lap current;\n ...\n return current;\n}\n</code></pre>\n<p>And then the caller can write:</p>\n<pre><code>LapWatch<> watch;\nstd:vector<Lap> laps;\nlaps.push_back(watch.lap());\n</code></pre>\n<h1>Use <code>std::move()</code> instead of <code>static_cast<Lap&&>()</code></h1>\n<p>If you really want to move an object, use <a href=\"https://en.cppreference.com/w/cpp/utility/move\" rel=\"nofollow noreferrer\"><code>std::move()</code></a>, it is shorter and less error-prone.</p>\n<p>Note that neither the cast nor <code>std::move()</code> will do anything in this case, since neither <code>Lap</code> nor <code>std::chrono::duration</code> has a move constructor, but it doesn't hurt either.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T20:06:59.707",
"Id": "507771",
"Score": "3",
"body": "Also consider RAII and removing the `go` and `stop` functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T05:41:58.717",
"Id": "507810",
"Score": "0",
"body": "Thank you for the review, are you sure about your first point( loss of precision)? I tried out your example but it gives the expected answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T05:47:41.053",
"Id": "507811",
"Score": "0",
"body": "What you're saying about laps makes sense, but if I didn't have hold of the laps, how do I store the split time? Time elapsed between two laps"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T08:37:19.973",
"Id": "507824",
"Score": "0",
"body": "Ah hm, I didn't realize that `std::chrono::hours` actually has seconds resolution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T08:40:29.967",
"Id": "507825",
"Score": "0",
"body": "As for the split time: you only need to remember the `time_point` of the previous lap."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T19:55:14.160",
"Id": "257109",
"ParentId": "257099",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "257109",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T13:44:43.680",
"Id": "257099",
"Score": "4",
"Tags": [
"c++",
"datetime"
],
"Title": "Stop Watch class in C++ using chrono"
}
|
257099
|
<p>I've implemented a simple vector-like structure. I would appreciate all criticism relevant to code.
I have also published code under github. Here is the link to source code + unit test for most functions:
<a href="https://github.com/Nethius/mystd" rel="nofollow noreferrer">https://github.com/Nethius/mystd</a></p>
<pre><code>const double_t expansion_ratio = 1.5;
namespace mystd {
template<class T>
class vector {
size_t _size;
size_t _capacity;
char *_data;
typedef T *iterator;
typedef const T *const_iterator;
typedef T &reference;
typedef const T &const_reference;
void reallocate(size_t capacity);
void move_forward(iterator dest, iterator from, size_t count);
void move_backward(iterator dest, iterator from, size_t count);
public:
vector();
explicit vector(size_t size);
vector(size_t size, const T &initial);
vector(const vector<T> &vector);
vector(vector<T> &&vector) noexcept;
vector(std::initializer_list<T> list);
template<class input_iterator, typename = typename std::enable_if_t<std::_Is_iterator<input_iterator>::value>>
vector(input_iterator first, input_iterator last);
~vector();
reference operator[](size_t pos);
const_reference operator[](size_t pos) const;
reference at(size_t pos);
const_reference at(size_t pos) const;
vector<T> &operator=(const vector<T> &vector);
vector<T> &operator=(vector <T> &&vector) noexcept;
void assign(size_t count, const_reference value);
template<class input_iterator, typename = typename std::enable_if_t<std::_Is_iterator<input_iterator>::value>>
void assign(input_iterator first, input_iterator last);
iterator insert(const_iterator pos, const_reference value);
iterator insert(const_iterator pos, T &&value);
iterator insert(const_iterator pos, size_t count, const_reference value);
template<class input_iterator, typename = typename std::enable_if_t<std::_Is_iterator<input_iterator>::value>>
iterator insert(const_iterator pos, input_iterator first, input_iterator last);
iterator insert(const_iterator pos, std::initializer_list<T> list);
template<typename ... Args>
iterator emplace(const_iterator pos, Args &&... args);
iterator erase(const_iterator pos);
iterator erase(const_iterator first, const_iterator last);
size_t size() const;
size_t max_size() const;
size_t capacity() const;
bool empty() const;
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
iterator rbegin();
const_iterator rbegin() const;
const_iterator rcbegin() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
iterator rend();
const_iterator rend() const;
const_iterator rcend() const;
reference front();
const_reference front() const;
reference back();
const_reference back() const;
iterator data();
const_iterator data() const;
void push_back(const_reference value);
void push_back(T &&value);
void pop_back();
template<typename ... Args>
void emplace_back(Args &&... args);
void reserve(size_t size);
void resize(size_t count);
void resize(size_t count, const_reference value);
void shrink_to_fit();
void clear();
template<class T>
friend void swap(vector<T> &left, vector<T> &right);
template<class T>
friend bool operator==(const vector <T> &left, const vector <T> &right);
template<class T>
friend bool operator!=(const vector <T> &left, const vector <T> &right);
template<class T>
friend bool operator<(const vector <T> &left, const vector <T> &right);
template<class T>
friend bool operator<=(const vector <T> &left, const vector <T> &right);
template<class T>
friend bool operator>(const vector <T> &left, const vector <T> &right);
template<class T>
friend bool operator>=(const vector <T> &left, const vector <T> &right);
};
template<class T>
vector<T>::vector() : _size(0), _capacity(0), _data(nullptr) {
}
template<class T>
vector<T>::vector(size_t size) : _size(size), _capacity(_size), _data(new char[sizeof(T) * size]()) {
}
template<class T>
vector<T>::vector(size_t size, const T &initial) : vector(size) {
for (size_t i = 0; i < _size; i++)
new(_data + sizeof(T) * i) T(initial);
}
template<class T>
vector<T>::vector(const vector <T> &vector) : vector(vector._size) {
for (size_t i = 0; i < _size; i++)
new(_data + sizeof(T) * i) T(vector[i]);
}
template<class T>
vector<T>::vector(vector<T> &&vector) noexcept : vector(vector._size) {
swap(*this, vector);
}
template<class T>
vector<T>::vector(std::initializer_list<T> list) : vector(list.size()) {
for (size_t i = 0; i < _size; i++)
new(_data + sizeof(T) * i) T(*(list.begin() + i));
}
template<class T>
template<class input_iterator, typename>
vector<T>::vector(input_iterator first, input_iterator last) : vector(std::distance(first, last)) {
auto it = first;
for (size_t i = 0; i < _size; i++) {
new(_data + sizeof(T) * i) T(*(it));
it = std::next(it);
}
}
template<class T>
vector<T>::~vector() {
delete[] _data;
}
template<class T>
T &vector<T>::operator[](size_t pos) {
return *(reinterpret_cast<iterator>(_data + sizeof(T) * pos));
}
template<class T>
const T &vector<T>::operator[](size_t pos) const {
return *(reinterpret_cast<iterator>(_data + sizeof(T) * pos));
}
template<class T>
vector<T> &vector<T>::operator=(const vector <T> &vector) {
if (*this != vector) {
swap(*this, mystd::vector<T>(vector));
}
return *this;
}
template<class T>
vector<T> &vector<T>::operator=(vector<T> &&vector) noexcept {
if (*this != vector) {
swap(*this, vector);
}
return *this;
}
template<class T>
typename vector<T>::iterator vector<T>::begin() {
return reinterpret_cast<iterator>(_data);
}
template<class T>
typename vector<T>::const_iterator vector<T>::begin() const {
return reinterpret_cast<iterator>(_data);
}
template<class T>
typename vector<T>::const_iterator vector<T>::cbegin() const {
return begin();
}
template<class T>
typename vector<T>::iterator vector<T>::end() {
return reinterpret_cast<iterator>(_data + sizeof(T) * _size);
}
template<class T>
typename vector<T>::const_iterator vector<T>::end() const {
return reinterpret_cast<iterator>(_data + sizeof(T) * _size);
}
template<class T>
typename vector<T>::const_iterator vector<T>::cend() const {
return end();
}
template<class T>
size_t vector<T>::size() const {
return _size;
}
template<class T>
size_t vector<T>::capacity() const {
return _capacity;
}
template<class T>
bool vector<T>::empty() const {
return _size == 0;
}
template<class T>
typename vector<T>::reference vector<T>::front() {
return *begin();
}
template<class T>
typename vector<T>::const_reference vector<T>::front() const {
return *cbegin();
}
template<class T>
typename vector<T>::reference vector<T>::back() {
return *(end() - 1);
}
template<class T>
typename vector<T>::const_reference vector<T>::back() const {
return *(cend() - 1);
}
template<class T>
void swap(vector<T> &left, vector<T> &right) {
using std::swap; //enable ADL? https://stackoverflow.com/questions/5695548/public-friend-swap-member-function
swap(left._size, right._size);
swap(left._capacity, right._capacity);
swap(left._data, right._data);
}
template<class T>
void vector<T>::push_back(const_reference value) {
if (_size >= _capacity) {
reallocate(_size * expansion_ratio);
}
new(end()) T(value);
_size++;
}
template<class T>
void vector<T>::push_back(T &&value) {
if (_size >= _capacity) {
reallocate(_size * expansion_ratio);
}
*end() = std::move(value);
_size++;
}
template<class T>
void vector<T>::reallocate(size_t capacity) {
_capacity = capacity;
char *new_data = new char[sizeof(T) * _capacity]();
iterator new_begin = reinterpret_cast<iterator>(new_data);
for (auto it = begin(); it != end(); it++)
*new_begin++ = std::move(*it);
delete[] _data;
_data = new_data;
}
template<class T>
void vector<T>::move_forward(vector::iterator dest, vector::iterator from, size_t count) {
if (dest == from)
return;
iterator _dest = dest;
iterator _from = from;
for (size_t i = 0; i < count; i++)
*_dest++ = std::move(*_from++);
}
template<class T>
void vector<T>::move_backward(vector::iterator dest, vector::iterator from, size_t count) {
if (dest == from)
return;
iterator _dest = dest + count - 1;
iterator _from = from + count - 1;
for (size_t i = count; i > 0; i--)
*_dest-- = std::move(*_from--);
}
template<class T>
void vector<T>::assign(size_t count, const_reference value) {
swap(*this, vector<T>(count, value));
}
template<class T>
template<class input_iterator, typename>
void vector<T>::assign(input_iterator first, input_iterator last) {
swap(*this, vector<T>(first, last));
}
template<class T>
template<typename... Args>
typename vector<T>::iterator vector<T>::emplace(vector::const_iterator pos, Args &&... args) {
size_t index = pos - reinterpret_cast<iterator>(_data);
if (_size >= _capacity) {
reallocate(_size * expansion_ratio);
}
iterator it = reinterpret_cast<iterator>(_data + sizeof(T) * index);
move_backward(it + 1, it, _size - index);
*it = T(std::forward<Args>(args) ...);
_size++;
return it;
}
template<class T>
typename vector<T>::iterator vector<T>::insert(vector::const_iterator pos, const_reference value) {
return emplace(pos, value);
}
template<class T>
typename vector<T>::iterator vector<T>::insert(vector::const_iterator pos, T &&value) {
return emplace(pos, std::move(value));
}
template<class T>
typename vector<T>::iterator vector<T>::insert(vector::const_iterator pos, size_t count, const_reference value) {
if (!count)
return const_cast<iterator>(pos);
size_t index = pos - reinterpret_cast<iterator>(_data);
if (_size + count >= _capacity) {
reallocate((_size + count) * expansion_ratio);
}
iterator it = reinterpret_cast<iterator>(_data + sizeof(T) * index);
move_backward(it + count, it, _size - index);
for (size_t i = 0; i < count; i++)
*(it + i) = value;
_size += count;
return it;
}
template<class T>
template<class input_iterator, typename>
typename vector<T>::iterator
vector<T>::insert(vector::const_iterator pos, input_iterator first, input_iterator last) {
size_t n = std::distance(first, last);
if (!n)
return const_cast<iterator>(pos);
size_t index = pos - reinterpret_cast<iterator>(_data);
if (_size + n >= _capacity) {
reallocate((_size + n) * expansion_ratio);
}
iterator dest = reinterpret_cast<iterator>(_data + sizeof(T) * index);
move_backward(dest + n, dest, _size - index);
auto from = first;
for (size_t i = 0; i < n; i++) {
*(dest + i) = *(from);
from = std::next(from);
}
_size += n;
return dest;
}
template<class T>
typename vector<T>::iterator vector<T>::insert(vector::const_iterator pos, std::initializer_list<T> list) {
return insert(pos, list.begin(), list.end());
}
template<class T>
void vector<T>::pop_back() {
erase(end() - 1);
}
template<class T>
typename vector<T>::iterator vector<T>::erase(vector::const_iterator pos) {
size_t index = pos - reinterpret_cast<iterator>(_data);
iterator it = reinterpret_cast<iterator>(_data + sizeof(T) * index);
it->~T();
if (pos != end() - 1)
move_forward(it, it + 1, _size - index);
_size--;
return it;
}
template<class T>
typename vector<T>::iterator vector<T>::erase(vector::const_iterator first, vector::const_iterator last) {
size_t n = 0;
for (auto curr = first; curr <= last; ++curr)
++n;
if (!n)
return const_cast<iterator>(last);
size_t index = first - reinterpret_cast<iterator>(_data);
iterator it = reinterpret_cast<iterator>(_data + sizeof(T) * index);
for (size_t i = 0; i < n; i++)
(it + i)->~T();
move_forward(it, it + n, _size - (index + n));
_size -= n;
return it;
}
template<class T>
typename vector<T>::iterator vector<T>::data() {
return reinterpret_cast<iterator>(_data);
}
template<class T>
typename vector<T>::const_iterator vector<T>::data() const {
return data();
}
template<class T>
template<typename... Args>
void vector<T>::emplace_back(Args &&... args) {
emplace(end(), args ...);
}
template<class T>
void vector<T>::reserve(size_t size) {
if (size > _capacity)
reallocate(size);
}
template<class T>
void vector<T>::shrink_to_fit() {
reallocate(_size);
}
template<class T>
void vector<T>::clear() {
for (auto it = begin(); it != end(); it++)
(it)->~T();
_size = 0;
}
template<class T>
void vector<T>::resize(size_t count) {
if (count > _capacity)
reallocate(count * expansion_ratio);
_size = count;
}
template<class T>
void vector<T>::resize(size_t count, const_reference value) {
iterator it = reinterpret_cast<iterator>(_data);
if (count > _size) {
size_t lastElementIndex = _size;
resize(count);
it = begin();
for (size_t i = lastElementIndex; i < count; i++)
*(it + i) = value;
} else {
for (size_t i = count; i < _size; i++)
(it + i)->~T();
}
_size = count;
}
template<class T>
bool operator==(const vector<T> &left, const vector<T> &right) {
if (left._size != right._size)
return false;
for (size_t i = 0; i < left._size; i++) {
if (*(reinterpret_cast<T *>(left._data + sizeof(T) * i)) !=
*(reinterpret_cast<T *>(right._data + sizeof(T) * i)))
return false;
}
return true;
}
template<class T>
bool operator!=(const vector<T> &left, const vector<T> &right) {
return !(left == right);
}
template<class T>
bool operator<(const vector<T> &left, const vector<T> &right) {
size_t size = left.size() < right.size() ? left.size() : right.size();
for (size_t i = 0; i < size; i++) {
if (*(reinterpret_cast<T *>(left._data + sizeof(T) * i)) <
*(reinterpret_cast<T *>(right._data + sizeof(T) * i)))
return true;
}
return false;
}
template<class T>
bool operator<=(const vector<T> &left, const vector<T> &right) {
return !(left > right);
}
template<class T>
bool operator>(const vector<T> &left, const vector<T> &right) {
size_t size = left.size() < right.size() ? left.size() : right.size();
for (size_t i = 0; i < size; i++) {
if (*(reinterpret_cast<T *>(left._data + sizeof(T) * i)) >
*(reinterpret_cast<T *>(right._data + sizeof(T) * i)))
return true;
}
return false;
}
template<class T>
bool operator>=(const vector<T> &left, const vector<T> &right) {
return !(left < right);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Hi and welcome to CodeReview,</p>\n<p>There is a lot to unravel here, mostly concerning readability and robust code.</p>\n<ol>\n<li><p><code>typedef</code> is a relict from C that has been completely superseded by <code>using</code> declarations, so your aliases should read:</p>\n<pre><code> using iterator = T*;\n using const_iterator = const T*;\n using reference = T&;\n using const_reference = const T&;\n</code></pre>\n<p>Note that in this case it was even actively confusing as the <code>*</code> and the <code>&</code> where located directly at the name of the alias.</p>\n</li>\n<li><p>You have chosen a size based notation rather a pointer based one. That is possible but involves quite a lot of calculations that can be avoided by going with the conventional <code>first, last, end</code> pointers.</p>\n</li>\n<li><p>Your data members can and should be member initialized, so that there is no possibility to forget to initialize them</p>\n<pre><code> size_t _size{0};\n size_t _capacity{0};\n char *_data{nullptr};\n</code></pre>\n</li>\n<li><p>Your choice of <code>char*</code> as the underlying buffer is both incorrect and unnecessary. The first observation is that only <code>unsigned char</code> and <code>byte</code> are allowed to represent memory, so the usage of <code>char</code> is wrong. Also alignment might be a huge and hard to debug issue. Why not go with plain <code>T*</code>. That way you can also get rid of all the pesky <code>reinterpret_cast</code></p>\n</li>\n<li><p>I see no benefit in separating the member function declarations from their definition. You need them in the header anyway, so why add all this biolerplate?</p>\n<p>Note that this can also introduce correctness issues especially regarding templated friend functions. (There is a talk from Ben Saks about making friends that I would recommend here)</p>\n</li>\n<li><p>You can default the constructor when you use member intializer.</p>\n</li>\n<li><p>You vector notably differs from the std implementation in that it does not value initializes the members. This is due to choosing <code>char</code> as the underlying buffer type, which is trivial. This will almost certainly introduce bugs.</p>\n</li>\n<li><p>You are using placement new in the <code>size, const reference</code> constructor. This would not be necessary if you would use a <code>T*</code> buffer. Also alignment will most certainly bite you.</p>\n</li>\n<li><p>You should always use braces around <code>for</code> and <code>if</code>. There is literally no reason to not use braces even for single line bodies. It introduces a whole slew of super hard to debug bugs for the incredible gain of a single LoC saved.</p>\n</li>\n<li><p>Your move constructor is completely wrong. You should <code>move</code> the content of the input to your vector and not swap the elements. Think about the difference in lifetimes this makes.</p>\n</li>\n<li><p>Use the simples method available. You want to increment an iterator. Which is better <code>++it</code> or <code>it = std::next(it)</code>?</p>\n</li>\n<li><p>Your copy assignment is also completely broken. I do not really know why you name your arguments same as the class, given that that will confuse everyone. But this should not even compile, as you cannot swap with a const reference. It is const after all. You need to copy the elements around.</p>\n</li>\n<li><p>All the reinterpret_cast can go</p>\n</li>\n<li><p>You are using post-increment, which suggests that you should read up on the difference between <code>++i</code> and <code>i++</code>. One of the two does a copy.</p>\n</li>\n<li><p>Currently you are doing no bounds check for your accessors. If you are open that you will crash and burn when someone uses it incorrectly that is fine. Not nice, but technically correct. Maybe an assert here and there would help?</p>\n</li>\n<li><p>You are open coding a lot of common algorithms. It generally is better to simply use std::copy rather than writing the loop by hand.</p>\n</li>\n<li><p>Everytime you use swap it is mostly wrong</p>\n</li>\n<li><p>You are completely neglecting exception safety. If that is intentional you should make it clear.</p>\n</li>\n<li><p>Please do not check integers against 0 via <code>!</code></p>\n</li>\n<li><p>You should reuse internal methods more often. Why is there reinterpret_cast everywhere when you have <code>begin</code> and <code>end</code> and could simply loop over the iterators they give you?</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T16:28:37.067",
"Id": "507856",
"Score": "0",
"body": "As long as he is using `new` alignement will never be an issue."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:13:37.510",
"Id": "257142",
"ParentId": "257100",
"Score": "3"
}
},
{
"body": "<h3>Notes:</h3>\n<p>There are multiple places where you don't correctly start or end the lifetime of an object. After allocating the raw memory you have allocated <code>capacity</code> space for objects, <strong>BUT</strong> you have not started the lifetime of any objects in the storage and thus your <code>size</code> is zero.</p>\n<p>When adding objects to the storage they <strong>MUST</strong> be constructed (not assigned to). This means as <code>size</code> is incremented you should always be using placement new (thus calling the constructor) and start the object lifetime. When <code>size</code> decreases you need to manually call the destructor and end the object lifetime. Anything from <code>[size..capacity)</code> is not constructed and thus its lifetime has not started.</p>\n<p>There are a couple of places where you assign to objects who's lifetime has not started (assignment assumes the lifetime has started). There are also a couple of places where you don't end the lifetime when you decrease the size (which would mean they could leak or accidentally be constructed onto).</p>\n<p>See: Default constructor. Move constructor</p>\n<hr />\n<p>You need to understand the strong exception guarantee. This basically says that a mutation works correctly or it fails (probably with an exception) <strong>BUT</strong> if it fails the state remains unchanged (and thus valid).</p>\n<p>To make this work usually this means that mutations happen on temporary objects and state is swapped with the temporary using exception safe operations.</p>\n<p>see: resize</p>\n<hr />\n<p>The calls to resize if very subtly broken (this happened to me as well when I first tried to write vector).</p>\n<pre><code> reallocate(_size * expansion_ratio); // does not work if _size is 1.\n // if your expansion_ratio is 1.5\n // would work for 2 or greater.\n</code></pre>\n<h3>Self Plug</h3>\n<p>I wrote a series of articles on the vector that is worth reading:</p>\n<p><a href=\"https://lokiastari.com/series/\" rel=\"nofollow noreferrer\">https://lokiastari.com/series/</a></p>\n<h3>Style</h3>\n<p>You use a C style when annotating your types for pointers and references by placing the '*' or '&' with the variable rather than with the type.</p>\n<p>In C++ we usually place these annotations with the type so that all the type information is placed together. This is because in C++ type information is much more important.</p>\n<pre><code>vector& operator=(vector const& copy); // Notice the '&' with the type.\n</code></pre>\n<p>You store the data in <code>char*</code>. This means you have a lot of <code>reinterpret_cast<>()</code> to convert the pointer back to a <code>T*</code> I would simply change the data member in to a <code>T*</code> member and use the <code>reinterpret_cast<>()</code> once.</p>\n<h3>Code Review:</h3>\n<p>Prefer to use <code>using</code> over <code>typedef</code></p>\n<pre><code> typedef T *iterator;\n typedef const T *const_iterator;\n typedef T &reference;\n typedef const T &const_reference;\n\n\n using iterator = T*;\n using const_iterator = const T*;\n using reference = T&;\n using const_reference = const T&;\n</code></pre>\n<hr />\n<p>Your methods are simply a list of methods with an empty line between them.</p>\n<pre><code> vector();\n\n explicit vector(size_t size);\n\n vector(size_t size, const T &initial);\n\n vector(const vector<T> &vector);\n</code></pre>\n<p>You should make this easier to read. One way to do this is to group together functions that have similar functionality. Constructors/Assignment Op/Insert/Query etc. Something.</p>\n<hr />\n<p>I suppose you can check this.</p>\n<pre><code> template<class input_iterator, typename = typename std::enable_if_t<std::_Is_iterator<input_iterator>::value>>\n vector(input_iterator first, input_iterator last);\n</code></pre>\n<p>I don't see the point. If they don't act like iterators it will fail to compile.</p>\n<hr />\n<p>I see why you did this:</p>\n<pre><code> void push_back(const_reference value); \n void push_back(T &&value);\n</code></pre>\n<p>But I think it is clearer to write like this:</p>\n<pre><code> void push_back(T const& value); \n void push_back(T&& value);\n</code></pre>\n<hr />\n<p>You don't need the template part here.</p>\n<pre><code> template<class T>\n friend void swap(vector<T> &left, vector<T> &right);\n</code></pre>\n<p>or in the following friend declarations.</p>\n<hr />\n<p>The reason to make these operations standalone functions is to allow the left value to auto convert into a vector when comparing something to a vector on the right hand side.</p>\n<pre><code> template<class T>\n friend bool operator==(const vector <T> &left, const vector <T> &right);\n</code></pre>\n<p>Since this conversion can never happen (your only single parameter construcror is explicit). There is not need to make this a friend and it just simpler to make it a member of the class.</p>\n<hr />\n<p><strong>This is broken:</strong></p>\n<p>Because it is public.</p>\n<pre><code> template<class T>\n vector<T>::vector(size_t size) : _size(size), _capacity(_size), _data(new char[sizeof(T) * size]()) {\n }\n</code></pre>\n<p>You have allocated space for you <code>size</code> elements. <strong>BUT</strong> you have not constructed the elements of type <code>T</code> this is simply raw uninitialized memory. You need to call the default constructor for each element in the vector.</p>\n<p>After reading your other constructors you seem to be using this to allocate the space then the other constructors finish up the initialization. But because this is public it is broken. An alternative is to make it private.</p>\n<p>But a couple of the other constructors should not be using this anyway.</p>\n<p>Note: You want the capacity to be equal to the size? This means that the next element added is going to force a re-start.</p>\n<hr />\n<p>Note: If you fix the above constructor (to initialize the members) you can not use it here:</p>\n<pre><code> template<class T>\n vector<T>::vector(size_t size, const T &initial) : vector(size) {\n for (size_t i = 0; i < _size; i++)\n new(_data + sizeof(T) * i) T(initial);\n }\n</code></pre>\n<hr />\n<p>This is a very expensive move constructor.</p>\n<pre><code> template<class T>\n vector<T>::vector(vector<T> &&vector) noexcept : vector(vector._size) {\n swap(*this, vector);\n }\n</code></pre>\n<p>You allocate the underlying data and then swap the content. Set the current pointer to <code>nullptr</code> and then swap. Not only is this expensive (memory allocation), but the destiantion object is not in a valid state. It has <code>size</code> elements none of which are initialized.</p>\n<pre><code> template<class T>\n vector<T>::vector(vector<T>&& move) noexcept\n : _size{0}\n , _capacity{0}\n , _data{nulptr}\n {\n swap(move);\n }\n</code></pre>\n<hr />\n<p><strike>This is wrong.</strike>OK. I see the construction of temporary now.</p>\n<pre><code> template<class T>\n vector<T> &vector<T>::operator=(const vector <T> &vector) {\n if (*this != vector) {\n swap(*this, mystd::vector<T>(vector));\n }\n return *this;\n }\n</code></pre>\n<p><strike>You are attempting to modify the input parameter (which is both const and reference to something else that should not be changed).</p>\n<p>It seems to be a corruption of the copy and swap idiom.</strike></p>\n<p>The test for self assignment is counter productive. It will actually slow things down (on average). Self assignment is exceedingly rare so the test for self assignment actually slows down the normal case. Now you do need to correctly handle self assignment but because it is so rare it is acceptable for that action to be pesimized so you can optimize the normal situation.</p>\n<pre><code> template<class T>\n vector<T> &vector<T>::operator=(vector <T> const& input)\n {\n vector<T> copy(input); // Copy.\n swap(copy); // Swap with the current with copy (see below)\n\n return *this;\n }\n</code></pre>\n<hr />\n<p>Again the test of self assignment is a pesimization of the normal case while trying to optimize the very rare case. Optimize for the most common situation.</p>\n<pre><code> template<class T>\n vector<T> &vector<T>::operator=(vector<T> &&vector) noexcept {\n if (*this != vector) {\n swap(*this, vector);\n }\n return *this;\n }\n</code></pre>\n<p>I would simplify to:</p>\n<pre><code> template<class T>\n vector<T> &vector<T>::operator=(vector<T>&& move) noexcept\n {\n swap(move); // swap is safe for self assignment.\n return *this;\n }\n</code></pre>\n<hr />\n<p>These functions are so small and simple.</p>\n<pre><code> template<class T>\n size_t vector<T>::size() const {\n return _size;\n }\n\n template<class T>\n size_t vector<T>::capacity() const {\n return _capacity;\n }\n\n template<class T>\n bool vector<T>::empty() const {\n return _size == 0;\n }\n</code></pre>\n<p>I would put them inline in the header file. If a function is simply a line I normally just put it inside the class declaration:</p>\n<pre><code> class vector\n {\n // STUFF\n size_t size() const {return _size;}\n size_t capacity() const {return _capacity;}\n bool empty() const {return _size == 0;}\n };\n</code></pre>\n<hr />\n<p>Yes. The enable of ADL is the standard pattern for swap.</p>\n<p>Yes you do need a standalone swap. But why not <strong>also</strong> have a swap member function to simplify things?</p>\n<pre><code> template<class T>\n void swap(vector<T> &left, vector<T> &right) {\n using std::swap; //enable ADL? https://stackoverflow.com/questions/5695548/public-friend-swap-member-function\n swap(left._size, right._size);\n swap(left._capacity, right._capacity);\n swap(left._data, right._data);\n }\n</code></pre>\n<p>I would write like this:</p>\n<pre><code> class vector\n {\n // STUFF\n void swap(vector& other) noexcept // swap needs to noexcept so\n { // it can be called from noexcept members\n using std::swap; //enable ADL? YES.\n swap(_size, other._size);\n swap(_capacity, other._capacity);\n swap(_data, other._data);\n }\n friend void swap(vector& lhs, vector& rhs) {lhs.swap(rhs);}\n };\n \n</code></pre>\n<hr />\n<p>Subtle break: When size is 1.</p>\n<pre><code> template<class T>\n void vector<T>::push_back(const_reference value) {\n if (_size >= _capacity) {\n //\n // size = 1;\n // size * expansion_ratio => (1 * 1.5) => 1.5\n // reallocate accepts (size_t an integer) thus the parameter\n // will be truncated.\n // \n // So the value passed here is 1\n reallocate(_size * expansion_ratio);\n }\n new(end()) T(value);\n _size++;\n }\n</code></pre>\n<hr />\n<p>This is broken:</p>\n<pre><code>template<class T>\nvoid vector<T>::push_back(T &&value) {\n if (_size >= _capacity) {\n reallocate(_size * expansion_ratio);\n }\n\n // This is wrong.\n // Using the assignment assumes that the destination is properly\n // constructed member. The value at end() has not been constructed.\n // So you must use the constructor (preferably move).\n *end() = std::move(value);\n\n // To do this correctly you must use the placement new.\n // Like you do everywhere else.\n new(end()) T(std::move(value));\n _size++;\n}\n</code></pre>\n<hr />\n<p>Lot of issues here:</p>\n<pre><code> template<class T>\n void vector<T>::reallocate(size_t capacity) {\n _capacity = capacity;\n\n char *new_data = new char[sizeof(T) * _capacity]();\n iterator new_begin = reinterpret_cast<iterator>(new_data);\n\n // Not all types support move so this can use copy or move\n // depending on the type. Which is good.\n //\n // But not all copy constructors are `noexcept` so this can potentially\n // throw. If it throws then you need to make sure you do not leak.\n // the pointers. \n for (auto it = begin(); it != end(); it++)\n // These objects have not been created so you can not use assign.\n // So you need to use placement new (with move) to construct in\n // in place.\n *new_begin++ = std::move(*it);\n\n // Though normally destructors are noexcept so it should not throw.\n // you can not make that assumption with all random types (which is T).\n // so you have to assume that it can potentially throw. If it throws\n // when you call delete here you leave your object in an invalid state\n // **AND** you leak the value of `new_data`.\n //\n // You can solve both of these by swapping first then calling delete.\n //\n // Another issue is that the destructors of T are not called here.\n delete[] _data;\n _data = new_data;\n }\n</code></pre>\n<p>Use the copy and swap idiom to solve the issue.</p>\n<pre><code> template<class T>\n void vector<T>::reallocate(size_t capacity)\n {\n vector<T> newVersion(*this, capacity); // construct a new version\n // with extra capacity\n // you will need a new constructor\n // for this.\n\n // But any exceptions are self contained.\n // and will not affect this object and prevent leaking.\n\n // Now swap the internal data.\n // the destructor of newVersion will do the cleanup automatically.\n swap(newVersion);\n }\n</code></pre>\n<hr />\n<p>Resizing means you either need to add or remove items.</p>\n<pre><code> template<class T>\n void vector<T>::resize(size_t count) {\n\n // Why not >=\n if (count > _capacity)\n reallocate(count * expansion_ratio);\n\n // This changes the size but you may need to construct\n // the objects if you are increasing the size.\n // or if you reduce size you are going to need to destory\n // the items you removed.\n _size = count;\n }\n</code></pre>\n<hr />\n<p>You try and do the resize correctly here:</p>\n<pre><code> template<class T>\n void vector<T>::resize(size_t count, const_reference value) {\n\n // STUFF\n for (size_t i = lastElementIndex; i < count; i++)\n\n // Can not use assignment here.\n // You need to use normal construction here.\n *(it + i) = value;\n }\n</code></pre>\n<hr />\n<pre><code> template<class T>\n bool operator==(const vector<T> &left, const vector<T> &right) {\n if (left._size != right._size)\n return false;\n for (size_t i = 0; i < left._size; i++) {\n\n // why not use the methods you have already defined.\n if (left[i] != right[i]) {return false;}\n\n // Very hard to read.\n if (*(reinterpret_cast<T *>(left._data + sizeof(T) * i)) !=\n *(reinterpret_cast<T *>(right._data + sizeof(T) * i)))\n return false;\n }\n return true;\n }\n</code></pre>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T18:32:00.160",
"Id": "257157",
"ParentId": "257100",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257157",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T14:18:17.523",
"Id": "257100",
"Score": "7",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"template",
"vectors"
],
"Title": "re-implementation of std::vector"
}
|
257100
|
<p>I have written some Go code that produces the output I would like, but I am unsure if the code itself "smells" good. I would like to know if it contains any anti-patterns, exemplifies bad practices, or lacks the proper idioms one would expect to see in a program written in Golang. Details of the program follow.</p>
<p>I have recently started programming in Go, and have been looking for ways to practice my skills. I come from a Python background and lately have been reading up on compiler design. So in an attempt to practice both of these nascent interests, this morning I wrote a bit of Go code to lex a string into a series of tokens. The lexer recognizes numbers, common whitespace characters, and the binary operators for addition and subtraction.</p>
<p>I based this lexer on an <a href="https://docs.python.org/3/library/re.html#writing-a-tokenizer" rel="nofollow noreferrer">example of creating a tokenizer</a> I found in the Python documentation for the re (regex) library. Thus my code uses the <a href="https://golang.org/pkg/regexp/" rel="nofollow noreferrer">regexp package</a> of the Go standard library. I plan on segmenting the code into separate files / packages, but for now I have it all in one file for readability.</p>
<p>The code itself is below. Specific questions are contained in the comments, but please share any issues you find with the code. I am liking the imperative and "simple" style of Go, and would like to make sure I do not start any poor coding habits when writing Go code in the future.</p>
<p>Here is a Go Playground link to the code as well: <a href="https://play.golang.org/p/jfuWRyOipMM" rel="nofollow noreferrer">https://play.golang.org/p/jfuWRyOipMM</a></p>
<pre><code>package main
import (
"regexp"
"strconv"
"strings"
"fmt"
)
// Is it best practice to enumerate string constants like this?
const (
Plus = "Plus"
Minus = "Minus"
Number = "Number"
Skip = "Skip"
Newline = "Newline"
)
// Token struct for keeping track of tokens
type Token struct {
Type string
// How to best signify that a value could be a string or an int?
Value interface{}
Line int
Column int
}
// Tokenize converts a string into a slice of tokens
func Tokenize(text string) []Token {
// Is this mapping a good way of keeping track of token patterns?
groupNamesPatterns := map[string]string{
Plus: `\+`,
Minus: `-`,
Number: `[\d]+`,
Skip: `[ \t]`,
Newline: `\n`,
}
// Create the Regex pattern with all the named groups
var patternStrings []string
for groupName, pattern := range groupNamesPatterns {
groupPattern := fmt.Sprintf(`(?P<%s>%s)`, groupName, pattern)
patternStrings = append(patternStrings, groupPattern)
}
pattern := regexp.MustCompile(strings.Join(patternStrings, "|"))
groupNames := pattern.SubexpNames()
// Create the tokens list
var tokens []Token
line := 1
column := 0
matches := pattern.FindAllStringSubmatch(text, -1)
for _, m := range matches {
// Iterate through match group names to find the name of the
// matched group
for i, matchedText := range m[1:] {
if matchedText != "" {
groupName := groupNames[i+1]
if groupName == Newline {
line += 1
column = 0
break
}
if groupName != Skip {
t := Token{groupName, "", line, column}
// Set the value of the token to either the parsed string
// or raw string
if parsed, err := strconv.Atoi(matchedText); err != nil {
t.Value = matchedText
} else {
t.Value = parsed
}
tokens = append(tokens, t)
}
column += len(matchedText)
break
}
}
}
return tokens
}
func main() {
// Example of tokenizing string spanning multiple lines
text := `
1
+ 2
- 3`
tokens := Tokenize(text)
for _, token := range tokens {
fmt.Printf("%#v\n", token)
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>String Constants</h2>\n<p>An alternative way for representing your constants if you don't need their string representations would be to use the <a href=\"https://golang.org/ref/spec#Iota\" rel=\"nofollow noreferrer\">iota</a> identifier built into golang to assign auto-incrementing enumerations like so:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>const (\n Plus = iota // 0\n Minus // 1\n Number // 2\n Skip // 3\n Newline // 4\n)\n</code></pre>\n<p>This is actually how the go tokens are defined: <a href=\"https://github.com/golang/go/blob/master/src/go/token/token.go\" rel=\"nofollow noreferrer\">https://github.com/golang/go/blob/master/src/go/token/token.go</a></p>\n<p>You may however want these string values to use later on in a different part of your lexer depending on what you do.</p>\n<h2>How to best signify that a value could be a string or an int?</h2>\n<p>In my opinion, you <strong>really</strong> shouldn't be trying to store different types in the same variable. Go isn't like Python in this regard, and on that note, I would try to avoid the use of the empty interface <code>interface{}</code> unless it is truly necessary/adds value to the application (a good example of it adding value is in the <a href=\"https://github.com/stretchr/testify\" rel=\"nofollow noreferrer\">stretchr/testify</a> package for their assert functions).</p>\n<p>For this particular use case here are some alternatives I can think of:</p>\n<ul>\n<li>More complex: Store the underlying value as a slice of bytes ([]byte)</li>\n<li>Simpler: Accept the performance penalty and just use strings (maybe it's a simplification you use, for now, then you can refactor to use bytes later)</li>\n</ul>\n<p>In both of these cases, you would convert back to the original value when needed based upon the type of the token (which it looks like you are already storing, isn't that convenient?).</p>\n<h2>Is this mapping a good way of keeping track of token patterns?</h2>\n<p>Seems perfectly good to me! </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T16:54:14.047",
"Id": "508522",
"Score": "1",
"body": "Thanks for the advice! I was aware of using iota for emulating enums, but I think I would prefer to use string literal values for now. Thanks also for pointing out alternatives for how I'm storing token values. I've extended this project to be a [2D ASCII graph parser](https://github.com/PappasBrent/flagon) (the readme needs updating), and am no longer storing integer values, so think I'll strictly be storing string values for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-11T23:24:40.800",
"Id": "511590",
"Score": "0",
"body": "My comment was going to be that it might be simpler to reason about to use a lexer that loops over the characters instead of a regex-based lexer. However, I see you've already done that over at the repo - nice! I added a few commits on your commit over there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T02:31:04.383",
"Id": "257424",
"ParentId": "257104",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T17:21:27.283",
"Id": "257104",
"Score": "4",
"Tags": [
"beginner",
"go",
"lexical-analysis"
],
"Title": "Idiomatic Go Lexer"
}
|
257104
|
<p>Looking for more simple one liner for environment variable check with default value in csharp, any help is appreciated.</p>
<pre><code>public static string GetEnvironmentVariable1(string envName, string defaultValue)
{
var env = Environment.GetEnvironmentVariable(envName);
return string.IsNullOrEmpty(env) ? defaultValue : env;
}
</code></pre>
<p>Tried this code, but getting compiler error that possible null reference could be returned</p>
<pre><code>public static string GetEnvironmentVariable2(string envName, string defaultValue)
{
return string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)) ? defaultValue : Environment.GetEnvironmentVariable(envName);
}
</code></pre>
|
[] |
[
{
"body": "<p>Use <code>??</code>. <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator\" rel=\"nofollow noreferrer\">Null-coalescing operator</a>.</p>\n<p>Null check only</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string GetEnvironmentVariable(string name, string defaultValue)\n => Environment.GetEnvironmentVariable(name) ?? defaultValue;\n</code></pre>\n<p>Null and empty string check</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string GetEnvironmentVariable(string name, string defaultValue)\n => Environment.GetEnvironmentVariable(name) is string v && v.Length > 0 ? v : defaultValue;\n</code></pre>\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching\" rel=\"nofollow noreferrer\">Pattern matching</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T23:52:20.620",
"Id": "257121",
"ParentId": "257105",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T17:36:19.600",
"Id": "257105",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Environment variable check with default value in csharp"
}
|
257105
|
<p><strong>I am computing shortest paths of graphs using Python Networkx and Matplotlib.</strong> I'm focused on animating the <a href="https://en.wikipedia.org/wiki/Route_inspection_problem" rel="nofollow noreferrer">route inspection problem</a> path in particular here.
My goal is to <strong>smoothly render such animation to visually look at the path and ultimately save the animation in mp4</strong> via FFmpeg (but that's another topic).</p>
<p>My issue is that the animation is not smooth at all for the graph and path I'm currently working on: 418 nodes, 558 edges and a path of 783 steps.</p>
<p>Given that I have a fast computer, I believe my code can clearly be improved or, unlikely, I have reached the limit of matplotlib for my use-case.</p>
<p>The below code runs correctly but as you may see, it draws the path slowly and slower at each path step.
I think it takes me around 30' to draw 300 steps.</p>
<p>I have seen that the code runs faster if I'm now displaying the nodes labels so they are not displayed with this code.</p>
<p><strong>Because I only want to change the color of edges and nodes, there might be a more efficient approach than mine as I believe I'm drawing the entire graph at each step. I don't know how to just change the color of nodes/edges without redrawing everything as I'm new to all of that.</strong></p>
<p>Here is the path animation of the below script I generated differently:
(It took around 3 hrs... for the below script to run, taking one picture at each step which I used to generate this smooth video)
<a href="https://www.youtube.com/watch?v=-ObZcSWGhdM" rel="nofollow noreferrer">https://www.youtube.com/watch?v=-ObZcSWGhdM</a></p>
<p><strong>Code:</strong></p>
<pre><code># Import libraries
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
# Define Graph
G = nx.Graph()
G.add_edges_from([(1, 3, {'weight': 99}), (2, 3, {'weight': 73}), (3, 4, {'weight': 45}), (4, 104, {'weight': 166}), (4, 6, {'weight': 89}), (6, 103, {'weight': 127}), (103, 104, {'weight': 76}), (104, 106, {'weight': 45}), (106, 108, {'weight': 54}), (108, 110, {'weight': 49}), (110, 115, {'weight': 39}), (110, 111, {'weight': 85}), (111, 113, {'weight': 49}), (111, 114, {'weight': 31}), (114, 115, {'weight': 82}), (108, 109, {'weight': 203}), (106, 107, {'weight': 218}), (104, 105, {'weight': 229}), (105, 107, {'weight': 47}), (107, 109, {'weight': 69}), (5, 6, {'weight': 222}), (5, 8, {'weight': 49}), (7, 8, {'weight': 28}), (8, 13, {'weight': 107}), (13, 14, {'weight': 80}), (12, 13, {'weight': 80}), (14, 15, {'weight': 81}), (15, 10, {'weight': 63}), (9, 10, {'weight': 33}), (10, 11, {'weight': 127}), (6, 11, {'weight': 96}), (11, 17, {'weight': 68}), (26, 103, {'weight': 213}), (15, 16, {'weight': 69}), (16, 17, {'weight': 62}), (17, 25, {'weight': 76}), (16, 23, {'weight': 102}), (23, 24, {'weight': 31}), (24, 31, {'weight': 25}), (22, 23, {'weight': 75}), (22, 15, {'weight': 112}), (13, 20, {'weight': 124}), (14, 21, {'weight': 116}), (20, 21, {'weight': 79}), (21, 22, {'weight': 77}), (18, 19, {'weight': 74}), (19, 20, {'weight': 80}), (12, 19, {'weight': 119}), (35, 22, {'weight': 99}), (34, 35, {'weight': 15}), (33, 34, {'weight': 137}), (32, 33, {'weight': 46}), (29, 32, {'weight': 39}), (29, 100, {'weight': 181}), (100, 101, {'weight': 51}), (27, 101, {'weight': 162}), (27, 28, {'weight': 31}), (26, 27, {'weight': 36}), (25, 26, {'weight': 19}), (25, 30, {'weight': 30}), (28, 30, {'weight': 20}), (28, 29, {'weight': 50}), (32, 51, {'weight': 197}), (50, 51, {'weight': 99}), (33, 50, {'weight': 188}), (46, 50, {'weight': 150}), (44, 46, {'weight': 75}), (44, 45, {'weight': 52}), (35, 44, {'weight': 114}), (43, 46, {'weight': 71}), (35, 36, {'weight': 28}), (36, 37, {'weight': 16}), (37, 38, {'weight': 123}), (38, 40, {'weight': 95}), (40, 41, {'weight': 85}), (40, 42, {'weight': 86}), (38, 39, {'weight': 114}), (20, 38, {'weight': 100}), (40, 36, {'weight': 154}), (31, 34, {'weight': 131}), (30, 31, {'weight': 36}), (99, 100, {'weight': 47}), (32, 99, {'weight': 182}), (97, 98, {'weight': 188}), (98, 99, {'weight': 1}), (94, 97, {'weight': 46}), (93, 94, {'weight': 41}), (92, 93, {'weight': 62}), (91, 92, {'weight': 14}), (92, 95, {'weight': 34}), (94, 95, {'weight': 46}), (91, 96, {'weight': 72}), (56, 91, {'weight': 91}), (51, 56, {'weight': 87}), (55, 56, {'weight': 81}), (49, 50, {'weight': 63}), (48, 49, {'weight': 53}), (49, 53, {'weight': 104}), (53, 55, {'weight': 128}), (52, 53, {'weight': 68}), (46, 47, {'weight': 69}), (53, 54, {'weight': 76}), (55, 61, {'weight': 132}), (61, 87, {'weight': 63}), (82, 87, {'weight': 105}), (82, 88, {'weight': 42}), (88, 93, {'weight': 121}), (88, 89, {'weight': 97}), (89, 90, {'weight': 56}), (55, 90, {'weight': 70}), (86, 87, {'weight': 31}), (85, 86, {'weight': 48}), (59, 86, {'weight': 69}), (59, 60, {'weight': 55}), (59, 61, {'weight': 44}), (57, 59, {'weight': 67}), (58, 59, {'weight': 47}), (59, 69, {'weight': 187}), (417, 69, {'weight': 59}), (68, 69, {'weight': 9}), (68, 70, {'weight': 16}), (70, 78, {'weight': 67}), (70, 71, {'weight': 73}), (71, 72, {'weight': 34}), (72, 73, {'weight': 21}), (72, 74, {'weight': 21}), (71, 76, {'weight': 69}), (76, 77, {'weight': 69}), (77, 81, {'weight': 36}), (80, 81, {'weight': 16}), (81, 82, {'weight': 18}), (82, 83, {'weight': 22}), (80, 83, {'weight': 20}), (83, 85, {'weight': 47}), (84, 85, {'weight': 58}), (78, 84, {'weight': 33}), (78, 79, {'weight': 33}), (79, 80, {'weight': 50}), (75, 76, {'weight': 69}), (77, 384, {'weight': 104}), (384, 119, {'weight': 12}), (119, 382, {'weight': 50}), (384, 383, {'weight': 53}), (382, 381, {'weight': 69}), (75, 381, {'weight': 88}), (381, 118, {'weight': 10}), (118, 380, {'weight': 34}), (379, 380, {'weight': 76}), (118, 386, {'weight': 152}), (385, 386, {'weight': 74}), (66, 385, {'weight': 69}), (66, 67, {'weight': 20}), (66, 64, {'weight': 51}), (64, 65, {'weight': 22}), (63, 64, {'weight': 41}), (75, 385, {'weight': 157}), (71, 66, {'weight': 87}), (62, 67, {'weight': 83}), (67, 68, {'weight': 93}), (382, 383, {'weight': 14}), (372, 383, {'weight': 76}), (379, 377, {'weight': 25}), (377, 378, {'weight': 40}), (386, 378, {'weight': 67}), (378, 375, {'weight': 55}), (375, 376, {'weight': 29}), (343, 375, {'weight': 74}), (374, 375, {'weight': 61}), (374, 344, {'weight': 59}), (374, 373, {'weight': 41}), (373, 345, {'weight': 122}), (373, 372, {'weight': 83}), (343, 345, {'weight': 89}), (343, 376, {'weight': 74}), (112, 376, {'weight': 27}), (112, 375, {'weight': 40}), (112, 342, {'weight': 39}), (341, 342, {'weight': 35}), (340, 341, {'weight': 42}), (342, 387, {'weight': 79}), (387, 388, {'weight': 34}), (388, 389, {'weight': 116}), (388, 391, {'weight': 94}), (391, 392, {'weight': 39}), (371, 372, {'weight': 55}), (370, 371, {'weight': 42}), (367, 372, {'weight': 165}), (371, 346, {'weight': 115}), (345, 346, {'weight': 96}), (346, 347, {'weight': 74}), (347, 117, {'weight': 6}), (117, 352, {'weight': 75}), (346, 351, {'weight': 157}), (366, 352, {'weight': 74}), (351, 352, {'weight': 20}), (366, 358, {'weight': 157}), (368, 359, {'weight': 152}), (359, 360, {'weight': 24}), (360, 361, {'weight': 62}), (361, 362, {'weight': 28}), (361, 126, {'weight': 86}), (125, 126, {'weight': 77}), (102, 125, {'weight': 69}), (126, 124, {'weight': 210}), (126, 127, {'weight': 66}), (127, 128, {'weight': 35}), (127, 360, {'weight': 94}), (358, 359, {'weight': 31}), (357, 358, {'weight': 28}), (356, 357, {'weight': 23}), (355, 356, {'weight': 22}), (354, 355, {'weight': 63}), (353, 354, {'weight': 21}), (353, 364, {'weight': 64}), (364, 365, {'weight': 12}), (357, 363, {'weight': 51}), (351, 241, {'weight': 198}), (241, 242, {'weight': 13}), (128, 242, {'weight': 80}), (363, 242, {'weight': 50}), (366, 367, {'weight': 29}), (367, 369, {'weight': 22}), (368, 369, {'weight': 6}), (366, 368, {'weight': 26}), (120, 369, {'weight': 20}), (120, 401, {'weight': 104}), (120, 410, {'weight': 93}), (401, 410, {'weight': 104}), (410, 411, {'weight': 16}), (416, 411, {'weight': 133}), (393, 416, {'weight': 30}), (93, 416, {'weight': 71}), (393, 394, {'weight': 85}), (97, 394, {'weight': 39}), (394, 418, {'weight': 78}), (98, 395, {'weight': 106}), (395, 396, {'weight': 17}), (396, 399, {'weight': 36}), (399, 400, {'weight': 57}), (125, 400, {'weight': 89}), (398, 400, {'weight': 29}), (397, 398, {'weight': 23}), (396, 397, {'weight': 28}), (398, 399, {'weight': 33}), (418, 405, {'weight': 24}), (405, 406, {'weight': 24}), (406, 408, {'weight': 28}), (418, 407, {'weight': 31}), (407, 408, {'weight': 20}), (408, 409, {'weight': 19}), (393, 409, {'weight': 81}), (409, 412, {'weight': 39}), (412, 413, {'weight': 17}), (413, 414, {'weight': 15}), (402, 414, {'weight': 78}), (402, 403, {'weight': 45}), (403, 404, {'weight': 26}), (404, 412, {'weight': 34}), (403, 406, {'weight': 45}), (362, 402, {'weight': 57}), (401, 402, {'weight': 18}), (400, 362, {'weight': 57}), (397, 405, {'weight': 40}), (411, 413, {'weight': 21}), (101, 102, {'weight': 104}), (102, 105, {'weight': 288}), (109, 123, {'weight': 136}), (123, 131, {'weight': 120}), (123, 124, {'weight': 142}), (124, 129, {'weight': 73}), (129, 130, {'weight': 72}), (130, 131, {'weight': 76}), (130, 242, {'weight': 202}), (130, 132, {'weight': 150}), (114, 121, {'weight': 231}), (121, 141, {'weight': 35}), (121, 122, {'weight': 58}), (122, 140, {'weight': 41}), (240, 241, {'weight': 44}), (239, 240, {'weight': 93}), (240, 282, {'weight': 71}), (282, 281, {'weight': 77}), (281, 280, {'weight': 34}), (281, 286, {'weight': 87}), (286, 285, {'weight': 30}), (280, 285, {'weight': 82}), (239, 280, {'weight': 72}), (282, 283, {'weight': 51}), (283, 284, {'weight': 31}), (350, 283, {'weight': 65}), (350, 287, {'weight': 65}), (287, 286, {'weight': 17}), (285, 289, {'weight': 53}), (289, 301, {'weight': 123}), (301, 303, {'weight': 49}), (303, 302, {'weight': 55}), (303, 346, {'weight': 85}), (287, 288, {'weight': 72}), (350, 349, {'weight': 60}), (349, 348, {'weight': 21}), (350, 351, {'weight': 31}), (239, 132, {'weight': 203}), (132, 133, {'weight': 178}), (133, 135, {'weight': 100}), (134, 135, {'weight': 37}), (135, 136, {'weight': 41}), (135, 140, {'weight': 221}), (138, 139, {'weight': 112}), (139, 140, {'weight': 25}), (140, 141, {'weight': 52}), (141, 142, {'weight': 39}), (142, 144, {'weight': 68}), (143, 144, {'weight': 55}), (144, 145, {'weight': 38}), (136, 137, {'weight': 80}), (136, 183, {'weight': 41}), (183, 181, {'weight': 93}), (181, 182, {'weight': 21}), (182, 184, {'weight': 98}), (183, 184, {'weight': 22}), (184, 148, {'weight': 113}), (184, 185, {'weight': 73}), (183, 189, {'weight': 80}), (148, 149, {'weight': 39}), (149, 150, {'weight': 54}), (150, 154, {'weight': 81}), (154, 158, {'weight': 77}), (158, 159, {'weight': 45}), (157, 158, {'weight': 96}), (156, 157, {'weight': 49}), (155, 156, {'weight': 59}), (152, 156, {'weight': 28}), (152, 153, {'weight': 40}), (153, 154, {'weight': 53}), (149, 153, {'weight': 76}), (148, 151, {'weight': 54}), (151, 152, {'weight': 29}), (185, 150, {'weight': 90}), (185, 186, {'weight': 18}), (186, 187, {'weight': 25}), (187, 188, {'weight': 13}), (188, 189, {'weight': 21}), (142, 181, {'weight': 161}), (182, 144, {'weight': 173}), (189, 185, {'weight': 48}), (147, 148, {'weight': 91}), (146, 147, {'weight': 51}), (301, 304, {'weight': 28}), (304, 321, {'weight': 173}), (320, 321, {'weight': 11}), (320, 325, {'weight': 55}), (323, 325, {'weight': 84}), (322, 323, {'weight': 41}), (325, 326, {'weight': 53}), (324, 326, {'weight': 82}), (316, 320, {'weight': 154}), (315, 316, {'weight': 51}), (316, 317, {'weight': 44}), (317, 318, {'weight': 91}), (317, 328, {'weight': 109}), (328, 333, {'weight': 93}), (326, 327, {'weight': 110}), (315, 329, {'weight': 215}), (329, 330, {'weight': 69}), (330, 390, {'weight': 89}), (330, 337, {'weight': 66}), (332, 337, {'weight': 68}), (332, 331, {'weight': 29}), (328, 331, {'weight': 36}), (331, 334, {'weight': 155}), (326, 334, {'weight': 82}), (334, 335, {'weight': 30}), (332, 335, {'weight': 151}), (336, 339, {'weight': 60}), (339, 340, {'weight': 21}), (340, 376, {'weight': 15}), (337, 341, {'weight': 112}), (337, 338, {'weight': 128}), (335, 339, {'weight': 24}), (319, 320, {'weight': 28}), (307, 319, {'weight': 34}), (306, 307, {'weight': 82}), (305, 319, {'weight': 125}), (307, 308, {'weight': 53}), (308, 309, {'weight': 60}), (309, 310, {'weight': 50}), (309, 311, {'weight': 68}), (308, 312, {'weight': 85}), (314, 316, {'weight': 70}), (299, 301, {'weight': 39}), (299, 300, {'weight': 40}), (298, 299, {'weight': 53}), (298, 297, {'weight': 147}), (294, 297, {'weight': 63}), (294, 295, {'weight': 19}), (295, 296, {'weight': 89}), (296, 266, {'weight': 131}), (266, 265, {'weight': 16}), (265, 264, {'weight': 41}), (264, 267, {'weight': 120}), (289, 290, {'weight': 86}), (290, 291, {'weight': 102}), (291, 292, {'weight': 30}), (292, 293, {'weight': 42}), (293, 294, {'weight': 37}), (270, 295, {'weight': 184}), (296, 268, {'weight': 128}), (267, 268, {'weight': 37}), (268, 269, {'weight': 66}), (269, 270, {'weight': 26}), (270, 271, {'weight': 15}), (271, 272, {'weight': 28}), (272, 273, {'weight': 14}), (273, 274, {'weight': 27}), (274, 247, {'weight': 39}), (247, 246, {'weight': 39}), (245, 246, {'weight': 29}), (245, 244, {'weight': 31}), (244, 243, {'weight': 22}), (239, 243, {'weight': 73}), (244, 279, {'weight': 110}), (278, 279, {'weight': 58}), (290, 279, {'weight': 96}), (277, 278, {'weight': 46}), (277, 291, {'weight': 97}), (277, 247, {'weight': 107}), (246, 278, {'weight': 104}), (274, 275, {'weight': 78}), (272, 293, {'weight': 196}), (292, 276, {'weight': 89}), (262, 266, {'weight': 88}), (262, 263, {'weight': 38}), (261, 262, {'weight': 74}), (260, 261, {'weight': 43}), (259, 260, {'weight': 28}), (256, 259, {'weight': 81}), (258, 259, {'weight': 34}), (258, 257, {'weight': 53}), (257, 265, {'weight': 74}), (254, 257, {'weight': 89}), (254, 255, {'weight': 37}), (254, 253, {'weight': 49}), (254, 252, {'weight': 74}), (252, 264, {'weight': 51}), (252, 227, {'weight': 69}), (226, 227, {'weight': 40}), (227, 228, {'weight': 137}), (228, 229, {'weight': 128}), (229, 230, {'weight': 67}), (230, 231, {'weight': 64}), (231, 232, {'weight': 69}), (228, 267, {'weight': 100}), (251, 269, {'weight': 72}), (250, 271, {'weight': 107}), (250, 229, {'weight': 28}), (223, 229, {'weight': 118}), (223, 224, {'weight': 38}), (224, 225, {'weight': 141}), (224, 228, {'weight': 106}), (225, 227, {'weight': 88}), (220, 221, {'weight': 65}), (221, 222, {'weight': 84}), (222, 223, {'weight': 66}), (223, 217, {'weight': 107}), (217, 218, {'weight': 47}), (218, 219, {'weight': 36}), (218, 415, {'weight': 88}), (216, 217, {'weight': 72}), (215, 216, {'weight': 83}), (222, 216, {'weight': 90}), (215, 221, {'weight': 79}), (221, 230, {'weight': 66}), (230, 249, {'weight': 93}), (248, 249, {'weight': 64}), (248, 231, {'weight': 105}), (247, 248, {'weight': 52}), (273, 249, {'weight': 50}), (220, 231, {'weight': 53}), (213, 220, {'weight': 72}), (213, 214, {'weight': 30}), (213, 232, {'weight': 42}), (232, 245, {'weight': 171}), (243, 237, {'weight': 55}), (237, 238, {'weight': 77}), (237, 236, {'weight': 54}), (212, 236, {'weight': 102}), (212, 211, {'weight': 20}), (235, 236, {'weight': 91}), (235, 238, {'weight': 55}), (238, 239, {'weight': 55}), (234, 235, {'weight': 33}), (234, 233, {'weight': 59}), (233, 211, {'weight': 50}), (212, 213, {'weight': 52}), (214, 215, {'weight': 141}), (210, 211, {'weight': 35}), (209, 210, {'weight': 68}), (209, 208, {'weight': 22}), (208, 207, {'weight': 10}), (207, 206, {'weight': 16}), (206, 205, {'weight': 19}), (205, 204, {'weight': 30}), (205, 194, {'weight': 66}), (206, 193, {'weight': 47}), (192, 207, {'weight': 66}), (191, 209, {'weight': 64}), (116, 191, {'weight': 17}), (190, 116, {'weight': 13}), (116, 192, {'weight': 82}), (192, 193, {'weight': 55}), (188, 190, {'weight': 103}), (193, 194, {'weight': 69}), (194, 195, {'weight': 105}), (203, 204, {'weight': 122}), (203, 195, {'weight': 63}), (202, 203, {'weight': 39}), (202, 201, {'weight': 87}), (201, 200, {'weight': 97}), (202, 196, {'weight': 58}), (195, 196, {'weight': 40}), (196, 197, {'weight': 85}), (197, 198, {'weight': 94}), (198, 200, {'weight': 25}), (199, 200, {'weight': 64}), (198, 177, {'weight': 48}), (197, 201, {'weight': 47}), (176, 177, {'weight': 93}), (176, 197, {'weight': 55}), (176, 178, {'weight': 33}), (178, 179, {'weight': 56}), (178, 180, {'weight': 46}), (175, 176, {'weight': 86}), (174, 175, {'weight': 40}), (175, 196, {'weight': 56}), (173, 174, {'weight': 69}), (174, 195, {'weight': 56}), (172, 173, {'weight': 116}), (173, 169, {'weight': 62}), (169, 170, {'weight': 52}), (170, 171, {'weight': 76}), (168, 169, {'weight': 123}), (168, 172, {'weight': 65}), (187, 172, {'weight': 104}), (172, 193, {'weight': 60}), (166, 170, {'weight': 98}), (166, 167, {'weight': 20}), (165, 166, {'weight': 33}), (165, 168, {'weight': 51}), (186, 165, {'weight': 133}), (150, 165, {'weight': 113}), (165, 163, {'weight': 90}), (163, 164, {'weight': 39}), (164, 167, {'weight': 70}), (161, 164, {'weight': 102}), (163, 160, {'weight': 109}), (154, 163, {'weight': 104}), (167, 162, {'weight': 164}), (314, 313, {'weight': 58})])
# Define nodes gps coords for plotting
nodes_coords = [[2.2562154, 48.9010192], [2.2552395, 48.9016349], [2.2561504, 48.9019072], [2.256213, 48.9023117], [2.2533483, 48.9022124], [2.2560583, 48.9031052], [2.2526502, 48.9024669], [2.2529865, 48.9025795], [2.2539978, 48.9033062], [2.254378, 48.90346], [2.2559377, 48.9039617], [2.2512099, 48.9031913], [2.2522591, 48.9034114], [2.2532497, 48.9037264], [2.2542639, 48.9040196], [2.255091, 48.9043102], [2.2558433, 48.904568], [2.2496848, 48.903958], [2.2506347, 48.9041945], [2.2516522, 48.9044511], [2.252662, 48.9046991], [2.2536487, 48.9049375], [2.2546109, 48.9051719], [2.2549951, 48.905281], [2.2557699, 48.9052503], [2.2560158, 48.9052059], [2.2562064, 48.9055009], [2.2558068, 48.9056019], [2.2557576, 48.9060545], [2.2555949, 48.9054919], [2.2550966, 48.9054932], [2.2556871, 48.9064052], [2.2550969, 48.9062517], [2.2533605, 48.9057877], [2.2531638, 48.9057675], [2.2527857, 48.9058181], [2.2527457, 48.9056766], [2.2511718, 48.9052887], [2.2497184, 48.9049283], [2.2507196, 48.9060941], [2.2496744, 48.9057506], [2.2495699, 48.9062557], [2.2513712, 48.9071609], [2.2526377, 48.9067325], [2.2532956, 48.9069103], [2.2522934, 48.907371], [2.2519614, 48.9079488], [2.2532156, 48.9082075], [2.2538981, 48.9083691], [2.2542177, 48.9078397], [2.2554719, 48.9081671], [2.2525332, 48.9090399], [2.2534123, 48.90925], [2.2530558, 48.9098965], [2.25506, 48.90965], [2.255269, 48.9089348], [2.2540012, 48.9107575], [2.2540107, 48.9110728], [2.2546194, 48.9112061], [2.2543603, 48.9116704], [2.2547269, 48.9108195], [2.2564689, 48.91308], [2.2573643, 48.9135046], [2.2578772, 48.9133618], [2.2581772, 48.9133246], [2.2578468, 48.9129075], [2.2575729, 48.9129246], [2.2566296, 48.9123618], [2.2565339, 48.9123161], [2.2568035, 48.9122761], [2.2577766, 48.9121258], [2.2582331, 48.9120772], [2.2585157, 48.9120658], [2.2582288, 48.9118886], [2.2586523, 48.9114136], [2.2577236, 48.9115026], [2.2576733, 48.9108796], [2.2566948, 48.9116761], [2.2570773, 48.9115161], [2.2570686, 48.9110647], [2.2571947, 48.9109475], [2.2570307, 48.9108279], [2.2568339, 48.9109761], [2.2562731, 48.9115704], [2.2562035, 48.9110504], [2.2555558, 48.9111047], [2.255594, 48.9108279], [2.2571386, 48.9104589], [2.2558423, 48.9102656], [2.2559971, 48.9097697], [2.2564539, 48.9091764], [2.2566337, 48.909212], [2.2574349, 48.9093881], [2.2575482, 48.9090306], [2.2569313, 48.9089723], [2.2566629, 48.9085482], [2.2576685, 48.9086267], [2.2580299, 48.9069557], [2.2580295, 48.9069669], [2.2581246, 48.9065475], [2.2582265, 48.9060973], [2.2595008, 48.9065057], [2.2576214, 48.9036038], [2.258192, 48.9030371], [2.2608928, 48.9040789], [2.2585407, 48.9027078], [2.2611337, 48.903683], [2.2590035, 48.9023244], [2.2615141, 48.9031121], [2.2593649, 48.9019535], [2.2599979, 48.9013088], [2.2612097, 48.9125436], [2.260279, 48.9009098], [2.2603523, 48.9014573], [2.2598385, 48.902108], [2.2674267, 48.9046065], [2.2631137, 48.9096459], [2.2598567, 48.9113223], [2.2591258, 48.9108471], [2.2616782, 48.9090033], [2.2631586, 48.9024119], [2.2628072, 48.90288], [2.2630198, 48.9038252], [2.2623468, 48.9050269], [2.2604064, 48.906693], [2.2614383, 48.9068184], [2.2623244, 48.9069216], [2.262792, 48.9069735], [2.2633002, 48.9052333], [2.2642648, 48.9053513], [2.2640068, 48.9046878], [2.2662902, 48.9055766], [2.2673633, 48.9041359], [2.2659173, 48.9040821], [2.2661083, 48.9037712], [2.2664721, 48.9034902], [2.2654807, 48.9031913], [2.264644, 48.9035978], [2.2632434, 48.9031973], [2.2633401, 48.9029807], [2.2635971, 48.9025452], [2.2637881, 48.9022197], [2.263517, 48.9014261], [2.2641711, 48.9016668], [2.2644167, 48.9013619], [2.2659446, 48.9014456], [2.2665042, 48.9017256], [2.2675759, 48.9021491], [2.2680658, 48.9022883], [2.2686981, 48.9025468], [2.2677508, 48.901677], [2.2680723, 48.9015171], [2.2685604, 48.9016879], [2.2692138, 48.9019026], [2.2675292, 48.9009815], [2.2682062, 48.9012765], [2.2685407, 48.9008935], [2.2697018, 48.9012894], [2.2699891, 48.9009349], [2.2710794, 48.9014187], [2.271658, 48.9016826], [2.2727461, 48.9028625], [2.2704859, 48.9023202], [2.2709616, 48.9024744], [2.2700183, 48.9030713], [2.2704252, 48.9032074], [2.270521, 48.9030343], [2.2697773, 48.9034972], [2.2712268, 48.9040632], [2.2715847, 48.9036559], [2.2724917, 48.903983], [2.2694406, 48.9040422], [2.2708196, 48.9045498], [2.2716365, 48.9048681], [2.2721175, 48.9050445], [2.2731382, 48.9054236], [2.274212, 48.9058739], [2.273371, 48.9051651], [2.274031, 48.905418], [2.2736921, 48.9048041], [2.2657764, 48.9028344], [2.2659614, 48.9026847], [2.2668887, 48.9032382], [2.2671231, 48.9031211], [2.2681017, 48.9032536], [2.2682582, 48.9033777], [2.2681951, 48.903597], [2.2680666, 48.9036817], [2.2677938, 48.9036361], [2.2673991, 48.9044948], [2.2675058, 48.9047469], [2.2684708, 48.9043492], [2.269155, 48.9045468], [2.2699618, 48.9048639], [2.2712455, 48.9052976], [2.2717233, 48.9054723], [2.272744, 48.9058413], [2.2738731, 48.9062439], [2.2745752, 48.9065469], [2.273713, 48.9064429], [2.2724316, 48.9062142], [2.2713243, 48.905923], [2.270826, 48.905793], [2.2693245, 48.9053044], [2.2691194, 48.9050719], [2.2689375, 48.9049471], [2.26872, 48.9049211], [2.2686013, 48.9049653], [2.2683007, 48.9049965], [2.2679048, 48.9055527], [2.2679447, 48.9058675], [2.2681243, 48.9060031], [2.2687562, 48.9062129], [2.2690023, 48.9059987], [2.2709032, 48.9062137], [2.2719633, 48.9064763], [2.2729046, 48.9066791], [2.2735216, 48.906783], [2.2733397, 48.9070794], [2.2695981, 48.9065442], [2.2703734, 48.9068299], [2.2713859, 48.9071938], [2.2721611, 48.9075058], [2.2726171, 48.9076682], [2.2743091, 48.908283], [2.2741894, 48.9090284], [2.2736517, 48.9089442], [2.2719104, 48.9084966], [2.2705944, 48.9077431], [2.2699098, 48.9073435], [2.2692446, 48.9069632], [2.2685289, 48.9065601], [2.2672885, 48.9059808], [2.2665336, 48.9061732], [2.2663407, 48.9064377], [2.2674448, 48.9068071], [2.2670989, 48.9072378], [2.2661648, 48.9069225], [2.2658755, 48.9073837], [2.2646118, 48.9072657], [2.2640264, 48.9071848], [2.2638568, 48.9071498], [2.2667601, 48.9076832], [2.2670129, 48.9077859], [2.267392, 48.9079083], [2.2677347, 48.9080464], [2.2682086, 48.9082068], [2.2685359, 48.9077867], [2.2692974, 48.9080752], [2.2702284, 48.9078244], [2.2704685, 48.9082794], [2.2730951, 48.9094461], [2.2743286, 48.9094969], [2.2739111, 48.9098387], [2.2743133, 48.9100381], [2.273694, 48.910819], [2.2731767, 48.910479], [2.272831, 48.9108932], [2.2727534, 48.9111977], [2.2727417, 48.911445], [2.2722382, 48.9116514], [2.2721749, 48.9109912], [2.2716607, 48.9110588], [2.2726719, 48.9098062], [2.2723442, 48.9101019], [2.2721867, 48.9102008], [2.2712374, 48.9092823], [2.2707741, 48.9091386], [2.2699911, 48.9088482], [2.269676, 48.9087415], [2.2695043, 48.9086658], [2.2691657, 48.9085576], [2.2690081, 48.9084865], [2.2686766, 48.9083768], [2.2684112, 48.9090522], [2.2682322, 48.9093352], [2.2679432, 48.9091509], [2.2673895, 48.9089533], [2.2666618, 48.9087454], [2.2657314, 48.9080209], [2.2652728, 48.9079841], [2.2642436, 48.9078518], [2.2641038, 48.9083003], [2.2645233, 48.9083297], [2.2654909, 48.9087377], [2.2650826, 48.9087598], [2.2648477, 48.9087818], [2.2646743, 48.9094215], [2.2653231, 48.9091972], [2.2663454, 48.9095824], [2.2675951, 48.9099931], [2.2679669, 48.9101127], [2.2684889, 48.9102634], [2.2689398, 48.9104142], [2.2691929, 48.9103674], [2.2704031, 48.9102634], [2.268133, 48.9106117], [2.266116, 48.9105857], [2.2654515, 48.9103986], [2.2655702, 48.910045], [2.2649532, 48.910279], [2.2643667, 48.9097486], [2.2642828, 48.9102412], [2.2647414, 48.9104875], [2.2653231, 48.9108514], [2.2658544, 48.9111381], [2.2659903, 48.9118675], [2.2666964, 48.911759], [2.2674906, 48.911633], [2.2681547, 48.911525], [2.2675522, 48.9122404], [2.2667854, 48.9125239], [2.2662651, 48.9127309], [2.2663336, 48.9132483], [2.2654573, 48.9138647], [2.2654093, 48.9134058], [2.2648206, 48.9134688], [2.264711, 48.9126499], [2.2655463, 48.9119615], [2.2651766, 48.9120335], [2.2650328, 48.912029], [2.2643334, 48.9109694], [2.264285, 48.9113353], [2.2635177, 48.9114514], [2.2644235, 48.912083], [2.2637089, 48.9121768], [2.2638868, 48.9131596], [2.2633592, 48.9136496], [2.2625931, 48.914287], [2.2616662, 48.9143797], [2.2628752, 48.9136949], [2.262475, 48.9137271], [2.2631873, 48.912824], [2.2626075, 48.9123158], [2.2622102, 48.912382], [2.261987, 48.9129747], [2.2615453, 48.9137895], [2.2597952, 48.9137838], [2.2618976, 48.9124362], [2.2616237, 48.9124767], [2.2613122, 48.9127984], [2.260833, 48.9127939], [2.2620653, 48.9118306], [2.2619261, 48.9115686], [2.2626904, 48.9111419], [2.2631283, 48.9103252], [2.2631915, 48.9096595], [2.264121, 48.9094753], [2.2638475, 48.9094188], [2.2639647, 48.9088819], [2.263549, 48.9089396], [2.2632847, 48.9089795], [2.2634289, 48.9085191], [2.2631399, 48.9084874], [2.2633015, 48.9079316], [2.2630093, 48.9078815], [2.2630574, 48.9076736], [2.2626826, 48.9077091], [2.2622566, 48.9077451], [2.2619322, 48.9077271], [2.2611271, 48.9075653], [2.2608027, 48.9076911], [2.2637496, 48.907593], [2.2635595, 48.9079466], [2.2637069, 48.9079082], [2.2622918, 48.9090983], [2.26203, 48.9092935], [2.2619401, 48.9090983], [2.2618736, 48.9091266], [2.2616389, 48.9100996], [2.2615685, 48.9104721], [2.2608181, 48.9105465], [2.2610331, 48.9112761], [2.2611308, 48.9116434], [2.261205, 48.9121854], [2.2614834, 48.9123754], [2.2606032, 48.9121648], [2.2606618, 48.9125244], [2.260271, 48.9121288], [2.2602827, 48.911443], [2.2598567, 48.9114096], [2.2598059, 48.9107931], [2.259802, 48.9106698], [2.2590789, 48.9107418], [2.2587819, 48.9128198], [2.2597746, 48.9126914], [2.2599935, 48.9132462], [2.2596456, 48.9134491], [2.2589304, 48.9143764], [2.2604515, 48.9144591], [2.2584497, 48.913765], [2.2579142, 48.9137599], [2.2586938, 48.9091509], [2.2581521, 48.9084752], [2.2588707, 48.9077377], [2.2590973, 48.9077195], [2.2594786, 48.9076941], [2.2597218, 48.9075633], [2.2593184, 48.9074253], [2.2600977, 48.9074689], [2.2608768, 48.9082346], [2.2606398, 48.9081958], [2.2600977, 48.9083957], [2.2598916, 48.9085872], [2.2593847, 48.9080465], [2.2595223, 48.9082404], [2.2592447, 48.9084144], [2.2594851, 48.9084943], [2.2595212, 48.9086655], [2.2604166, 48.9091216], [2.2601929, 48.9091362], [2.2599347, 48.9088928], [2.260161, 48.908944], [2.2603271, 48.9088699], [2.2747081, 48.9069078], [2.2584055, 48.9093463], [2.2557686, 48.912472], [2.2590996, 48.9081554]]
# Define path we want to aniate as a list of nodes to travel through
path = [102, 125, 126, 124, 129, 130, 131, 123, 109, 123, 124, 126, 125, 400, 398, 397, 405, 406, 403, 404, 412, 413, 414, 402, 403, 406, 408, 409, 408, 407, 418, 405, 418, 394, 393, 409, 412, 413, 411, 416, 411, 410, 401, 410, 120, 369, 368, 359, 368, 366, 358, 357, 356, 355, 354, 353, 364, 365, 364, 353, 354, 355, 356, 357, 358, 357, 363, 242, 241, 351, 350, 349, 348, 349, 350, 287, 288, 287, 286, 281, 286, 285, 280, 281, 282, 240, 282, 283, 284, 283, 350, 351, 352, 351, 241, 240, 239, 238, 235, 234, 233, 211, 210, 209, 191, 116, 190, 188, 190, 116, 192, 193, 194, 205, 194, 195, 174, 173, 169, 168, 165, 163, 160, 163, 165, 166, 165, 186, 165, 150, 149, 153, 152, 153, 154, 163, 164, 161, 164, 167, 162, 167, 166, 170, 171, 170, 169, 168, 172, 173, 174, 175, 176, 178, 180, 178, 179, 178, 176, 177, 198, 200, 199, 200, 198, 197, 176, 175, 196, 197, 201, 200, 201, 202, 203, 202, 196, 195, 203, 204, 205, 206, 207, 192, 116, 191, 209, 210, 211, 212, 236, 235, 238, 237, 243, 237, 236, 212, 213, 214, 215, 216, 215, 221, 220, 231, 248, 231, 220, 213, 232, 231, 232, 245, 232, 213, 212, 211, 210, 209, 208, 207, 206, 193, 172, 187, 188, 189, 188, 187, 186, 187, 186, 185, 150, 154, 158, 159, 158, 157, 156, 155, 156, 152, 151, 148, 147, 146, 147, 148, 149, 148, 184, 185, 189, 183, 184, 182, 181, 182, 144, 145, 144, 143, 144, 142, 141, 142, 181, 183, 136, 137, 136, 135, 134, 135, 140, 139, 138, 139, 140, 122, 121, 114, 111, 113, 111, 110, 115, 114, 121, 141, 140, 135, 133, 132, 239, 243, 244, 279, 278, 246, 278, 277, 291, 277, 247, 248, 249, 273, 249, 230, 231, 230, 221, 222, 216, 217, 218, 415, 218, 219, 218, 217, 223, 222, 223, 224, 223, 229, 230, 229, 228, 224, 225, 227, 228, 229, 250, 271, 272, 273, 274, 275, 274, 247, 246, 245, 244, 279, 290, 289, 290, 291, 292, 276, 292, 293, 294, 293, 272, 271, 270, 295, 270, 269, 251, 269, 268, 267, 228, 227, 226, 227, 252, 264, 252, 254, 253, 254, 255, 254, 257, 265, 257, 258, 259, 256, 259, 260, 261, 262, 263, 262, 266, 265, 264, 267, 268, 296, 266, 296, 295, 294, 297, 298, 299, 300, 299, 301, 303, 302, 303, 346, 351, 352, 366, 352, 117, 347, 346, 345, 346, 371, 370, 371, 372, 367, 369, 120, 401, 402, 362, 361, 126, 127, 360, 127, 128, 242, 130, 132, 239, 280, 285, 289, 301, 304, 321, 320, 319, 305, 319, 307, 308, 312, 308, 309, 311, 309, 310, 309, 308, 307, 306, 307, 319, 320, 316, 314, 313, 314, 316, 317, 318, 317, 328, 333, 328, 331, 334, 335, 332, 331, 334, 326, 327, 326, 324, 326, 325, 323, 322, 323, 325, 320, 316, 315, 329, 330, 390, 330, 337, 338, 337, 341, 337, 332, 335, 339, 336, 339, 340, 341, 342, 387, 388, 391, 392, 391, 388, 389, 388, 387, 342, 112, 342, 341, 340, 376, 112, 375, 374, 344, 374, 373, 372, 373, 345, 343, 375, 343, 376, 375, 378, 386, 378, 377, 379, 380, 118, 381, 118, 386, 385, 66, 64, 63, 64, 65, 64, 66, 67, 62, 67, 68, 70, 78, 79, 80, 81, 80, 83, 85, 84, 78, 70, 71, 72, 74, 72, 73, 72, 71, 66, 385, 75, 76, 75, 381, 382, 383, 382, 119, 384, 77, 81, 82, 83, 85, 86, 87, 86, 59, 58, 59, 57, 59, 60, 59, 61, 87, 82, 88, 93, 416, 393, 394, 97, 94, 95, 92, 93, 88, 89, 90, 55, 61, 59, 69, 417, 69, 68, 70, 71, 76, 77, 384, 383, 372, 367, 366, 358, 359, 360, 361, 362, 400, 399, 398, 397, 396, 399, 396, 395, 98, 99, 98, 97, 94, 93, 92, 91, 96, 91, 56, 51, 56, 55, 53, 54, 53, 52, 53, 49, 48, 49, 50, 46, 47, 46, 43, 46, 44, 45, 44, 35, 36, 40, 42, 40, 41, 40, 38, 39, 38, 37, 36, 37, 38, 20, 19, 18, 19, 12, 13, 20, 21, 14, 21, 22, 35, 34, 33, 50, 51, 32, 99, 100, 101, 27, 28, 29, 28, 30, 31, 30, 25, 26, 27, 26, 103, 26, 25, 17, 11, 17, 16, 23, 22, 15, 10, 9, 10, 11, 6, 5, 8, 7, 8, 13, 14, 15, 16, 23, 24, 31, 34, 33, 32, 29, 100, 101, 102, 105, 107, 106, 107, 109, 108, 110, 108, 106, 104, 103, 6, 4, 3, 2, 3, 1, 3, 4, 104, 105, 102]
#path = [102, 125, 126, 127, 128, 242] # simpler path for testing
# SIMPLE graph definition (for testing)
#G = nx.Graph()
#G.add_edges_from([(1,2, {'weight': 1}), (3,4, {'weight': 1}), (2,5, {'weight': 1}), (4,5, {'weight': 1}), (6,7, {'weight': 1}), (8,9, {'weight': 1}), (4,7, {'weight': 1}), (1,7, {'weight': 1}), (3,5, {'weight': 1}), (2,7, {'weight': 1}), (5,8, {'weight': 1}), (2,9, {'weight': 1}), (5,1, {'weight': 1})])
#nodes_coords = [[1,2], [1,5], [6,5], [3,5], [4,1], [6,2], [2,8], [3,3], [2,5]]
#path = [6, 7, 2, 9, 8, 5, 2, 1, 5, 3, 4, 7, 1, 5, 4]
# Define the list of edges and store nodes coords as a parameter
edges = [e for e in G.edges]
for u, v in enumerate(nodes_coords):
G.nodes[u+1]['pos'] = (v[0], v[1])
# Draw the graph before animating the path
edges_color = ["#d9d9d9" for u in G.edges]
nodes_color = ["#a7a7a7" for u in G.nodes]
nx.draw(G, nx.get_node_attributes(G, 'pos'), node_size=140, font_size=6, width=2, node_color=nodes_color, edge_color=edges_color)
#nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, node_size=140, font_size=6, width=2, node_color=nodes_color, edge_color=edges_color) # with nodes labels -> much slower
fig = plt.gcf()
# Animation function
def animate(frame):
global nodes_color, edges_color
# Color in red the currently visited path node
nodes_color = ["red" if (u == path[frame]) else "#a7a7a7" for u in G.nodes]
# Set the new visited edge of the path in green (cumulative coloring of what has been visited)
if (frame > 0):
try:
edges_color[edges.index((min(path[frame-1],path[frame]), max(path[frame-1],path[frame])))] = "green"
except ValueError:
edges_color[edges.index((max(path[frame-1],path[frame]), min(path[frame-1],path[frame])))] = "green"
else:
time.sleep(3) # to allow me to increase the the matplotlib graph window before starting to draw the path
edges_color = ["#d9d9d9" for u in G.edges] # all edges in grey before showing the circuit in green
nx.draw(G, nx.get_node_attributes(G, 'pos'), node_size=140, font_size=6, width=2, node_color=nodes_color, edge_color=edges_color)
#plt.savefig("graph-" + str(frame) + ".jpg", quality=100, optimize=True,) # save image of the current graph - for testing
#nx.draw(G, nx.get_node_attributes(G, 'pos'), with_labels=True, node_size=140, font_size=6, width=2, node_color=nodes_color, edge_color=edges_color) # with nodes labels -> much slower
anim = animation.FuncAnimation(fig, animate, frames=len(path), interval=200, blit=False, repeat=False, cache_frame_data=False)
plt.show()
</code></pre>
<p>If you want to test with a simpler graph/path, you can comment the first block "Define Graph" and uncomment the next one "SIMPLE graph definition (for testing)".</p>
<p>Here is how smooth it looks with this small test graph and path:
<a href="https://i.stack.imgur.com/1SI6Z.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1SI6Z.gif" alt="enter image description here" /></a></p>
<p>For the big graph/path, I cannot save it to show you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T22:25:45.820",
"Id": "507778",
"Score": "0",
"body": "Recently I also needed to make some animations in matplotlib and ended up simply saving the frames of choice to later merge them with 3rd party software. I found that extremely efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T23:52:10.357",
"Id": "507784",
"Score": "0",
"body": "Thanks for the feedback @KaPy3141, I agree. More control. That's what I've done with Photoshop and I could control the speed, quality and format. The issue is that it took 3hrs for my code to display my animation (and therefore obtain the frames)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:06:02.263",
"Id": "507786",
"Score": "0",
"body": "How many frames do you need to generate? Recently, I generated 10000 frames in just some minutes, while my plots must have been way more complex (3d plots)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:07:10.790",
"Id": "507787",
"Score": "0",
"body": "Wait, I get the problem: You must specify the size and resolution! Just make the pictures smaller!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:08:03.287",
"Id": "507788",
"Score": "0",
"body": "And check the speed of your script without plotting, just in case..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T18:22:22.893",
"Id": "257107",
"Score": "2",
"Tags": [
"python",
"performance",
"graph",
"animation",
"matplotlib"
],
"Title": "Slow render of a graph path using python matplotlib animation"
}
|
257107
|
<p>I've written a program that finds the difference between data and gives output.
Here's the code:</p>
<pre class="lang-py prettyprint-override"><code>import json
import numpy as np
print("This is a basic machine learning thing.")
baseData = {"collecting":True,"x":[],"y":[]}
while baseData["collecting"]:
baseData["x"].append(float(input("X:")))
baseData["y"].append(float(input("Y:")))
if input("Do you want to keep feeding data? Press enter for yes, or type anything for no.") != "":
baseData["collecting"] = False
if len(baseData["x"]) == len(baseData["y"]):
xdata = baseData["x"]
ydata = baseData["y"]
nums = []
for i in range(len(xdata)):
nums.append(xdata[i] - ydata[i])
median = np.median(nums)
else:
print("malformed data")
def getY(x):
pass
while True:
data = input("X/Data:")
print(int(data)-median)
</code></pre>
<p>To work the program, give it X and Y data, then give it X data and it will predict Y data.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T22:16:33.157",
"Id": "507776",
"Score": "0",
"body": "Do you have a particular question or concern with your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T22:43:24.350",
"Id": "507780",
"Score": "0",
"body": "@KaPy3141 I want to know some ways I can improve or minify this code."
}
] |
[
{
"body": "<p>Maybe you should check validity of the input and ask again if input is wrong?</p>\n<pre><code>while baseData["collecting"]:\n baseData["x"].append(float(input("X:")))\n</code></pre>\n<p>This is always True, so just discard this part:</p>\n<pre><code>if len(baseData["x"]) == len(baseData["y"]):\n</code></pre>\n<p>Maybe you should give an option to exit?</p>\n<pre><code>while True:\n data = input("X/Data:")\n print(int(data)-median)\n</code></pre>\n<p>And in general, calling this a "machiene-learning thing" is quite a stretch of imagination, no? Maybe you should have a look at how to fit data. I.e. a basic linear model fit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T23:48:03.227",
"Id": "257119",
"ParentId": "257111",
"Score": "2"
}
},
{
"body": "<p><code>baseData</code> should be split into 3 separate variables(<code>collecting</code>, <code>xdata</code>, <code>ydata</code>); there is no reason for it to be a dict.</p>\n<pre><code>nums = []\nfor i in range(len(xdata)):\n nums.append(xdata[i] - ydata[i])\n</code></pre>\n<p>can be written more Pythonically as:</p>\n<pre><code>nums = []\nfor x, y in zip(xdata, ydata):\n nums.append(x - y)\n</code></pre>\n<p>or even just:</p>\n<pre><code>nums = [x - y for x, y in zip(xdata, ydata)]\n</code></pre>\n<p>You don't need to import numpy only for the media; stdlib <code>statistics.median</code> should work just fine.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:30:00.837",
"Id": "257125",
"ParentId": "257111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T20:37:41.530",
"Id": "257111",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"machine-learning"
],
"Title": "Machine Learning Program"
}
|
257111
|
<p>First of all, I am here to explore unsafe features of Rust, if you are the kind of guy who likes "safe" Rust and will start nagging about using safe features of Rust I will still happily read your comment and learn about the safe alternatives.</p>
<p>That said, I am looking to enhance my knowledge about <strong>unsafe Rust</strong>. The documentation is very scarce and not very well documented. Little by little, thanks to help from Stack Overflow users (especially @kmdreko) and my perseverance I was able to make it work. My program is able
to send large files (4Gb) over UDP.</p>
<p>As I always look to improve the quality of my code I wonder if someone could take a look at <a href="https://github.com/agavrel/rust_udp_server_client" rel="nofollow noreferrer">my source code</a> and let me know how I could improve it.</p>
<hr />
<h3>server.rs</h3>
<pre class="lang-rs prettyprint-override"><code>const UDP_HEADER: usize = 8;
const IP_HEADER: usize = 20;
const AG_HEADER: usize = 4;
const MAX_CHUNK_SIZE: usize = (64 * 1024 - 1) - UDP_HEADER - IP_HEADER - AG_HEADER;
use std::net::UdpSocket;
use std::io;
use std::fs::File;
use std::io::prelude::*;
use std::alloc::{alloc, dealloc, Layout};
use std::mem;
use std::{mem::MaybeUninit};
// cmp -l 1.jpg 2.jpg
#[inline(always)]
fn memcpy(dst_ptr:*mut u8, src_ptr:*const u8, len:usize) {
unsafe {
std::ptr::copy_nonoverlapping(src_ptr, dst_ptr, len);
}
}
#[inline(always)]
fn next_power_of_two(n:u32) -> u32 {
return 32 - (n - 1).leading_zeros();
}
#[inline(always)]
fn write_chunks_to_file(filename: &str, bytes:&[u8]) -> Result<bool, io::Error> {
let mut file = File::create(filename)?;
file.write_all(bytes)?;
Ok(true)
}
use std::thread;
fn main() {
let socket = UdpSocket::bind("0.0.0.0:8888").expect("Could not bind socket");
let filename = "2.jpg";
let mut count = 0;
let mut chunks_cnt:u32 = 0xffff;
let mut total_size:usize = 0;
let mut layout;
unsafe { layout = MaybeUninit::<Layout>::uninit().assume_init(); };
let mut bytes_buf;
unsafe { bytes_buf = MaybeUninit::<*mut u8>::uninit().assume_init(); };
loop {
let mut buf = [0u8; MAX_CHUNK_SIZE + AG_HEADER];
let sock = socket.try_clone().expect("Failed to clone socket");
match socket.recv_from(&mut buf) {
Ok((size, src)) => { // thanks https://doc.rust-lang.org/beta/std/net/struct.UdpSocket.html#method.recv_from
total_size += size;
let packet_index:usize = (buf[0] as usize) << 8 | buf[1] as usize;
if count == 0 {
chunks_cnt = (buf[2] as u32) << 8 | buf[3] as u32;
let n:usize = 0x10000 << next_power_of_two(chunks_cnt);
// assert_eq!(n.count_ones(), 1); // can check with this function that n is aligned on power of 2
unsafe {
layout = Layout::from_size_align_unchecked(n, mem::align_of::<u8>());
bytes_buf = alloc(layout);
}
}
unsafe {
let dst_ptr = bytes_buf.offset((packet_index*MAX_CHUNK_SIZE) as isize);
memcpy(dst_ptr, &buf[AG_HEADER], size-AG_HEADER);
};
thread::spawn(move || {
//let s = String::from_utf8_lossy(&buf);
println!("receiving packet {} from: {}", packet_index, src);
sock.send_to(&buf, &src).expect("Failed to send a response");
});
println!("count: {}", count);
count+=1;
}
Err(e) => {
eprintln!("couldn't recieve a datagram: {}", e);
}
}
if count == chunks_cnt { // all chunks have been collected, write bytes to file
let bytes = unsafe { std::slice::from_raw_parts(bytes_buf, total_size) };
let result = write_chunks_to_file(filename, &bytes);
match result {
Ok(true) => println!("Succesfully created file: {}", true),
Ok(false) => println!("Could not create file: {}", false),
Err(e) => println!("Error: {}", e),
}
count = 0;
total_size = 0;
unsafe { dealloc(bytes_buf, layout); }
}
}
}
</code></pre>
<hr />
<h3>client.rs</h3>
<pre class="lang-rs prettyprint-override"><code>const UDP_HEADER: usize = 8;
const IP_HEADER: usize = 20;
const AG_HEADER: usize = 4;
const MAX_DATA_LENGTH: usize = (64 * 1024 - 1) - UDP_HEADER - IP_HEADER;
use std::io::Read;
use std::net::UdpSocket;
use std::io;
pub fn get_chunks_from_file(mut filename: String,total_size: &mut usize) -> Result<Vec<Vec<u8>>, io::Error> {
filename.pop(); // get read of the trailing '\n' in user input.
let mut file = std::fs::File::open(filename)?;
let mut list_of_chunks = Vec::new();
let chunk_size = MAX_DATA_LENGTH - AG_HEADER;
loop {
let mut chunk = Vec::with_capacity(chunk_size);
let n = file
.by_ref()
.take(chunk_size as u64)
.read_to_end(&mut chunk)?;
*total_size += n;
if n == 0 {
break;
}
list_of_chunks.push(chunk);
if n < chunk_size {
break;
}
}
Ok(list_of_chunks)
}
fn main() {
let socket = UdpSocket::bind("127.0.0.1:8000").expect("Could not bind client socket");
let mut buffer = [0u8; MAX_DATA_LENGTH];
socket.connect("127.0.0.1:8888").expect("Could not connect to server");
loop {
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read from stdin");
println!("{}", input);
let mut total_size: usize = 0;
let result: Result<Vec<Vec<u8>>, io::Error> = get_chunks_from_file(input, &mut total_size); // : Result<u8:u8>
match result {
Ok(chunks) => {
let nb: u16 = chunks.len() as u16;
let mut index: u16 = 0;
let header: &mut[u8;4] = &mut[
(index >> 8) as u8,
(index & 0xff) as u8,
(nb >> 8) as u8,
(nb & 0xff) as u8,
]; //input.as_bytes();
for chunk in chunks.iter() {
header[1] = (index & 0xff) as u8;
header[0] = (index >> 8) as u8;
let data:Vec<u8> = [header.as_ref(), chunk].concat();
//println!("FILE {} BYTES\n {:?}", index, chunk);
println!(
"size: {} FILE {:?} of {} BYTES\n {:?}",
total_size,
(header[0] as u16) << 8 | header[1] as u16,
nb - 1,
[0]
);
println!("{}", index);
socket.send(&data).expect("Failed to write to server");
socket.recv_from(&mut buffer).expect("Could not read into buffer");
index += 1;
}
}
Err(e) => println!("Error: {}", e),
}
//print!( "{}",str::from_utf8(&buffer).expect("Could not write buffer as string"));
// println!( "Chunk received by server {:?}", &buffer);
}
}
</code></pre>
<hr />
<h3>The ones I am aware of</h3>
<p>There are a few things I am especially concerned and already know that could be improved like this function:</p>
<pre class="lang-rs prettyprint-override"><code>fn write_chunks_to_file(filename: &str, bytes:&[u8]) -> Result<bool, io::Error> {
let mut file = File::create(filename)?;
file.write_all(bytes)?;
Ok(true)
}
</code></pre>
<p>I wrote it this way in order to make the compilation works but even I, the creator, can acknowledge that it does not make any sense! What would be a good Result to return?</p>
<p>And also the following warning when I compile the server file:</p>
<pre><code>warning: the type `std::alloc::Layout` does not permit being left uninitialized
--> udp-server.rs:43:23
|
43 | unsafe { layout = MaybeUninit::<Layout>::uninit().assume_init(); };
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| this code causes undefined behavior when executed
| help: use `MaybeUninit<T>` instead, and only call `assume_init` after initialization is done
|
= note: `#[warn(invalid_value)]` on by default
note: `std::num::NonZeroUsize` must be non-null (in this struct field)
</code></pre>
<p>Kindly appreciating any peer review.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T14:51:47.590",
"Id": "508216",
"Score": "2",
"body": "Welcome to Code Review! Could you please update the title to accurately reflect what the code does, since lots of people are presumably playing with unsafe code it currently doesn't help distinguishing it from other posts."
}
] |
[
{
"body": "<h1>Ok, let's talk about <code>unsafe</code></h1>\n<p>Your use of <code>unsafe</code> is very unidiomatic, not because you're using it at all, but because you're not using it <em>correctly</em>; that is, to create a boundary between safe and unsafe code.</p>\n<h2>First, some definitions</h2>\n<p><strong>Soundness</strong> is the property code has when its behavior is <em>defined</em> according to the abstract machine. Basically, sound code is code that means something, whereas unsound code doesn't mean anything, and may therefore <em>do</em> anything.</p>\n<p><strong>Safety</strong> is the property code has when its soundness can be <em>guaranteed</em> according to the rules of the language.</p>\n<p>Safety is subordinate to soundness. All code you write ought to be sound, whether it is unsafe or not. In a language like C, all code is unsafe, and it falls to the programmer to guarantee its soundness. In most languages considered safe, unsoundness is prevented by various runtime mechanisms (such as garbage collection to prevent dangling pointers). The tricky thing for a language like Rust is to allow unsafe code without letting the unsafety "leak out" into safe code. This is where <code>unsafe</code> comes in. In Rust, <strong><code>unsafe</code></strong> as a keyword can be used in a couple of different ways, but it is all about creating a <em>boundary</em> between safe and unsafe code.</p>\n<h2>A pointless (and dangerous) use of <code>unsafe</code></h2>\n<p>With the preliminaries out of the way, we can discuss what's wrong with a function definition like this one:</p>\n<pre><code>fn memcpy(dst_ptr:*mut u8, src_ptr:*const u8, len:usize) {\n unsafe {\n std::ptr::copy_nonoverlapping(src_ptr, dst_ptr, len);\n }\n}\n</code></pre>\n<p>This function does not maintain a boundary between unsafe and safe code. In fact, it pokes a hole right through that boundary because <code>memcpy</code> can be called in safe code, but will still create unsoundness if called with the wrong arguments. <code>copy_nonoverlapping</code> is marked <code>unsafe</code> because it imposes certain requirements on its caller that cannot be checked by the compiler. You can read these requirements in <a href=\"https://doc.rust-lang.org/std/ptr/fn.copy_nonoverlapping.html#safety\" rel=\"nofollow noreferrer\">its documentation</a>:</p>\n<blockquote>\n<p>Behavior is undefined if any of the following conditions are violated:</p>\n<ul>\n<li><p><code>src</code> must be <a href=\"https://doc.rust-lang.org/std/ptr/index.html#safety\" rel=\"nofollow noreferrer\">valid</a> for reads of <code>count * size_of::<T>()</code> bytes.</p>\n</li>\n<li><p><code>dst</code> must be <a href=\"https://doc.rust-lang.org/std/ptr/index.html#safety\" rel=\"nofollow noreferrer\">valid</a> for writes of <code>count * size_of::<T>()</code> bytes.</p>\n</li>\n<li><p>Both <code>src</code> and <code>dst</code> must be properly aligned.</p>\n</li>\n<li><p>The region of memory beginning at <code>src</code> with a size of <code>count * size_of::<T>()</code> bytes must <em>not</em> overlap with the region of memory\nbeginning at <code>dst</code> with the same size.</p>\n</li>\n</ul>\n<p>Like <a href=\"https://doc.rust-lang.org/std/ptr/fn.read.html\" rel=\"nofollow noreferrer\"><code>read</code></a>, <code>copy_nonoverlapping</code> creates a bitwise copy of <code>T</code>, regardless of\nwhether <code>T</code> is <a href=\"https://doc.rust-lang.org/std/marker/trait.Copy.html\" rel=\"nofollow noreferrer\"><code>Copy</code></a>. If <code>T</code> is not <a href=\"https://doc.rust-lang.org/std/marker/trait.Copy.html\" rel=\"nofollow noreferrer\"><code>Copy</code></a>, using <em>both</em> the values\nin the region beginning at <code>*src</code> and the region beginning at <code>*dst</code> can\n<a href=\"https://doc.rust-lang.org/std/ptr/fn.read.html#ownership-of-the-returned-value\" rel=\"nofollow noreferrer\">violate memory safety</a>.</p>\n</blockquote>\n<p>Because <code>memcpy</code> doesn't guarantee any of these requirements, but passes the responsibility for doing so on to its caller, <code>memcpy</code> is <em>unsafe</em>, despite not being an <code>unsafe fn</code>. Using an <code>unsafe</code> block inside the function is not merely pointless (because <code>memcpy</code> does not guarantee any of the soundness requirements of <code>copy_nonoverlapping</code>) but actually dangerous (because <code>memcpy</code> itself is not marked <code>unsafe</code>, so it can be called from non-<code>unsafe</code> contexts without the compiler's gentle reminder to check the list of requirements above).</p>\n<p>We can fix this by (1) removing the <code>unsafe</code> block inside the function, (2) marking <code>memcpy</code> appropriately, and (3) adding a comment to the function to indicate what soundness requirements it has.</p>\n<pre><code>/// A wrapper for ptr::copy_nonoverlapping with different argument order.\n/// Safety: see `std::ptr::copy_nonoverlapping`.\nunsafe fn memcpy(dst_ptr: *mut u8, src_ptr: *const u8, len: usize) {\n std::ptr::copy_nonoverlapping(src_ptr, dst_ptr, len);\n}\n</code></pre>\n<p>(Aside: This function doesn't really carry its weight. Just call <code>ptr::copy_nonoverlapping</code> and get used to the unusual argument order. But I'm focusing on <code>unsafe</code> for the moment.)</p>\n<h2>An unsound use of <code>unsafe</code></h2>\n<p>Your code has one clear-cut example of unsoundness. Recall that unsoundness is worse than mere unsafety. Driving on a bridge with no guardrails is unsafe; unsound is when your car ends up in the river.</p>\n<pre><code> unsafe { layout = MaybeUninit::<Layout>::uninit().assume_init(); };\n</code></pre>\n<p>This car is in a river. There are certain bit patterns that are not permitted for <code>Layout</code>, and constructing a <code>Layout</code> that contains them leads to instant UB (undefined behavior). In C we might call these "trap representations". Calling <code>assume_init</code> on a value that is not initialized permits the compiler to assume one of these invalid values, and therefore "optimize" this code to do anything, or merely delete it. The warning message (which should really be a hard error, but I think it is a warning for backward compatibility reasons) hints at how to fix it:</p>\n<pre><code> | help: use `MaybeUninit<T>` instead, and only call `assume_init` after initialization is done\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n</code></pre>\n<p>To fix this, we change the type of <code>layout</code> to <code>MaybeUninit<Layout></code> (note that <code>uninit</code> does not require <code>unsafe</code>):</p>\n<pre><code> let mut layout = MaybeUninit::<Layout>::uninit();\n</code></pre>\n<p>And only call <code>assume_init()</code> later, when you know you have initialized it and want to use the value:</p>\n<pre><code> unsafe {\n layout.as_mut_ptr().write(Layout::from_size_align_unchecked(n, mem::align_of::<u8>()));\n bytes_buf = alloc(layout.assume_init());\n }\n</code></pre>\n<p>This is a bit clunky today, unfortunately. With the unstable feature <code>maybe_uninit_extra</code>, you could use <a href=\"https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.write\" rel=\"nofollow noreferrer\"><code>write</code></a> to make it more concise and less <code>unsafe</code>. (The other place where you use <code>layout</code>, later, would still need to use <code>assume_init()</code>.)</p>\n<h2>A sketchy use of <code>unsafe</code></h2>\n<p>The compiler warns about <code>layout</code>, but it doesn't warn about the same thing with <code>bytes_buf</code>:</p>\n<pre><code> unsafe { bytes_buf = MaybeUninit::<*mut u8>::uninit().assume_init(); };\n</code></pre>\n<p>Unfortunately, just because the compiler doesn't warn about it doesn't mean it's sound. I'm not sure what the exact semantics are here; in fact, Rust's exact semantics haven't been completely nailed down, so it might be that <em>nobody</em> knows whether this is sound or not. The deprecation notice for <a href=\"https://doc.rust-lang.org/std/mem/fn.uninitialized.html\" rel=\"nofollow noreferrer\"><code>mem::uninitialized</code></a> (which does exactly the same thing as the line above) seems to hint that putting an uninitialized value in a typed variable may be insta-UB even for integers. So it's probably best to avoid that here as well.</p>\n<p>You could do the same thing as with <code>layout</code>, and call <code>assume_init()</code> only after actually initializing the pointer, but don't do that. Just initialize <code>bytes_buf</code> to <code>std::ptr::null_mut()</code> and call it a day.</p>\n<h2>Other <code>unsafe</code> issues</h2>\n<p>Let's go back to this <code>unsafe</code> block:</p>\n<pre><code> unsafe {\n layout.as_mut_ptr().write(Layout::from_size_align_unchecked(n, mem::align_of::<u8>()));\n bytes_buf = alloc(layout.assume_init());\n }\n</code></pre>\n<p>First things first: let's document all the safety requirements and how we're upholding them. There are four <code>unsafe fn</code>s in this block (<code>write</code>, <code>from_size_align_unchecked</code>, <code>alloc</code>, and <code>assume_init</code>).</p>\n<ul>\n<li><p><a href=\"https://doc.rust-lang.org/std/primitive.pointer.html#method.write\" rel=\"nofollow noreferrer\"><code><*mut T>::write</code> refers</a> to <a href=\"https://doc.rust-lang.org/std/ptr/fn.write.html\" rel=\"nofollow noreferrer\"><code>ptr::write</code></a>, which just has two preconditions:</p>\n<blockquote>\n<p>Behavior is undefined if any of the following conditions are violated:</p>\n<ul>\n<li><p><code>dst</code> must be <a href=\"https://doc.rust-lang.org/std/ptr/index.html#safety\" rel=\"nofollow noreferrer\">valid</a> for writes.</p>\n</li>\n<li><p><code>dst</code> must be properly aligned. Use <a href=\"https://doc.rust-lang.org/std/ptr/fn.write_unaligned.html\" rel=\"nofollow noreferrer\"><code>write_unaligned</code></a> if this is not the\ncase.</p>\n</li>\n</ul>\n</blockquote>\n<p><code>MaybeUninit::as_mut_ptr</code> does guarantee these, since that's more or less the whole point of it (<code>MaybeUninit::write</code>, on nightly, is safe.) The documentation doesn't <em>explicitly</em> talk about validity and alignment of the returned pointer; however, that's clearly the intent and the example correct usage also shows basically the same thing. So let's add a comment to that effect:</p>\n<pre><code>// SAFETY: layout.as_mut_ptr() is valid for writing and properly aligned\n</code></pre>\n<p>(Note that assigning directly to <code>*layout.as_mut_ptr()</code> is potentially risky because it causes the previous value to be dropped. Although <code>Layout</code> doesn't have drop glue, using <code>write</code> instead relieves us from having to worry about that additional precondition.)</p>\n</li>\n<li><p><a href=\"https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.from_size_align_unchecked\" rel=\"nofollow noreferrer\"><code>Layout::from_size_align_unchecked</code> requires</a> that the caller manually uphold the following conditions checked by <a href=\"https://doc.rust-lang.org/std/alloc/struct.Layout.html#method.from_size_align\" rel=\"nofollow noreferrer\"><code>from_size_align</code></a>:</p>\n<blockquote>\n<ul>\n<li><p><code>align</code> must not be zero,</p>\n</li>\n<li><p><code>align</code> must be a power of two,</p>\n</li>\n<li><p><code>size</code>, when rounded up to the nearest multiple of <code>align</code>,\nmust not overflow (i.e., the rounded value must be less than\nor equal to <code>usize::MAX</code>).</p>\n</li>\n</ul>\n</blockquote>\n<p>The first two are trivial because <code>mem::align_of::<u8>()</code> is an alignment by definition. The last one is also true because <code>n</code> is created by shifting <code>0x10000</code> left, which can't round up to <code>usize::MAX</code> (let's agree to ignore the possibility of <code>u8</code> having a massive alignment requirement on some obtuse, exotic target.)</p>\n<pre><code>// SAFETY: align_of<u8>() is nonzero and a power of two because it is an alignment\n// SAFETY: no shift amount will make 0x10000 << x round up to usize::MAX\n</code></pre>\n</li>\n<li><p><code>alloc(layout.assume_init())</code> has undefined behavior when <code>n</code> is zero, which can happen any time <code>0x10000 << next_power_of_two(chunks_cnt)</code> overflows. This can't happen on platforms where <code>usize</code> is 64 bits, but it can happen on 32-bit platforms, easily if <code>cnt_chunks</code> is zero (which will happen any time you try to handle an <a href=\"https://www.rfc-editor.org/rfc/rfc2675\" rel=\"nofollow noreferrer\">IPv6 jumbogram</a>).</p>\n<p>It's not obvious how you should deal with this, since it relates to how you handle incorrect or unexpected data. However, I suggest trying a little harder to make <code>n</code> guaranteed to be greater than 0. Using <code>checked_</code> methods on integers instead of plain operators like <code><<</code> might help you deal with overflowing arithmetic.</p>\n<pre><code>// SAFETY: layout's size is n, which is guaranteed >0 because...?\n</code></pre>\n</li>\n<li><p>Finally, <code>layout.assume_init()</code> is sound, as we just discussed, because <code>layout</code> was just initialized in the previous line. This is another <code>unsafe fn</code> that <code>MaybeUninit::write</code> will remove the need for.</p>\n<pre><code>// SAFETY: layout is initialized right before calling assume_init()\n</code></pre>\n</li>\n</ul>\n<p>Phew. It's a lot of work to check all this stuff, right? And I didn't even get to the other two <code>unsafe</code> blocks. At least this one doesn't appear to have any data races in it.</p>\n<p>It might seem like a lot of these conditions are trivially true, and ideally that will usually be the case, but as we saw in this example, there can be a lot of nuance to manually checking that you are using an <code>unsafe fn</code> correctly. The value of <code>unsafe</code> is that if you can check the rules <em>locally</em> (in or in the immediate vicinity of the <code>unsafe</code> block), then you can wrap it in a regular, safe function and <em>not</em> have to go on checking those rules <em>globally</em> (every time you call it).</p>\n<h2>But why are you actually using <code>unsafe</code>?</h2>\n<p>Checking and manually commenting all the <code>unsafe</code> in a project is a chore, which is one good reason to minimize your use of <code>unsafe</code> to only the cases where it's <em>really</em> needed. For instance: do you really <em>need</em> to avoid the checks done by <code>Layout::from_size_align</code>? Is calling <code>Layout::array::<u8>(n).unwrap()</code> really going to hurt your performance so much? (Note that in this case, if the <code>unsafe</code> code was sound, the <code>unwrap()</code> will never get called – so don't be concerned about making your server unstable; if adding the <code>unwrap()</code> makes it crash, it was already unstable.)</p>\n<p>None of this review is meant to convince you <em>not</em> to use <code>unsafe</code>. If you <em>really do</em> need that maybe-two-cycles of performance that you <em>might</em> save from skipping the checks, you <em>should</em> use <code>unsafe</code> pretty much like this. But don't waste your time eliminating a couple of checks that might not even be in the compiled code. Even <em>and especially</em> when your goal is performance, you should start with reliable, predictable, safe code, profile it, and then start attacking your bottlenecks.</p>\n<p>This is a really long review already, so I'm not going to try to rewrite your server in only safe code. I've already seen (and made) comments on some of your SO questions about how to do that, and like I said, my object is not to convince you not to use <code>unsafe</code> at all. Just use it correctly: maintain a boundary between safe and unsafe code, document the soundness requirements of unsafe code and show how you satisfy them.</p>\n<p>That said, here's some other non-safety-related thoughts (I might come back and add to this):</p>\n<h1>Miscellaneous</h1>\n<ul>\n<li><p>Regarding <code>write_chunks_to_file</code>, you can simply return a <code>Result<(), io::Error></code> (or equivalently <code>io::Result<()></code>), since the <code>Ok</code> variant conveys no additional information (<code>()</code> is a unit type, which conveys no information and takes up no space). This is also what <code>write_all</code> returns.</p>\n</li>\n<li><p><code>next_power_of_two</code> confused me for a while because it's named the same as a <a href=\"https://doc.rust-lang.org/std/primitive.u32.html#method.next_power_of_two\" rel=\"nofollow noreferrer\">standard library function</a>, but does something different. Consider renaming it, or just rewriting your logic to use the standard function.</p>\n</li>\n<li><p>This might not do what you think:</p>\n<pre><code> thread::spawn(move || {\n println!("receiving packet {} from: {}", packet_index, src);\n sock.send_to(&buf, &src).expect("Failed to send a response");\n });\n</code></pre>\n<p><code>move ||</code> causes <code>buf</code> and <code>src</code> to be copied into the closure, even though they're only used by reference. This does make the whole thing work, so maybe that's what you wanted, but it does make a big copy when it seems you're trying to avoid that.</p>\n</li>\n<li><p>The <code>0x10000</code> magic number should probably be a constant, maybe <code>MAX_DATAGRAM_SIZE</code>?</p>\n</li>\n<li><p>It's a good idea to use <code>rustfmt</code>. Yeah, you might not like all the reformattings it does. But it's better than uneven indentation and less annoying to people reading your code (including you in 6 months).</p>\n</li>\n<li><p>It's a better idea to use <code>cargo</code>. I made a Cargo project by running <code>cargo init projectname</code> and moving both files into <code>projectname/src/bin</code> (I had to create the <code>bin</code> directory). Putting things in <code>bin</code> makes them standalone binaries which Cargo will build along with everything else when you run <code>cargo build</code>.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T01:00:51.447",
"Id": "508138",
"Score": "0",
"body": "What a quality (and sound!) answer!! I have never seen such an excellent answer before. Clear, well explained, and show the code. Really thankful!!\nPS: For memcpy I had already changed it before but appreciate the idea of the wrapper. ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:50:15.633",
"Id": "257274",
"ParentId": "257112",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257274",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T20:42:42.853",
"Id": "257112",
"Score": "3",
"Tags": [
"rust"
],
"Title": "Playing with unsafe code: Sending files over UDP"
}
|
257112
|
<p>I am learning Rust and decided to create a simple program to calculate n-th Fibonacci number. It uses a vector for memoization. The program works, but what would you suggest to improve here? Maybe store <code>memo</code> inside <code>fib</code> function as a static variable?</p>
<p>I tried to use <code>u32</code> everywhere, but 48-th fib number doesn't fit into <code>u32</code>, so I decided to use <code>u64</code>.</p>
<pre><code>use std::io;
use std::io::Write;
use std::str::FromStr;
fn fib(n: u32, memo: &mut Vec<u64>) -> u64 {
if n < 2 {
return n as u64;
}
else if memo[(n-1) as usize] != 0 {
return memo[(n-1) as usize];
}
memo[(n-1) as usize] = fib(n - 1, memo) + fib(n - 2, memo);
memo[(n-1) as usize]
}
fn main() {
loop {
print!("n = ");
io::stdout().flush().unwrap();
let mut str: String = String::new();
io::stdin().read_line(&mut str)
.expect("Error getting number");
str.pop();
match u32::from_str(&str) {
Ok(n) => {
let mut memo: Vec<u64> = vec![0; n as usize];
println!("fib({})={}", n, fib(n, &mut memo));
break;
}
Err(_e) => {
println!("Error parsing number.");
println!("Try again");
}
};
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T08:53:03.927",
"Id": "507826",
"Score": "0",
"body": "Related Q&A [Recursive Fibonacci in Rust with memoization](https://codereview.stackexchange.com/q/204555)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T15:44:13.930",
"Id": "507854",
"Score": "3",
"body": "I am not familiar with Rust conventions, but I feel some comments should be in place, if only to split segments of main, and to define what fibonacci does (maybe this is redundant, since most people already know the function, but good habits are best learned early). You mention overflow due to u32/u64. This is an example of stuff which often should/could be mentioned in-code, although it is often commented in-documentation instead."
}
] |
[
{
"body": "<p>Looks good in general. Your main loop for parsing the input is generally idiomatic, except I would remove that pesky <code>.unwrap()</code> and explicitly report the error: <code>.flush().expect("Yikes! Failed to flush stdout!")</code></p>\n<p>The <code>fib</code> logic is a bit convoluted in terms of readability, mainly for two reasons: first the <code>(n-1)</code> everywhere in the memoization vec, and second the fact that the memoization entry could be <code>0</code> and this implicitly behaves like a <code>None</code> value. At the cost of an extra hash computation, it would be most natural to use a <code>HashMap</code> for memoization,\nsomething like this:</p>\n<pre><code>use std::collections::HashMap;\n\nfn fib(n: u32, memo: &mut HashMap<u32, u64>) -> u64 {\n if n < 2 {\n return n as u64;\n }\n memo.get(&n).cloned().unwrap_or_else(|| {\n let result = fib(n - 1, memo) + fib(n - 2, memo);\n memo.insert(n, result);\n result\n })\n}\n</code></pre>\n<p>Much cleaner! One would have to do some profiling to see the extent of the performance difference. Alternatively if you still want to use a Vec, remove the <code>n - 1</code> offset, and consider letting the vector grow: currently your code</p>\n<pre><code>memo[(n-1) as usize]\n</code></pre>\n<p>has a silent runtime error when the memo map is not large enough --- not good.\nLetting it grow also has the advantage that you don't need to initialize with <code>0</code>s.\nGrowing won't make any performance difference from what you have now as long as you <a href=\"https://doc.rust-lang.org/std/vec/struct.Vec.html#method.with_capacity\" rel=\"noreferrer\">initialize with a starting capacity <code>Vec::with_capacity</code></a>.\nIf you don't allow the vec to grow, use the <a href=\"https://doc.rust-lang.org/std/primitive.slice.html#method.get\" rel=\"noreferrer\"><code>memo.get(i)</code> method</a> instead of <code>memo[i]</code>, or as a last resort, heavily document the in-bounds requirement and add <code>debug_assert!(n <= memo.len())</code> to raise an error in debug mode on out-of-bounds input.</p>\n<p>Using a static variable for memoization is an option, but as it <a href=\"https://doc.rust-lang.org/book/ch19-01-unsafe-rust.html#accessing-or-modifying-a-mutable-static-variable\" rel=\"noreferrer\">requires unsafe to modify</a> and generally leads to less transparent performance for the end user, I wouldn't recommend it over having a slightly more complex API.</p>\n<p>Finally, you mention that <code>fib(n)</code> gets too large as <code>n</code> grows for a <code>u32</code> -- indeed, it is even too large for a <code>u64</code>, looks like starting at <code>n = 94</code>. So <code>fib</code> is actually a great use case for using a true (unbounded) integer library, such as the <a href=\"https://docs.rs/num/0.4.0/num/struct.BigInt.html\" rel=\"noreferrer\"><code>num::BigInt</code> crate</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T10:32:06.387",
"Id": "507831",
"Score": "0",
"body": "\"code `memo[(n-1) as usize]` has a silent runtime error when the memo map is not large enough\" - it does not, because if n = 0, it will use the branch: `if n < 2` at the top. I tested it with n = 0 and 1. It works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T01:30:04.220",
"Id": "507893",
"Score": "2",
"body": "@user4035 Maybe I was unclear -- I am not talking about n = 0, but the case where `n > memo.len()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T22:34:43.917",
"Id": "257114",
"ParentId": "257113",
"Score": "6"
}
},
{
"body": "<p>I like this. Your code is clean and pretty readable. I recommend using <code>rustfmt</code>, if only because it will stop annoying people on the internet from recommending you use <code>rustfmt</code>. But the minor code formatting differences are not something to be overly concerned about, if you have a style and stick with it.</p>\n<p>I have two major suggestions:</p>\n<ol>\n<li><p>Don't populate the cache with a sentinel value (zero) and then test whether each value is zero or not. Instead, make the vector start small and grow as you populate it. To avoid reallocation, you can initialize it with a large capacity and small length. You can further simplify the logic by (a) using <code>push</code> to add a value to the cache when you know the length is <code>n</code>; and (b) initializing the cache to <code>[0, 1]</code>, which will play into the next point:</p>\n</li>\n<li><p>Split <code>fib</code> into two functions: one that takes a cache as argument, and one that creates the cache inside itself (and calls the first one to do the heavy lifting). If you expose both of these in an API, then the user can decide whether reusing the cache is appropriate or not.</p>\n</li>\n</ol>\n<p>Here's the main code with both suggestions implemented:</p>\n<pre><code>fn fib_cached(n: u32, memo: &mut Vec<u64>) -> u64 {\n if (n as usize) < memo.len() {\n memo[n as usize]\n } else {\n let ret = fib_cached(n - 2, memo) + fib_cached(n - 1, memo);\n // At this point we know that memo.len() is at least n, because\n // fib_cached(n - 1, memo) will have populated memo[n-1]. Furthermore, if\n // memo.len() had been greater than n, we would have taken the other\n // branch of the if. There are no other functions capable of modifying\n // memo because we hold a &mut reference to it, so memo.len() is exactly n\n // and push(ret) will make memo[n] = ret.\n memo.push(ret);\n ret\n }\n}\n\nfn fib(n: u32) -> u64 {\n let mut cache = Vec::with_capacity(n as usize);\n cache.extend(&[0, 1]);\n fib_cached(n, &mut cache)\n}\n</code></pre>\n<p>Here are some more observations, in no particular order:</p>\n<ul>\n<li><p>Even this modified version is somewhat fragile, since it's easy to call <code>fib_cached</code> with a too-small cache, which may panic. If you were writing a library for others to use, I would suggest making a wrapper type around <code>Vec<u64></code> so you can insist on correctly-initialized caches. This would be a start:</p>\n<pre><code>struct FibCache {\n data: Vec<u64>,\n}\n\nimpl FibCache {\n fn with_capacity(n: usize) -> Self {\n let mut data = Vec::with_capacity(n);\n data.extend(&[0, 1]);\n FibCache {data}\n }\n}\n\nfn fib_cached(n: u32, memo: &mut FibCache) -> u64 {\n if (n as usize) < memo.data.len() {\n memo.data[n as usize]\n } else {\n let ret = fib_cached(n - 2, memo) + fib_cached(n - 1, memo);\n memo.data.push(ret);\n ret\n }\n}\n\nfn fib(n: u32) -> u64 {\n let mut cache = FibCache::with_capacity(n as usize);\n fib_cached(n, &mut cache)\n}\n</code></pre>\n<p>This means nobody can call <code>fib_cached</code> without creating a <code>FibCache</code> object with a constructor you define. It also lets you make backwards-compatible changes to the type of cache -- you could use a <code>HashMap</code>, as 6005 suggests, or another data structure, without changing the outward-facing API of the library.</p>\n</li>\n<li><p><code>n as usize</code> is another source of fragility. Casting between integer types can have surprising results, so you're usually well-advised to use <code>usize::try_from(n).unwrap()</code> instead, which will panic if the conversion can't be done. In <em>this</em> code, I don't regard this as a major issue because <code>u32</code> is losslessly convertible to <code>usize</code> on virtually all Rust targets and because any <code>n</code> that would overflow a <code>usize</code>, on any target, is already too large for this algorithm. Just be aware you should normally use the conversion traits instead of casting.</p>\n</li>\n<li><p>Changing <code>fib</code> to use internal static state is pretty simple, using <code>lazy_static</code> or <code>once_cell</code>. I'll use <code>lazy_static</code> here, and assume the <code>FibCache</code> API above:</p>\n<pre><code>fn fib(n: u32) -> u64 {\n use lazy_static::lazy_static; // 1.4.0\n use std::sync::Mutex;\n lazy_static! {\n static ref CACHE: Mutex<FibCache> = Mutex::new(FibCache::with_capacity(10));\n }\n fib_cached(n, &mut *CACHE.lock().expect("Could not lock static cache"))\n}\n</code></pre>\n<p>Whether this is a <em>good idea</em> or not is rather up for debate. Ultimately it's replacing contention for one resource (the heap) with contention for another resource (the lock). Neither is necessarily the best choice, which is why it's important to expose <code>fib_cached</code> as well so your users aren't stuck with your choice of implementation for <code>fib</code>. Making access to <code>FibCache</code> lock-free could make static memory much more appealing by removing the contention aspect.</p>\n</li>\n<li><p>Don't use <code>str</code> as the name of a variable, since it's also the name of a built-in type. It will mess with syntax highlighting (as it does on this very site).</p>\n</li>\n<li><p><em>Obviously</em>, this is a slow and wasteful algorithm for calculating Fibonacci numbers. So I assume what you're looking for is feedback on the general shape and style of the solution, not the choice of algorithm, and I've written this review based on that assumption. Peter's review deals with algorithmic improvements.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:28:24.353",
"Id": "507789",
"Score": "0",
"body": "Great suggestions, particularly the use of `lazy_static` / `once_cell`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T08:34:05.473",
"Id": "507822",
"Score": "1",
"body": "Taking a lock to access the tiny array sounds pretty terrible, like *never* worth it instead of \"only worth it in contrived cases to answer Fib(n) queries very fast from an array that stays hot in cache\". What *could* be worth it is lock-free atomics; I assume Rust has a way to something equivalent to C++ `std::atomic<>`. A memory_order_relaxed load from the array will either be 0 or the value we want; if 0, we can go and compute that Fibonacci number from lower elements... As long as we always check for 0, don't assume that seeing a non-zero means lower entries are also non-0, we're fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T08:34:47.970",
"Id": "507823",
"Score": "0",
"body": "Blocking multiple writers isn't needed; they'll both be writing the same value. Once nobody's writing (to the same cache line), you get perfect read-side scaling to N readers on N CPU cores."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T11:41:54.847",
"Id": "507839",
"Score": "0",
"body": "Good points @Peter. I'm happy to sweep the awfulness of locking under the \"irrelevant for *this* algorithm, but *maybe*...\" rug, for the most part. More practically, using `&mut` in the API almost insists upon the lock, since it's an exclusive reference, but you could certainly relax that to `&` and use atomics from the Rust standard library instead. If I get bored enough this afternoon, maybe I'll try it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:06:05.180",
"Id": "507840",
"Score": "1",
"body": "I posted an answer about algorithmic optimizations (e.g. keeping track of your memo cache fill point instead of basically linear-searching for it backwards). I notice you used `fib_cached(n - 2, memo) + fib_cached(n - 1, memo);` but didn't comment on doing n-2 first, which is what current rustc seems to do, even if there's no language guarantee of eval order(?). I wrote some about the effect: turns out no reduction in total number of calls, or of memo-cache misses, but it does cut the max recursion depth in half. (I don't really know Rust, so unfortunately I didn't flesh out some of the ideas)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T23:51:44.210",
"Id": "257120",
"ParentId": "257113",
"Score": "11"
}
},
{
"body": "<p>Why use slow recursion for the case where you do need to fill the cache? Just to make memoization look good by comparing it to an O(Fib(n)) naive implementation instead of an O(n) simple loop? That's not a great choice if you're actually trying to answer queries for Fib(n) as fast as possible.</p>\n<p>Although to be fair, Fib(93) is the largest value that will fit in a u64, so in real life you'd just fill the array when you allocate the cache because it's so fast, then every query is a single array index, after a bounds check (explicit in the source or using <code>memo.get(i)</code>).</p>\n<p>Or don't cache at all, since the max 93 iterations will go very fast, especially on a 64-bit CPU. Perhaps <a href=\"https://doc.rust-lang.org/std/primitive.u64.html#method.overflowing_add\" rel=\"nofollow noreferrer\">using <code>x.overflowing_add(y)</code></a> or <code>.checked_add</code> to detect overflow, although checking <code>n</code> against a known constant ahead of the loop will keep that work out of the loop. Anyway, let's imagine you were using arbitrary precision num::BigInt, or a different function with similar recursion but less fast growth, so the memo cache could get big enough to be interesting. Or just for the sake of optimizing.</p>\n<hr />\n<p><strong>If you kept a fill-position counter as part of a memo object, you could fill it up to where you need with a simple x+=y; y+=x; unrolled loop.</strong> That can over-fill by 1 past where you need, but it's so cheap that it's worth it. Just make sure to use <code>.wrapping_add()</code> so it's safe even on overflow, or start your array with <code>memo[0] = Fib(0) = 0</code>, avoiding the <code>n-1</code> and making your pairs end with an odd number. So 0,1 2,3 ... 92,93 ending with 93, the last Fibonacci number that doesn't overflow u64.</p>\n<p>What you're doing now is effectively a (recursive) linear search for the highest non-zero entry in your memo cache<sup>1</sup>. If you don't want to keep a previous fill mark, you can at least speed up the search. If you drop the recursion, it would be easy to write a loop that steps backwards more than 1 element at a time. (e.g. by 4 might be good here, or larger if the max possible cache size is a lot larger than 93). This does make things more complex: the possibility of <code>n-4</code> wrapping means you'd want a <code>checked_sub</code>, or fill the first 4 Fib memo entries to start with.</p>\n<p>You <em>could</em> even binary search: you can tell whether you're above or below the point you're looking for by checking it against 0. And you only need to get close, e.g. stop on a non-zero when the known range is small. (This would be pain to do recursively, but would make sense as a search loop ahead of a fill-the-memo iterative loop.)</p>\n<p>If you want to keep the recursion, <strong>having <code>fib(n-2, memo)</code> evaluated first limits recursion depth</strong>. That gives you a linear search with a stride of 2 instead of 1, reducing the max recursion depth by a factor of 2. But it turns out there's no saving in total work, though. After fib n-2 runs, the fib n-1 in the same line will also miss in the memo cache and itself recurse. If you did it in the other order, fib n-1 then fib n-2, the n-2 calls would always return right away. We can fix this by having fib(n) fill the memo cache up to n+1 by doing another add, basically sneaking an unrolled iteration in there.</p>\n<p>Apparently Rust <a href=\"https://doc.rust-lang.org/nightly/reference/expressions.html?highlight=evaluation%20order#evaluation-order-of-operands\" rel=\"nofollow noreferrer\">evaluation order <em>is</em> guaranteed</a> left-to-right for the operands of operators like <code>+</code> <a href=\"https://codereview.stackexchange.com/questions/257113/n-th-fibonacci-number-with-memoization/257140#comment508567_257140\">in the latest nightly builds</a>. Before that, all I could find were old discussions <a href=\"https://stackoverflow.com/questions/24508640/what-are-sequence-point-sequenced-before-rules-in-rust\">like this</a>), where there was no definite conclusion about any guarantee. In practice at least, <code>rustc</code> 1.50 <em>does</em> run the left hand side first in this case (<a href=\"https://godbolt.org/z/3h15nW\" rel=\"nofollow noreferrer\">https://godbolt.org/z/3h15nW</a>). To guarantee that the <code>n-2</code> call runs first, you can do it in a separate statement. I chose to use an initializer list, which is also guaranteed for the latest nightly, and which does in practice do what I want with earlier rustc.</p>\n<pre><code>// memo[(n-1) as usize] = fib(n - 1, memo) + fib(n - 2, memo);\n\n let (mut x, y) = (fib(n - 2, memo), fib(n - 1, memo));\n x += y;\n memo[(n-1) as usize] = x;\n memo[n as usize] = y + x; // fill an extra entry so the fib(n-1) in our caller will hit in cache\n</code></pre>\n<p>(I'm only barely learning Rust myself, that's not a coding-style recommendation. I posted this review almost entirely to review the algorithmic choices, not the Rust details.)</p>\n<p>This of course requires memo[] to have allocated space higher up. As @trentcl pointed out, you could be using <code>memo.push()</code> to simplify allocation, avoiding the caller needing to reserve space beyond where it wants to fill. (The caller shouldn't have to be managing the dynamic-array bounds of the memo cache at all, unless that caller is a wrapper around the recursive function which exposes a clean API.)</p>\n<p>I added instrumentation (counting up total calls, and memo misses (calls that get past the first if/else) in the otherwise-unused <code>memo[0]</code>). <a href=\"https://godbolt.org/z/1rc1s3\" rel=\"nofollow noreferrer\">https://godbolt.org/z/1rc1s3</a> is a hacked up version I was playing around with to learn some Rust and see if I could get the compiler to do bounds checking once for <code>n</code>, not repeatedly for <code>n-1</code> and <code>n-2</code> (nope). Anyway, input is replaced by a string literal; The Godbolt compiler explorer lets you run programs these days, but not with interactive input.</p>\n<p>That last line updating <code>memo[n]</code> along with evaluating <code>fib(n-2)</code> first cuts each of total calls and misses in about half. e.g. for fib(40):</p>\n<ul>\n<li>original strategy: calls 79, misses 39</li>\n<li>fib(n-2) first, updating memo to make its sibling hit: calls = 41, misses = 20</li>\n</ul>\n<hr />\n<p><strong>Footnote 1</strong>: Keep in mind that unless you use a different algorithm<sup>2</sup> for evaluating the Nth Fibonacci number, you'll evaluate all previous numbers along the way, so the memo cache will have a contiguous range of set values, and above that all 0. Unless you want to only cache a pair of numbers every 32 or something: e.g. on a memo hit you have a starting point to iterate from with a small upper bound on how much work needs to be done to get from there to the Fib(n) you want. Shrinks your cache by a factor of 16; could be valuable for num::BigInt.</p>\n<p>sub-footnote 2: It's possible to do Fib(n) in log2(n) steps <a href=\"https://stackoverflow.com/questions/32659715/assembly-language-x86-how-to-create-a-loop-to-calculate-fibonacci-sequence/32685824#32685824\">with the <s>Lucas sequence</s> binary matrix exponentiation method</a> which each use a couple integer multiplies and adds, still pure integer math. No risk of FP rounding error from the closed-form golden-ratio power closed-form formula. You wouldn't be building your cache along the way (although maybe you could do some?)</p>\n<p>Or as <a href=\"https://codereview.stackexchange.com/questions/163354/using-2-threads-to-compute-the-nth-fibonacci-number-with-memoization/163366#163366\">this answer points out</a>, there's <code>F(n) = 4 * F(n-3) + F(n-6)</code> which only fills in every 3rd entry. But it means doing all the work for F(n) doesn't help at all for F(n+1). Maybe there's some mathematical trick to pick up somewhere and get an adjacent pair of Fibonacci numbers out of this, so you could go from this every-third cache to any arbitrary number you need, but I don't know it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T17:03:33.420",
"Id": "507861",
"Score": "0",
"body": "I believe the function argument eval order is covered by Rust's blanket guarantee of \"no breakage in safe code post-1.0\" even though it's not explicitly documented anywhere (which would obviously be preferable). My review swapped them mostly on a hunch; I wasn't sure it would make a difference, but limiting the maximum recursion depth makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T18:43:49.367",
"Id": "507866",
"Score": "0",
"body": "I strongly disagree with the first sentence. Using recursion to calculate fibonacci numbers is [**not slow**](https://gist.github.com/klmr/301e1eca5aa096fb7cf4d4b7d961ad01), unless you use a naïve algorithm. A straightforward recursive implementation on C is *as fast* as the optimal iterative implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T00:26:50.093",
"Id": "507891",
"Score": "0",
"body": "@trentcl: Note that the concern here isn't eval-order of *function* args within one call, it's of the left and right sides of operator `+`. (Or in my rewrite, operator `,` in an initializer list.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T00:35:16.523",
"Id": "507892",
"Score": "1",
"body": "@KonradRudolph: When I said \"slow recursion\", I didn't mean to imply that *all* recursion is slow, just that *this* recursive strategy is slow; doing about twice as many steps as necessary (even with memoization), and each step doing much more work than a simple loop. (But also, you need the resulting machine-code to be iterative for maximum performance. Yes, you can get that by writing your recursion in a way that the compiler can handle. Or see my [hand-written x86 asm](//stackoverflow.com/a/32661389/224132) that cleverly IMO handles odd vs. even N for branchless unroll to fill an array.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T09:40:53.787",
"Id": "507909",
"Score": "2",
"body": "@PeterCordes Ah, of course. Anyway, regarding your parenthetical note, the code I posted is tail recursive, and the equivalent C version obviously compiles down to assembly code without any calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:11:00.183",
"Id": "508124",
"Score": "1",
"body": "@PeterCordes I found this great video explaining the fast matrix multiplication algorithm for calculating fibs: https://www.youtube.com/watch?v=EEb6JP3NXBI."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T02:23:04.713",
"Id": "508140",
"Score": "0",
"body": "@user4035: yeah, @ rcgldr's \"Lucas Sequence\" answer I linked is doing the same math as exponentiating a 2x2 matrix, I think. Good explanation of why it works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T06:34:32.353",
"Id": "508154",
"Score": "0",
"body": "@PeterCordes I think he is calling it a wrong name. I couldn't find \"Lucas sequence\" for fib generation anywhere in the Internet. He is doing matrix exponentiation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T06:38:23.813",
"Id": "508155",
"Score": "0",
"body": "@user4035: I don't really know about the Lucas sequence or whether it's possible to describe that as being related to it. I'd suggest commenting on that linked answer and see what rcgldr has to say; maybe they'll want to update their answer to describe it that way. (Especially if you link a useful summary of how matrix exponentiation works; preferably text; most people would rather skim a page to find the parts they're already familiar with than watch a video.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T13:08:39.350",
"Id": "508567",
"Score": "1",
"body": "I've just learned that the [nightly reference now specifies left-to-right, as-written-in-the-source-code evaluation order](https://doc.rust-lang.org/nightly/reference/expressions.html?highlight=evaluation%20order#evaluation-order-of-operands) for most expressions, including arithmetic operators and tuple expressions (initializer lists). This relatively recent change hasn't yet hit stable, which is why it's hard to find."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:01:48.053",
"Id": "257140",
"ParentId": "257113",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "257120",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-13T21:27:37.327",
"Id": "257113",
"Score": "9",
"Tags": [
"rust",
"fibonacci-sequence"
],
"Title": "n-th Fibonacci number with memoization"
}
|
257113
|
<p>I'm iterating through a list to generate calendars, the issue is each generator function has the same <code>this.addToCalendar()</code> function. I'd like to know how I could condense this into only being called once, rather than in each function.</p>
<p>The main generators I'd like to look at are the ones within <code>method</code>, where I am generating calendar links as well as calling an external api.</p>
<p>CSS has been removed to focus on JS logic.</p>
<pre><code><template>
<div>
<ul>
<li v-for="(calendar, i) in calendars" :key="i">
<button @click="calendar.generator">
<span>{{ calendar.type }}</span>
</button>
</li>
</ul>
<button @click="setExpanded(false)">
Close
</button>
</div>
</template>
<script>
import {
ICalendar,
GoogleCalendar,
OutlookCalendar,
YahooCalendar,
} from 'datebook'
import { mapActions, mapGetters } from 'vuex'
export default {
data() {
return {
calendars: [
{ type: 'Apple', generator: this.generateAppleCalendar },
{ type: 'Google', generator: this.generateGoogleCalendar },
{ type: 'Outlook', generator: this.generateOutlookCalendar },
{ type: 'Yahoo', generator: this.generateYahooCalendar },
],
success: null,
error: null,
}
},
computed: {
...mapGetters({
event: 'event/event',
expanded: 'calendar/expanded',
userType: 'user/userType',
}),
eventLocation() {
return `${this.event.location_street}, ${this.event.location_city}, ${this.event.location_state}. ${this.event.location_zip}`
},
generateConfig() {
const config = {
title: this.event.title,
location: this.eventLocation,
description: this.event.description,
start: new Date(this.event.start_time),
end: new Date(this.event.end_time),
}
return config
},
},
methods: {
...mapActions({
setExpanded: 'calendar/setExpanded',
}),
generateAppleCalendar() {
const icalendar = new ICalendar(this.generateConfig)
icalendar.download()
this.addToCalendar()
},
generateGoogleCalendar() {
const googleCalendar = new GoogleCalendar(this.generateConfig)
this.openInNewTab(googleCalendar.render())
this.addToCalendar()
},
generateOutlookCalendar() {
const outlookCalendar = new OutlookCalendar(this.generateConfig)
this.openInNewTab(outlookCalendar.render())
this.addToCalendar()
},
generateYahooCalendar() {
const yahooCalendar = new YahooCalendar(this.generateConfig)
this.openInNewTab(yahooCalendar.render())
this.addToCalendar()
},
openInNewTab(url) {
const win = window.open(url, '_blank') // Opening a new tab with the url
win.focus() // Focussing the users browser to new tab
},
async addToCalendar() {
let url
if (this.userType === 'guest') {
url = `event/${this.event.id}/add-guest-user`
} else {
url = `event/${this.event.id}/guest`
}
const response = await this.$axios.post(url)
if (response.status === 201) {
this.success = true
} else {
this.error = true
}
},
},
}
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T10:58:59.350",
"Id": "508194",
"Score": "1",
"body": "There is not enough information in your question to answer. Required is... How the calendars relate? How does instantiating a calendar effect the state and thus behavior of `addToCalendar`? Do all calendars require the call? Are you expecting only one valid calendar, some calendars to be successful, or all calendars to set `this.success = true`? What should happen to calendars that result in `this.error = true`? Do you know ahead of instantiating calendars which you want?"
}
] |
[
{
"body": "<blockquote>\n<p>I'd like to know how I could condense this into only being called once, rather than in each function.</p>\n</blockquote>\n<p>One option would be to make a method that accepted the calendar or type and called the associated method</p>\n<pre><code>methods:\n generateCalendar(type) {\n const generateMethod = `generate${type}Calendar`\n if (typeof this[generateMethod] === 'function')\n this[generateMethod]()\n this.addToCalendar()\n }\n }\n</code></pre>\n<p>Then pass the type:</p>\n<pre><code><button @click="generateCalendar(calendar.type)">\n</code></pre>\n<p>If the only property being accessed in the loop was that type property then destructuring assignment would allow it to be simplified:</p>\n<pre><code> <li v-for="({ type }, i) in calendars" :key="i">\n <button @click="generateCalendar(type)"> \n <span>{{ calendar.type }}</span>\n </button\n \n</code></pre>\n<p>Alternatively, with using the method above the <code>generator</code> properties of the calendars could be removed, and <code>calendars</code> could perhaps just be an array of strings.</p>\n<p>Also, it seems that three of the four calendar methods are nearly identical other than the class of calendar object created: <code>generateGoogleCalendar</code>, <code>generateOutlookCalendar</code> and <code>generateYahooCalendar</code>. A generic method could be used to replace those three methods (and accept the calendar type as a parameter to be used to dynamically invoke a constructor) or create them dynamically in a loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T18:06:53.100",
"Id": "257357",
"ParentId": "257127",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257357",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T00:59:42.973",
"Id": "257127",
"Score": "2",
"Tags": [
"javascript",
"ecmascript-6",
"iteration",
"generator",
"vue.js"
],
"Title": "Iterating through a list to generate calendars"
}
|
257127
|
<pre><code> Table "matrices"
Column | Type | Modifiers
--------+--------+-----------
matrix | text[] | not null
</code></pre>
<blockquote>
<p>rows count 2,values are in this format given below</p>
</blockquote>
<pre><code> matrix
-------------------
{{1,2,3},{4,5,6}}
{{a,b,c},{d,e,f}}
</code></pre>
<p>output i'm looking for in this format</p>
<pre><code> matrix
---------------------
{{1,4},{2,5},{3,6}}
{{a,d},{b,e},{c,f}}
</code></pre>
<p>can anybody suggest me a better solution, i tried crosstab with giving 2 integer value,it didn't work in my server,these syntaxes are new to me.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T07:59:41.073",
"Id": "507820",
"Score": "0",
"body": "Welcome to Code Review! Unfortunately your post is off-topic because (1) there is no code for us to review, and (2) the title of your question is of the form \"how do I do X?\" which is likely a better fit for [Stack Overflow](https://stackoverflow.com/). Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T05:24:54.313",
"Id": "257134",
"Score": "0",
"Tags": [
"database",
"postgresql",
"lua-table"
],
"Title": "how to Transpose two-dimensional arrays values from rows into columns in postgres?"
}
|
257134
|
<p>I seek a fast implementation of <code>(x / y).imag</code>, where <code>x, y</code> are complex 2D arrays (PyTorch tensors already on GPU). My approach is to move computation to a CUDA kernel via <code>cupy</code>, interfacing C and Python. Requirements:</p>
<ul>
<li>Faster than <code>(x / y).imag</code></li>
<li>Using same or less memory than <code>(x / y).imag</code></li>
<li>Output is same as <code>(x / y).imag</code> within float precision</li>
<li><code>#include</code>s must be supported by CuPy (which is largely limited to standard CUDA libraries afaik)</li>
</ul>
<hr>
<p><strong>My attempt</strong>:</p>
<pre><code>extern "C" __global__
void cdiv_imag(float x[240][240000][2], float y[240][240000][2],
float out[240][240000]) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
int j = blockIdx.y * blockDim.y + threadIdx.y;
if (i >= 240 || j >= 240000)
return;
float A = x[i][j][0];
float B = x[i][j][1];
float C = y[i][j][0];
float D = y[i][j][1];
out[i][j] = (B*C - A*D) / (C*C + D*D);
}
</code></pre>
<p>This uses half the memory, since <code>x / y</code> yields a temp array of reals & imaginary, but is still ultimately slower per my benchmarks on GTX 1070:</p>
<pre><code>0.02320581099999992 sec (avg of 1000 runs)
0.01924530900000002 sec (avg of 1000 runs)
</code></pre>
<p><a href="https://pastebin.com/GVKMYjdW" rel="nofollow noreferrer">Full code</a>; Win 10 x64, Python 3.7.9, CuPy 8.3.0, PyTorch 1.8.0.</p>
<pre class="lang-py prettyprint-override"><code>import torch
import numpy as np
import cupy as cp
from collections import namedtuple
from timeit import timeit
def timer(fn, number=1000):
print(timeit(fn, number=number) / number)
Stream = namedtuple('Stream', ['ptr'])
#%%##################################################################
kernel = cp.RawKernel(r'''
extern "C" __global__
void cdiv_imag(float x[240][240000][2], float y[240][240000][2],
float out[240][240000]) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
int j = blockIdx.y * blockDim.y + threadIdx.y;
if (i >= 240 || j >= 240000)
return;
float A = x[i][j][0];
float B = x[i][j][1];
float C = y[i][j][0];
float D = y[i][j][1];
out[i][j] = (B*C - A*D) / (C*C + D*D);
}
''', 'cdiv_imag')
#%%##################################################################
shape = (240, 240000)
x = torch.randn(shape, dtype=torch.complex64, device='cuda')
y = torch.fliplr(x.clone().detach())
threadsperblock = (32, 32)
blockspergrid_x = int(np.ceil(y.shape[0] / threadsperblock[0]))
blockspergrid_y = int(np.ceil(y.shape[1] / threadsperblock[1]))
blockspergrid = (blockspergrid_x, blockspergrid_y)
#%%##################################################################
def f1(x, y):
out = torch.zeros(shape, dtype=torch.float32, device='cuda')
xv, yv = torch.view_as_real(x), torch.view_as_real(y)
kernel(
grid=blockspergrid, block=threadsperblock,
args=[xv.data_ptr(), yv.data_ptr(), out.data_ptr()],
stream=Stream(ptr=torch.cuda.current_stream().cuda_stream))
return out
def f2(x, y):
return (x / y).imag
# ensure outputs agree within float precision
adiff = torch.abs(f1(x, y) - f2(x, y))
assert adiff.mean() < 1e-8
# dummy run to factor out caching & warm up GPU
for _ in range(2000):
f1(x, y)
f2(x, y)
#%%##################################################################
timer(lambda: f1(x, y))
timer(lambda: f2(x, y))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T10:49:17.287",
"Id": "507833",
"Score": "0",
"body": "Your 'Full code' link refers to a log-in page. Please include all relevant code in the question itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T20:51:35.143",
"Id": "525617",
"Score": "0",
"body": "Which is more important \"Faster than (x / y).imag\" or \"Using same or less memory than (x / y).imag\"? Would the first be acceptable without the 2nd?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T21:10:51.023",
"Id": "525618",
"Score": "1",
"body": "@chux-ReinstateMonica First is acceptable as long as not using more than x2 the memory."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T06:50:46.423",
"Id": "257137",
"Score": "1",
"Tags": [
"python",
"c",
"cuda",
"pytorch"
],
"Title": "Complex division for imaginary part"
}
|
257137
|
<p><strong>Exercise:</strong>
Write a prime number-test isPrime(num: Int), which for integer m >= 2 checks, if the integer is a prime number or not.</p>
<p><strong>My solution:</strong></p>
<pre><code>fun main(args: Array<String>) {
var isPrime: Boolean = false
for (i in 2..101) {
isPrime = isPrime(i)
if (isPrime) {
println("$i => ${isPrime(i)}")
}
}
}
fun isPrime(num: Int): Boolean {
val upperLimit = num / 2;
var i = 2
while (i <= upperLimit) {
if (num % i == 0) {
return false
}
i++
}
return true
}
</code></pre>
<p><strong>Could my solution become improved concerning efficiency?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:44:32.073",
"Id": "507843",
"Score": "0",
"body": "You might also be interested in looking at another Kotlin prime generator question: https://codereview.stackexchange.com/q/253690/31562"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:55:36.180",
"Id": "507844",
"Score": "0",
"body": "@SimonForsberg Thanks a lot. :)"
}
] |
[
{
"body": "<p>Two easy improvements</p>\n<p>Check up to the square root of n rather than n/2. So for 101 you only need to check n up to 10 not 50. If your number isn't prime then 1 of it's factors must be less than it equal to its square root.</p>\n<p>Don't check multiples of 2, so do a single test to see if the number can be divided by 2 then only test odd numbers starting at 3.</p>\n<p>So if you test 101 for primeness these's changes mean that instead of testing for divisibilty by 2..50 you only test 2,3,5,7,9</p>\n<p>Other things to consider</p>\n<p>Use the primes below square root n. So if you know that 2,3,5,7 are the only primes below square root of 101 you only need to test for divisibilty by these numbers to show 101 is prime.</p>\n<p>A more complex solution would be to look at a deterministic version of the Miller Rabin test as described <a href=\"https://en.m.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test\" rel=\"nofollow noreferrer\">here</a> this works well if you just want to know if a specific value is prime.</p>\n<p>Most efficient if you want all primes below n would be a <a href=\"https://en.m.wikipedia.org/wiki/Generation_of_primes\" rel=\"nofollow noreferrer\">prime number sieve</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:33:14.833",
"Id": "257143",
"ParentId": "257141",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "257143",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T12:05:02.733",
"Id": "257141",
"Score": "2",
"Tags": [
"primes",
"integer",
"kotlin"
],
"Title": "Write a Kotlin-function isPrimeNumber"
}
|
257141
|
<p>I attempted to make a smart/dynamic array implementation in C which is supposed to be a hybrid between a C++ vector/stack/queue.</p>
<p>This is what i came up with:</p>
<p>Header (smart_array.h):</p>
<pre><code>#pragma once
#include <stddef.h>
typedef struct smart_array smart_array_t;
void smart_array_alloc(smart_array_t** array, size_t capacity);
void smart_array_free(smart_array_t** array);
int smart_array_resize(smart_array_t* array, size_t capacity);
void smart_array_capacity(smart_array_t* array, size_t* capacity);
void smart_array_total(smart_array_t* array, size_t* total);
void smart_array_empty(smart_array_t* array, int* empty);
int smart_array_set(smart_array_t* array, size_t index, void* item);
int smart_array_set_back(smart_array_t* array, void* item);
int smart_array_set_top(smart_array_t* array, void* item);
void smart_array_get(smart_array_t* array, size_t index, void** item);
void smart_array_get_back(smart_array_t* array, void** item);
void smart_array_get_top(smart_array_t* array, void** item);
int smart_array_push_back(smart_array_t* array, void* item);
int smart_array_push_top(smart_array_t* array, void* item);
int smart_array_pop(smart_array_t* array, size_t index);
int smart_array_pop_back(smart_array_t* array);
int smart_array_pop_top(smart_array_t* array);
int smart_array_clear(smart_array_t* array);
</code></pre>
<p>Source File: (smart_array.c):</p>
<pre><code>#include "smart_array.h"
#include <stdlib.h>
struct smart_array {
void** items;
size_t total;
size_t capacity;
};
void smart_array_alloc(smart_array_t** array, size_t capacity) {
if(!(*array = malloc(sizeof(struct smart_array))))
return;
if(!((*array)->items = malloc(sizeof(void*) * capacity))) {
free(*array);
*array = 0;
return;
}
(*array)->capacity = capacity;
(*array)->total = 0;
}
void smart_array_free(smart_array_t** array) {
if(array && *array) {
free((*array)->items);
free(*array);
*array = 0;
}
}
int smart_array_resize(smart_array_t* array, size_t capacity) {
if(array) {
void **items = realloc(array->items, sizeof(void*) * capacity);
if(items) {
array->items = items;
array->capacity = capacity;
return 0;
}
}
return 1;
}
void smart_array_capacity(smart_array_t* array, size_t* capacity) {
*capacity = !array ? 0 : array->capacity;
}
void smart_array_total(smart_array_t* array, size_t* total) {
*total = !array ? 0 : array->total;
}
void smart_array_empty(smart_array_t* array, int* empty) {
*empty = array->total == 0;
}
int smart_array_set(smart_array_t* array, size_t index, void* item) {
if(array) {
if (index >= 0 && index < array->total) {
array->items[index] = item;
return 0;
}
}
return 1;
}
int smart_array_set_back(smart_array_t* array, void* item) {
size_t total;
smart_array_total(array, &total);
return smart_array_set(array, total - 1, item);
}
int smart_array_set_top(smart_array_t* array, void* item) {
return smart_array_set(array, 0, item);
}
void smart_array_get(smart_array_t* array, size_t index, void** item) {
if(array && item) {
if (index >= 0 && index < array->total)
*item = array->items[index];
else
*item = 0;
}
}
void smart_array_get_back(smart_array_t* array, void** item) {
size_t total;
smart_array_total(array, &total);
smart_array_get(array, total - 1, item);
}
void smart_array_get_top(smart_array_t* array, void** item) {
smart_array_get(array, 0, item);
}
int smart_array_push_back(smart_array_t* array, void* item) {
if(array) {
if(array->capacity == array->total) {
if(smart_array_resize(array, array->capacity * 2))
return 1;
}
array->items[array->total++] = item;
return 0;
}
return 1;
}
int smart_array_push_top(smart_array_t* array, void* item) {
if(array) {
if(array->capacity == array->total) {
if(smart_array_resize(array, array->capacity * 2))
return 1;
}
array->total++;
for(size_t s = array->total; s > 0; --s)
array->items[s] = array->items[s - 1];
array->items[0] = item;
return 0;
}
return 1;
}
int smart_array_pop(smart_array_t* array, size_t index) {
if(array && (index >= 0) && (index < array->total)) {
array->items[index] = 0;
for (int i = index; i < array->total - 1; ++i) {
array->items[i] = array->items[i + 1];
array->items[i + 1] = NULL;
}
array->total--;
if ((array->total > 0) && ((array->total) == (array->capacity / 4))) {
if(smart_array_resize(array, array->capacity / 2))
return 0;
}
}
return 1;
}
int smart_array_pop_back(smart_array_t* array) {
size_t total;
smart_array_total(array, &total);
return smart_array_pop(array, total - 1);
}
int smart_array_pop_top(smart_array_t* array) {
return smart_array_pop(array, 0);
}
int smart_array_clear(smart_array_t* array) {
int empty;
smart_array_empty(array, &empty);
while(!empty) {
smart_array_pop_top(array);
smart_array_empty(array, &empty);
}
return 0;
}
</code></pre>
<p>Test (main.c):</p>
<pre><code>#include "smart_array.h"
#include <stdlib.h>
#include <stdio.h>
void print_smart_array(smart_array_t* array) {
size_t total, capacity;
smart_array_total(array, &total);
smart_array_capacity(array, &capacity);
printf("Array total: %i\n", total);
printf("Array capacity: %i\n", capacity);
printf("Array items:\n");
for(size_t i = 0; i < total; ++i) {
int* val;
smart_array_get(array, i, (void**)&val);
printf("\t%i\n", *val);
}
}
int main(void) {
smart_array_t* a;
smart_array_alloc(&a, 4);
int* x = malloc(sizeof(int));
int* y = malloc(sizeof(int));
int* z = malloc(sizeof(int));
int* w = malloc(sizeof(int));
*x = 3;
*y = 56;
*z = 100;
*w = 87;
smart_array_push_back(a, x);
smart_array_push_back(a, x);
smart_array_push_top(a, w);
smart_array_push_back(a, w);
smart_array_push_top(a, y);
print_smart_array(a);
smart_array_clear(a);
print_smart_array(a);
free(x);
free(y);
free(z);
free(w);
smart_array_free(&a);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>File Structure</h2>\n<p>The code is well organised into testing, implementation, and headers. Including <code>stddef.h</code> is appropriate in your header since you use <code>size_t</code>.</p>\n<h2>Consistency</h2>\n<p>Consider making sure the pointers are valid, for example, with <code>assert</code>, or at least in documentation, before writing to them. The users of this code might not understand, and it's not ideal for them to go sifting through your code to find the problem. At least, have it consistent; in <code>smart_array_set</code> it checks for null when the others do not.</p>\n<p><code>typedef struct smart_array smart_array_t</code> is potentially problematic. See discussion <a href=\"https://stackoverflow.com/q/231760/2472827\">type followed by _t represent</a> and <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html#typedefs\" rel=\"nofollow noreferrer\">Linux Kernel Style Guide</a>. I think that one's users should be free to express it as a <code>typedef</code>, so I would just stick with <code>struct smart_array</code>; C and C++ are different languages.</p>\n<h2>Return Values</h2>\n<p>Returning <code>void</code> from <code>smart_array_alloc</code> is problematic because there are two different paths it could take; one would have to query the pointer to see if it succeeded. It should be easy to use properly, and as it stands, using this without checking is an (undocumented) mistake.</p>\n<p>I would expect <code>smart_array_get(_*)</code> to return the item. As it stands, one has a pointer to the item passed in and it returns <code>void</code>. This can be annoying when functional composition is desired. Same thing with most of one's other functions. At least shortly document them explaining the change from C++.</p>\n<p>I expect some sort of error or feedback when accessing out-of-bounds, but this does nothing. It is arguably not the best choice.</p>\n<h2>Constructor Simplification</h2>\n<p>I would expect <code>smart_array_alloc</code> is going to be called with the default constructor most of the time, so I would consider make one not including <code>capacity</code> that calls the one that does.</p>\n<p>The two allocations are properly handled by <code>smart_array_alloc</code>, but they could be simplified by calling <code>smart_array_free</code> instead. One doesn't need two allocations, since it's aligned already, it would be simpler to allocate it as one.</p>\n<pre><code>if(!(*array = malloc(sizeof struct smart_array + sizeof(void*) * capacity)\n return (fail);\n(*array)->items = (void *)(*array + 1);\n</code></pre>\n<p>In fact, there are multiple memory allocations that could be all calling <code>smart_array_resize</code>.</p>\n<blockquote>\n<p>If ptr is a null pointer, realloc() shall be equivalent to malloc() for the specified size.</p>\n</blockquote>\n<p>I would consider exposing the <code>struct smart_pointer</code> in the header for allocation on the stack and simplifying this even more, but that's a design decision that is not always appropriate.</p>\n<h2>Zero Values</h2>\n<p><code>smart_array_set_back</code> and <code>smart_array_set_top</code> will have undefined behaviour when empty or capacity is zero.</p>\n<h2>Use of Private Members</h2>\n<p>I think it's okay to use <code>total</code> as a data member in this private code instead of getting it through the public outward-facing <code>smart_array_total</code>. <code>smart_array_clear</code>, with access to private members, should be very simple.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T00:25:42.823",
"Id": "257170",
"ParentId": "257145",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257170",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T14:04:10.043",
"Id": "257145",
"Score": "3",
"Tags": [
"c",
"array",
"memory-management"
],
"Title": "Smart/Dynamic array in C"
}
|
257145
|
<p>On this script I look up properties in an array of objects. There is an original array of strings <code>list</code> to get the objects that match the <code>name</code> property, then I look up their respective line managers, <code>reports</code> recursively but only up to the <code>rank</code> 2, finally I merge their entries with the manager ones.</p>
<p>I was wondering if there is a more efficient way to achieve this result as I am having to make an object to index the managers that have already been checked, otherwise I get duplicates when two people have the same manager. Also having to specify the <code>rank</code> limit twice.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const data = [
{
name: 'rebecca',
reports: '',
rank: 1
},
{
name: 'will',
reports: 'rebecca',
rank: 2
},
{
name: 'jose',
reports: 'will',
rank: 3
},
{
name: 'tomas',
reports: 'jose',
rank: 4,
},
{
name: 'matt',
reports: 'jose',
rank: 5
},{
name: 'alison',
reports: 'john',
rank: 5
}
]
// Initial list of names
const list = ['tomas', 'matt']
// Get the people on the list first
const filterList = data.filter(({ name }) => list.includes(name))
// Helper object to account for managers already checked and avoid duplicates
const managers = {}
// Find missing managers recursively
const findManager = (manager) => {
const next = data.find(({ name }) => name === manager)
managers[next.name] = true
return next.rank > 2 ? [next, ...findManager(next.reports)] : [next]
}
// Get the line managers for the filterList array
const missingManagers = []
for (const { reports, rank } of filterList) {
if (!list.includes(reports) && rank > 2 && !managers[reports] ) {
missingManagers.push(...findManager(reports))
}
}
const result = [...missingManagers, ...filterList]
console.log(result)</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:05:07.307",
"Id": "507945",
"Score": "0",
"body": "*I get duplicates when two people have the same manager*. Sounds like a job for StackOverflow, not CodeReview which is intended for reviewing (not debugging) working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:20:00.413",
"Id": "507948",
"Score": "0",
"body": "Well not really, because I did fix that on my code, so my code is a working code. Was just asking for a better approach if any. You know if I take this to stackoverflow someone just like you would tell me it belongs here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T00:54:09.883",
"Id": "507978",
"Score": "0",
"body": "You may be right. At times it seems like a slight change of wording can change interpretation. I can see how this: \"... having to make an object ... otherwise I get duplicates.\" means the code works. My thought is that duplicates in a recursive search means either bad data - someone is (eventually) his own manager - or a code defect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T01:45:46.030",
"Id": "507982",
"Score": "0",
"body": "If you care to actually read and test the code you will know the reason I get duplicates is because some people on the data array have the same manager, the data is not wrong, the code could be better, sure, but that's why it is here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T02:10:27.090",
"Id": "507984",
"Score": "0",
"body": "I apologize for not understanding what is going on. What is the goal? Find the management chain from, say, from `tomas` to `matt`, or the management chain from each of these persons as the `reports` person? How is `rank` related to the given (person) object? Is rank is where that person falls with a given management chain, say, starting with `tomas` and ending with `matt`? I'm just seeing this as a sorting issue so far."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T02:29:42.703",
"Id": "507985",
"Score": "0",
"body": "cont ... I think pre-organizing `data` as an 2D array using `reports` as the first index then all persons reporting to him/her will simplify traversing for any purpose whatsoever. This code is traversing, linking, extracting all at once. It cannot be fundamentally improved without `data` structured for traversal. Unless the `reports` chain loops back upon itself this is the way to go."
}
] |
[
{
"body": "<p>From a medium review;</p>\n<ul>\n<li>This code belongs in a well named function</li>\n<li>I always forget about destructuring in a <code>filter</code>, very nice</li>\n<li>Mapping to an object automatically removes dupes, something I (ab)use in my counter</li>\n<li><code>const findManager = (manager) </code> should probably be <code>const findManager = (employee)</code></li>\n<li><code>const findManager = (employee) </code> should probably be <code>const findLineManagers = (employee)</code></li>\n<li>From there, <code>next</code> should probably be <code>manager</code> , it is definitely not 'next' but more 'actual' ;)</li>\n<li>You are not using semicolons, unless you understand <a href=\"http://www.bradoncode.com/blog/2015/08/26/javascript-semi-colon-insertion/\" rel=\"nofollow noreferrer\">all nuances</a>, you should use them</li>\n<li>It's more idiomatic in recursive programming to first check for the exit condition than then to check at the end if you should recurse or not</li>\n</ul>\n<p>I struggled with this counter-proposal. I imagine in a codebase I maintain I would want my data structure to be linked. So this function gets a linked version of the data and then gets what is needed in what I think is an easier manner. YMMV.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Initial list of names\n\nfunction indexPeopleData(peopleData){\n //Index by name\n const indexedPeople = peopleData.reduce((out,person) => (out[person.name] = person, out), {});\n //Make reports point to a people object\n peopleData.forEach(person => person.reports = indexedPeople[person.reports]);\n return indexedPeople;\n}\n\nfunction getLineManagers(peopleData, names){\n const indexedPeople = indexPeopleData(peopleData);\n //Return list of employees and their managers\n let out = {}, name;\n while(name = names.pop()){\n out[name] = indexedPeople[name];\n if(out[name].reports.rank > 1){\n names.push(out[name].reports.name);\n }\n }\n return Object.values(out);\n}\n\nvar data = [\n {\n name: 'rebecca',\n reports: '',\n rank: 1\n },\n {\n name: 'will',\n reports: 'rebecca',\n rank: 2\n },\n {\n name: 'jose',\n reports: 'will',\n rank: 3\n },\n {\n name: 'tomas',\n reports: 'jose',\n rank: 4,\n },\n {\n name: 'matt',\n reports: 'jose',\n rank: 5\n },{\n name: 'alison',\n reports: 'john',\n rank: 5\n }\n];\n\nconsole.log(getLineManagers(data, ['tomas', 'matt']));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T10:25:58.047",
"Id": "507911",
"Score": "0",
"body": "Thanks for your response, it is an interesting approach, however the output is incorrect, it should be a flat collection of objects in an array with no deeper levels."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T18:16:29.267",
"Id": "257156",
"ParentId": "257148",
"Score": "1"
}
},
{
"body": "<h2>V poor naming!</h2>\n<p>I have to say that you must improve your naming because as presented the code is unreadable. Not only is the naming very poor, the comments made it even worse, being misplaced or directly counter the name of the function (I presume) the comments describe.</p>\n<p>The only way I could workout what your code should do was to run it and look at the result. I then guessed based on one example.</p>\n<p>My guess is...</p>\n<p>Given a list of manager names list all managers they report to up to rank 2, including managers in the given list.</p>\n<h2>Maps</h2>\n<p>When you need to search for items in a list by a given field you use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Map\">Map</a>. Convert the list to a Map indexed by the field you want to search by. To Find an item in a map the complexity is <span class=\"math-container\">\\$O(1)\\$</span></p>\n<h2>Sets</h2>\n<p>When you need to create a list without duplicates use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a>. You add items to the set and it automatically ensures only one copy of each item.</p>\n<h2>Rewrite</h2>\n<p>Using a map and set to create the array of managers in the chain up from given manager names, including the given manager name.</p>\n<p>There is no indication as to the order of the resulting array so no code was added to ensure that the order matched your example.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nconst manager = (name, reports, rank) => ({name, reports, rank});\nconst data = [ manager(\"rebecca\", \"\", 1), manager(\"will\", \"rebecca\", 2), manager(\"jose\", \"will\", 3), manager(\"tomas\", \"jose\", 4), manager(\"matt\", \"jose\", 5), manager(\"alison\", \"john\", 5)];\n\nfunction managersByField(field, managers) {\n return new Map(managers.map(manager => [manager[field], manager]));\n}\nfunction managmentChain(name, maxRank, managers, chain) {\n var next = managers.get(name);\n while (next?.rank >= maxRank) {\n chain.add(next);\n next = managers.get(next.reports);\n }\n}\nfunction createReport(managers, maxRank, ...names) {\n const res = new Set();\n while (names.length) {\n managmentChain(names.pop(), maxRank, managers, res);\n }\n return [...res];\n}\n\nconsole.log(createReport(managersByField(\"name\", data), 2, 'tomas', 'matt'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>NOTE!</strong> The data MUST NOT contain cyclic references. Example of cyclic reference. "A" reports to "B" and "B" reports to "A".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:44:44.387",
"Id": "508058",
"Score": "0",
"body": "Thanks for your response, it does work very well. And a nice usage of `Map` and `Set`. I don't understand why you re-wrote the original array with the `manager` function, you could use the original `data` array and would work fine. Also there is no need to pass `name` field as a parameter. And the intention was to send the `tomas` and `matt` as an array not as string parameters in a function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:59:11.263",
"Id": "508176",
"Score": "0",
"body": "@Álvaro The data provided did not give enough of a test. I use the spread operator for arrays as you can pass either individual items or an array using the spread operator eg `createReport(managersByField(\"name\", data), 2, ...list)`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T14:48:05.623",
"Id": "257244",
"ParentId": "257148",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T15:30:27.443",
"Id": "257148",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"array",
"ecmascript-6"
],
"Title": "Recursively find data in array of objects"
}
|
257148
|
<p>I wrote this Rust code to parse my financials from a YAML file and my main concern is the large <code>match</code> branches (although general code review is welcome; still a Rust beginner):</p>
<pre><code>extern crate yaml_rust;
use yaml_rust::{Yaml, YamlLoader};
fn main() -> Result<(), std::io::Error> {
let doc = std::fs::read_to_string("finances.yaml")?;
let data = YamlLoader::load_from_str(&doc).unwrap();
let doc = &data[0];
let map = doc.as_hash().unwrap();
for (k, v) in map.iter() {
println!("{}: ", k.as_str().unwrap());
let sum = unwrap_value(v);
println!("== {}", sum);
println!();
}
Ok(())
}
fn unwrap_value(v: &Yaml) -> f32 {
match v {
Yaml::Hash(v) => {
let mut sum = 0.;
for (k, vv) in v.iter() {
match vv {
Yaml::String(_vv) => {
print!("\t\t {}: ", k.as_str().unwrap());
}
Yaml::Integer(_vv) => {
print!("\t\t {}: ", k.as_str().unwrap());
}
_ => {
println!("\t* {}:", k.as_str().unwrap());
}
}
sum += unwrap_value(vv);
}
sum
}
Yaml::Array(v) => {
let mut sub_sum = 0.;
for h in v.iter() {
sub_sum += unwrap_value(h);
}
println!("\t= {}", sub_sum);
sub_sum
}
Yaml::String(v) => {
let tot: f32 = v
.split("+")
.fold(0., |sum, s| sum + s.trim().parse::<f32>().unwrap());
println!("{}", tot);
tot
}
Yaml::Integer(v) => {
println!("{}", v);
*v as f32
}
_ => 0.,
}
}
</code></pre>
<p>Here's a sample YAML of the file I'm parsing:</p>
<pre><code>---
'2021-01-01':
apartment:
- rent: 2750
transportation:
- uber: 87.69 + 55.36 + 26 + 42 + 42 + 34.92 + 25.76 + 42 + 42
- bus: 12
'2021-02-01':
apartment:
- rent: 2750
bills:
- elctricity: 27
transportation:
- uber: 87.69 + 55.36 + 26 + 42 + 42 + 34.92 + 25.76 + 42 + 42
- bus: 12
</code></pre>
<p>and this is the output for the example above:</p>
<pre><code>2021-01-01:
* apartment:
rent: 2750
= 2750
* transportation:
uber: 397.73
bus: 12
= 409.73
== 3159.73
2021-02-01:
* apartment:
rent: 2750
= 2750
* bills:
elctricity: 27
= 27
* transportation:
uber: 397.73
bus: 12
= 409.73
== 3186.73
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T16:54:19.147",
"Id": "507857",
"Score": "2",
"body": "Can you please also add the output of your program to your post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T16:57:33.727",
"Id": "507858",
"Score": "0",
"body": "Thanks @zeta. I just did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T16:12:25.123",
"Id": "508440",
"Score": "0",
"body": "Your YAML is unusual because the `-`s turn the innermost structure into a sequence of strings instead of a map. Is that intentional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T07:51:24.183",
"Id": "508551",
"Score": "0",
"body": "Just a small aside: you might be interested in [`ledger-cli`](https://www.ledger-cli.org/) or similar applications."
}
] |
[
{
"body": "<h1>Structure your data</h1>\n<p>The reason you need nested <code>match</code>es is that even after parsing the YAML document into a <code>Yaml</code> object, it's still essentially unstructured data. Not every YAML object will have the right shape, so you have to validate it piece by piece as you traverse it. Worse, you'll have to validate it all over again next time you try to traverse it. This is inefficient and ugly.</p>\n<p>Define some data structures that will hold the information currently held in a YAML document. How you define these depends on how rigid the data format is and what you plan to do with it. Here's one way to do it. You'll need to add <code>chrono</code> to your dependencies.</p>\n<pre><code>use chrono::NaiveDate as Date;\n\nstruct Document {\n by_date: HashMap<Date, Expenses>,\n}\n\nstruct Expenses {\n by_category: HashMap<String, Vec<Entry>>,\n}\n\nstruct Entry {\n payee: String,\n payments: Vec<f32>,\n}\n</code></pre>\n<p>Define what it means to total up the whole <code>Document</code> by deferring to its contents:</p>\n<pre><code>impl Document {\n fn total(&self) -> f32 {\n // the total of a Document is the sum of the total expenses on each date\n self.by_date.values().map(|expenses| expenses.total()).sum()\n }\n}\n\nimpl Expenses {\n fn total(&self) -> f32 {\n // the total is the sum of the totals of each Entry in each category\n self.by_category.values().flat_map(|entries| entries.iter().map(Entry::total)).sum()\n }\n}\n\nimpl Entry {\n fn total(&self) -> f32 {\n // the total is the sum of all the individual payments\n self.payments.iter().sum()\n }\n}\n</code></pre>\n<sup>\n<p><strong>Note 1:</strong> I am completely ignoring the printing part of <code>unwrap_value</code>. You could add that to the above code relatively easily, but it would be noisy and not super instructive, so I'm just going to focus on the totaling.</p>\n<p><strong>Note 2:</strong> It might sometimes be useful to write a <code>Total</code> trait and implement it for <code>Entry</code>, <code>Document</code> and <code>Expenses</code>, instead of having three unrelated functions. But it doesn't seem useful here, so I didn't.</p>\n</sup>\n<br>\n<h1>Deserialize with Serde</h1>\n<p>Now, the only problem that remains is how to turn a YAML document into a <code>Document</code>. You <em>could</em> write code to convert from a <code>Yaml</code> object, but the bulk of the work has been done for you already by the <strong>Serde</strong> library. Serde is an extremely versatile library for serialization and deserialization of just about any Rust data structure from just about any data format. Any time you're considering serialization, unless you know you need something specific, it's a good idea to start with Serde. You'll need to add <code>serde</code>, <code>serde-yaml</code> and <code>serde-derive</code> to your dependencies.</p>\n<p>When the data format is flexible, you might just add <code>#[derive(Deserialize)]</code> on all your structs to get the default behavior. In this case, since there's a particular YAML format we're trying to match, we need to add some annotations to explain to Serde just how to put things together. I used <code>chrono::NaiveDate</code> in part because it already implements <code>Deserialize</code>, which makes this task easier by half.</p>\n<pre><code>#[derive(Deserialize)]\n#[serde(transparent)]\nstruct Document {\n by_date: HashMap<Date, Expenses>,\n}\n\n#[derive(Deserialize)]\n#[serde(transparent)]\nstruct Expenses {\n by_category: HashMap<String, Vec<Entry>>,\n}\n\n#[derive(Deserialize)]\n#[serde(try_from = "HashMap<String, String>")]\nstruct Entry {\n payee: String,\n payments: Vec<f32>,\n}\n\nimpl TryFrom<HashMap<String, String>> for Entry {\n type Error = String;\n fn try_from(value: HashMap<String, String>) -> Result<Self, Self::Error> {\n for (payee, etc) in value {\n let payments = etc.split('+')\n .map(|s| s.trim().parse::<f32>())\n .collect::<Result<_, _>>()\n .map_err(|e| e.to_string())?;\n return Ok(Entry { payee, payments });\n }\n Err("Empty map".to_owned())\n }\n}\n</code></pre>\n<p>I didn't have to actually write any code for <code>Document</code> and <code>Expenses</code>; I just used the <code>serde(transparent)</code> attribute to tell Serde to treat those structs exactly the same as their contained types. For <code>Entry</code>, since Serde's YAML deserializer can already parse a string like <code>rent: 2750</code> into a <code>HashMap<String, String></code>, I just implemented <code>TryFrom<HashMap<String, String>></code> and told Serde to use that. This handy trick requires less code and is easier to wrap your head around than a full <code>Deserialize</code> implementation, but may be slightly slower.</p>\n<p>Now all we have to do is use it:</p>\n<pre><code>let doc: Document = serde_yaml::from_str(&doc).unwrap();\nprintln!("total: {}", doc.total());\n</code></pre>\n<p>For a small initial investment in code, your data is now made of meaningful, Rusty types like <code>Date</code> and <code>HashMap</code> instead of all different <code>Yaml</code> values. You can add a little bit more code to also support serialization, and because Serde is a general purpose (de)serialization library and not a particular data format, switching to another format like JSON or bincode (should you want to) is just a couple lines of code.</p>\n<h1>And another thing</h1>\n<p>Floating-point numbers are bad for money because they have variable precision. Use a decimal library, or fixed-point arithmetic (i.e. store an integer number of the smallest possible amount of money – cents instead of dollars.) If you absolutely must use floating-point numbers, at least use <code>f64</code>, and don't say I didn't warn you not to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T05:28:19.850",
"Id": "508548",
"Score": "1",
"body": "\"don't say I didn't warn you\": +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T02:08:47.367",
"Id": "257460",
"ParentId": "257150",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "257460",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T16:47:53.147",
"Id": "257150",
"Score": "1",
"Tags": [
"beginner",
"rust",
"yaml"
],
"Title": "Parsing financials from a YAML file. Is this normal/idiomatic in Rust?"
}
|
257150
|
<p>This works for me, but is this the right way to create this timer?</p>
<p>I might be naive about this but I think this is close to perfect in pure JS.</p>
<p>What would be the drawbacks of using this Timer compared to creating it in a different way?</p>
<ul>
<li>Click start and the timer starts to countdown.</li>
<li>Click reset and the timer resets back to the starting time.</li>
</ul>
<p>HTML:</p>
<pre><code><button onclick='startStopTimer()'>Start</button>
<button onclick='startStopTimer()'>Reset</button>
<h1>00:10</h1>
</code></pre>
<p>JavaScript:</p>
<pre><code>console.clear()
let timer = document.querySelector('h1')
let startingTime = 9
let startTimer;
let startStopTimer = () => {
if(startTimer){
clearInterval(startTimer);
timer.innerHTML = '00:10'
startingTime = 9
return startTimer = undefined
}else{
return startTimer = setInterval(()=>{
timer.innerHTML = `00:0${startingTime--}`
}, 1000)
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T13:22:59.847",
"Id": "507921",
"Score": "0",
"body": "Consider the naming `restart` vs `reset`. To me, `reset` means put it back to zero and `restart` means put it back to zero and start the timer again. Could just be me though."
}
] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li>You use <code>9</code> twice, this should be assigned to a nicely named global constant</li>\n<li>You hard code both <code>9</code> and <code>00:10</code>, this is not flexible. I would expect to be able to change <code>9</code> to <code>99</code> and to have the timer start at <code>01:40</code></li>\n<li>Similarly, <code>00:0${startingTime--}</code> does not allow for much flexibility in the script</li>\n<li>The browser <a href=\"https://www.goat1000.com/2011/03/23/how-accurate-is-window.setinterval.html\" rel=\"nofollow noreferrer\">tries</a> to honor the <code>1000</code>, <a href=\"https://stackoverflow.com/questions/8173580/setinterval-timing-slowly-drifts-away-from-staying-accurate\">but it cannot be trusted</a>. You are supposed to keep track of the original start and deduct that from current time to determine how much time has passed. Otherwise the timer is not reliable.</li>\n<li>Placing the timer in a <code>h1</code> element is probably not a good idea semantically</li>\n<li>Your entire code should be in a well named (self executing) function</li>\n<li>I am not sure why you return anything in <code>startStopTimer</code>? If you are never using the returned value, then just drop the <code>return</code> keyword</li>\n<li>since <code>clearInterval</code> returns <code>undefined</code> and because it makes sense, I would go for <code>startTimer = clearInterval(startTimer);</code></li>\n<li>Why <code>console.clear()</code>? Production code should avoid <code>console</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T20:52:09.760",
"Id": "507964",
"Score": "0",
"body": "I thought I was good lol, guess not. Thanks for theses informative gems! Console.clear() is there because I was playing around in codepen. I just copied my whole script. I’ll make sure to keep that out of production code for sure."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T18:32:20.790",
"Id": "257158",
"ParentId": "257151",
"Score": "3"
}
},
{
"body": "<h3>HTML</h3>\n<ul>\n<li>The inline <code>onClick</code> event handler attached to your HTML element probably works fine; however there are better ways to deal with the events in pure JS. Next time, add the event handlers in the JS file like so: <code>element.addEventListener('click', callbackName)</code>.</li>\n<li><code>h1</code> is a header. I'd not place the timer value inside that particular tag. I think that <code>span</code> would be better here according to semantic HTML rules.</li>\n</ul>\n<h3>JavaScript</h3>\n<ul>\n<li>Some of your <code>let</code>-based variables could be changed to <code>const</code>. The idea is to use <code>const</code> whenever it's possible. If it's not, only then use <code>let</code>.</li>\n<li><code>innerHTML</code> is a dangerous method. It might be used to perform XSS attacks. Try to avoid it to display text on your website.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T21:01:27.277",
"Id": "507965",
"Score": "0",
"body": "Your right I should have used addEventListener for a “pure” js timer. I do need to think about semantics more when I write HTML. It isn’t good practice to not do so. Thanks for that. I should have used innerText instead of innerHTML."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T21:03:00.000",
"Id": "507966",
"Score": "0",
"body": "No problem :) Good luck with refactoring !"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T20:23:57.027",
"Id": "257164",
"ParentId": "257151",
"Score": "3"
}
},
{
"body": "<h2>Countdowns</h2>\n<p>Some points missed or skimmed over by other answers.</p>\n<ul>\n<li><p><strong>Visibility:</strong></p>\n<p>Always keep DOM interaction to a minimum. In timers you should check if the document is visible before you make changes that may not be viewed by the client.</p>\n<p>Timers are one such app that contains animations that the client will not continually watch.</p>\n<p>Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API\" rel=\"nofollow noreferrer\">page visibility API</a> to check for page visibility and listen to visibility change events.</p>\n</li>\n<li><p><strong>Time element:</strong></p>\n<p>Use appropriate elements. To display a time such as a count down use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTimeElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTimeElement\">HTMLTimeElement</a> and set its <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTimeElement/dateTime\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTimeElement dateTime\">HTMLTimeElement.dateTime</a> property to match the visible countdown time.</p>\n<p>This gives meaning to the content and lets machines understand what the content represents.</p>\n</li>\n<li><p><strong>Text is not Markup:</strong></p>\n<p>Never use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Element innerHTML\">Element.innerHTML</a> to set text only content as it will force a CPU/GPU expensive re-flow. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Node textContent\">Node.textContent</a> and avoid the expensive re-flow.</p>\n</li>\n<li><p><strong>Calculate Time</strong></p>\n<p>Timers such as <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"nofollow noreferrer\" title=\"MDN Web API's WindowOrWorkerGlobalScope setInterval\">setInterval</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\" rel=\"nofollow noreferrer\" title=\"MDN Web API's WindowOrWorkerGlobalScope setTimeout\">setTimeout</a> should not be use to measure time. To measure time till an event store the expected time and calculate the time from now till then.</p>\n<p>Avoid using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval\" rel=\"nofollow noreferrer\" title=\"MDN Web API's WindowOrWorkerGlobalScope setInterval\">setInterval</a> as it can fire well off the expected interval, rather calculate the time until the next visual change and use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\" rel=\"nofollow noreferrer\" title=\"MDN Web API's WindowOrWorkerGlobalScope setTimeout\">setTimeout</a></p>\n</li>\n<li><p><strong>Scope:</strong></p>\n<p>Avoid using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. let\">let</a> in the global scope as its scope is un-intuitive and may throw errors due to clashes with existing named variables unrelated to you code.</p>\n</li>\n<li><p><strong>Add don't set listeners:</strong></p>\n<p>Never set event listeners directly eg <code>onclick="somefunction"</code> as the event listener can be overwritten by accident by you, or by poorly written 3rd party code or extensions</p>\n<p>Always use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\" title=\"MDN Web API's EventTarget addEventListener\">EventTarget.addEventListener</a> to add event listeners.</p>\n</li>\n<li><p><strong>Disable unusable UI</strong></p>\n<p>A button that does nothing should be disabled.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Following points outlined above the snippet implements a countdown timer with start/restart and stop buttons.</p>\n<p>The code details...</p>\n<ul>\n<li>Isolates scope using <code>{}</code></li>\n<li>Calculates timer value rather than count time using timer events</li>\n<li>Calculates time till next visual change rather than use unreliable interval timer.</li>\n<li>Uses the correct element to display time. Also sets the machine readable property <code>dateTime</code>. (note that I was lazy and only set the seconds)</li>\n<li>Adds event listeners rather than set event listeners.</li>\n<li>Listens to <code>visibilityChange</code> so that the time the client sees is always correct.</li>\n<li>Checks the page visibility before making visual changes to the page. (note the last event will make changes to the DOM)</li>\n<li>Disables the stop button when there is nothing to stop.</li>\n<li>Stores the timer length as the buttons <code>value</code> property (Note that the stop button has a value of 0)</li>\n</ul>\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>{ // to isolate the scope of your code from any existing code.\n const TICK_RESOLUTION = 1000; // in ms\n const TIMER_LENGTH = 10; // multiples of TICK_RESOLUTION\n startBtn.value = TIMER_LENGTH * TICK_RESOLUTION;\n \n startBtn.addEventListener(\"click\", startStopTimer);\n stopBtn.addEventListener(\"click\", startStopTimer);\n document.addEventListener(\"visibilityChange\", tick);\n \n let endTime, timeHdl;\n function startStopTimer(event) {\n endTime = performance.now() + Number(event.target.value); \n tick();\n }\n function tick() {\n clearTimeout(timeHdl);\n var till = endTime - performance.now();\n till = till <= 0 ? 0 : till; \n if (till) {\n if (document.visibilityState === \"visible\") {\n stopBtn.disabled = false;\n timeEl.textContent = (till / TICK_RESOLUTION + 1 | 0);\n }\n timeEl.dateTime = \"PT0H0M\" + (till / TICK_RESOLUTION + 1 | 0) + \"S\";\n timeHdl = setTimeout(tick, (till % TICK_RESOLUTION) + 10);\n } else {\n timeEl.dateTime = \"PT0H0M0S\";\n timeEl.textContent = 0;\n stopBtn.disabled = true;\n }\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div {\n font-family: arial;\n font-size: 48px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><button id=\"startBtn\" value=\"0\">Start</button>\n<button id=\"stopBtn\" disabled value=\"0\">Stop</button>\n<div><time id=\"timeEl\" dateTime=\"PT0H0M0S\">0</time> seconds</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:59:42.020",
"Id": "508110",
"Score": "0",
"body": "Wow, I didn’t know about the time element!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:10:18.753",
"Id": "257234",
"ParentId": "257151",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T16:48:43.887",
"Id": "257151",
"Score": "2",
"Tags": [
"javascript",
"timer"
],
"Title": "A Countdown Timer with reset functionality in pure Javascript"
}
|
257151
|
<p>Can you guys review my GraphQL search pagination function? I'm afraid there could be some performance issues, or something. Especially at the aggregation section and this <code>const result: any = await this.BooksModel.findOne(</code> section.</p>
<p>I'm using MongoDB as the database and string ISO Date as cursor.</p>
<p>I tried looking for any search pagination example on the internet but found none.</p>
<pre class="lang-js prettyprint-override"><code>async getBooks({
first,
after,
last,
before,
search,
}: {
first?: number | null
after?: string | null
last?: number | null
before?: string | null
search?: string | null
}) {
if (first && last)
throw new AppError(
'`first` and `last` cannot be used at the same time',
400,
)
if (!first && !last)
throw new AppError('Either `first` or `last` is required', 400)
if (after && before)
throw new AppError(
'`after` and `before` cannot be used at the same time',
400,
)
if (search && last)
throw new AppError('`search` and `last` is not allowed', 400)
if (search) {
let score = null
if (after) {
const date = new Date(after)
const result: any = await this.BooksModel.findOne(
{
created: date,
$text: { $search: search },
},
{ score: { $meta: 'textScore' } },
)
score = result._doc.score
}
const filter = { score: { $lt: score } }
const limit = first ? first : last!
const books = await this.BooksModel.aggregate([
{ $match: { $text: { $search: search } } },
{ $addFields: { score: { $meta: 'textScore' }, id: '$_id' } },
...(score ? [{ $match: filter }] : []),
{ $sort: { score: { $meta: 'textScore' } } },
{ $limit: limit },
])
return books
} else {
const sort = { created: first ? -1 : 1 }
const limit = first ? first : last!
const books = await this.BooksModel.find({
...(after ? { created: { $lt: new Date(after) } } : null),
...(before ? { created: { $gt: new Date(before) } } : null),
})
.sort(sort)
.limit(limit)
.exec()
return books
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T17:39:25.323",
"Id": "257153",
"Score": "1",
"Tags": [
"javascript",
"pagination",
"cursor",
"graphql"
],
"Title": "Cursor-based search result pagination"
}
|
257153
|
<p>For some reason, I am trying to implement a various type tuple flatten tool with the following requirements:</p>
<ul>
<li><p>The nested <code>Tuple</code> object <code>Tuple<Tuple<...>></code> can be unwrapped into <code>Tuple<...></code>.</p>
</li>
<li><p>There are various types in the nested <code>Tuple</code> object.</p>
</li>
<li><p>The return type is set on <code>Tuple<...></code> (not generic <code>object</code>).</p>
</li>
</ul>
<p>I have checked <em><a href="https://stackoverflow.com/q/55108347/6667035">how to flatten nested tuples in c#?</a></em>. <a href="https://stackoverflow.com/a/55108883/6667035">JuanR's answer</a> is good but the same type is specified in <code>Tuple</code>. As the result, the following <code>TupleFlattener</code> has been implemented.</p>
<p><strong>The experimental implementation</strong></p>
<pre><code>public static class TupleFlattener
{
public static Tuple<T1> Perform<T1>(in Tuple<Tuple<T1>> input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
return new Tuple<T1>(input.Item1.Item1);
}
public static Tuple<T1, T2> Perform<T1, T2>(in Tuple<Tuple<T1, T2>> input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
return new Tuple<T1, T2>(input.Item1.Item1, input.Item1.Item2);
}
public static Tuple<T1, T2, T3> Perform<T1, T2, T3>(in Tuple<Tuple<T1, T2, T3>> input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
return new Tuple<T1, T2, T3>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3);
}
public static Tuple<T1, T2, T3, T4> Perform<T1, T2, T3, T4>(in Tuple<Tuple<T1, T2, T3, T4>> input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
return new Tuple<T1, T2, T3, T4>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4);
}
public static Tuple<T1, T2, T3, T4, T5> Perform<T1, T2, T3, T4, T5>(in Tuple<Tuple<T1, T2, T3, T4, T5>> input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
return new Tuple<T1, T2, T3, T4, T5>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4, input.Item1.Item5);
}
public static Tuple<T1, T2, T3, T4, T5, T6> Perform<T1, T2, T3, T4, T5, T6>(in Tuple<Tuple<T1, T2, T3, T4, T5, T6>> input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
return new Tuple<T1, T2, T3, T4, T5, T6>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4, input.Item1.Item5, input.Item1.Item6);
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7> Perform<T1, T2, T3, T4, T5, T6, T7>(in Tuple<Tuple<T1, T2, T3, T4, T5, T6, T7>> input)
{
if (input is null) throw new ArgumentNullException(nameof(input));
return new Tuple<T1, T2, T3, T4, T5, T6, T7>(input.Item1.Item1, input.Item1.Item2, input.Item1.Item3, input.Item1.Item4, input.Item1.Item5, input.Item1.Item6, input.Item1.Item7);
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<pre><code>Tuple<Tuple<int, char, double>> tupleInput =
new Tuple<Tuple<int, char, double>>(new Tuple<int, char, double>(10, 'a', 5.5));
var output = TupleFlattener.Perform(tupleInput);
Console.WriteLine($"Output type: {output.GetType()}");
Console.WriteLine($"Item1: {output.Item1}");
Console.WriteLine($"Item2: {output.Item2}");
Console.WriteLine($"Item3: {output.Item3}");
</code></pre>
<p>The output of the above test:</p>
<pre><code>Output type: System.Tuple`3[System.Int32,System.Char,System.Double]
Item1: 10
Item2: a
Item3: 5.5
</code></pre>
<p>If there is any possible improvement, please let me know.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T18:41:41.370",
"Id": "507865",
"Score": "3",
"body": "As for me there's no sense to wrap single `Tuple` with `Tuple`. Anyway if that happened, it's the reason to investigate why, instead of making the workaround."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-23T21:38:57.457",
"Id": "508785",
"Score": "0",
"body": "Aren't tuples immutable? If so, why `return new Tuple<T1, T2...>(input.Item1.Item1, ...);` instead of just `return input.Item1;`"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T18:09:24.380",
"Id": "257155",
"Score": "0",
"Tags": [
"c#",
"generics"
],
"Title": "Various type Tuple flatten tool implementation"
}
|
257155
|
<p>This is my solution to a <a href="//stackoverflow.com/q/66628354/14737198">"vacancy test" task</a>.</p>
<p>I'm not sure at all if I have correctly implemented the task, but here is my solution.</p>
<p>Goals of code:</p>
<ol>
<li>Parse rows of table from a URL and extract some data (make a list of jsons from this data).</li>
<li>Parse rows of table from a URL and download PDF (link is placed inside a row).</li>
</ol>
<p>Code:</p>
<pre><code>import asyncio
import aiofiles
from aiohttp import ClientSession as aiohttp_ClientSession
from bs4 import BeautifulSoup
from pathlib import Path as pathlib_Path
from json import dumps as json_dumps
from loguru import logger
from sys import platform as sys_platform
# # # HARDCODED # # #
MIN_YEAR = 2018
MAX_YEAR = 2020
def is_key_in_dict(dict_key: str, array: list):
for i, dict_ in enumerate(array):
if dict_['form_number'] == dict_key:
return i
async def load_page(url: str, session, ):
async with session.get(url=url, ) as resp:
if 200 <= resp.status <= 299:
return await resp.read()
else:
logger.error(f'Can not access a page, returned status code: {resp.status_code}')
async def parse_page_forms_json(rows: list) -> list[str]: # Every page contain set of forms
page_forms = []
for row in rows:
try:
form_number = row.findChild(['LeftCellSpacer', 'a']).string.split(' (', 1)[0] # split to remove non eng ver
current_year = int(row.find(name='td', attrs={'class': 'EndCellSpacer'}).string.strip())
index = is_key_in_dict(dict_key=form_number, array=page_forms)
if index is None:
page_forms.append({
'form_number': form_number, # Title in reality
'form_title': row.find(name='td', attrs={'class': 'MiddleCellSpacer'}).string.strip(),
'min_year': current_year,
'max_year': current_year,
})
else: # If exists - modify form
if page_forms[index]['min_year'] > current_year:
page_forms[index]['min_year'] = current_year
elif page_forms[index]['max_year'] < current_year:
page_forms[index]['max_year'] = current_year
except Exception as e:
logger.error(f'Error: {e}')
return [json_dumps(page_form) for page_form in page_forms] # What to do whit this data?
async def save_page_form_pdf(rows, session):
for row in rows:
try:
current_year = int(row.find(name='td', attrs={'class': 'EndCellSpacer'}).string.strip())
form_number_elem = row.findChild(['LeftCellSpacer', 'a']) # link and name
form_number = form_number_elem.string.split(' (', 1)[0] # split to remove non eng ver
if MIN_YEAR <= current_year <= MAX_YEAR:
resp = await load_page(url=form_number_elem.attrs['href'], session=session)
# See https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir
pathlib_Path(form_number).mkdir(parents=True, exist_ok=True) # exist_ok - skip FileExistsError
filename = f"{form_number}/{form_number}_{current_year}.pdf"
async with aiofiles.open(file=filename, mode='wb') as f:
await f.write(resp)
except Exception as e:
logger.error(f'Can not save file, error: {e}')
async def main():
async with aiohttp_ClientSession() as session:
tasks = []
pagination = 0
while 1:
url = (f'https://apps.irs.gov/app/picklist/list/priorFormPublication.html?'
f'indexOfFirstRow={pagination}&'
f'sortColumn=sortOrder&'
f'value=&criteria=&'
f'resultsPerPage=200&'
f'isDescending=false')
page = await load_page(url=url, session=session)
soup = BeautifulSoup(page, 'html.parser')
table = soup.find(name='table', attrs={'class': 'picklist-dataTable'}) # Target
rows = table.find_all(name='tr')[1:] # [1:] - Just wrong HTML
if rows:
tasks.append(await parse_page_forms_json(rows=rows)) # Task 1
tasks.append(await save_page_form_pdf(rows=rows, session=session)) # Task 2
pagination += 200
else: # Stop pagination
break
await asyncio.gather(*tasks)
pass
if __name__ == '__main__':
# See https://github.com/encode/httpx/issues/914#issuecomment-622586610 (exit code is 0, but error is exists)
if sys_platform.startswith('win'):
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
logger.add('errors.txt', level='ERROR', rotation="30 days", backtrace=True)
asyncio.run(main())
</code></pre>
<p>The logic of code:</p>
<ol>
<li>Asynchronously get a page with table rows (tax forms)</li>
<li>Do some actions with forms (blocking and non-blocking)</li>
<li>Repeat
P.s. You can skip code of all functions except <code>main</code>, <code>load_page</code> and <code>save_page_form_pdf</code> (they are no matter).</li>
</ol>
<p>Questions:</p>
<ol>
<li>Have I picked a good architecture? Especially I'm curious about the self-implemented <code>if item not in list</code> python pattern because this pattern is good for a simple object inside a list, but I have a list of the <code>dict</code>s and checking by <code>dict</code> key. After some experiments, I didn't find a better realization than presented here.</li>
<li>Is an asynchronous solution good enough? It's my first experience with asynchronous web scraping.</li>
<li>Maybe I need to optimize the check whether the form already exists in the list of forms, and not iterate over the entire list every time, but apply some sorting algorithm or something else?</li>
<li>Do I need to add <code>await</code> keyword in a <code>tasks.append(await save_page_form_pdf(rows=rows, session=session))</code> line?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T13:56:40.543",
"Id": "507926",
"Score": "0",
"body": "Unfortunately this question is _off-topic_ because this site is for reviewing **working** code. Please [take the tour](https://codereview.stackexchange.com/tour) and read up at our [help center](https://codereview.stackexchange.com/help/on-topic). When the code works then feel free to [edit] the post to include it for a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:41:17.157",
"Id": "507928",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ, Okay, I will fix it in a few hours"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:46:45.083",
"Id": "507929",
"Score": "1",
"body": "When it's working, please add a good description of what the program is supposed to do. Then the question will be ready for reopening."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T12:21:35.430",
"Id": "508198",
"Score": "0",
"body": "@TobySpeight The code is working now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T12:38:39.130",
"Id": "508202",
"Score": "1",
"body": "You need a little update (still says \"code is incorrect currently\"). Also, what's the code supposed to do? Can you summarise what's on the other end of that link, so that the question is self-contained? Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T12:51:29.320",
"Id": "508205",
"Score": "0",
"body": "@TobySpeight done"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T19:47:42.830",
"Id": "257159",
"Score": "0",
"Tags": [
"python",
"parsing",
"web-scraping",
"asynchronous"
],
"Title": "Asynchronous web scraping"
}
|
257159
|
<p>I am able to make the clock layout and get the time but I don't understand how to continuously update the time.<br />
I made the layout using Java labels and I have to change their texts continuously</p>
<pre><code>calendar=Calendar.getInstance();
frame =new JFrame();
panel= new JPanel();
hour=calendar.get(Calendar.HOUR);
minute=calendar.get(Calendar.MINUTE);
second=calendar.get(Calendar.SECOND);
</code></pre>
<p>a <code>calendar</code> is the name of my <code>Calendar</code> object</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T21:10:08.863",
"Id": "507884",
"Score": "0",
"body": "Calendar is not advised to be used any more - try [LocalTime](https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T21:11:51.210",
"Id": "507885",
"Score": "0",
"body": "You can create a [TimerTask for the Timer](https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html) which will get called regularly if you say want to continually (every second) update the clock output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T04:16:27.093",
"Id": "507896",
"Score": "0",
"body": "the problem is that the assignment requires me to use calendar class"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T04:37:34.687",
"Id": "507897",
"Score": "0",
"body": "Go ahead use Calendar - what you've done is fine for the first call. You'll need to call `setTime()` each time your timer task runs. I would add some comments to where you are using the calendar pointing to this <https://stackoverflow.com/questions/29927362/localtime-from-date> or one of the other articles about Date/Calendar/Time - or to the javadoc for java.util.Time.LocalTime- to show you researched whether it's a good thing to do or not :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T08:45:58.153",
"Id": "520273",
"Score": "0",
"body": "its ok u got it and thanks for the method idea i used the try and catch to help me continously update time in an interval"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T19:55:15.627",
"Id": "257163",
"Score": "1",
"Tags": [
"java"
],
"Title": "digital clock in java using calendar class"
}
|
257163
|
<p><a href="https://leetcode.com/problems/delete-and-earn/" rel="nofollow noreferrer">https://leetcode.com/problems/delete-and-earn/</a></p>
<blockquote>
<p>Given an array nums of integers, you can perform operations on the
array.</p>
<p>In each operation, you pick any nums[i] and delete it to earn nums[i]
points. After, you must delete every element equal to nums[i] - 1 or
nums[i] + 1.</p>
<p>You start with 0 points. Return the maximum number of points you can
earn by applying such operations.</p>
<p>Example 1:</p>
<p>Input: nums = [3,4,2] Output: 6 Explanation: Delete 4 to earn 4
points, consequently 3 is also deleted. Then, delete 2 to earn 2
points. 6 total points are earned. Example 2:</p>
<p>Input: nums = [2,2,3,3,3,4] Output: 9 Explanation: Delete 3 to earn 3
points, deleting both 2's and the 4. Then, delete 3 again to earn 3
points, and 3 again to earn 3 points. 9 total points are earned.</p>
<p>Constraints:</p>
<p>1 <= nums.length <= 2 * 10^4 <br>
1 <= nums[i] <= 10^4</p>
</blockquote>
<p>please review for performance, I know I am copying the dictionary over and over again.
Leetcode offers a solution based on range of numbers array[10001]. I don't like that solution (counting sort). my head usually sees this is a dictionary.. but I think there is room for optimizations.
Thanks</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
namespace DynamicProgrammingQuestions
{
/// <summary>
/// https://leetcode.com/problems/delete-and-earn/
/// </summary>
[TestClass]
public class DeleteAndEarnTest
{
[TestMethod]
public void TestMethod1()
{
int[] nums = {3, 4, 2};
Assert.AreEqual(6, DeleteAndEarn(nums));
Assert.AreEqual(6, DeleteAndEarn2(nums));
}
[TestMethod]
public void TestMethod2()
{
int[] nums = { 2, 2, 3, 3, 3, 4 };
Assert.AreEqual(9, DeleteAndEarn(nums));
Assert.AreEqual(9, DeleteAndEarn2(nums));
}
[TestMethod]
public void FailedTestMethod()
{
int[] nums = { 1,1,1,2,4,5,5,5,6 };
Assert.AreEqual(18, DeleteAndEarn(nums));
Assert.AreEqual(18, DeleteAndEarn2(nums));
}
[TestMethod]
public void FailedTestMethod2()
{
int[] nums = { 3,1 };
Assert.AreEqual(4, DeleteAndEarn(nums));
Assert.AreEqual(4, DeleteAndEarn2(nums));
}
public int DeleteAndEarn(int[] nums)
{
if (nums == null || nums.Length == 0)
{
return 0;
}
var dict = new Dictionary<int, int>();
foreach (var curr in nums)
{
if (!dict.ContainsKey(curr))
{
dict.Add(curr, 1);
}
else
{
dict[curr]++;
}
}
int max = 0;
foreach (var key in dict.Keys)
{
max = Math.Max(max, Helper(key, new Dictionary<int, int>(dict)));
}
return max;
}
private int Helper(int key, Dictionary<int, int> dict)
{
int max = key * dict[key];
dict.Remove(key);
if (dict.ContainsKey(key + 1))
{
dict.Remove(key + 1);
}
if (dict.ContainsKey(key - 1))
{
dict.Remove(key - 1);
}
int temp = 0;
foreach (var curr in dict.Keys.ToList())
{
temp = Math.Max(temp,Helper(curr, new Dictionary<int, int>(dict)));
}
return max + temp;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T12:16:11.530",
"Id": "508301",
"Score": "0",
"body": "Are you concerned about speed or memory consumption? Have you performed any profiling with different datasets?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T15:37:12.990",
"Id": "508331",
"Score": "0",
"body": "speed profiling, no I have not"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T15:39:38.737",
"Id": "508334",
"Score": "0",
"body": "I can't see the definition of `DeleteAndEarn2`. Could you share that as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T17:43:57.733",
"Id": "508353",
"Score": "0",
"body": "Sorry that is another trial I had. Please ignore"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T21:56:13.010",
"Id": "257166",
"Score": "0",
"Tags": [
"c#",
"performance",
"programming-challenge",
"dynamic-programming"
],
"Title": "LeetCode: Delete and Earn C#"
}
|
257166
|
<p>I have written a fairly simple bot that provides information or additional choice based on the user's query. It runs well and does the job, however, I was wondering how can I optimize my code and use the telebot better?</p>
<p>Currently the main action happens in the query handler and something tells me that I am missing possible efficiency gains (when I will attempt to build more choices for example). Below is the code, simplified for demonstration purposes:</p>
<pre><code>import telebot
from telebot import types
token = bottoken
bot = telebot.TeleBot(token)
@bot.message_handler(commands=['start'])
def welcome(message):
# here i give the main choice that is always visible to the user
markup = types.ReplyKeyboardMarkup(resize_keyboard=False)
item1 = types.KeyboardButton("Button1")
item2 = types.KeyboardButton("Button2")
markup.add(item1, item2)
bot.send_message(message.chat.id, "Welcome message".format(message.from_user, bot.get_me()),
parse_mode='html', reply_markup=markup)
@bot.message_handler(content_types=['text'])
def main_choice(message):
# here i develop each of the main choices and redirect to the callback handler
if message.text == 'Button1':
# Forward to callback handler
markup = types.InlineKeyboardMarkup()
item1 = types.InlineKeyboardButton("Yes", callback_data = 'demo_yes')
item2 = types.InlineKeyboardButton("No", callback_data = 'demo_no')
markup.add(item1, item2)
bot.send_message(message.chat.id, 'Some text', reply_markup=markup)
elif message.text == 'Button2':
# some logic
else :
bot.send_message(message.chat.id, 'Sorry, i dont understand. You can use /help to check how i work')
@bot.callback_query_handler(func=lambda call: True)
def tempo(call):
# here a handle the queries launched both by main buttons and the inline keyboard
if call.data == "demo_yes":
keyboard = types.InlineKeyboardMarkup()
item1 = types.InlineKeyboardButton("Text1", callback_data = 'call1')
item2 = types.InlineKeyboardButton("Text2", callback_data = 'call2')
keyboard.add(item1,item2)
bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)
elif call.data == "demo_no":
kkeyboard = types.InlineKeyboardMarkup()
item1 = types.InlineKeyboardButton("Text3", callback_data = 'call3')
item2 = types.InlineKeyboardButton("Text4", callback_data = 'call4')
keyboard.add(item1,item2)
bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)
if call.data == "call1":
keyboard = types.InlineKeyboardMarkup()
item1 = types.InlineKeyboardButton("Text5", callback_data = 'another_call1')
item2 = types.InlineKeyboardButton("Text6", callback_data = 'another_call2')
keyboard.add(item1,item2)
bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)
elif call.data == "call2":
kkeyboard = types.InlineKeyboardMarkup()
item1 = types.InlineKeyboardButton("Text7", callback_data = 'another_call3')
item2 = types.InlineKeyboardButton("Text8", callback_data = 'another_call4')
keyboard.add(item1,item2)
bot.send_message(call.message.chat.id, 'message', reply_markup = keyboard)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:06:21.237",
"Id": "513462",
"Score": "3",
"body": "\"Below is the code, simplified for demonstration purposes\" Next time, please don't simplify the code. We can handle big pieces of code, but we'd be wasting your and our time by providing a review that turns out to be non-applicable to your actual code because that happens to look slightly different."
}
] |
[
{
"body": "<p>From my point of view you can use a visitor pattern for this with a simple dictionary, specially for your operations, here is a small example:</p>\n<p>Insead of this</p>\n<pre><code>@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n # here a handle the queries launched both by main buttons and the inline keyboard \n\n\n if call.data == "demo_yes":\n\n keyboard = types.InlineKeyboardMarkup()\n ......\n</code></pre>\n<p>Use the following</p>\n<pre><code>tempo_operations = {"demo_yes" : demo_yes_function,\n "demo_no" : demo_no_function, \n ....}\n\n@bot.callback_query_handler(func=lambda call: True)\ndef tempo(call):\n\n if call.data in tempo_operations:\n tempo_operations[call.data]()\n else:\n print("Operation not supported")\n</code></pre>\n<p>Hope you can get the idea :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T19:58:53.950",
"Id": "507963",
"Score": "0",
"body": "That's not a visitor pattern, it's a lookup table. Since the OP is looking for efficiency, a call to `dict.get` would be preferable to a call to both `__contains__` and `__getitem__`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T12:49:26.883",
"Id": "513469",
"Score": "1",
"body": "While I agree on the fact that it's not exactly a [visitor pattern](https://sourcemaking.com/design_patterns/visitor), the proposed solution certainly answers OP's concern regarding \"I am missing possible efficiency gains (when I will attempt to build more choices for example)\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T11:57:39.713",
"Id": "257179",
"ParentId": "257167",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T23:02:52.477",
"Id": "257167",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"telegram"
],
"Title": "How to optimize my telegram bot written in Python?"
}
|
257167
|
<p>Recently, I've explored using rust as a scripting language for unity.
My current method involves creating a DLL from rust, and loading it into my game at runtime. It requires that the user use a library I've made which has specific datatypes that I use to link unity and rust together, and must also be compiled as a library <code>cdylib</code>.
I've thought about ways I can try and improve this since I'm not entirely sure if the method I've decided to use is the cleanest or most efficient.</p>
<p>example of usage:</p>
<pre class="lang-rust prettyprint-override"><code>use runity::{DataStruct, Vector3, String};
/* We now define some functions
These are core functions that if not included,
will not be run.
*/
// This function is called when the script is first run
#[no_mangle]
pub extern "C" fn awake(mut _data: DataStruct) -> DataStruct{
_data
}
// This function is called after awake, use it to initialize values and setup the rest of the script
#[no_mangle]
pub extern "C" fn start(mut data: DataStruct) -> DataStruct{
data.transform.position = Vector3::translate(data.transform.position, Vector3::new(0.0, 5.0, 0.0));
data
}
// This function is run every frame
#[no_mangle]
pub extern "C" fn update(mut data: DataStruct) -> DataStruct{
let tag = String::from_str("Player").unwrap(); // Get the tag for "Player"
let player_obj = data.game_object.get_gameobject_from_tag(tag); // Get the game object associated with the tag
let pos_to_go_towards = player_obj.transform.position; // get the position of the player
data.transform.position = Vector3::lerp(data.transform.position, pos_to_go_towards, 0.00015); // move towards the player using lerp
data
}
</code></pre>
<p>Another way I'd like to improve is the way I manage the loaded DLLs from within unity. These scripts highlight my current method I use:</p>
<pre class="lang-cs prettyprint-override"><code>using System.Runtime.InteropServices;
using System;
using UnityEngine;
using TMPro;
using System.Collections.Generic;
using UnityEngine.Scripting;
[assembly: Preserve]
/* This script acts as a sort of buffer
between the DLL (used for scripting)
and the unity engine.
This script should be attached to the game object you want the script to affect.
*/
namespace runity_test
{
public class runity: MonoBehaviour
{
/* Variables */
// Our DLL name
public string DLLName = "runity.dll";
// Error text
public TMP_Text errorText;
// A copy of our position
public Vector3 position;
// Some variables to store per update info
public GameObject m_gameObject;
public Transform m_transform;
public DataStruct dataStruct;
// Our function pointers, so we can recycle them rather than waste
// processing time reloading the DLL
StartDelegate start;
UpdateDelegate update;
// A pointer to our loaded DLL so we can free it on exit
IntPtr loadedDLLPtr;
// An object pool to avoid calling Find on gameobjects every frame
Dictionary<string, UnityEngine.GameObject> objectPool = new Dictionary<string, UnityEngine.GameObject>();
// We use these booleans to check if we should run the respective unity functions.
// This is so we can check collisions conditionally.
bool runStart;
bool runUpdate;
/* Import our functions (start, update and awake) as delegates, as they will be pointers to the functions
* since we want to load them dynamically at runtime
*/
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate DataStruct StartDelegate(DataStruct data);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate DataStruct UpdateDelegate(DataStruct data);
/* Define the structs to use to interface with rust with. This gives
* the option to implement safe, rust compatiable datatypes which
* we can't guarantee with unity */
[StructLayout(LayoutKind.Sequential)]
public struct Vector3
{
public float x;
public float y;
public float z;
}
[StructLayout(LayoutKind.Sequential)]
public struct Transform
{
public Vector3 position;
}
[StructLayout(LayoutKind.Sequential)]
public struct GameObject
{
public IntPtr tag;
public Transform transform;
public FindGameObjectWithTagDelegate GetGameObjectByTag;
}
[StructLayout(LayoutKind.Sequential)]
public struct DataStruct
{
public Transform transform;
public GameObject gameObject;
}
/* Define our delegates, which are callbacks to functions we want to use
* in rust */
public delegate GameObject FindGameObjectWithTagDelegate(IntPtr name); // This delegate acts as FindGameObjectWithTag
/* Run built-in unity functions */
void Awake()
{
(Delegate startFunction, IntPtr startPtr) = DLLPool.LoadFunctionFromDLL(DLLName, "start", typeof(StartDelegate));
if (startPtr != IntPtr.Zero)
{
Debug.Log("Running function!");
runStart = true;
start = (StartDelegate)startFunction;
}
(Delegate updateFunction, IntPtr updatePtr) = DLLPool.LoadFunctionFromDLL(DLLName, "update", typeof(UpdateDelegate));
if (updatePtr != IntPtr.Zero)
{
Debug.Log("Running function!");
runUpdate = true;
update = (UpdateDelegate)updateFunction;
}
// We now assign our delegates to point to our functions.
// Initialize values with no value (should be set in Rust's start function)
m_transform = new Transform { };
m_gameObject = new GameObject { };
dataStruct = new DataStruct { };
}
// Start is called before the first frame update
void Start()
{
if (runStart)
{
m_transform.position = new Vector3 { x = 0, y = 0, z = 0 };
m_gameObject.transform = m_transform;
m_gameObject.GetGameObjectByTag = new FindGameObjectWithTagDelegate(GetGameObjectFromTag);
dataStruct.transform = m_transform;
dataStruct.gameObject = m_gameObject;
dataStruct = start(dataStruct);
m_gameObject = dataStruct.gameObject;
m_transform = dataStruct.transform;
position = m_transform.position;
NativeMethods.Free(dataStruct.gameObject.tag);
}
}
// Update is called once per frame
void Update()
{
if (runUpdate)
{
m_gameObject.transform = m_transform;
dataStruct.transform = m_transform;
dataStruct.gameObject = m_gameObject;
dataStruct = update(dataStruct);
m_gameObject = dataStruct.gameObject;
m_transform = dataStruct.transform;
position = m_transform.position;
transform.position = new UnityEngine.Vector3(position.x, position.y, position.z);
NativeMethods.Free(dataStruct.gameObject.tag);
}
}
// This function releases all our pointers to remain safe
private void OnDestroy()
{
// This is VERY important, we must free and release the link before we exit!
NativeMethods.Free(m_gameObject.tag);
Debug.Log("Released pointers properly");
DLLPool.UnloadAll();
}
/* We can now define the functions we want to expose to rust */
// This method converts `FindGameObjectWithTag` into our custom defined structs
public GameObject GetGameObjectFromTag(IntPtr tag)
{
GameObject gameObject = new GameObject { transform = new Transform { position = new Vector3 { x = 0, y = 0, z = 0, } } };
// We check if the object with its tag is not already pooled. If it is, we make sure it hasn't been destroyed and then take it from the pool.
// otherwise, we load it and add it to the pool
if (objectPool.ContainsKey(Marshal.PtrToStringAnsi(tag)))
{
UnityEngine.GameObject foundObj = objectPool[Marshal.PtrToStringAnsi(tag)];
if (foundObj == null)
{
foundObj = UnityEngine.GameObject.FindGameObjectWithTag(Marshal.PtrToStringAnsi(tag));
Transform transform = new Transform { position = new Vector3 { x = foundObj.transform.position.x, y = foundObj.transform.position.y, z = foundObj.transform.position.z } };
gameObject.transform = transform;
gameObject.tag = tag;
objectPool.Add(Marshal.PtrToStringAnsi(tag), foundObj);
}
else
{
Transform transform = new Transform { position = new Vector3 { x = foundObj.transform.position.x, y = foundObj.transform.position.y, z = foundObj.transform.position.z } };
gameObject.transform = transform;
gameObject.tag = tag;
}
}
else
{
UnityEngine.GameObject foundObj = UnityEngine.GameObject.FindGameObjectWithTag(Marshal.PtrToStringAnsi(tag));
if (foundObj == null)
{
Debug.LogWarning("Warning: Tag -> " + Marshal.PtrToStringAnsi(tag) + " was not found. Falling back to default transform. ");
Transform transform = new Transform { position = new Vector3 { x = 0, y = 0, z = 0 } };
gameObject.transform = transform;
gameObject.tag = tag;
}
else
{
Transform transform = new Transform { position = new Vector3 { x = foundObj.transform.position.x, y = foundObj.transform.position.y, z = foundObj.transform.position.z } };
gameObject.transform = transform;
gameObject.tag = tag;
objectPool.Add(Marshal.PtrToStringAnsi(tag), foundObj);
}
}
return gameObject;
}
}
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>using System.Runtime.InteropServices;
using System.Collections.Generic;
using System;
using UnityEngine;
/*
This class will pool loaded DLL's to save from loading the same DLL multiple times.
It will also manage the unloading of said DLL's (This must be called however)
Attach this script to a gameobject.
*/
namespace runity_test
{
/// <summary>
/// This class contains some functions from the native windows library
/// to help us load and release libraries at runtime.
/// </summary>
static class NativeMethods
{
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string dllToLoad);
[DllImport("kernel32.dll")]
public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName);
[DllImport("kernel32.dll")]
public static extern bool FreeLibrary(IntPtr hModule);
public static void Free(IntPtr ptr)
{
Marshal.FreeCoTaskMem(ptr);
}
}
public class DLLPool: MonoBehaviour
{
public static Dictionary<string, IntPtr> dllPool = new Dictionary<string, IntPtr>();
private static DLLPool instance;
public static DLLPool Instance { get { return instance; } }
private void Awake()
{
if (instance != null && instance != this)
{
Destroy(this.gameObject);
}
else
{
instance = this;
}
}
/// <summary>
/// This function loads a DLL from the stored dictionary.
///
/// This helps you save time by loading DLL's loaded already, rather than load them again
/// </summary>
/// <param name="dllName"></param>
/// <returns></returns>
public static IntPtr GetDLL(string dllName)
{
if (dllPool.ContainsKey(dllName))
{
return dllPool[dllName];
}
return IntPtr.Zero;
}
/// <summary>
/// This function takes the name of the DLL to load
///
/// These DLL's are expected to be stored in the `Assets/Plugins/` folder
/// </summary>
/// <param name="dllName"></param>
/// <returns></returns>
public static IntPtr LoadDLL(string dllName)
{
if (GetDLL(dllName) != IntPtr.Zero)
{
return GetDLL(dllName);
}
//Get the path of the Game data folder
string m_Path = Application.dataPath;
#if UNITY_EDITOR
string path = m_Path + "/Plugins/" + dllName;
#else
string path = m_Path + "/Plugins/x86_64/" + dllName;
#endif
Debug.Log("Loading DLL: " + path);
// Load the DLL library
IntPtr loadedDLLPtr = NativeMethods.LoadLibrary(path);
if (loadedDLLPtr == IntPtr.Zero)
{
Debug.LogError("Error! The library " + dllName + " couldn't be found!");
return IntPtr.Zero;
}
else
{
Debug.Log("Successfully loaded DLL: " + path);
}
dllPool.Add(dllName, loadedDLLPtr);
return loadedDLLPtr;
}
public static (Delegate, IntPtr) LoadFunctionFromDLL(string dllName, string functionName, Type delegateType)
{
try
{
if (GetDLL(dllName) != IntPtr.Zero)
{
Debug.Log("DLL exists in pool, loading from pool...");
IntPtr dllPtr = GetDLL(dllName);
IntPtr functionPtr = NativeMethods.GetProcAddress(dllPtr, "update");
if (functionPtr == IntPtr.Zero)
{
Debug.LogWarning("Couldn't find function '" + functionName + "' in " + dllName + ", '" + functionName + "' in unity won't be run!");
}
Delegate function = Marshal.GetDelegateForFunctionPointer(functionPtr, delegateType);
Debug.Log("Loaded function '" + functionName + "' from " + dllName + " successfully!");
return (function, functionPtr);
}
else
{
Debug.Log("DLL not loaded, loading DLL...");
IntPtr dllPtr = LoadDLL(dllName);
IntPtr functionPtr = NativeMethods.GetProcAddress(dllPtr, "update");
if (functionPtr == IntPtr.Zero)
{
Debug.LogWarning("Couldn't find function '" + functionName + "' in " + dllName + ", '" + functionName + "' in unity won't be run!");
}
Delegate function = Marshal.GetDelegateForFunctionPointer(functionPtr, delegateType);
Debug.Log("Loaded function '" + functionName + "' from " + dllName + " successfully!");
return (function, functionPtr);
}
}
catch (Exception e)
{
Debug.Log("Error when loading function from DLL - " + e);
return (null, IntPtr.Zero);
}
}
public static void UnloadAll()
{
Debug.Log("Total DLLs currently loaded: " + dllPool.Count);
// This is important - free all our loaded libraries
foreach (string name in dllPool.Keys)
{
Debug.Log("Releasing DLL: " + name);
NativeMethods.FreeLibrary(dllPool[name]);
}
}
}
}
</code></pre>
<p>The link to the repo (if you'd like to take a look at the way I've implemented the datatypes, too many files to copy here):
<a href="https://github.com/dimitribobkov/runity" rel="nofollow noreferrer">https://github.com/dimitribobkov/runity</a></p>
<p>Thanks for the help in advance :)</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-14T23:59:40.237",
"Id": "257169",
"Score": "2",
"Tags": [
"game",
"rust",
"library",
"unity3d",
"dynamic-loading"
],
"Title": "How should I go about implementing rust into the unity3d engine?"
}
|
257169
|
<p>I'm working on converting my basic cryptocurrency miner from C# to C++ for performance reasons (I've been told that C++ is faster in many aspects). However, that aside, the focus of this post is to get some feedback for a very basic port of <code>ReadLine</code>, <code>Write</code> and <code>WriteLine</code> as I understand them, from C# to C++. This way, I don't get too far along before learning lessons the hard way.</p>
<p><strong>Console.h</strong></p>
<p>From my understanding, this file is mostly meant for definitions, such as an <code>interface</code> in C# in that implementation should not occur here, though it's not disallowed (<em>unlike C# where it is disallowed</em>):</p>
<pre><code>#pragma once
#include <string>
using namespace std;
class Console
{
public:
static string ReadLine();
static void Write(string input);
static void WriteLine(string input);
};
</code></pre>
<p><strong>Console.cpp</strong></p>
<p>The concept of separating definition from implementation is a bit new to me (outside of <code>interface</code>s and members marked as <code>abstract</code> in C#). The part that threw me off here is that the <code>static</code> keyword is dropped when writing out the function:</p>
<pre><code>#include "Console.h"
#include <iostream>
#include <string>
using namespace std;
string Console::ReadLine() {
string result;
cin >> result;
return result;
}
void Console::Write(string input) { cout << input; }
void Console::WriteLine(string input) { cout << input + "\n"; }
</code></pre>
<p><strong>CryptoSandbox.cpp</strong></p>
<p>This is my entry point, I didn't really change much. I simply replaced the original <code>cout << "Hello World"</code> with <code>Console::WriteLine(...)</code>, which required inclusion of <code>Console.h</code> to compile, so lesson learned fast there:</p>
<pre><code>#include "Console.h"
#include <string>
using namespace std;
int main() {
Console::Write("Starting the crypto sandbox. Please tell us your name: ");
string userName = Console::ReadLine();
Console::WriteLine("Welcome to the crypto sandbox, " + userName + "!");
}
</code></pre>
<p>The goal of this post is to learn what I can simplify, and anything that can be done better. A few questions hitting me hard are:</p>
<ul>
<li>How does organization not become quickly overwhelming based on how VS Community creates the initial project structure?</li>
<li>Why is <code>static</code> not accepted in the <code>cpp</code> file when the declaration states <code>static void</code> in the <code>h</code> file?</li>
</ul>
<p>Outside of those two questions (<em>entirely optional, by the way</em>), my primary focus is certainly feedback on my port.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T01:54:17.707",
"Id": "507894",
"Score": "0",
"body": "Why are you creating a class for that? What's wrong with using `cin` and `cout` directly everywhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T02:42:13.130",
"Id": "507895",
"Score": "0",
"body": "@1201ProgramAlarm purely for my familiarity to be honest."
}
] |
[
{
"body": "<p>Don't use:</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>In the header file it is really bad and can break code. But even in the source file is considered bad practice.</p>\n<p>see: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n<hr />\n<p>This does not read a line:</p>\n<pre><code>string Console::ReadLine() {\n string result;\n cin >> result; // This reads a single space separated word:\n return result;\n}\n</code></pre>\n<p>Use <code>std::getline()</code></p>\n<pre><code>std::string Console::ReadLine() {\n std::string result;\n std::getline(std::cin, result);\n return result;\n}\n</code></pre>\n<hr />\n<blockquote>\n<p>How does organization not become quickly overwhelming based on how VS Community creates the initial project structure?</p>\n</blockquote>\n<p>I don't understand what this means.</p>\n<blockquote>\n<p>Why is static not accepted in the cpp file when the declaration states static void in the h file?</p>\n</blockquote>\n<p>Why waste the developers time adding in words the compiler already knows.</p>\n<hr />\n<p>When transferring from one language to another a direct translation is usually not advisable. You have to use the other language in the way it is designed to be used, otherwise you are not going to get the improvements you desire.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:34:46.270",
"Id": "507949",
"Score": "1",
"body": "The answer to \"why is static not accepted\" can be expanded. As a rule of thumb, C++ tries to keep everything as source file only; if that is not possible, it prefers header file only; if that does not work either, the code is placed in both header and source file. \"static\" needs to be known at compile time, not just at link time, to know whether `Console::ReadLine` is valid code, so it has to be included in the header file. It does not have to be included in the source file too, because there can only be one `ReadLine` function with that signature that is either static or non-static; not both."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T02:48:47.103",
"Id": "257174",
"ParentId": "257172",
"Score": "4"
}
},
{
"body": "<p>If your class contains only static methods and data members, you're better off not using a class at all. Makes more sense to wrap those functions in a namespace, and you can use them just like you're using now.</p>\n<pre><code>namespace Console\n{\n std::string GetLine();\n}\n</code></pre>\n<hr />\n<p>Your <code>Write</code> functions take a string by value, which creates a copy of the string. If your string is long enough, it'll lead to another allocation and can degrade performance. Use a const reference <code>const std::string&</code> or if you're using C++17, string view: <code>std::string_view</code>.</p>\n<hr />\n<p>Your <code>WriteLine</code> functions appends a <code>\\n</code> to every string, which creates a new temporary string, which again might allocate. If you want to write a newline, simply append to the stream. <code>std::cout << input << '\\n';</code>.</p>\n<hr />\n<p>C++ isn't faster just by virtue of it being C++. You really need to understand what's happening "behind-the-scenes" to take full advantage of the language.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T16:08:05.187",
"Id": "507937",
"Score": "1",
"body": "I don't understand how I missed the string addition. Good catch. Like the use of namespace rather than a class should have mentioned that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T12:54:48.803",
"Id": "257182",
"ParentId": "257172",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257174",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T01:03:10.637",
"Id": "257172",
"Score": "0",
"Tags": [
"c#",
"c++",
"console"
],
"Title": "C# to C++: Basic Console Replication"
}
|
257172
|
<p>I've just picked coding back up for the first time in a long time, so I understand if your eyes bleed looking at this code. It all works, but I'd be grateful for any tips (how to improve the python code, how to use Spacy's semantic similarity vector feature better, how to make it work faster, etc).</p>
<p>The main product of the code is the list_of_matches list, which shows how I got from one page to another. Clearly this example goes from "frog" to "crystal", but theoretically those could be anything.</p>
<pre><code>import spacy
import wikipedia
import en_core_web_lg
nlp = en_core_web_lg.load()
word_1 = 'frog'
word_2 = 'crystal'
count = 0
closest_match = word_1
list_of_matches = []
link_list_1 = [nlp(word) for word in(wikipedia.page("Frog", auto_suggest=False).links)]
for item in link_list_1:
print(item)
while float(item.similarity(nlp(word_2))) != 1.0 and count != 20:
if closest_match.lower() == word_2:
list_of_matches.append(word_2)
break
list_of_matches.append(closest_match)
try:
link_list = [nlp(word) for word in wikipedia.page(closest_match, auto_suggest=False).links]
except wikipedia.exceptions.DisambiguationError:
pass
count += 1
highest_match = 0
for item in link_list:
if(item.vector_norm):
if float(item.similarity(nlp(word_2))) != 0.0:
similarity = (item.text, word_2, item.similarity(nlp(word_2)))
#print(similarity)
link, word_2, vector = similarity
if vector > highest_match and link not in list_of_matches:
highest_match = vector
closest_match = link
print(closest_match, highest_match)
print(list_of_matches)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T05:43:55.880",
"Id": "507899",
"Score": "1",
"body": "Is the indentation correct? Or should the `while` loop be indented further (in the body of the `for item in link_list_1` loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:35:37.727",
"Id": "507950",
"Score": "0",
"body": "@RootTwo No, it's meant to be outside of the while loop. While I'm sure there's a better way of doing this, I couldn't think of it at the moment. The `for item in link_list_1` loop is simply there to assign the 'item' variable so it could be used in the condition of the while loop"
}
] |
[
{
"body": "<h3>First a few observations, then we'll try to improve things.</h3>\n<ul>\n<li>"Frog" in the first list comprehension should be <code>closest_match</code> (which is initialized to 'frog').</li>\n<li>The two list comprehensions are identical, which suggests the code could be rearranged to eliminate the redundancy.</li>\n<li>In the <code>while</code> loop, <code>item.similarity()</code> already returns a float, so the <code>float()</code> call is redundant. Also, it seems fishy that the test involves whatever happend to be the last item in <code>link_list_1</code> or <code>linked_list</code>.</li>\n<li>Avoid hard coding "magic numbers" like 1.0, 0.0, and 20 in the code. Use a defined constants with meaningful names to make the code clearer. For example, <code>while item.similarity(nlp(word_2))) != PERFECT_MATCH</code>.</li>\n<li>I suspect calling <code>nlp()</code> is computationally expensive, but the code calls <code>nlp(word_2)</code> repeatedly.</li>\n<li><code>word</code> is a poor variable name, particularly when the page titles or links often have multiple words.</li>\n<li>If a <code>DisambiguationError</code> is raised, the error is ignored. But, <code>closest_match</code> isn't changed, so the error will repeat the next time through the loop...until the loop count limit is reached.</li>\n</ul>\n<h3>Now let's try to improve the code.</h3>\n<p>It looks like the basic idea behind your code is to try to get from one Wikipedia page to a target page by following links. The strategy for picking which link to follow is to pick the one with text that is most similar to the target page name. There doesn't appear to be any kind of breadth first search or back tracking or anything.</p>\n<p>You got the code to grab the links on a page. Right now, the code runs <code>nlp()</code> on each link and check if it is similar to the target before checking if it's already been visited.</p>\n<pre><code>raw_links = wikipedia.page(current_page, auto_suggest=False).links\nnew_links = (link for link in raw_links if link not in path)\n</code></pre>\n<p>According to the <code>spacy</code> documentation it is more efficient to use <a href=\"https://spacy.io/usage/processing-pipelines#processing\" rel=\"nofollow noreferrer\"><code>nlp.pipe()</code></a>, to process a sequence of texts. <code>nlp.pipe()</code> is a generator that yields a spacy.Doc for each text in the input.</p>\n<pre><code>next_pages = nlp.pipe(new_links)\n</code></pre>\n<p>But we want the page with the highest similarity to the target page. The Python builtin <code>max()</code> should work with an approriate key function:</p>\n<pre><code>target_page = nlp(target) # this is done once outside the loop\n\nnext_page = max(nlp.pipe(new_links), key=target_page.similarity)\n</code></pre>\n<p>Of course, package it all up in a function:</p>\n<pre><code>def find_path(start, target, limit=20):\n start = start.lower()\n target = target.lower()\n \n try: \n target_page = nlp(target)\n \n current = start\n path = [start]\n\n for _ in range(limit):\n raw_links = wikipedia.page(current, auto_suggest=False).links\n new_links = (link.lower() for link in raw_links if link not in path) \n best_page = max(nlp.pipe(new_links), key=target_page.similarity)\n\n current = best_page.text\n path.append(current)\n \n if current == target:\n return path\n \n except wikipedia.exceptions.DisambiguationError as e:\n print(e)\n \n return []\n \nSTART = "frog"\nTARGET = "crystal" \n\nprint(find_path(START, TARGET))\n</code></pre>\n<p>Note: I don't have <code>spacy</code> so I couldn't test this code. It may have some bugs, but based on the docs, I think it should point you in the right direction.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T22:19:53.730",
"Id": "257372",
"ParentId": "257173",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T01:19:33.870",
"Id": "257173",
"Score": "1",
"Tags": [
"python",
"natural-language-processing",
"wikipedia"
],
"Title": "Finding a path from one wikipedia page to another using semantic similarity of links (Spacy)"
}
|
257173
|
<p>I'm currently trying to speeding up my python code.
The code should calculate all the possible routes in a maze that is generated from a black and white image. The maze should be solved starting from the 0,j pixel of the image to every point in the bottom of the image(Better explained in the image attached).<a href="https://i.stack.imgur.com/jqs8D.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jqs8D.jpg" alt="enter image description here" /></a></p>
<p>At the moment my code takes 3 min for analyze 240x120 pixel image. I would like to analyze an image that is 16000 x 1000, do you think is possible?</p>
<p>I have tryed to cythonize my code but I didn't sucseed in it, so I was trying to solv my problem within python.</p>
<p>Tell me if you have any idea to speed up my code. Thank you in advance!</p>
<p>This is an example of Interpred picture (only with 0 and 1) and output results (with incremental number from 1) where an extra step is added wherever there is a 0 in the matrix (0 represents passage, 1 is wall)<a href="https://i.stack.imgur.com/mO0pC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mO0pC.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/KpXsb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KpXsb.png" alt="enter image description here" /></a></p>
<pre class="lang-py prettyprint-override"><code>
from matplotlib.image import imread
import numpy as np
from time import time
start_time = time()
image= imread("white_fibers2.jpg")
array_of_tuples = map(tuple, image)
image2 = tuple(array_of_tuples)
threshold= 170
image1 = np.zeros((len(image2),len(image2[0])))
for i in range(len(image2)):
for j in range(len(image2[i])):
if image2[i][j] >threshold:
image1[i][j]=0
else:
image1[i][j]=1 ### matrix AKA wall in the labyrinth
f = np.zeros(len(image2[1]))
##### from array image 1 to tuple image 3
# array_of_tuples1 = map(tuple, image1)
# image3 = tuple(array_of_tuples1)
image3=np.array(image1)
for w in range(len(image3[1])-1):
if image1[0,w]==0:
start = 0, w
end = len(image2)-1, 0
##### empty matrix that will store the possible moves
m = []
for i in range(len(image3)):
m.append([])
for j in range(len(image3[i])):
m[-1].append(0)
i,j = start
m[i][j] = 1
def make_step(k,m,image3):
for i in range(len(m)):
for j in range(len(m[i])):
if m[i][j] == k:
if i>0 and m[i-1][j] == 0 and image3[i-1][j] == 0: ##### if there is space in Maze (no space no way) and there is space in the path (to avoid that goes back)
m[i-1][j] = k + 1 ####### on top of the square i,j
if j>0 and m[i][j-1] == 0 and image3[i][j-1] == 0:
m[i][j-1] = k + 1 ####### on left of the square i,j
if i<len(m)-1 and m[i+1][j] == 0 and image3[i+1][j] == 0:
m[i+1][j] = k + 1 ####### on bottom of the square i,j
if j<len(m[i])-1 and m[i][j+1] == 0 and image3[i][j+1] == 0:
m[i][j+1] = k + 1 ####### on right of the square i,j
####### continue to perform step till the end point is reached + if there is a cul-de-sac it
k = 0
while m[end[0]][end[1]] == 0 :
if k<600:
k += 1
make_step(k,m, image3)
# make_step(k,m, image3)
print (k)
else:
break
path=np.array(m)
f = np.vstack((f,path[end[0]])) ###### f contain the final line of the final line of the paths
else: ######## if the starting block of the maze is a wall fill the row of "f" with zeros
p = np.zeros(len(image2[1]))
f = np.vstack((f,p))
########
f1=np.delete(f,np.where(~f.any(axis=1))[0], axis=0) ##### remove the row with only 0s
ns =[]
for i in range(len(f1)):
a= f1[i,:]
ns.append(np.min(a[np.nonzero(a)]))
rz=0
for i in range(len(ns)):
rz= rz+ 1/(ns[i])
Rzi = 1/rz
end_time = time()
print (end_time - start_time)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T12:03:58.310",
"Id": "507914",
"Score": "0",
"body": "Could you please provide an example matrix (interpreted picture) and your validated output for that matrix?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T12:07:37.587",
"Id": "507916",
"Score": "1",
"body": "Also please try to plot the actual output of the code, instead of drawing the path by hand!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T19:44:39.523",
"Id": "507962",
"Score": "4",
"body": "16,000 x 1000 should be an easy task, if approached correctly. The problem is not that you don't micro-optimize enough, the problem lies in your principle algorithm. It looks like you have a four times nested loop, when you should use something like breadth first search to solve the problem in linear theim."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T08:33:02.443",
"Id": "507992",
"Score": "0",
"body": "Thanks Andreas T, the bredth first search seems like a promising technique to use. However I have a starting point for my maze but not an single end point (i Want to find the shorter route to reach the other end of the maze, so, all the points in the last row are possible ending points), therefore I don t know how to backroute in order to find the shorthest path."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T00:35:15.823",
"Id": "508136",
"Score": "4",
"body": "As already noted, you need a better algorithm, not minor tweaks. Here's an explanation for the [A* algorithm](https://stackoverflow.com/a/3097677/55857). It's a variation on BFS designed to visit all nodes and find shortest path. In your case, the weights are all 1. Regarding multiple endpoints, after creating the graph from the image, you can attach an extra pseudo-node to the graph that connects to all nodes/pixels in the last row (and only to those nodes). Treat that extra node as the goal for A*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T23:05:07.973",
"Id": "508258",
"Score": "4",
"body": "I second FMc. A* would be one of the better algorithms to use in this scenario. If you would like sample code for how to implement it in Python, [this page](https://www.redblobgames.com/pathfinding/a-star/introduction.html) has the best explanation I've seen yet"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T11:55:17.250",
"Id": "257178",
"Score": "3",
"Tags": [
"python",
"performance"
],
"Title": "Solve maze with python, speed issue"
}
|
257178
|
<p>I am going to make this code below into the second release of my library, but I want to make sure I haven't missed anything. If there are improvements that can be made, I'd like to implement them.</p>
<p>This code is also <a href="https://github.com/lunAr-creator/pw-gen" rel="nofollow noreferrer">on GitHub</a>.</p>
<pre><code>import random
import secrets
import string
import urllib.request
class Simple():
def __init__(self, length: int, characters = None):
'''A simple password'''
self.length = length
self.characters = characters
self.output = []
def generate(self, num_of_passwords: int):
'''
Generates a password depending on the num_of_passwords
and the arugments provided in the simple class
'''
characters = ''
if self.characters is None:
characters = string.ascii_letters + string.digits
else:
characters = self.characters
for i in range(num_of_passwords):
password = ''
for c in range(self.length):
password += secrets.choice(characters)
self.output.append(password)
return self.output
def return_result(self, index: int):
'''
Returns the password which is at the specified index
in the output list.
'''
try:
return self.output[index]
except IndexError:
print(f'Incorrect index specified. Please provide an index relevant to the number of passwords generated')
def clear_results(self):
'''Clears the output list if you want to make way for new passwords'''
self.output.clear()
class Complex(Simple):
def __init__(self, length, string_method, numbers=True, special_chars=False):
'''
Creates a customisable password depending on length,
string_method, numbers and special_chars
'''
characters = ''
self.output = []
methods: dict = {
"upper": string.ascii_uppercase,
"lower": string.ascii_lowercase,
"both": string.ascii_letters,
}
characters += methods[string_method]
if numbers:
characters += string.digits
if special_chars:
characters += string.punctuation
super().__init__(length=length, characters=characters)
class Memorable(Simple):
def __init__(self, numbers=True):
'''A memorable password'''
self.numbers = numbers
self.output = []
def generate(self, num_of_passwords: int):
'''Gets some random words'''
word_url = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'}
req = urllib.request.Request(word_url, headers=headers)
response = response = urllib.request.urlopen(req)
long_txt = response.read().decode()
words = long_txt.splitlines()
'''
Generates the password containing 2 words
and numbers if self.numbers == True
'''
for i in range(num_of_passwords):
password = ''
two_words = ''
for i in range(2):
two_words += secrets.choice(words).title()
password = two_words
if self.numbers == True:
for i in range(random.randint(3, 4)):
password += secrets.choice(string.digits)
self.output.append(password)
return self.output
# Test Scenarios
if __name__ == "__main__":
var = Memorable()
print(var.generate(3))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:01:26.097",
"Id": "507943",
"Score": "0",
"body": "You're getting your dictionary from _the web_? That's one of the first places I would attack this, through DNS spoofing or flat-out interception. Don't you have a standard system wordlist (e.g. `/usr/share/dict/words`) that you could use instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:16:40.030",
"Id": "507947",
"Score": "0",
"body": "well i wasnt sure if making a package allowed you to have files other than the ones required to make a library work. sorry :/ how can i implement a standard system wordlist?"
}
] |
[
{
"body": "<h2>1. Add even more typing</h2>\n<p>It's good that you use some basic type annotations but you should use them everywhere, not just on a few select parameters. Have a look at the <code>typing</code> module, especially if you want to support Python versions before 3.9. For example, your function signatures could be</p>\n<pre><code>def __init__(self, length: int, characters: Optional[str] = None):\ndef generate(self, num_of_passwords: int) -> None:\ndef __init__(self, length: int, string_method: Literal["upper", "lower", "both"], numbers: bool = True, special_chars: bool = False):\n</code></pre>\n<h2>2. Keyword-only parameters</h2>\n<p>This is a personal suggestion and I am sure you will find people who disagree with me on it. In your current code, <code>Complex(5, "lower", True, False)</code> is a valid call; yet, it is completely meaningless to a reader. By making the last two parameters <a href=\"https://www.python.org/dev/peps/pep-3102/\" rel=\"nofollow noreferrer\">keyword-only</a>, you force the user to be more expressive: <code>Complex(5, "lower", numbers=True, special_chars=False)</code>.</p>\n<p>On that note, I suggest to give the parameters more expressive names such as <code>include_numbers</code> and <code>include_special_characters</code>.</p>\n<h2>3. Add better docstrings</h2>\n<p>You should ask yourself: who do you write your code documentation for? Right now, comments like "A simple password" don't provide much helpful information to anyone except for maybe yourself. What makes a password "simple"? Does it only contain numbers and letters? Is it short? Is it easy to remember? The same holds true for "complex", "memorable" and other terms. I'll do a shameless plug of my own <a href=\"https://tollko.blog/?p=199\" rel=\"nofollow noreferrer\">recent blog post</a> on that topic for more information.</p>\n<h2>4. Security</h2>\n<p>In the context of "passwords", "security" should always be mentioned, even if you feel that for your particular purpose you don't actually need it. Toby Speight already commented that getting words from a dictionary in the web with a hardcoded URL gives a pretty good target for attackers. An easy and platform-independent workaround would be to include a complete word dictionary in your package itself so there is no need to get it via HTTP.</p>\n<p>Another issue might come up due to the fact that <code>random</code>, which you use to build your passwords, is not cryptographically secure. The <code>secrets</code> module, which you also used, is already a better alternative.</p>\n<h2>5. Enums</h2>\n<p>This point, again, might be a bit controversial. Instead of using "method" strings, <code>"upper"</code>, <code>"lower"</code>, and <code>"both"</code>, I'd suggest to use an enum class instead, which makes it easier for your IDE to help you and gives you errors more quickly should you try to use a value that does not exist.</p>\n<pre><code>class PasswordGenerationStrategy(enum.Enum):\n Upper = "upper"\n Lower = "lower"\n Both = "both"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:53:53.843",
"Id": "257195",
"ParentId": "257185",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "257195",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T14:58:14.907",
"Id": "257185",
"Score": "4",
"Tags": [
"python",
"random"
],
"Title": "Library for generating passwords"
}
|
257185
|
<p>I write an app server that uses TCP socket on Linux. When there is no traffic (no data is sent by client, no client <code>connect()</code> or <code>close()</code>), the process sleeps on <code>epoll_wait()</code> while waiting for events hit the socket file descriptors.</p>
<h3>What is a good thing to do while the process is sleeping?</h3>
<p>So my initiative is to make the sleep time short and force the process to read from memory again and again until the events come.</p>
<p>Reason for doing this is that to keep critical (for performance) data hot in the cache.</p>
<ul>
<li>Is that a worthwhile thing to do?</li>
<li>Or better I let the process sleeping until events come?</li>
</ul>
<h2>My understanding</h2>
<p>While the process is sleeping on <code>epoll_wait()</code> for too long, the kernel will schedule to run other processes.</p>
<p>If my app is scheduled away for too long, then its data on memory will be evicted from the cache, as cache is shared across multiple processes, then other processes' data will take place in the cache.</p>
<h2><code>epoll_wait</code> documentation</h2>
<ul>
<li><a href="https://man7.org/linux/man-pages/man2/epoll_wait.2.html" rel="nofollow noreferrer">https://man7.org/linux/man-pages/man2/epoll_wait.2.html</a></li>
<li>Can also be read from <code>man 2 epoll_wait</code>.</li>
</ul>
<h2>Relevant Part of Code (<code>event_loop</code> and <code>exec_epoll_wait</code>)</h2>
<pre><code>struct srv_tcp_state {
int epoll_fd;
int tcp_fd;
int tun_fd;
bool stop;
struct_pad(0, 3);
struct cl_slot_stk client_stack;
struct srv_cfg *cfg;
struct client_slot *clients;
uint16_t *epoll_map;
/*
* We only support maximum of CIDR /16 number of clients.
* So this will be `uint16_t [256][256]`
*/
uint16_t (*ip_map)[256];
/* Counters */
uint32_t read_tun_c;
uint32_t write_tun_c;
struct bc_arr bc_arr_ct;
utsrv_pkt_t send_buf;
struct iface_cfg siff;
bool need_iface_down;
bool aff_ok;
struct_pad(1, 4);
cpu_set_t aff;
};
static int exec_epoll_wait(int epoll_fd, struct epoll_event *events,
int maxevents, struct srv_tcp_state *state)
{
int err;
int retval;
int timeout = 50; /* in milliseconds */
retval = epoll_wait(epoll_fd, events, maxevents, timeout);
if (unlikely(retval == 0)) {
/*
* epoll_wait() reaches timeout
*
* TODO: Do something meaningful here.
*/
/*
* Force the process to read critical data so
* it is always hot (at least in L2 or L3?)
*/
memcmp_explicit(state, state, sizeof(*state));
return 0;
}
if (unlikely(retval < 0)) {
err = errno;
if (err == EINTR) {
retval = 0;
prl_notice(0, "Interrupted!");
return 0;
}
pr_err("epoll_wait(): " PRERF, PREAR(err));
return -err;
}
return retval;
}
static int event_loop(struct srv_tcp_state *state)
{
int retval = 0;
int maxevents = 64;
int epoll_fd = state->epoll_fd;
struct epoll_event events[64];
/* Shut the valgrind up! */
memset(events, 0, sizeof(events));
while (likely(!state->stop)) {
retval = exec_epoll_wait(epoll_fd, events, maxevents, state);
if (unlikely(retval == 0))
continue;
if (unlikely(retval < 0))
goto out;
retval = handle_events(state, events, retval);
if (unlikely(retval < 0))
goto out;
}
out:
return retval;
}
</code></pre>
<h3><code>memcmp_explicit</code></h3>
<p>This code is located in different file, this prevents compiler to inline or optimize or remove the <code>memcmp</code> call (which happens when <code>epoll_wait</code> reaches its timeout).</p>
<pre class="lang-c prettyprint-override"><code>int memcmp_explicit(const void *s1, const void *s2, size_t n)
{
return memcmp(s1, s2, n);
}
</code></pre>
<h2><code>likely</code> and <code>unlikely</code> macros</h2>
<pre class="lang-c prettyprint-override"><code>#define likely(EXPR) __builtin_expect(!!(EXPR), 1)
#define unlikely(EXPR) __builtin_expect(!!(EXPR), 0)
</code></pre>
<h2>About <code>__builtin_expect</code></h2>
<ul>
<li><a href="https://stackoverflow.com/questions/7346929/what-is-the-advantage-of-gccs-builtin-expect-in-if-else-statements">https://stackoverflow.com/questions/7346929/what-is-the-advantage-of-gccs-builtin-expect-in-if-else-statements</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:57:26.290",
"Id": "507952",
"Score": "1",
"body": "At least 2 functions are missing from the code, `likely()` and `unlikely()`. In addition the function `exec_epoll_wait()` contains `TODO` in the comments. In the Code Review Community we review finished code and need all referenced functions to be able to do a good review. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask). I look forward to you updating the question so that I can do a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T21:24:12.597",
"Id": "507967",
"Score": "0",
"body": "*[`memcmp_explicit()`] prevents compiler to inline or optimize or remove the `memcmp`* - does it, without separate compilation and/or cheating on, say *const correctness*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T22:13:51.460",
"Id": "507969",
"Score": "0",
"body": "@pacmaninbw oh I missed that, they are actually a macro, I edited the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T22:20:01.353",
"Id": "507971",
"Score": "0",
"body": "@greybeard I don't understand, could you elaborate? (The compilation of `memcmp_explicit` is separated from that event loop, anyway)."
}
] |
[
{
"body": "<h1>Keeping the cache hot</h1>\n<blockquote>\n<p>So my initiative is to make the sleep time short and force the process to read from memory again and again until the events come.</p>\n<p>Reason for doing this is that to keep critical (for performance) data hot in the cache.</p>\n</blockquote>\n<p>If nothing else running on the same CPU, there is no reason for the cache to go cold. Things in the cache don't time out, they just stay there until they are evicted when necessary.</p>\n<p>If there are other processes running, then your strategy might help your socket server, but there are several issues with this:</p>\n<ul>\n<li>It is selfish; you might prevent other processes from keeping their data in the cache, thus lowering their performance.</li>\n<li>It might not work at all, since once another process gets a time slice, their memory access patterns may evict your data from the cache again.</li>\n<li>By not staying idle, your CPU might not get a chance to go into a low power state, thus keeping your cache literally hot.</li>\n</ul>\n<p>My recommendation is to just use an infinite timeout for <code>epoll_wait()</code>.</p>\n<h1>About <code>memcmp_explicit()</code></h1>\n<p>Be aware that compilers are getting better and better at optimizing things. Even if you put <code>memcmp_explicit()</code> in a different translation unit than where it is called, the compiler might optimize it out if <a href=\"https://en.wikipedia.org/wiki/Interprocedural_optimization#WPO_and_LTO\" rel=\"nofollow noreferrer\">link time optimization</a> is enabled.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T22:32:04.290",
"Id": "257205",
"ParentId": "257188",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257205",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T15:08:56.560",
"Id": "257188",
"Score": "1",
"Tags": [
"performance",
"c",
"linux",
"socket"
],
"Title": "Utilizing idle socket server to do meaningful thing (timeout after sleep on epoll_wait)"
}
|
257188
|
<p>Hi guys how you doing??</p>
<p>I just finished creating an <code>rsync</code> helper program that reads its configuration file using a program that I also created and it deletes some cache directories that I included in the config file plus a few commands for cleaning the system, then it creates a directory on my hard drive with the date of today and starts backing up the system.</p>
<p>For this tool I used C. I know that it may sound strange choice for a wrapper program to be written in C, but the truth I like creating tools in C, so I don't know what about you guys but I think the results aren't bad.</p>
<p>So here is the code:</p>
<ol>
<li><code>errors.h</code></li>
</ol>
<pre><code>#ifndef ERRORS_H
#define ERRORS_H
void handle_files_error(const char *, char *);
int check_input_size(int, int);
void handle_general_error(const char *);
void handle_strstr_error(const char *);
#endif
</code></pre>
<ol start="2">
<li><code>errors.c</code></li>
</ol>
<pre><code>/*
*This header is for handling errors
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "errors.h"
/*
*This function will handle errors that occurres
*while managing files and prints the right message.
*/
void handle_files_error(const char *message, char *file_path) {
char full_message[300];
if(check_input_size(sizeof(full_message), strlen(message)+strlen(file_path))) { //Check the final full_message size
fprintf(stderr, "The size of the inserted string in errors.c -> handle_files_error is invalid.\n");
exit(EXIT_FAILURE);
}
strcpy(full_message, message);
strcat(full_message, file_path);
perror(full_message);
exit(EXIT_FAILURE);
}
/*
*This function will check if the size of the input is
*valid and can fit in the array without overflowing it.
*0 for valid, 1 otherwise.
*/
int check_input_size(int valid_size, int input_size) {
if(input_size < valid_size)
return 0;
else
return 1;
}
/*
*This function will handle general errors and display
*the relevant message.
*/
void handle_general_error(const char *message) {
fprintf(stderr, "%s\n", message);
exit(EXIT_FAILURE);
}
/*
*This function will handle errors for the strstr() function
*and it will display the write message if a string wasnt found.
*/
void handle_strstr_error(const char *serched_str) {
fprintf(stderr, "Error occurred while serching for unit : %s.\n", serched_str);
}
</code></pre>
<ol start="3">
<li><code>config_man.h</code></li>
</ol>
<pre><code>#ifndef CONFIG_MAN_H
#define CONFIG_MAN_H
int check_file_existence(char *);
void create_config_file(char *, const char*);
void write_config_unit(char *, const char *, const char *);
char *read_config_unit(char *, const char *);
int check_unit_existence(const char *, char *);
void read_reg_syntax(char *, char *, int);
int read_list_syntax(char *, char *, int);
#endif
</code></pre>
<ol start="4">
<li><code>config_man.c</code></li>
</ol>
<pre><code>/*
*This header contains all required functions to manage configuration files.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "errors.h" //Header for error handling
#include "config_man.h"
/*
*The function will check if the given file in the
*file path exists. It retruns 1 for yes and 0 for no.
*/
int check_file_existence(char *file_path) {
FILE *fp;
fp = fopen(file_path, "r");
if(fp == NULL) //if file doesnt exists
return 0;
fclose(fp);
return 1;
}
/*
*A function to create a configuration file with the given path.
*Then it'll write a comentted discription and instruction for this file.
*/
void create_config_file(char *file_path, const char *description) {
FILE *fp;
const char *config_instruct = {
"################################################################\n"
"#--------------------------------------------------------------#\n"
"# [Instructions] #\n"
"#--------------------------------------------------------------#\n"
"################################################################\n"
"# Please it's very important to make sure there are 3 charact- #\n"
"# ers between the unit name and its configurations. #\n"
"# For example: #\n"
"# #\n"
"# UnitName = configurations #\n"
"# #\n"
"# As you can see there are 3 characters between the unit name #\n"
"# and the configurations (2 spaces and an equal sign). Be awa- #\n"
"# re that each new line terminates the unit's configurations. #\n"
"# If the unit's configurations are too long you can put it in- #\n"
"# side a pair of braces and make it a list. For example: #\n"
"# #\n"
"# VeryLongUnit = { #\n"
"# config_1 #\n"
"# config_2 #\n"
"# config_3 #\n"
"# config_4 #\n"
"# } <- Don't forget to close the list #\n"
"# #\n"
"# If the list is group of commands you can add '&&' to the end #\n"
"# of each line. If the command requires root privileges you #\n"
"# can just add sudo to the command. For example: #\n"
"# #\n"
"# CommandsUnit = { #\n"
"# command 1 && #\n"
"# sudo root_command 2 && #\n"
"# command 3 && #\n"
"# sudo root_command 3 && #\n"
"# command 4 #\n"
"# } #\n"
"# #\n"
"# Be aware that every new line in the list syntax is converted #\n"
"# into a space, and '}' terminates the list. #\n"
"# Note: Please if you want to use indention for the list, only #\n"
"# use tabs, becuase they are ignored while reading a list. #\n"
"# Lastly as you can see hashes ('#') are ignored. #\n"
"# By the way, sorry for the hard syntax I really tried to make #\n"
"# as easy as I can and that's the result. I hope you like it :)#\n"
"################################################################\n"
};
fp = fopen(file_path, "w");
if(fp == NULL) //Check if error occurred
handle_files_error("An error occurred in create_config_file() while creating ", file_path);
fprintf(fp, "%s\n", description);
fprintf(fp, "%s\n", config_instruct);
fclose(fp);
}
/*
*This function takes a unit name and a description then it'll
*write the description to it so youll know how to configure it.
*/
void write_config_unit(char *file_path, const char *unit_name, const char *unit_desc) {
FILE *fp;
fp = fopen(file_path, "a");
if(fp == NULL) //Check if error occurred
handle_files_error("An error occurred in write_config_unit() while opening ", file_path);
fprintf(fp, "%s", unit_name);
fprintf(fp, "%s", " = ");
fprintf(fp, "%s\n", unit_desc);
fclose(fp);
}
/*
*This function will read all the config file, it'll
*ignore every commented line (with '#'), it will search
*for the desired unit's confgis. If the unit exists it will
*return a pointer to it, otherwise it will return NULL.
*/
char *read_config_unit(char *file_path, const char *unit_name) {
FILE *fp;
char unit_buffer[400]; //Buffer for the unit name and its configs
char *configs_beginning; //Pointer to the targeted unit's configs beginning
static char read_configs[500]; //Array for the read configs
unsigned int config_status = 0; //1 = list, 0 = one line configurations
fp = fopen(file_path, "r");
if(fp == NULL) //Check if error occurred
handle_files_error("An error occurred in read_config_file() while reading ", file_path);
memset(read_configs, '\0', sizeof(read_configs)); //Make sure the static array is empty
//Loop in the file's content
while(fgets(unit_buffer, 400, fp) != NULL) {
//If the beginning of a line is commented or empty
if(*unit_buffer=='#' || *unit_buffer=='\n' || *unit_buffer=='\0')
continue; //Ignore and read next line
if(config_status) { //If list was found
if(read_list_syntax(unit_buffer, read_configs, sizeof(read_configs))) //If reading list
continue; //read the next line of the list
fclose(fp);
return read_configs;
}
else {
if(check_unit_existence(unit_name, unit_buffer)) //If unit wasnt found in line
continue; //Read the next one
/*The address of the beginning of the unit's configurations =
beginning of the line + len of the unit name + 3 bytes (2 spaces and '=' sign)*/
configs_beginning = unit_buffer + strlen(unit_name) + 3;
if(*(configs_beginning) == '{') { //If unit configs is beginning of a list
config_status = 1;
continue;
}
else {
read_reg_syntax(configs_beginning, read_configs, sizeof(read_configs));
fclose(fp);
return read_configs;
}
}
}
fclose(fp);
return NULL;
}
/*
*This function reads the regular configurations syntax,
*Then passes it to the config_buffer.
*/
void read_reg_syntax(char *config_beginning, char *configs_buffer, int buffer_size) {
int i = 0;
while(1)
switch(config_beginning[i]) {
case '\n':
configs_buffer[i] = '\0'; //teminate line
return; //exit
case '\0': //Line is terminated
return; //exit
default:
//Check for overflow
if(check_input_size(buffer_size, i+1)) {
fprintf(stderr, "The size of the inserted string in config_man.c -> read_reg_syntax is invalid.\n");
exit(EXIT_FAILURE);
}
//insert char into the configs_buffer
configs_buffer[i] = config_beginning[i];
i++;
break;
}
}
/*
*This function will read the syntax of a list, if finished reading itll
*return 0, if still reading it will return 1 to read the next line.
*/
int read_list_syntax(char *line_beginning, char *configs_buffer, int buffer_size) {
int char_cnt, i;
char_cnt = strlen(configs_buffer); //number of characters in configs_buffer
i = 0;
while(1) { //Loop and read line until reaching '\n' or ';'
switch(line_beginning[i]) {
case '}': //If end of list
configs_buffer[char_cnt] = '\0'; //terminate line
return 0; //Finished reading list
case '\t': //Ignore indention
break;
case '\n': //Convert to one space
//Make sure there is no overflow
if(check_input_size(buffer_size, char_cnt+1)) {
fprintf(stderr, "The size of the inserted string in config_man.c -> read_list_syntax is invalid.\n");
exit(EXIT_FAILURE);
}
configs_buffer[char_cnt] = ' ';
return 1; //Read next line
default:
//Make sure there is no overflow
if(check_input_size(buffer_size, char_cnt+1)) {
fprintf(stderr, "The size of the inserted string in config_man.c -> read_list_syntax is invalid.\n");
exit(EXIT_FAILURE);
}
configs_buffer[char_cnt] = line_beginning[i];
char_cnt++;
break;
}
i++;
}
}
/*
*This function takes a unit name and pointer to the beginning
*of the unit's line and it then it finds the unit's name which is
*the first word then it checks if the founded unit and the passed
*one are equal and the same.
*0 = equal, 1 = not equal
*/
int check_unit_existence(const char *unit_name, char *line_begin) {
unsigned int i;
char unit_to_check[50]; //Array for the unit name that needs to be checked
//Get unit name
for(i=0; line_begin[i]!='\n' && line_begin[i]!='\t' && line_begin[i]!=' ' && line_begin[i]!='\0'; i++) {
//Make sure there is no overflow
if(check_input_size(sizeof(unit_to_check), i+1)) {
fprintf(stderr, "The size of the inserted string in config_man.c -> check_unit_existence is invalid.\n");
exit(EXIT_FAILURE);
}
unit_to_check[i] = line_begin[i];
}
if(strcmp(unit_name, unit_to_check) == 0) //If equal
return 0;
else //Not equal
return 1;
}
</code></pre>
<ol start="5">
<li>sys_backup.h</li>
</ol>
<pre><code>#ifndef SYS_BACKUP_H
#define SYS_BACKUP_H
void delete_dirs(char *);
void get_date(int *);
char *make_backup_dir(char *, int *);
void backup_sys(const char *, char *);
#endif
</code></pre>
<ol start="6">
<li><code>sys_backup.c</code></li>
</ol>
<pre><code>/*
*This program will make some cleaning that you regularly do
*before the full system backup. And then itll create new dir
*in your storage device with date, to make the system backup in
*it useng rsync. The program will use system() to connect all the
*command line tools together and automate this process. Lastly
*its good to note that tho program reads all the commands and
*your customaized cleaning process from a config file with the
*following path: ~/.config/sys_backup
*/
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include "config_man.h" //For config files managment
#include "errors.h" //Error handling header
#include "sys_backup.h"
int main() {
const char *config_desc = {
"################################################################\n"
"# This configuration file purposes are to provide to the #\n"
"# sys_backup.c program the right cleaning process and storage #\n"
"# device path, customized to your own needs and preferences. #\n"
"################################################################"
};
const char *units_list[] = {
"DirsToClean", "CleaningCommands", "DevicePath",
"RsyncCommand", "\0"
};
const char *units_desc[] = {
"Dirs path you regularly clean, like some cache dirs",
"{\n"
"\tCommands for cleaning your sysem, like:\n"
"\tsudo pacman -Sc (for deleting uninstalled packages\n"
"\tfrom the cache in arch based distros)\n"
"}",
"Your storage device path hdd, usb or whatever you use",
"sudo rsync -aAXHv --exclude={\"/dev/*\",\"/proc/*\",\"/sys/*\""
",\"/tmp/*\",\"/run/*\",\"/mnt/*\",\"/media/*\",\"/lost+found\"} / ",
"\0"
};
char *config_path = "/.config/sys_backup";
char config_full_path[60];
char *home, *configurations, *backup_path;
int date[3]; //Array for the date of today
unsigned int i;
/*Get configuration's file path*/
home = getenv("HOME"); //Get home path
//Check for overflow
if(check_input_size(sizeof(config_full_path), strlen(home)+strlen(config_path))) {
fprintf(stderr, "The size of the inserted string in sys_backup.c -> main() is invalid.\n");
exit(EXIT_FAILURE);
}
strcpy(config_full_path, home);
strcat(config_full_path, config_path);
if(check_file_existence(config_full_path) == 0) { //Check if config file exists
create_config_file(config_full_path, config_desc);
for(i=0; *units_desc[i]!='\0'; i++)
write_config_unit(config_full_path, *(units_list+i), *(units_desc+i));
printf("Please configure the prorgram's config file in the following path: %s.\n", config_full_path);
return 0;
}
/*Read the configured units*/
if((configurations=read_config_unit(config_full_path, units_list[0])) == NULL) { //Unit wasnt found
handle_strstr_error(units_list[0]);
exit(EXIT_FAILURE);
}
delete_dirs(configurations);
if((configurations=read_config_unit(config_full_path, units_list[1])) == NULL) { //Unit wasnt found
handle_strstr_error(units_list[1]);
exit(EXIT_FAILURE);
}
system(configurations);
if((configurations=read_config_unit(config_full_path, units_list[2])) == NULL) { //Unit wasnt found
handle_strstr_error(units_list[2]);
exit(EXIT_FAILURE);
}
get_date(date); //Get the date of today and pass it to the date array
backup_path = make_backup_dir(configurations, date); //Create backup dir and get its path
if((configurations=read_config_unit(config_full_path, units_list[3])) == NULL) { //Unit wasnt found
handle_strstr_error(units_list[3]);
exit(EXIT_FAILURE);
}
backup_sys(configurations, backup_path); //Backup system in the created dir
return 0;
}
/*
*This function will delete the given argument dirs.
*/
void delete_dirs(char *dirs_path) {
char full_command[700];
const char *command = "rm -rf ";
const char *danger_message = {
"Nice try, but we wont let you destroy your system ;)\n"
"Please make sure that DirsToClean unit is configured properly "
"and there is no sign of standalone root tree (\"/\")."
};
unsigned int i;
//Loop in dirs_path yo make sure no one removing the root tree by mistake
for(i=0; i<strlen(dirs_path); i++)
if(dirs_path[i]==' ' && dirs_path[i+1]=='/' && dirs_path[i+2]==' ') {
fprintf(stderr, "%s\n", danger_message);
exit(EXIT_FAILURE);
}
//Check for overflow
if(check_input_size(sizeof(full_command), strlen(dirs_path)+strlen(command))) {
fprintf(stderr, "The size of the inserted string in sys_backup.c -> delete_dirs is invalid.\n");
exit(EXIT_FAILURE);
}
//Copy command to buffer (rm -rf dirs_path) to delete dirs.
strcpy(full_command, command);
strcat(full_command, dirs_path);
system(full_command); //Execute command
}
/*
*This function will get the date of today, and it'll insert it to the passed date array.
*/
void get_date(int *date) {
long int sec_since_epoch;
struct tm current_time, *time_ptr;
sec_since_epoch = time(0);
time_ptr = &current_time; //Set time pointer to the current_time struct
localtime_r(&sec_since_epoch, time_ptr);
//Pass today's date to the array
*date = time_ptr->tm_mday;
*(date+1) = time_ptr->tm_mon + 1; //+1 because months range from 0 - 11
*(date+2) = time_ptr->tm_year - 100; //-100 because tm_year is number of passed years since 1900
}
/*
*A function that gets pointer to int array that contains the
*date of today and create a backup dir in the passed path
*passed date. Then it will return the full path of the created dir.
*/
char *make_backup_dir(char *device_path, int *date_array) {
char dir_name[10], full_command[200];
const char *command = "mkdir ";
static char backup_path[150]; //The returned full backup path
//Convert the date_array to a string so will use it to name the dir in the device path
sprintf(dir_name, "%02d", *date_array);
sprintf((dir_name+3), "%02d", *(date_array+1));
sprintf(dir_name, "%02d", *date_array);
sprintf(dir_name+6, "%d", *(date_array+2));
dir_name[2] = dir_name[5] = '-';
//Check for overflow
if(check_input_size(sizeof(backup_path), strlen(device_path)+strlen(dir_name))) {
fprintf(stderr, "The size of the inserted string in sys_backup.c -> make_backup_dir is invalid.\n");
exit(EXIT_FAILURE);
}
strcpy(backup_path, device_path);
strcat(backup_path, dir_name); //Complete the full dir path
//Check for overflow
if(check_input_size(sizeof(full_command), strlen(command)+strlen(backup_path))) {
fprintf(stderr, "The size of the inserted string in sys_backup.c -> make_backup_dir is invalid.\n");
exit(EXIT_FAILURE);
}
strcpy(full_command, command); //Insert command to the full_command
strcat(full_command, backup_path); //Complete the command
system(full_command); //Execute the command
return backup_path;
}
/*
*This function will make the full system backup using rsync to the passed dir path.
*/
void backup_sys(const char *command, char *backup_path) {
char full_command[500];
/*Prepare command*/
//Check for overflow
if(check_input_size(sizeof(full_command), strlen(command)+strlen(backup_path)+sizeof("/"))) {
fprintf(stderr, "The size of the inserted string in sys_backup.c -> backup_sys is invalid.\n");
exit(EXIT_FAILURE);
}
strcpy(full_command, command);
strcat(full_command, backup_path);
strcat(full_command, "/");
system(full_command); //Execute the command
}
</code></pre>
<ol start="7">
<li>Here is a config example</li>
</ol>
<pre><code>################################################################
# This configuration file purposes are to provide to the #
# sys_backup.c program the right cleaning process and storage #
# device path, customized to your own needs and preferences. #
################################################################
################################################################
#--------------------------------------------------------------#
# [Instructions] #
#--------------------------------------------------------------#
################################################################
# Please it's very important to make sure there are 3 charact- #
# ers between the unit name and its configurations. #
# For example: #
# #
# UnitName = configurations #
# #
# As you can see there are 3 characters between the unit name #
# and the configurations (2 spaces and an equal sign). Be awa- #
# re that each new line terminates the unit's configurations. #
# If the unit's configurations are too long you can put it in- #
# side a pair of braces and make it a list. For example: #
# #
# VeryLongUnit = { #
# config_1 #
# config_2 #
# config_3 #
# config_4 #
# } <- Don't forget to close the list #
# #
# If the list is group of commands you can add '&&' to the end #
# of each line. If the command requires root privileges you #
# can just add sudo to the command. For example: #
# #
# CommandsUnit = { #
# command 1 && #
# sudo root_command 2 && #
# command 3 && #
# sudo root_command 3 && #
# command 4 #
# } #
# #
# Be aware that every new line in the list syntax is converted #
# into a space, and '}' terminates the list. #
# Note: Please if you want to use indention for the list, only #
# use tabs, becuase they are ignored while reading a list. #
# Lastly as you can see hashes ('#') are ignored. #
# By the way, sorry for the hard syntax I really tried to make #
# as easy as I can and that's the result. I hope you like it :)#
################################################################
DirsToClean = {
~/.cache/spotify
~/.cache/mozilla/firefox/9jizeht4.default-release/thumbnails
~/.cache/tracker3
~/.cache/mozilla/firefox/9jizeht4.default-release/cache2
~/.cache/zoom
~/.local/share/Trash/files/*
~/.cache/torbrowser/download/*
~/.cache/yarn
}
CleaningCommands = {
sudo pacman -Sc &&
sudo paccache -rk2 &&
sudo journalctl --vacuum-time=1weeks
}
DevicePath = /run/media/yan/HDD/
#This is the default command which backups all the necessary directories.
#You can of course change it to your needs.
RsyncCommand = sudo rsync -aAXHv --exclude={"/dev/*","/proc/*","/sys/*","/tmp/*","/run/*","/mnt/*","/media/*","/lost+found"} /
</code></pre>
<p>I would like honest reviews and feedback that would help me to improve the code and more important my coding skills.
Here is a link to the program's repo if its easier for you to read it there:
<a href="https://github.com/yankh764/full-system-backup" rel="nofollow noreferrer">https://github.com/yankh764/full-system-backup</a></p>
<p>Thanks for any review.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:40:10.937",
"Id": "508055",
"Score": "0",
"body": "This is not by any stretch of the imagination functional programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:43:54.383",
"Id": "508057",
"Score": "0",
"body": "You may have meant procedural programming, but there's no tag for that, and anyway that's implied enough by the `c` tag."
}
] |
[
{
"body": "<h2>Language</h2>\n<blockquote>\n<p>I know that it may sound strange choice for a wrapper program to be written in C</p>\n</blockquote>\n<p>Yeah, about that. For practice, fine; but overall C isn't the right tool for this job. A more abstract scripting language such as Python will buy you shorter code with more memory safety, more operating system portability, and built-in support for better handling of alternate character encodings, locales, etc., etc., etc.</p>\n<h2>Typo</h2>\n<p><code>erros.h</code> -> <code>errors.h</code></p>\n<p><code>serching</code> -> <code>searching</code></p>\n<p><code>prorgram</code> -> <code>program</code></p>\n<h2>Constant parameters</h2>\n<pre><code>void handle_files_error(const char *message, char *file_path) {\n</code></pre>\n<p>should have <code>const</code> before <code>file_path</code> as well.</p>\n<h2>Truncation instead of failure</h2>\n<p><code>handle_files_error</code> is a nasty consequence of using non-memory-managed language, and would be comparatively trivial in a memory-managed language. Even if you were to stick to C, aborting on a message that's too long is the least friendly of your options. Instead, truncate to the length of your buffer; or better yet don't have a buffer at all and simply <code>fprintf</code> to <code>stderr</code>.</p>\n<h2>Utility functions</h2>\n<p><code>check_input_size</code> should not exist and makes the code less legible than simply doing the length comparison in place.</p>\n<h2>Default configuration</h2>\n<p>This whole default-config-if-missing mechanism:</p>\n<pre><code> if(check_file_existence(config_full_path) == 0) { //Check if config file exists\n create_config_file(config_full_path, config_desc);\n for(i=0; *units_desc[i]!='\\0'; i++)\n write_config_unit(config_full_path, *(units_list+i), *(units_desc+i));\n printf("Please configure the prorgram's config file in the following path: %s.\\n", config_full_path);\n return 0;\n }\n</code></pre>\n<p>can go away. The typical thing for Linux programs to do is require that a configuration file exist, and if it doesn't, fail outright; or (somewhat more complex) adopt a set of in-memory defaults. Writing a default configuration file if none exists is surprising behaviour.</p>\n<h2>Implicit array-to-pointer</h2>\n<p>This syntax is a little spooky:</p>\n<pre><code>const char *danger_message = {\n "Nice try, but we wont let you destroy your system ;)\\n"\n "Please make sure that DirsToClean unit is configured properly "\n "and there is no sign of standalone root tree (\\"/\\")."\n};\n</code></pre>\n<p>You're using an array literal but then dumping the array information and only keeping a pointer. For that reason, drop your braces - the string literal on its own is enough.</p>\n<h2>Dates by reference</h2>\n<p><code>get_date</code> is problematic. You're assuming that <code>int *date</code> is actually an array of three integers. Why not just pass three separate pointers? The intent is clearer and more explicit that way.</p>\n<p>Even if you kept your current pointer style - which you shouldn't - your array assignments</p>\n<pre><code>*date = time_ptr->tm_mday;\n*(date+1) = time_ptr->tm_mon + 1; //+1 because months range from 0 - 11\n*(date+2) = time_ptr->tm_year - 100; //-100 because tm_year is number of passed years since 1900\n</code></pre>\n<p>should turn into</p>\n<pre><code>date[0] = time_ptr->tm_mday;\ndate[1] = time_ptr->tm_mon + 1; //+1 because months range from 0 - 11\ndate[2] = time_ptr->tm_year - 100; //-100 because tm_year is number of passed years since 1900\n</code></pre>\n<p>But again, this will be a one-liner in Python.</p>\n<h2>Repeated <code>sprintf</code></h2>\n<p>You need to avoid your manual offsets here:</p>\n<pre><code>sprintf(dir_name, "%02d", *date_array);\nsprintf((dir_name+3), "%02d", *(date_array+1));\nsprintf(dir_name, "%02d", *date_array);\nsprintf(dir_name+6, "%d", *(date_array+2));));\ndir_name[2] = dir_name[5] = '-';\n</code></pre>\n<p>Instead,</p>\n<pre><code>sprintf(dir_name, "%02d-%02d-%d", date_array[0], date_array[1], date_array[2]);\n</code></pre>\n<h2>Security</h2>\n<p>There is ample opportunity for this program to be abused. You're forming command line strings using a fragile manual-memory-offset style in fixed-size buffers and then passing that off to <code>system</code>. Read <a href=\"https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152177\" rel=\"nofollow noreferrer\">this</a> for flavour. This is a recipe for disaster.</p>\n<p>Rather than shelling into <code>mkdir</code> for instance, just <a href=\"https://linux.die.net/man/2/mkdir\" rel=\"nofollow noreferrer\">call it from C</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T18:05:05.840",
"Id": "508085",
"Score": "0",
"body": "Thank you for your honest feedback and this full review I really appreciate it @Reinderien and im sorry that I don't know all these things but im kind of beginner so im trying to learn from books, documents, reviews and feedbacks from you guys. So thank you for trying to help, ill of course modify the code, improve it and try to make it as best as i can and even maybe ill do onother version of it in python or bash script"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:48:04.043",
"Id": "508097",
"Score": "1",
"body": "Great! If you do implement the above improvements, submit a second question with your new code. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T16:28:21.737",
"Id": "257257",
"ParentId": "257190",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T15:49:20.777",
"Id": "257190",
"Score": "4",
"Tags": [
"c",
"linux"
],
"Title": "rsync helper in C program"
}
|
257190
|
<p>In order to keep the fragmentation ratio of indices low, you should re-organize the indices from time to time on MSSQL. Microsoft describes in the link below how you can check the fragmentation of indices on tables in MSSQL and then how you can re-organize (re-build) the indices to reduce the fragmentation percentage:</p>
<p><a href="https://docs.microsoft.com/en-us/sql/relational-databases/indexes/reorganize-and-rebuild-indexes?view=sql-server-ver15" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/sql/relational-databases/indexes/reorganize-and-rebuild-indexes?view=sql-server-ver15</a></p>
<p>It would be nice to have a procedure that automatically re-organizes the indices in case the fragmentation percentage reaches a specific threshold. The procedure below does that:</p>
<pre><code>create procedure ui_reorganize_indices @db_name nvarchar(127), @table_name nvarchar(127)
as
begin
declare @avg_fragmentation_in_percent float
declare @index_name nvarchar(127)
declare @alter_index_command nvarchar(256)
declare rebuild_index_cursor cursor local for
select name AS IndedxName, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats
(DB_ID (@db_name)
, OBJECT_ID(@table_name)
, NULL
, NULL
, NULL) AS a
INNER JOIN sys.indexes AS b
ON a.object_id = b.object_id
AND a.index_id = b.index_id
and avg_fragmentation_in_percent > 20.0;
open rebuild_index_cursor
fetch next from rebuild_index_cursor into @index_name, @avg_fragmentation_in_percent
while @@fetch_status = 0
begin
select @alter_index_command = formatmessage('alter index %s on %s REORGANIZE', @index_name, @table_name)
print @alter_index_command
exec (@alter_index_command)
fetch next from rebuild_index_cursor into @index_name, @avg_fragmentation_in_percent
end
close rebuild_index_cursor
end
go
</code></pre>
<p>Have you guys used similar procedures to improve the health of your indices?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T10:03:21.123",
"Id": "512843",
"Score": "1",
"body": "Fortunately someone has already done the work for you on this. Check out https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T16:40:35.497",
"Id": "257192",
"Score": "0",
"Tags": [
"sql-server",
"t-sql"
],
"Title": "Re-organizing indices in case of fragmentation is T-SQL"
}
|
257192
|
<p>Here is a <a href="https://www.oracle.com/java/technologies/javase/codeconventions-statements.html" rel="nofollow noreferrer">reference</a> to how switch statements should be formatted (I've never seen this used at the two companies I've worked at):</p>
<p><a href="https://i.stack.imgur.com/aekqJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aekqJ.png" alt="enter image description here" /></a></p>
<p>And a <a href="https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html" rel="nofollow noreferrer">contradictory one</a>, which I am partial to (and is IntelliJ IDEA default):</p>
<p><a href="https://i.stack.imgur.com/ToK45.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ToK45.png" alt="enter image description here" /></a></p>
<p>The obvious discrepancy is in the tabbing of the case statement - whether it's</p>
<pre class="lang-java prettyprint-override"><code>switch(case) {
case x:
}
</code></pre>
<p>or</p>
<pre class="lang-java prettyprint-override"><code>switch(case) {
case x:
}
</code></pre>
<p>Is there a right or wrong one?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:40:16.903",
"Id": "507951",
"Score": "2",
"body": "This post isn't really suited for Code Review (because you're not asking us to review code). It would be better off on Stackoverflow, but would probably get closed there too as it is **opinion based**. Indeed, Oracle did not make a Mistake here, it's just a different **code style**."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T18:40:48.080",
"Id": "507957",
"Score": "0",
"body": "correct me if im wrong, but if their documentation says, quite literally, that a particular command should \"have the following form\", doesn't that mean they are making a statement of fact as to java syntax? I'm just trying to ascertain that because the first example doesn't look right to me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T18:55:36.073",
"Id": "507960",
"Score": "2",
"body": "The document you are reading is not a syntax guide, it is about **code conventions** or **code style**. Both examples are syntactically correct and either might be correct style depending on which conventions you adhere to. And by the way, the document you linked is **wildly** outdated: \"The last revision to this document was made on April 20, 1999\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T21:26:48.637",
"Id": "507968",
"Score": "1",
"body": "Of course, SunSoft is right and everyone even mentioning the possibility of deviating a heretic. (Where do you suggest to place loop labels?)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T17:01:46.423",
"Id": "257193",
"Score": "1",
"Tags": [
"java",
"formatting"
],
"Title": "Does Oracle have a mistake in their documentation regarding switch case formatting?"
}
|
257193
|
<p>I implemented lazy_map - <a href="https://github.com/tinytrashbin/lazy_map" rel="nofollow noreferrer">https://github.com/tinytrashbin/lazy_map</a>.</p>
<p><strong>Can someone help with reviews ?</strong></p>
<p>lazy_map is an implementation of unordered_map that has O(1) cost
of copying irrespective of the current size of map.
The optimizations done for O(1) copy operation don't have any
visiable side-effect on the map interface no matter how lazy_map
is used. The value semantics of the map are preserved while copying. i.e.
any write operation on the copied map are totally independent of copied-from
map. For any two different lazy_map object, write operation on one have no
impact on the other one.
The map operations like insertion, deletion, loopup etc. continues
to costs O(1) all the time except in a special case of detachment.</p>
<h3>Client of lazy_map Must Know That</h3>
<ol>
<li><p>The iterator can get invalidated on any standard write operation. (unlike
std::unordered_map, which guarantees iterator stability on erase).
lazy_map offers two non standard methods <code>move_value</code> and
<code>move</code> to move out value of a key. lazy_map guarantees iterator stability
on 'move_value' and 'move' operation.</p>
</li>
<li><p>If the cost of copy for value-type is large, it's good idea to wrap the
value type in a <code>cow_wrapper</code>. (eg: <code>lazy_map<int, cow_wrapper<V>></code>
because the internal implementation of lazy_map might have to copy
the value a lot of time. The time complexity analysis here assumes
that cost of copying key/value is O(1).</p>
</li>
<li><p>Standard map methods, which expose mutable internal references, are <em>NOT</em>
supported. eg: non-const operator[], non-const iterator etc.</p>
</li>
<li><p>In addition to standard <code>find</code> method, <code>contains</code> method is
supported that takes a key and return a boolean.</p>
</li>
<li><p>Non standard method <code>move_value</code> and <code>move</code> takes a @key and
return a unique_ptr by moving the value at @key.
'move_value' returns nullptr if the value is shared by other objects.
'move' copies the value if the value is shared by other
objects. Both of these method return nullptr if the key doesn't exist.
ToDo(Mohit): Revisit this point.</p>
</li>
</ol>
<h3>Implementation Overview:</h3>
<p>The implementation of lazy_map stores the data of a map in a
chain of fragments. Each fragment stores the modification to be applied
on the map state. These fragments are shared across different map objects. If a
map is copied, the new object becomes another share holder of the old
fragment. (think std::shared_ptr). The map updates (insertion, deletion) on
the copied object are stored on a new fragment on top of the current
fragment. Fragments can have a parent fragment. These fragment create a tree
like structure. (similar to git commits). The absolute value of a fragment is
computed by applying the modification in current fragment on the absolute
value of parent fragment.</p>
<p>If a fragment have a long chain of parents (i.e. length of chain > @max_depth),
the absolute value of a fragment is computed and updated inplace and the
fragment is detached from it's parent. This operation is called detachment.
It's is the most expensive operation in lazy_map.
Note: default value of @max_depth is 3.</p>
<p>The iteration on lazy_map consts O(number_of_keys * depth_of_parents_chain). In
fact for most of the lazy_map APIs, a factor of @depth_of_parents_chain comes
into time complexity. Which is not a big deal if we use a small @max_depth.
Note that lazy_map is not optimized for deeply nested fragments. but it is
highly optimized for fragment trees with very high breadth/branches.
i.e. 1000s of copy of a very big map for making small modifications can save
cost of copying with lazy_map.</p>
<h3>Implementation Details:</h3>
<p>shared fragments in <code>lazy_map</code> are both value-immutable as well as
structure-immutable. Checkout <code>messy_lazy_map.md</code> as well, whose shared fragments
are value-immutable but not structure-immutable.</p>
<p>A fragment can be detached only if it has exactly one owner. Hence lazy_map
doesn't need to protect their fragments by a read-write lock.</p>
<p>Note that lazy_map don't track the depth of parents chain. They
needs to be detached manually when required. Generally it's good idea to
detach them manually if the fragment chain is going to be very large.</p>
<h3>Fragment:</h3>
<pre><code>struct Fragment {
std::shared_ptr<Fragment> parent;
std::unordered_map<K, V> key_values;
std::unordered_set<K> deleted_keys;
}
</code></pre>
<p>A fragment records the deleted keys as well as updated key-value pairs.</p>
<p>The absolute values of a fragment is computed as follows:</p>
<pre><code>AbsoluteValue(fragment) {
if (fragment.parent == nullptr) return fragment.key_values;
else {
let m = AbsoluteValue(*fragment.parent);
m.erase_keys(fragment.deleted_keys);
m.override_key_values(fragment.key_values);
return m;
}
}
</code></pre>
<p>Following invariants are guaranteed in every fragment.</p>
<ol>
<li><p><code>fragment.key_values</code> and <code>fragment.deleted_keys</code> should be disjoint.</p>
</li>
<li><p>if <code>x ∈ fragment.deleted_keys</code> then
(<code>fragment.parent</code> must not be <code>nullptr</code>
&& <code>x ∈ AbsoluteValue(fragment.parent)</code>)</p>
</li>
</ol>
<p>eg:</p>
<p>F1 = (key_values={1: 10, 2: 20, 3:30}, deleted_keys={}, parent=nullptr)</p>
<p>F2 = (key_values={2: 30, 4: 40}, deleted_keys={1}, parent=F1)</p>
<p>F3 = (key_values={1: 10, 7: 70, 6:60}, deleted_keys={2, 4}, parent=F2)</p>
<p>AbsoluteValue(F1) = {1: 10, 2: 20, 3:30}</p>
<p>AbsoluteValue(F2) = {2: 30, 3:30, 4: 40}</p>
<p>AbsoluteValue(F3) = {1: 10, 3: 30, 6: 60, 7:70}</p>
<p>Detached(F3):
= (key_values={1: 10, 3: 30, 6: 60, 7:70}, deleted_keys={}, parent=nullptr)</p>
<p>AbsoluteValue doesn't change by detachment.</p>
<hr />
<h3>lazy_map.cpp</h3>
<pre><code>
// Author: Mohit Saini (mohit.saini@thoughtspot.com)
// The documentation (ts/lazy_map.md) MUST be read twice
// before using this utility.
#ifndef TS_LAZY_MAP_HPP_
#define TS_LAZY_MAP_HPP_
#include <assert.h>
#include <memory>
#include <utility>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <string>
namespace ts {
namespace lazy_map_impl {
constexpr const char* key_error = "[lazy_map]: Key not found";
template<typename C, typename K>
inline bool contains_key(const C& c, const K& k) {
return (c.find(k) != c.end());
}
template<typename K, typename V>
class lazy_map {
class const_iter_impl;
using underlying_map = typename std::unordered_map<K, V>;
using underlying_const_iter = typename underlying_map::const_iterator;
public:
using key_type = K;
using mapped_type = V;
using value_type = std::pair<const K, V>;
using const_iterator = const_iter_impl;
using iterator = const_iterator;
using reference = value_type&;
using const_reference = const value_type&;
lazy_map() : node_(std::make_shared<Node>()) { }
lazy_map(std::initializer_list<value_type> values)
: node_(std::make_shared<Node>(values)) { }
template<typename InputIt>
lazy_map(InputIt first, InputIt last)
: node_(std::make_shared<Node>(first, last)) { }
bool detach() {
prepare_for_edit();
return detach_internal();
}
bool is_detached() const {
return (node_->parent_ == nullptr);
}
bool contains(const K& k) const {
return contains_internal(k);
}
size_t get_depth() const {
size_t depth = 0;
for (auto* p = &node_->parent_; (*p) != nullptr; p = &((*p)->parent_)) {
depth++;
}
return depth;
}
const V& at(const K& k) const {
for (auto* p = &node_; (*p) != nullptr; p = &((*p)->parent_)) {
if (contains_key((*p)->values_, k)) {
return (*p)->values_.at(k);
}
if (contains_key((*p)->deleted_keys_, k)) {
throw std::runtime_error(key_error);
}
}
throw std::runtime_error(key_error);
}
const V& operator[](const K& k) const {
return at(k);
}
size_t size() const {
return node_->size_;
}
bool empty() const {
return (node_->size_ == 0);
}
void insert_or_assign(const K& k, const V& v) {
prepare_for_edit();
node_->size_ += contains_internal(k) ? 0: 1;
node_->deleted_keys_.erase(k);
if (contains_key(node_->values_, k)) {
node_->values_.at(k) = v;
} else {
node_->values_.emplace(k, v);
}
}
void insert_or_assign(const K& k, V&& v) {
prepare_for_edit();
node_->size_ += contains_internal(k) ? 0: 1;
node_->deleted_keys_.erase(k);
if (contains_key(node_->values_, k)) {
node_->values_.at(k) = std::move(v);
} else {
node_->values_.emplace(k, std::move(v));
}
}
void insert_or_assign(const value_type& kv) {
insert_or_assign(kv.first, kv.second);
}
void insert_or_assign(value_type&& kv) {
insert_or_assign(kv.first, std::move(kv.second));
}
// Non standard method. insert_or_assign is the standard name for it (C++17).
inline void put(const K& k, const V& v) {
insert_or_assign(k, v);
}
// Non standard method. insert_or_assign is the standard name for it (C++17).
inline void put(const K& k, V&& v) {
insert_or_assign(k, std::move(v));
}
bool insert(const K& k, const V& v) {
if (contains_internal(k)) return false;
prepare_for_edit();
node_->deleted_keys_.erase(k);
node_->values_.emplace(k, v);
node_->size_++;
return true;
}
bool insert(const K& k, V&& v) {
if (contains_internal(k)) return false;
prepare_for_edit();
node_->deleted_keys_.erase(k);
node_->values_.emplace(k, std::move(v));
node_->size_++;
return true;
}
bool insert(const value_type& kv) {
return insert(kv.first, kv.second);
}
bool insert(value_type&& kv) {
return insert(kv.first, std::move(kv.second));
}
template<typename... Args>
bool emplace(const K& k, Args&&... args) {
if (contains_internal(k)) return false;
prepare_for_edit();
node_->deleted_keys_.erase(k);
node_->values_.emplace(std::piecewise_construct,
std::forward_as_tuple(k),
std::tuple<Args&&...>(std::forward<Args>(args)...));
node_->size_++;
return true;
}
void clear() {
// No need to prepare_for_edit.
node_ = std::make_shared<Node>();
}
bool erase(const K& k) {
if (not contains_internal(k)) return false;
prepare_for_edit();
node_->values_.erase(k);
if (contains_internal(k)) {
node_->deleted_keys_.insert(k);
}
node_->size_--;
return true;
}
// - Erase the given key and return the erased value. If the key-value pair
// is not shared by other objects, move the value in output. If the
// key-value pair is shared by other objects, copy the value for returning.
// - It is useful when we need to update a value efficiently.
// - Returns nullptr only if the key doesn't exists.
// - Non-standard map method.
std::unique_ptr<V> move_and_erase(const K& k) {
if (not contains_internal(k)) return nullptr;
prepare_for_edit();
std::unique_ptr<V> output;
if (contains_key(node_->values_, k)) {
output = std::make_unique<V>(std::move(node_->values_[k]));
} else {
output = std::make_unique<V>(at(k));
}
node_->values_.erase(k);
if (contains_internal(k)) {
node_->deleted_keys_.insert(k);
}
node_->size_--;
return output;
}
// - Move out the value of a key and return. Return nullptr if the key
// doesn't exists. If the value is shared by other objects, it will be
// copied.
// - It is useful when we need to update the value efficiently.
// - Equivalent of std::make_unique<V>(std::move(my_map[key])) in standard
// map.
// - Since lazy_map don't expose mutable iternal reference,
// only way to update a value of key is: copy/move it in a variable, update
// it and then insert_or_assign it again.
// - Return nullptr if either the key doesn't exists.
// - Non-standard map method.
std::unique_ptr<V> move(const K& k) {
if (not contains_internal(k)) return nullptr;
if (node_.unique() and contains_key(node_->values_, k)) {
return std::make_unique<V>(std::move(node_->values_[k]));
} else {
return std::make_unique<V>(at(k));
}
}
// Similar to move(k) method. In adding, it return the nullptr if the value
// is shared instead of copying value.
std::unique_ptr<V> move_only(const K& k) {
if (not contains_internal(k)) return nullptr;
if (node_.unique() and contains_key(node_->values_, k)) {
return std::make_unique<V>(std::move(node_->values_[k]));
}
return nullptr;
}
const_iter_impl begin() const {
return const_iter_impl(node_.get());
}
const_iter_impl end() const {
return const_iter_impl(nullptr);
}
const_iterator find(const K& k) const {
for (Node* p = node_.get(); p != nullptr; p = p->parent_.get()) {
auto it = p->values_.find(k);
if (it != p->values_.end()) {
return const_iterator(node_.get(), p, std::move(it));
}
if (contains_key(p->deleted_keys_, k)) {
return const_iterator();
}
}
return const_iterator();
}
private:
bool insert_internal(const K& k, const V& v) {
if (contains_internal(k)) return false;
node_->deleted_keys_.erase(k);
node_->values_.emplace(k, v);
node_->size_++;
return true;
}
bool contains_internal(const K& k) const {
for (Node* p = node_.get(); p != nullptr; p = p->parent_.get()) {
if (contains_key(p->values_, k)) {
return true;
}
if (contains_key(p->deleted_keys_, k)) {
return false;
}
}
return false;
}
void prepare_for_edit() {
if (not node_.unique()) {
auto new_node = std::make_shared<Node>(std::move(node_));
node_ = std::move(new_node);
}
}
bool detach_internal() {
if (node_->parent_ == nullptr) return false;
for (auto* p = &node_->parent_; (*p) != nullptr; p = &((*p)->parent_)) {
for (auto& v : (*p)->values_) {
if (not contains_key(node_->deleted_keys_, v.first)) {
node_->values_.emplace(v.first, v.second);
}
}
const auto& d = (*p)->deleted_keys_;
node_->deleted_keys_.insert(d.begin(), d.end());
}
node_->deleted_keys_.clear();
node_->parent_ = nullptr;
return true;
}
struct Node {
Node() = default;
explicit Node(std::shared_ptr<Node>&& parent)
: parent_(std::move(parent)), size_(parent_->size_) { }
explicit Node(std::initializer_list<value_type> values)
: values_(values), size_(values_.size()) { }
explicit Node(const std::unordered_map<K, V>& other_map)
: values_(other_map), size_(values_.size()) { }
explicit Node(std::unordered_map<K, V>&& other_map)
: values_(std::move(other_map)), size_(values_.size()) { }
template<typename InputIt>
Node(InputIt first, InputIt last)
: values_(first, last), size_(values_.size()) { }
std::shared_ptr<Node> parent_;
std::unordered_map<K, V> values_;
std::unordered_set<K> deleted_keys_;
size_t size_ = 0;
};
// The implementation of this iterator relies on the C++ standard's sayings,
// that comparison of two iterators from different container is undefined
// behavior. Hence iterator of a lazy_map object should not
// be compared with other lazy_map object.
// In this implementation we are also ensuring that we don't compare iterator
// of one unordered_map with another.
class const_iter_impl {
public:
// Default constructed iterator is the end() iterator.
const_iter_impl() = default;
const_iter_impl(const Node* head,
const Node* current,
underlying_const_iter&& it)
: head_(head), current_(current), it_(std::move(it)) {}
const_iter_impl(const Node* head): head_(head), current_(head) {
if (current_) {
it_ = current_->values_.begin();
if (not move_forward_to_closest_non_deleted_valid_position()) {
current_ = nullptr;
}
}
}
bool operator==(const const_iter_impl& o) const {
return (current_ == o.current_ && (current_ == nullptr || it_ == o.it_));
}
bool operator!=(const const_iter_impl& o) const {
return not (*this == o);
}
// Precondition(@current_ != nullptr)
const_iter_impl& operator++() {
assert(current_ != nullptr);
++it_;
if (not move_forward_to_closest_non_deleted_valid_position()) {
current_ = nullptr;
return *this;
}
return *this;
}
const_iter_impl& operator++(int) {
auto old = *this;
++(*this);
return old;
}
auto& operator*() const {
return *it_;
}
auto* operator->() const {
return it_.operator->();
}
private:
// - Precondition(@current_ != nullptr)
// - Postcondition(@current_ != nullptr)
// - The closest non-deleted valid position might be at 0 distance apart.
// (if we are already there).
// - Return false if reached end of stream.
bool move_forward_to_closest_non_deleted_valid_position() {
while(move_forward_to_closest_valid_position()) {
if (should_ignore_key(it_->first)) {
++it_;
continue;
} else {
return true;
}
}
return false;
}
// - Precondition(@current_ != nullptr)
// - Postcondition(@current_ != nullptr)
// - The closest valid position might be at 0 distance apart. (if we are
// already on a valid position).
// - Return false if we failed to move forward to a valid position.
bool move_forward_to_closest_valid_position() {
while (it_ == current_->values_.end()) {
if (current_->parent_ == nullptr) {
return false;
}
current_ = current_->parent_.get();
it_ = current_->values_.begin();
}
return true;
}
// Precondition(@current_ != nullptr)
bool should_ignore_key(const K& k) const {
for (auto c = head_; c != current_; c = c->parent_.get()) {
if (contains_key(c->values_, k)
or contains_key(c->deleted_keys_, k)) {
return true;
}
}
return false;
}
// Invariant(head_ != nullptr || current_ == nullptr)
const Node* head_ = nullptr;
// current_ == nullptr means that this iterator is the `end()`
const Node* current_ = nullptr;
// Belongs to the containr current_->values_ if current_ is not nullptr.
underlying_const_iter it_;
friend class lazy_map;
};
friend class lazy_map_test_internals;
std::shared_ptr<Node> node_;
};
</code></pre>
<hr />
<p>Thanks !</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T08:44:20.083",
"Id": "507993",
"Score": "0",
"body": "It's not clear in the question, but does this satisfy the same complexity constrains as `std::unordered_set` for the other operations? In particular, are `insert()` and `erase()` no worse than linear in the size?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T09:20:31.413",
"Id": "507996",
"Score": "1",
"body": "Actually amortized complexity is still O(1) (assuming depth is bounded by a small constant max_depth ~ 3) .. but in the worst case it can take more than O(size)... but this worst case is extremely rare to happen if we have a good hash function in std::unordered_map."
}
] |
[
{
"body": "<blockquote>\n<pre><code>// The documentation (ts/lazy_map.md) MUST be read twice\n// before using this utility.\n</code></pre>\n</blockquote>\n<p>Scary warning! I wonder whether that will be obeyed? It might be an idea to specifically mention pitfalls where we differ from standard unordered map.</p>\n<blockquote>\n<pre><code>#include <assert.h>\n</code></pre>\n</blockquote>\n<p>Prefer to use C++ library headers (i.e. <code><cassert></code>) rather than the deprecated C-compatibility headers.</p>\n<blockquote>\n<pre><code> using value_type = std::pair<const K, V>;\n</code></pre>\n</blockquote>\n<p>Consider declaring this as <code>= typename underlying_map::value_type</code> (which will be the same type, but a different way of thinking of it). I'm not sure which of the two is a better choice here.</p>\n<p>The <code>operator[]</code> is surprising in two ways: first, it performs all the same checks as <code>at()</code>, unlike the standard collections. Secondly, there's no non-const version to create a new key. Now I understand the insistence on reading the documentation file!</p>\n<blockquote>\n<pre><code> size_t size() const {\n</code></pre>\n</blockquote>\n<p>Typo: <code>std::size_t</code></p>\n<p>In <code>insert_or_assign()</code>, there's an inefficiency:</p>\n<blockquote>\n<pre><code>if (contains_key(node_->values_, k)) {\n node_->values_.at(k) = std::move(v);\n</code></pre>\n</blockquote>\n<p><code>contains_key()</code> finds the iterator for the key, but we don't retain that - it just returns a <code>bool</code>, so we end up having to find it again in <code>at()</code>.</p>\n<hr />\n<p>(partial review - Real Life just called)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:48:32.330",
"Id": "508038",
"Score": "0",
"body": "Thanks @toby..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T09:00:57.363",
"Id": "257221",
"ParentId": "257196",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T18:01:50.187",
"Id": "257196",
"Score": "4",
"Tags": [
"c++",
"hash-map",
"c++14",
"lazy"
],
"Title": "lazy_map implementation in C++ | Similar to unordered_map but O(1) copyable"
}
|
257196
|
<p>This is a follow up of <a href="https://codereview.stackexchange.com/questions/256579/skyscraper-solver-for-nxn-size">Skyscraper Solver for NxN Size</a></p>
<p>I followed the advice in the last question and changed my approach from generating Permutations to use <a href="https://en.wikipedia.org/wiki/Backtracking" rel="nofollow noreferrer">Backtracking</a> to solve the puzzle.</p>
<p>Unfortunately my solution is still to slow for certain tests.</p>
<p>Here are the worst test cases:</p>
<pre><code>struct TestDataProvider {
std::vector<int> clues;
std::vector<std::vector<int>> result;
std::vector<std::vector<int>> board;
};
TestDataProvider sky7_random{{0, 5, 0, 5, 0, 2, 0, 0, 0, 0, 4, 0, 0, 3,
6, 4, 0, 2, 0, 0, 3, 0, 3, 3, 3, 0, 0, 4},
{{{2, 3, 6, 1, 4, 5, 7},
{7, 1, 5, 2, 3, 4, 6},
{6, 4, 2, 3, 1, 7, 5},
{4, 5, 7, 6, 2, 3, 1},
{3, 2, 1, 5, 7, 6, 4},
{1, 6, 4, 7, 5, 2, 3},
{5, 7, 3, 4, 6, 1, 2}}}};
TestDataProvider sky11_medium_partial_2{
{1, 2, 2, 5, 3, 2, 5, 3, 5, 4, 3, 4, 2, 3, 1, 2, 3, 2, 4, 3, 4, 4,
3, 4, 3, 2, 3, 5, 3, 1, 2, 3, 3, 3, 3, 2, 3, 5, 2, 5, 3, 4, 2, 1},
{{11, 9, 10, 5, 8, 6, 2, 4, 1, 3, 7},
{9, 1, 3, 8, 7, 11, 6, 5, 2, 4, 10},
{6, 2, 1, 7, 3, 9, 8, 11, 5, 10, 4},
{7, 6, 4, 2, 10, 8, 1, 3, 9, 5, 11},
{2, 7, 6, 9, 4, 10, 3, 8, 11, 1, 5},
{4, 11, 2, 6, 9, 5, 10, 1, 3, 7, 8},
{1, 4, 7, 10, 2, 3, 5, 6, 8, 11, 9},
{3, 8, 5, 4, 11, 7, 9, 2, 10, 6, 1},
{10, 5, 8, 1, 6, 2, 11, 7, 4, 9, 3},
{5, 10, 11, 3, 1, 4, 7, 9, 6, 8, 2},
{8, 3, 9, 11, 5, 1, 4, 10, 7, 2, 6}},
{{0, 0, 10, 0, 8, 0, 2, 0, 1, 0, 0},
{0, 0, 0, 0, 7, 11, 0, 5, 0, 0, 0},
{0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 4},
{0, 0, 0, 0, 0, 0, 1, 3, 9, 0, 0},
{0, 0, 6, 0, 4, 0, 3, 0, 11, 1, 0},
{0, 0, 0, 6, 9, 0, 0, 1, 3, 0, 8},
{0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 9},
{0, 0, 0, 4, 11, 0, 0, 0, 0, 0, 1},
{10, 0, 8, 1, 0, 2, 11, 7, 4, 0, 0},
{5, 10, 0, 0, 0, 0, 0, 0, 0, 8, 0},
{0, 0, 9, 0, 5, 0, 0, 0, 7, 0, 6}}};
TEST(CodewarsBacktracking, sky7_random)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(sky7_random.clues),
sky7_random.result);
}
TEST(CodewarsBacktracking, sky11_medium_partial_2)
{
EXPECT_EQ(codewarsbacktracking::SolvePuzzle(
sky11_medium_partial_2.clues, sky11_medium_partial_2.board,
sky11_medium_partial_2.board.size()),
sky11_medium_partial_2.result);
}
</code></pre>
<p>The first test tries to solve a 7x7 Board with no skyscrapers on the grid. A few Skyscrapers are computed out of the clues provided but then my backtracking routine needs to insert ~440 mio times until the puzzle is solved.</p>
<p>The other test case is a 11x11 board which is already partially filled but also has not many clues.</p>
<p>On my system the run times look like this in release mode (Including other unit tests which are a lot faster):</p>
<pre><code>[----------] 35 tests from CodewarsBacktracking
[ RUN ] CodewarsBacktracking.sky4_easy
[ OK ] CodewarsBacktracking.sky4_easy (0 ms)
[ RUN ] CodewarsBacktracking.sky4_easy_2
[ OK ] CodewarsBacktracking.sky4_easy_2 (0 ms)
[ RUN ] CodewarsBacktracking.sky4_hard
[ OK ] CodewarsBacktracking.sky4_hard (0 ms)
[ RUN ] CodewarsBacktracking.sky4_hard_2
[ OK ] CodewarsBacktracking.sky4_hard_2 (0 ms)
[ RUN ] CodewarsBacktracking.sky6_easy
[ OK ] CodewarsBacktracking.sky6_easy (5 ms)
[ RUN ] CodewarsBacktracking.sky6_medium
[ OK ] CodewarsBacktracking.sky6_medium (3 ms)
[ RUN ] CodewarsBacktracking.sky6_hard
[ OK ] CodewarsBacktracking.sky6_hard (5 ms)
[ RUN ] CodewarsBacktracking.sky6_hard_2
[ OK ] CodewarsBacktracking.sky6_hard_2 (1 ms)
[ RUN ] CodewarsBacktracking.sky6_random
[ OK ] CodewarsBacktracking.sky6_random (13 ms)
[ RUN ] CodewarsBacktracking.sky6_random_2
[ OK ] CodewarsBacktracking.sky6_random_2 (1 ms)
[ RUN ] CodewarsBacktracking.sky6_random_3
[ OK ] CodewarsBacktracking.sky6_random_3 (3 ms)
[ RUN ] CodewarsBacktracking.sky7_medium
[ OK ] CodewarsBacktracking.sky7_medium (27 ms)
[ RUN ] CodewarsBacktracking.sky7_hard
[ OK ] CodewarsBacktracking.sky7_hard (54 ms)
[ RUN ] CodewarsBacktracking.sky7_very_hard
[ OK ] CodewarsBacktracking.sky7_very_hard (336 ms)
[ RUN ] CodewarsBacktracking.sky7_random
[ OK ] CodewarsBacktracking.sky7_random (72952 ms)
[ RUN ] CodewarsBacktracking.sky4_partial
[ OK ] CodewarsBacktracking.sky4_partial (0 ms)
[ RUN ] CodewarsBacktracking.sky4_partial_2
[ OK ] CodewarsBacktracking.sky4_partial_2 (0 ms)
[ RUN ] CodewarsBacktracking.sky5_partial
[ OK ] CodewarsBacktracking.sky5_partial (0 ms)
[ RUN ] CodewarsBacktracking.sky5_partial_2
[ OK ] CodewarsBacktracking.sky5_partial_2 (0 ms)
[ RUN ] CodewarsBacktracking.sky6_partial
[ OK ] CodewarsBacktracking.sky6_partial (0 ms)
[ RUN ] CodewarsBacktracking.sky6_partial_2
[ OK ] CodewarsBacktracking.sky6_partial_2 (1 ms)
[ RUN ] CodewarsBacktracking.sky7_easy_partial
[ OK ] CodewarsBacktracking.sky7_easy_partial (0 ms)
[ RUN ] CodewarsBacktracking.sky7_easy_partial_2
[ OK ] CodewarsBacktracking.sky7_easy_partial_2 (0 ms)
[ RUN ] CodewarsBacktracking.sky7_medium_partial
[ OK ] CodewarsBacktracking.sky7_medium_partial (1 ms)
[ RUN ] CodewarsBacktracking.sky7_hard_partial
[ OK ] CodewarsBacktracking.sky7_hard_partial (42 ms)
[ RUN ] CodewarsBacktracking.sky8_easy_partial
[ OK ] CodewarsBacktracking.sky8_easy_partial (1 ms)
[ RUN ] CodewarsBacktracking.sky8_medium_partial
[ OK ] CodewarsBacktracking.sky8_medium_partial (1 ms)
[ RUN ] CodewarsBacktracking.sky8_hard_partial
[ OK ] CodewarsBacktracking.sky8_hard_partial (1390 ms)
[ RUN ] CodewarsBacktracking.sky9_easy_partial
[ OK ] CodewarsBacktracking.sky9_easy_partial (1 ms)
[ RUN ] CodewarsBacktracking.sky9_easy_partial_2
[ OK ] CodewarsBacktracking.sky9_easy_partial_2 (1 ms)
[ RUN ] CodewarsBacktracking.sky10_easy_partial
[ OK ] CodewarsBacktracking.sky10_easy_partial (1 ms)
[ RUN ] CodewarsBacktracking.sky10_easy_partial_2
[ OK ] CodewarsBacktracking.sky10_easy_partial_2 (0 ms)
[ RUN ] CodewarsBacktracking.sky11_easy_partial
[ OK ] CodewarsBacktracking.sky11_easy_partial (2 ms)
[ RUN ] CodewarsBacktracking.sky11_medium_partial
[ OK ] CodewarsBacktracking.sky11_medium_partial (661 ms)
[ RUN ] CodewarsBacktracking.sky11_medium_partial_2
[ OK ] CodewarsBacktracking.sky11_medium_partial_2 (36910 ms)
[----------] 35 tests from CodewarsBacktracking (112413 ms total)
</code></pre>
<p>So I wonder is there any way to make the backtracking faster here or is there just no faster way to solve skyscraper puzzles? Is it possible to reduce the calls to the backtracking routine ?</p>
<p>I already try to abort the insertion as soon as the board is getting invalid. I cannot come up with another tweak to reduce the backtracking calls.</p>
<p>Below the full code for the backtracking.</p>
<p>The interesting part which does the backtracking is the function <code>guessSkyscrapers</code>:</p>
<pre><code>bool guessSkyscrapers(Board &board, const std::vector<int> &clues,
std::size_t x, std::size_t y, std::size_t size)
{
if (x == size) {
x = 0;
y++;
};
if (y == size) {
return true;
}
if (board.skyscrapers[y][x] != 0) {
if (!skyscrapersAreValidPositioned(board.skyscrapers, clues, x, y,
size)) {
return false;
}
if (guessSkyscrapers(board, clues, x + 1, y, size)) {
return true;
}
else {
return false;
}
}
for (int trySkyscraper = 1;
trySkyscraper <= static_cast<int>(board.skyscrapers.size());
++trySkyscraper) {
if (board.nopes[y][x].contains(trySkyscraper)) {
continue;
}
board.skyscrapers[y][x] = trySkyscraper;
if (!skyscrapersAreValidPositioned(board.skyscrapers, clues, x, y,
size)) {
continue;
}
if (guessSkyscrapers(board, clues, x + 1, y, size)) {
return true;
}
}
board.skyscrapers[y][x] = 0;
return false;
}
</code></pre>
<p>Let me know if you have any idea how to speed up solving this puzzles.</p>
<p>If you want to see the whole github project which contains:</p>
<p>-Backtracking Solution in one file (like here requirement for codewars)
-Backtracking Solution in multiple files
-Permutations Solution in one file (like here requirement for codewars)
-Permutations Solution in multiple files
-Full Unit test suite</p>
<p>You can find it <a href="https://github.com/SandroWissmann/Skyscrapers" rel="nofollow noreferrer">here</a></p>
<p>Full backtracking code:</p>
<p><strong>codewarsbacktracking.cpp</strong></p>
<pre><code>#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <unordered_set>
namespace codewarsbacktracking {
struct ClueHints {
ClueHints(std::size_t boardSize);
ClueHints();
void reverse();
void removeNopesOnSkyscrapers();
std::vector<int> skyscrapers{};
std::vector<std::vector<int>> nopes{};
};
ClueHints::ClueHints(std::size_t boardSize)
: skyscrapers{std::vector<int>(boardSize, 0)},
nopes{std::vector<std::vector<int>>(boardSize, std::vector<int>{})}
{
}
void ClueHints::reverse()
{
std::reverse(skyscrapers.begin(), skyscrapers.end());
std::reverse(nopes.begin(), nopes.end());
}
void ClueHints::removeNopesOnSkyscrapers()
{
for (std::size_t i = 0; i < skyscrapers.size(); ++i) {
if (skyscrapers[i] == 0) {
continue;
}
nopes[i].clear();
}
}
std::optional<ClueHints> getClueHints(int clue, std::size_t boardSize)
{
if (clue == 0) {
return {};
}
ClueHints clueHints{boardSize};
std::vector<std::unordered_set<int>> nopes(boardSize,
std::unordered_set<int>{});
if (clue == static_cast<int>(boardSize)) {
for (std::size_t i = 0; i < boardSize; ++i) {
clueHints.skyscrapers[i] = i + 1;
}
}
else if (clue == 1) {
clueHints.skyscrapers[0] = boardSize;
}
else if (clue == 2) {
nopes[0].insert(boardSize);
nopes[1].insert(boardSize - 1);
}
else {
for (std::size_t fieldIdx = 0;
fieldIdx < static_cast<std::size_t>(clue - 1); ++fieldIdx) {
for (std::size_t nopeValue = boardSize;
nopeValue >= (boardSize - (clue - 2) + fieldIdx);
--nopeValue) {
nopes[fieldIdx].insert(nopeValue);
}
}
}
assert(nopes.size() == clueHints.nopes.size());
for (std::size_t i = 0; i < nopes.size(); ++i) {
clueHints.nopes[i] = std::vector<int>(nopes[i].begin(), nopes[i].end());
}
return {clueHints};
}
std::optional<ClueHints> merge(std::optional<ClueHints> optFrontClueHints,
std::optional<ClueHints> optBackClueHints)
{
if (!optFrontClueHints && !optBackClueHints) {
return {};
}
if (!optFrontClueHints) {
optBackClueHints->reverse();
return optBackClueHints;
}
if (!optBackClueHints) {
return optFrontClueHints;
}
auto size = optFrontClueHints->skyscrapers.size();
ClueHints clueHints{size};
assert(optFrontClueHints->skyscrapers.size() ==
optFrontClueHints->nopes.size());
assert(optBackClueHints->skyscrapers.size() ==
optBackClueHints->nopes.size());
assert(optFrontClueHints->skyscrapers.size() ==
optBackClueHints->skyscrapers.size());
optBackClueHints->reverse();
for (std::size_t i = 0; i < optFrontClueHints->skyscrapers.size(); ++i) {
auto frontSkyscraper = optFrontClueHints->skyscrapers[i];
auto backSkyscraper = optBackClueHints->skyscrapers[i];
if (frontSkyscraper != 0 && backSkyscraper != 0) {
assert(frontSkyscraper == backSkyscraper);
clueHints.skyscrapers[i] = frontSkyscraper;
}
else if (frontSkyscraper != 0) {
clueHints.skyscrapers[i] = frontSkyscraper;
clueHints.nopes[i].clear();
}
else { // backSkyscraper != 0
clueHints.skyscrapers[i] = backSkyscraper;
clueHints.nopes[i].clear();
}
if (clueHints.skyscrapers[i] != 0) {
continue;
}
std::unordered_set<int> nopes(optFrontClueHints->nopes[i].begin(),
optFrontClueHints->nopes[i].end());
nopes.insert(optBackClueHints->nopes[i].begin(),
optBackClueHints->nopes[i].end());
clueHints.nopes[i] = std::vector<int>(nopes.begin(), nopes.end());
}
clueHints.removeNopesOnSkyscrapers();
return {clueHints};
}
void mergeClueHintsPerRow(std::vector<std::optional<ClueHints>> &clueHints)
{
std::size_t startOffset = clueHints.size() / 4 * 3 - 1;
std::size_t offset = startOffset;
for (std::size_t frontIdx = 0; frontIdx < clueHints.size() / 2;
++frontIdx, offset -= 2) {
if (frontIdx == clueHints.size() / 4) {
offset = startOffset;
}
int backIdx = frontIdx + offset;
clueHints[frontIdx] = merge(clueHints[frontIdx], clueHints[backIdx]);
}
clueHints.erase(clueHints.begin() + clueHints.size() / 2, clueHints.end());
}
std::vector<std::optional<ClueHints>>
getClueHints(const std::vector<int> &clues, std::size_t boardSize)
{
std::vector<std::optional<ClueHints>> clueHints;
clueHints.reserve(clues.size());
for (const auto &clue : clues) {
clueHints.emplace_back(getClueHints(clue, boardSize));
}
mergeClueHintsPerRow(clueHints);
return clueHints;
}
template <typename It> int missingNumberInSequence(It begin, It end)
{
int n = std::distance(begin, end) + 1;
double projectedSum = (n + 1) * (n / 2.0);
int actualSum = std::accumulate(begin, end, 0);
return projectedSum - actualSum;
}
class Nopes {
public:
Nopes(int size);
void insert(int value);
void insert(const std::vector<int> &values);
bool sizeReached() const;
int missingNumberInSequence() const;
bool contains(int value) const;
bool contains(const std::vector<int> &values);
bool isEmpty() const;
void clear();
std::vector<int> containing() const;
// for debug print
std::unordered_set<int> values() const;
private:
int mSize;
std::unordered_set<int> mValues;
};
Nopes::Nopes(int size) : mSize{size}
{
assert(size > 0);
}
void Nopes::insert(int value)
{
assert(value >= 1 && value <= mSize + 1);
mValues.insert(value);
}
void Nopes::insert(const std::vector<int> &values)
{
mValues.insert(values.begin(), values.end());
}
bool Nopes::sizeReached() const
{
return mValues.size() == static_cast<std::size_t>(mSize);
}
int Nopes::missingNumberInSequence() const
{
assert(sizeReached());
return codewarsbacktracking::missingNumberInSequence(mValues.begin(),
mValues.end());
}
bool Nopes::contains(int value) const
{
auto it = mValues.find(value);
return it != mValues.end();
}
bool Nopes::contains(const std::vector<int> &values)
{
for (const auto &value : values) {
if (!contains(value)) {
return false;
}
}
return true;
}
bool Nopes::isEmpty() const
{
return mValues.empty();
}
void Nopes::clear()
{
mValues.clear();
}
std::vector<int> Nopes::containing() const
{
std::vector<int> nopes;
nopes.reserve(mValues.size());
for (const auto &value : mValues) {
nopes.emplace_back(value);
}
return nopes;
}
std::unordered_set<int> Nopes::values() const
{
return mValues;
}
class Field {
public:
Field(int &skyscraper, Nopes &nopes);
void insertSkyscraper(int skyscraper);
void insertNope(int nope);
void insertNopes(const std::vector<int> &nopes);
bool fullOfNopes() const;
int skyscraper() const;
Nopes nopes() const;
bool hasSkyscraper() const;
std::optional<int> lastMissingNope() const;
private:
int &mSkyscraper;
Nopes &mNopes;
bool mHasSkyscraper = false;
};
Field::Field(int &skyscraper, Nopes &nopes)
: mSkyscraper{skyscraper}, mNopes{nopes}
{
}
void Field::insertSkyscraper(int skyscraper)
{
assert(mSkyscraper == 0 || skyscraper == mSkyscraper);
if (mHasSkyscraper) {
return;
}
mSkyscraper = skyscraper;
mHasSkyscraper = true;
mNopes.clear();
}
void Field::insertNope(int nope)
{
if (mHasSkyscraper) {
return;
}
mNopes.insert(nope);
}
void Field::insertNopes(const std::vector<int> &nopes)
{
if (mHasSkyscraper) {
return;
}
mNopes.insert(nopes);
}
bool Field::fullOfNopes() const
{
return mNopes.sizeReached();
}
int Field::skyscraper() const
{
return mSkyscraper;
}
Nopes Field::nopes() const
{
return mNopes;
}
bool Field::hasSkyscraper() const
{
return mHasSkyscraper;
}
std::optional<int> Field::lastMissingNope() const
{
if (!mNopes.sizeReached()) {
return {};
}
return mNopes.missingNumberInSequence();
}
struct Point {
int x;
int y;
};
inline bool operator==(const Point &lhs, const Point &rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y;
}
inline bool operator!=(const Point &lhs, const Point &rhs)
{
return !(lhs == rhs);
}
enum class ReadDirection { topToBottom, rightToLeft };
void nextDirection(ReadDirection &readDirection);
void advanceToNextPosition(Point &point, ReadDirection readDirection,
int clueIdx);
void nextDirection(ReadDirection &readDirection)
{
assert(readDirection != ReadDirection::rightToLeft);
int dir = static_cast<int>(readDirection);
++dir;
readDirection = static_cast<ReadDirection>(dir);
}
void advanceToNextPosition(Point &point, ReadDirection readDirection,
int clueIdx)
{
if (clueIdx == 0) {
return;
}
switch (readDirection) {
case ReadDirection::topToBottom:
++point.x;
break;
case ReadDirection::rightToLeft:
++point.y;
break;
}
}
class Row {
public:
Row(std::vector<std::vector<Field>> &fields, const Point &startPoint,
const ReadDirection &readDirection);
void insertSkyscraper(int pos, int skyscraper);
std::size_t size() const;
void addCrossingRows(Row *crossingRow);
bool hasOnlyOneNopeField() const;
void addLastMissingSkyscraper();
void addNopesToAllNopeFields(int nope);
bool allFieldsContainSkyscraper() const;
int skyscraperCount() const;
int nopeCount(int nope) const;
void guessSkyscraperOutOfNeighbourNopes();
enum class Direction { front, back };
bool hasSkyscrapers(const std::vector<int> &skyscrapers,
Direction direction) const;
bool hasNopes(const std::vector<std::vector<int>> &nopes,
Direction direction) const;
void addSkyscrapers(const std::vector<int> &skyscrapers,
Direction direction);
void addNopes(const std::vector<std::vector<int>> &nopes,
Direction direction);
std::vector<Field *> getFields() const;
private:
template <typename SkyIterator, typename FieldIterator>
bool hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin,
FieldIterator fieldItEnd) const;
template <typename NopesIterator, typename FieldIterator>
bool hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd) const;
template <typename SkyIterator, typename FieldIterator>
void addSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd);
template <typename NopesIterator, typename FieldIterator>
void addNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd);
template <typename IteratorType>
void insertSkyscraper(IteratorType it, int skyscraper);
template <typename IteratorType> void insertNope(IteratorType it, int nope);
template <typename IteratorType>
void insertNopes(IteratorType it, const std::vector<int> &nopes);
int getIdx(std::vector<Field *>::const_iterator cit) const;
int getIdx(std::vector<Field *>::const_reverse_iterator crit) const;
std::vector<Field *> getRowFields(const ReadDirection &readDirection,
std::vector<std::vector<Field>> &fields,
const Point &startPoint);
bool onlyOneFieldWithoutNope(int nope) const;
std::optional<int> nopeValueInAllButOneField() const;
void insertSkyscraperToFirstFieldWithoutNope(int nope);
bool hasSkyscraper(int skyscraper) const;
std::vector<Row *> mCrossingRows;
std::vector<Field *> mRowFields;
};
Row::Row(std::vector<std::vector<Field>> &fields, const Point &startPoint,
const ReadDirection &readDirection)
: mRowFields{getRowFields(readDirection, fields, startPoint)}
{
}
void Row::insertSkyscraper(int pos, int skyscraper)
{
assert(pos >= 0 && pos < static_cast<int>(mRowFields.size()));
assert(skyscraper > 0 && skyscraper <= static_cast<int>(mRowFields.size()));
auto it = mRowFields.begin() + pos;
insertSkyscraper(it, skyscraper);
}
std::size_t Row::size() const
{
return mRowFields.size();
}
void Row::addCrossingRows(Row *crossingRow)
{
assert(crossingRow != nullptr);
assert(mCrossingRows.size() < size());
mCrossingRows.push_back(crossingRow);
}
bool Row::hasOnlyOneNopeField() const
{
return skyscraperCount() == static_cast<int>(size() - 1);
}
void Row::addLastMissingSkyscraper()
{
assert(hasOnlyOneNopeField());
auto nopeFieldIt = mRowFields.end();
std::vector<int> sequence;
sequence.reserve(size() - 1);
for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) {
if ((*it)->hasSkyscraper()) {
sequence.emplace_back((*it)->skyscraper());
}
else {
nopeFieldIt = it;
}
}
assert(nopeFieldIt != mRowFields.end());
assert(skyscraperCount() == static_cast<int>(sequence.size()));
auto missingValue =
missingNumberInSequence(sequence.begin(), sequence.end());
assert(missingValue >= 0 && missingValue <= static_cast<int>(size()));
insertSkyscraper(nopeFieldIt, missingValue);
}
void Row::addNopesToAllNopeFields(int nope)
{
for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) {
if ((*it)->hasSkyscraper()) {
continue;
}
insertNope(it, nope);
}
}
bool Row::allFieldsContainSkyscraper() const
{
return skyscraperCount() == static_cast<int>(size());
}
int Row::skyscraperCount() const
{
int count = 0;
for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) {
if ((*cit)->hasSkyscraper()) {
++count;
}
}
return count;
}
int Row::nopeCount(int nope) const
{
int count = 0;
for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) {
if ((*cit)->nopes().contains(nope)) {
++count;
}
}
return count;
}
void Row::guessSkyscraperOutOfNeighbourNopes()
{
for (;;) {
auto optNope = nopeValueInAllButOneField();
if (!optNope) {
break;
}
insertSkyscraperToFirstFieldWithoutNope(*optNope);
}
}
bool Row::hasSkyscrapers(const std::vector<int> &skyscrapers,
Row::Direction direction) const
{
if (direction == Direction::front) {
return hasSkyscrapers(skyscrapers.cbegin(), skyscrapers.cend(),
mRowFields.cbegin(), mRowFields.cend());
}
return hasSkyscrapers(skyscrapers.cbegin(), skyscrapers.cend(),
mRowFields.crbegin(), mRowFields.crend());
}
bool Row::hasNopes(const std::vector<std::vector<int>> &nopes,
Direction direction) const
{
if (direction == Direction::front) {
return hasNopes(nopes.cbegin(), nopes.cend(), mRowFields.cbegin(),
mRowFields.cend());
}
return hasNopes(nopes.cbegin(), nopes.cend(), mRowFields.crbegin(),
mRowFields.crend());
}
void Row::addSkyscrapers(const std::vector<int> &skyscrapers,
Direction direction)
{
if (direction == Direction::front) {
addSkyscrapers(skyscrapers.begin(), skyscrapers.end(),
mRowFields.begin(), mRowFields.end());
}
else {
addSkyscrapers(skyscrapers.begin(), skyscrapers.end(),
mRowFields.rbegin(), mRowFields.rend());
}
}
void Row::addNopes(const std::vector<std::vector<int>> &nopes,
Direction direction)
{
if (direction == Direction::front) {
addNopes(nopes.begin(), nopes.end(), mRowFields.begin(),
mRowFields.end());
}
else {
addNopes(nopes.begin(), nopes.end(), mRowFields.rbegin(),
mRowFields.rend());
}
}
std::vector<Field *> Row::getFields() const
{
return mRowFields;
}
template <typename SkyIterator, typename FieldIterator>
bool Row::hasSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin,
FieldIterator fieldItEnd) const
{
auto skyIt = skyItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && skyIt != skyItEnd; ++fieldIt, ++skyIt) {
if (*skyIt == 0 && (*fieldIt)->hasSkyscraper()) {
continue;
}
if ((*fieldIt)->skyscraper() != *skyIt) {
return false;
}
}
return true;
}
template <typename NopesIterator, typename FieldIterator>
bool Row::hasNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd) const
{
auto nopesIt = nopesItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && nopesIt != nopesItEnd; ++fieldIt, ++nopesIt) {
if (nopesIt->empty()) {
continue;
}
if ((*fieldIt)->hasSkyscraper()) {
return false;
}
if (!(*fieldIt)->nopes().contains(*nopesIt)) {
return false;
}
}
return true;
}
template <typename SkyIterator, typename FieldIterator>
void Row::addSkyscrapers(SkyIterator skyItBegin, SkyIterator skyItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd)
{
auto skyIt = skyItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && skyIt != skyItEnd; ++fieldIt, ++skyIt) {
if (*skyIt == 0) {
continue;
}
insertSkyscraper(fieldIt, *skyIt);
}
}
template <typename NopesIterator, typename FieldIterator>
void Row::addNopes(NopesIterator nopesItBegin, NopesIterator nopesItEnd,
FieldIterator fieldItBegin, FieldIterator fieldItEnd)
{
auto nopesIt = nopesItBegin;
for (auto fieldIt = fieldItBegin;
fieldIt != fieldItEnd && nopesIt != nopesItEnd; ++fieldIt, ++nopesIt) {
if (nopesIt->empty()) {
continue;
}
insertNopes(fieldIt, *nopesIt);
}
}
template <typename FieldIterator>
void Row::insertSkyscraper(FieldIterator fieldIt, int skyscraper)
{
assert(mCrossingRows.size() == size());
if ((*fieldIt)->hasSkyscraper()) {
return;
}
(*fieldIt)->insertSkyscraper(skyscraper);
if (hasOnlyOneNopeField()) {
addLastMissingSkyscraper();
}
addNopesToAllNopeFields(skyscraper);
int idx = getIdx(fieldIt);
if (mCrossingRows[idx]->hasOnlyOneNopeField()) {
mCrossingRows[idx]->addLastMissingSkyscraper();
}
mCrossingRows[idx]->addNopesToAllNopeFields(skyscraper);
}
template <typename FieldIterator>
void Row::insertNope(FieldIterator fieldIt, int nope)
{
if ((*fieldIt)->hasSkyscraper()) {
return;
}
if ((*fieldIt)->nopes().contains(nope)) {
return;
}
(*fieldIt)->insertNope(nope);
auto optlastMissingNope = (*fieldIt)->lastMissingNope();
if (optlastMissingNope) {
insertSkyscraper(fieldIt, *optlastMissingNope);
}
if (onlyOneFieldWithoutNope(nope)) {
insertSkyscraperToFirstFieldWithoutNope(nope);
}
int idx = getIdx(fieldIt);
if (mCrossingRows[idx]->onlyOneFieldWithoutNope(nope)) {
mCrossingRows[idx]->insertSkyscraperToFirstFieldWithoutNope(nope);
}
}
template <typename IteratorType>
void Row::insertNopes(IteratorType it, const std::vector<int> &nopes)
{
for (const auto &nope : nopes) {
insertNope(it, nope);
}
}
int Row::getIdx(std::vector<Field *>::const_iterator cit) const
{
return std::distance(mRowFields.cbegin(), cit);
}
int Row::getIdx(std::vector<Field *>::const_reverse_iterator crit) const
{
return size() - std::distance(mRowFields.crbegin(), crit) - 1;
}
std::vector<Field *>
Row::getRowFields(const ReadDirection &readDirection,
std::vector<std::vector<Field>> &boardFields,
const Point &startPoint)
{
std::vector<Field *> fields;
fields.reserve(boardFields.size());
std::size_t x = startPoint.x;
std::size_t y = startPoint.y;
for (std::size_t i = 0; i < boardFields.size(); ++i) {
fields.emplace_back(&boardFields[y][x]);
if (readDirection == ReadDirection::topToBottom) {
++y;
}
else {
--x;
}
}
return fields;
}
bool Row::onlyOneFieldWithoutNope(int nope) const
{
auto cit = std::find_if(
mRowFields.cbegin(), mRowFields.cend(),
[nope](const auto &field) { return field->skyscraper() == nope; });
if (cit != mRowFields.cend()) {
return false;
}
if (nopeCount(nope) < static_cast<int>(size()) - skyscraperCount() - 1) {
return false;
}
return true;
}
std::optional<int> Row::nopeValueInAllButOneField() const
{
std::unordered_map<int, int> nopeAndCount;
for (auto cit = mRowFields.cbegin(); cit != mRowFields.cend(); ++cit) {
if (!(*cit)->hasSkyscraper()) {
auto nopes = (*cit)->nopes().containing();
for (const auto &nope : nopes) {
if (hasSkyscraper(nope)) {
continue;
}
++nopeAndCount[nope];
}
}
}
for (auto cit = nopeAndCount.cbegin(); cit != nopeAndCount.end(); ++cit) {
if (cit->second == static_cast<int>(size()) - skyscraperCount() - 1) {
return {cit->first};
}
}
return {};
}
void Row::insertSkyscraperToFirstFieldWithoutNope(int nope)
{
for (auto it = mRowFields.begin(); it != mRowFields.end(); ++it) {
if ((*it)->hasSkyscraper()) {
continue;
}
if (!(*it)->nopes().contains(nope)) {
insertSkyscraper(it, nope);
return; // there can be max one skyscraper per row;
}
}
}
bool Row::hasSkyscraper(int skyscraper) const
{
for (const auto &field : mRowFields) {
if (field->skyscraper() == skyscraper) {
return true;
}
}
return false;
}
class BorderIterator {
public:
BorderIterator(std::size_t boardSize);
Point point() const;
ReadDirection readDirection() const;
BorderIterator &operator++();
private:
int mIdx = 0;
std::size_t mBoardSize;
Point mPoint{0, 0};
ReadDirection mReadDirection{ReadDirection::topToBottom};
};
BorderIterator::BorderIterator(std::size_t boardSize) : mBoardSize{boardSize}
{
}
Point BorderIterator::point() const
{
return mPoint;
}
ReadDirection BorderIterator::readDirection() const
{
return mReadDirection;
}
BorderIterator &BorderIterator::operator++()
{
++mIdx;
if (mIdx == static_cast<int>(2 * mBoardSize)) {
return *this;
}
if (mIdx != 0 && mIdx % mBoardSize == 0) {
nextDirection(mReadDirection);
}
advanceToNextPosition(mPoint, mReadDirection, mIdx % mBoardSize);
return *this;
}
struct Board {
Board(std::size_t size);
void insert(const std::vector<std::optional<ClueHints>> &clueHints);
void insert(const std::vector<std::vector<int>> &startingSkyscrapers);
bool isSolved() const;
std::vector<std::vector<int>> skyscrapers{};
std::vector<std::vector<Nopes>> nopes;
std::vector<Row> mRows;
private:
std::vector<std::vector<int>> makeSkyscrapers(std::size_t size);
std::vector<std::vector<Nopes>> makeNopes(std::size_t size);
void makeFields();
void makeRows();
void connnectRowsWithCrossingRows();
std::vector<std::vector<Field>> mFields;
};
Board::Board(std::size_t size)
: skyscrapers{makeSkyscrapers(size)}, nopes{makeNopes(size)},
mFields{std::vector<std::vector<Field>>(skyscrapers.size())}
{
makeFields();
makeRows();
}
void Board::insert(const std::vector<std::optional<ClueHints>> &clueHints)
{
assert(clueHints.size() == mRows.size());
for (std::size_t i = 0; i < clueHints.size(); ++i) {
if (!clueHints[i]) {
continue;
}
mRows[i].addNopes(clueHints[i]->nopes, Row::Direction::front);
mRows[i].addSkyscrapers(clueHints[i]->skyscrapers,
Row::Direction::front);
}
}
void Board::insert(const std::vector<std::vector<int>> &startingSkyscrapers)
{
if (startingSkyscrapers.empty()) {
return;
}
std::size_t boardSize = mRows.size() / 2;
assert(startingSkyscrapers.size() == boardSize);
for (std::size_t i = 0; i < startingSkyscrapers.size(); ++i) {
mRows[i + boardSize].addSkyscrapers(startingSkyscrapers[i],
Row::Direction::back);
}
}
bool Board::isSolved() const
{
std::size_t endVerticalRows = mRows.size() / 2;
for (std::size_t i = 0; i < endVerticalRows; ++i) {
if (!mRows[i].allFieldsContainSkyscraper()) {
return false;
}
}
return true;
}
std::vector<std::vector<int>> Board::makeSkyscrapers(std::size_t size)
{
std::vector<int> skyscraperRow(size, 0);
return std::vector<std::vector<int>>(size, skyscraperRow);
}
std::vector<std::vector<Nopes>> Board::makeNopes(std::size_t size)
{
std::vector<Nopes> nopesRow(size, Nopes{static_cast<int>(size) - 1});
return std::vector<std::vector<Nopes>>(size, nopesRow);
}
void Board::makeFields()
{
mFields.reserve(skyscrapers.size());
for (auto &row : mFields) {
row.reserve(mFields.size());
}
for (std::size_t y = 0; y < skyscrapers.size(); ++y) {
mFields[y].reserve(skyscrapers.size());
for (std::size_t x = 0; x < skyscrapers[y].size(); ++x) {
mFields[y].emplace_back(Field{skyscrapers[y][x], nopes[y][x]});
}
}
}
void Board::makeRows()
{
BorderIterator borderIterator{mFields.size()};
std::size_t size = mFields.size() * 2;
mRows.reserve(size);
for (std::size_t i = 0; i < size; ++i, ++borderIterator) {
mRows.emplace_back(Row{mFields, borderIterator.point(),
borderIterator.readDirection()});
}
connnectRowsWithCrossingRows();
}
void Board::connnectRowsWithCrossingRows()
{
std::size_t boardSize = mRows.size() / 2;
std::vector<int> targetRowsIdx(boardSize);
std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), boardSize);
for (std::size_t i = 0; i < mRows.size(); ++i) {
if (i == mRows.size() / 2) {
std::iota(targetRowsIdx.begin(), targetRowsIdx.end(), 0);
std::reverse(targetRowsIdx.begin(), targetRowsIdx.end());
}
for (const auto &targetRowIdx : targetRowsIdx) {
mRows[i].addCrossingRows(&mRows[targetRowIdx]);
}
}
}
void debug_print(Board &board, const std::string &title)
{
std::cout << title << '\n';
for (std::size_t y = 0; y < board.skyscrapers.size(); ++y) {
for (std::size_t x = 0; x < board.skyscrapers[y].size(); ++x) {
if (board.skyscrapers[y][x] != 0) {
std::cout << std::setw(board.skyscrapers.size() * 2);
std::cout << "V" + std::to_string(board.skyscrapers[y][x]);
}
else if (board.skyscrapers[y][x] == 0 &&
!board.nopes[y][x].isEmpty()) {
auto nopes_set = board.nopes[y][x].values();
std::vector<int> nopes(nopes_set.begin(), nopes_set.end());
std::sort(nopes.begin(), nopes.end());
std::string nopesStr;
for (std::size_t i = 0; i < nopes.size(); ++i) {
nopesStr.append(std::to_string(nopes[i]));
if (i != nopes.size() - 1) {
nopesStr.push_back(',');
}
}
std::cout << std::setw(board.skyscrapers.size() * 2);
std::cout << nopesStr;
}
else {
std::cout << ' ';
}
}
std::cout << '\n';
}
std::cout << '\n';
}
template <typename Iterator> int visibleBuildings(Iterator begin, Iterator end)
{
int visibleBuildingsCount = 0;
int highestSeen = 0;
for (auto it = begin; it != end; ++it) {
if (*it != 0 && *it > highestSeen) {
++visibleBuildingsCount;
highestSeen = *it;
}
}
return visibleBuildingsCount;
}
bool rowsAreValid(const std::vector<std::vector<int>> &skyscrapers,
std::size_t x, std::size_t y, std::size_t size)
{
for (std::size_t xi = 0; xi < size; xi++) {
if (xi != x && skyscrapers[y][xi] == skyscrapers[y][x]) {
return false;
}
}
return true;
}
bool columnsAreValid(const std::vector<std::vector<int>> &skyscrapers,
std::size_t x, std::size_t y, std::size_t size)
{
for (std::size_t yi = 0; yi < size; yi++) {
if (yi != y && skyscrapers[yi][x] == skyscrapers[y][x]) {
return false;
}
}
return true;
}
std::tuple<int, int> getRowClues(const std::vector<int> &clues, std::size_t y,
std::size_t size)
{
int frontClue = clues[clues.size() - 1 - y];
int backClue = clues[size + y];
return {frontClue, backClue};
}
bool rowCluesAreValid(const std::vector<std::vector<int>> &skyscrapers,
const std::vector<int> &clues, std::size_t y,
std::size_t size)
{
auto [frontClue, backClue] = getRowClues(clues, y, size);
if (frontClue == 0 && backClue == 0) {
return true;
}
bool rowIsFull = std::find(skyscrapers[y].cbegin(), skyscrapers[y].cend(),
0) == skyscrapers[y].cend();
if (!rowIsFull) {
return true;
}
if (frontClue != 0) {
auto frontVisible =
visibleBuildings(skyscrapers[y].cbegin(), skyscrapers[y].cend());
if (frontClue != frontVisible) {
return false;
}
}
if (backClue != 0) {
auto backVisible =
visibleBuildings(skyscrapers[y].crbegin(), skyscrapers[y].crend());
if (backClue != backVisible) {
return false;
}
}
return true;
}
std::tuple<int, int> getColumnClues(const std::vector<int> &clues,
std::size_t x, std::size_t size)
{
int frontClue = clues[x];
int backClue = clues[size * 3 - 1 - x];
return {frontClue, backClue};
}
bool columnCluesAreValid(const std::vector<std::vector<int>> &skyscrapers,
const std::vector<int> &clues, std::size_t x,
std::size_t size)
{
auto [frontClue, backClue] = getColumnClues(clues, x, size);
if (frontClue == 0 && backClue == 0) {
return true;
}
std::vector<int> verticalSkyscrapers;
verticalSkyscrapers.reserve(size);
for (std::size_t yi = 0; yi < size; ++yi) {
verticalSkyscrapers.emplace_back(skyscrapers[yi][x]);
}
bool columnIsFull =
std::find(verticalSkyscrapers.cbegin(), verticalSkyscrapers.cend(),
0) == verticalSkyscrapers.cend();
if (!columnIsFull) {
return true;
}
if (frontClue != 0) {
auto frontVisible = visibleBuildings(verticalSkyscrapers.cbegin(),
verticalSkyscrapers.cend());
if (frontClue != frontVisible) {
return false;
}
}
if (backClue != 0) {
auto backVisible = visibleBuildings(verticalSkyscrapers.crbegin(),
verticalSkyscrapers.crend());
if (backClue != backVisible) {
return false;
}
}
return true;
}
bool skyscrapersAreValidPositioned(
const std::vector<std::vector<int>> &skyscrapers,
const std::vector<int> &clues, std::size_t x, std::size_t y,
std::size_t size)
{
if (!rowsAreValid(skyscrapers, x, y, size)) {
return false;
}
if (!columnsAreValid(skyscrapers, x, y, size)) {
return false;
}
if (!rowCluesAreValid(skyscrapers, clues, y, size)) {
return false;
}
if (!columnCluesAreValid(skyscrapers, clues, x, size)) {
return false;
}
return true;
}
bool guessSkyscrapers(Board &board, const std::vector<int> &clues,
std::size_t x, std::size_t y, std::size_t size)
{
if (x == size) {
x = 0;
y++;
};
if (y == size) {
return true;
}
if (board.skyscrapers[y][x] != 0) {
if (!skyscrapersAreValidPositioned(board.skyscrapers, clues, x, y,
size)) {
return false;
}
if (guessSkyscrapers(board, clues, x + 1, y, size)) {
return true;
}
else {
return false;
}
}
for (int trySkyscraper = 1;
trySkyscraper <= static_cast<int>(board.skyscrapers.size());
++trySkyscraper) {
if (board.nopes[y][x].contains(trySkyscraper)) {
continue;
}
board.skyscrapers[y][x] = trySkyscraper;
if (!skyscrapersAreValidPositioned(board.skyscrapers, clues, x, y,
size)) {
continue;
}
if (guessSkyscrapers(board, clues, x + 1, y, size)) {
return true;
}
}
board.skyscrapers[y][x] = 0;
return false;
}
std::vector<std::vector<int>>
SolvePuzzle(const std::vector<int> &clues,
std::vector<std::vector<int>> startingGrid, int)
{
assert(clues.size() % 4 == 0);
std::size_t boardSize = clues.size() / 4;
auto clueHints = getClueHints(clues, boardSize);
Board board{boardSize};
board.insert(clueHints);
board.insert(startingGrid);
if (board.isSolved()) {
return board.skyscrapers;
}
guessSkyscrapers(board, clues, 0, 0, board.skyscrapers.size());
return board.skyscrapers;
}
std::vector<std::vector<int>> SolvePuzzle(const std::vector<int> &clues)
{
return SolvePuzzle(clues, std::vector<std::vector<int>>{}, 0);
}
} // namespace codewarsbacktracking
</code></pre>
|
[] |
[
{
"body": "<h1>Use more efficient containers</h1>\n<p>There are several areas where your code can be improved by changing the containers you are using to hold the data:</p>\n<h2>Don't use nested <code>std::vector</code>s for 2D arrays</h2>\n<p>Instead of <code>std::vector<std::vector<Something>></code>, use a <code>std::vector<Something></code>. Make sure the size is big enough to hold the same number of elements of course. To look up the element at coordinates <code>x, y</code> of an <code>N * N</code> vector, use <code>[x + y * N]</code> as the array index.</p>\n<h2>Store positions in a single <code>std::size_t</code></h2>\n<p>Instead of passing <code>x</code> and <code>y</code> coordinates separately, consider passing an index into the flattened vector as described above. This saves a variable, and sometimes some calculations as well. For example:</p>\n<pre><code>if (x == size) {\n x = 0;\n y++;\n}\nif (y == size) {\n return true;\n}\n</code></pre>\n<p>Can be replaced with:</p>\n<pre><code>if (index == size) {\n return true;\n}\n</code></pre>\n<p>Assuming <code>size</code> is now the total number of elements in the grid.</p>\n<h2>Store information efficiently in bitmasks</h2>\n<p>Instead of using a <code>std::unordered_set<int></code> to remember a set of positions, use a <a href=\"https://en.wikipedia.org/wiki/Mask_(computing)\" rel=\"nofollow noreferrer\">bitmask</a>. You can use an <code>std::uint64_t</code> for this, and be able to handle sizes of up to 64, which I think will be more than you will ever need (maybe an <code>std::uint32_t</code> would also suffice).</p>\n<h1>Only store essential data in classes</h1>\n<p>Avoid storing redundant data in classes. For example, a <code>Field</code> has a reference to the skyscraper height, the <code>Nopes</code>, and a boolean to indicate whether there is a skyscraper already at that field. But, you only need a single bitmask as mentioned above to replace <code>Nopes</code>. If only a single bit is left set in the bitmask, you know that that indicates the actual height of the skyscraper. Operations on bitmasks are very fast, and by reducing the amount of data stored per field you reduce memory bandwidth and have a bigger chance that things fit into the CPU's cache.</p>\n<p>Note that with C++20 comes the <a href=\"https://en.cppreference.com/w/cpp/header/bit\" rel=\"nofollow noreferrer\"><code><bit></code> header</a>, which has some helpful functions when dealing with bitmasks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T06:40:50.030",
"Id": "507988",
"Score": "0",
"body": "So if I understand it correctly you would use only a bitmask to store nopes and skyscrapers. Like in the beginning set all bits e.g b1111 for n=4 and when there is a nope mask it out like b0111."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T06:54:31.933",
"Id": "507989",
"Score": "0",
"body": "Exactly. You could also invert the bits, so that a `1` is a nope, and then you can just initialize everything with zeroes, but I don't think it will matter much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:03:41.620",
"Id": "508074",
"Score": "0",
"body": "If you do `if (++index == size)` don't you then skip the first element on start of the backtracking?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:29:18.067",
"Id": "508093",
"Score": "0",
"body": "Yes, you are right, the `++` should not be used here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T16:38:51.687",
"Id": "508230",
"Score": "0",
"body": "I added the first optimization to the code. flatten the 2d array into a single vector but surprisingly it runs slower than before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T15:46:08.917",
"Id": "508438",
"Score": "0",
"body": "I made all the optimizations including the bitfield optimization but it good even worse. I wonder if I just implemented the bid fiddling with the bitfield wrong. I guess See here: https://github.com/SandroWissmann/Skyscrapers/tree/bitfield"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T18:22:32.993",
"Id": "508451",
"Score": "0",
"body": "It looks like you still have lots of loops over things that should not be necessary anymore with bitmasks. But if you want a proper review of the bitfield version, just go ahead and make a new question here on Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T21:34:01.390",
"Id": "508462",
"Score": "0",
"body": "yes I will get into the code again to clean it up and post it soon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T18:52:35.850",
"Id": "508529",
"Score": "0",
"body": "Ok like promised I posted the changed code here: https://codereview.stackexchange.com/questions/257451/skyscraper-solver-for-nxn-size-version-3"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T22:00:38.460",
"Id": "257203",
"ParentId": "257197",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T18:04:18.503",
"Id": "257197",
"Score": "1",
"Tags": [
"c++",
"performance",
"c++17"
],
"Title": "Skyscraper Solver for NxN Size Version 2 (Using Backtracking)"
}
|
257197
|
<p>I converted an old Wordpress Plugin of mine from jQuery to plain JavaScript using a cheat sheet. I was very surprised that it seems to work right out of the box on my first try.</p>
<pre><code>(function ($) {
$(document).ready(function ($) {
$('.comment-list > li .comment-reply').each(function () {
var reply = this;
/* collect every comment which needs a reply link */
var allchildren = $(reply).parent().children('.children').children().find(".comment-content");
$.each(allchildren, function (index, value) {
$(reply).clone().appendTo(value);
});
});
});
})(jQuery);
</code></pre>
<p>Became this:</p>
<pre><code>const replybtns = document.querySelectorAll(".comment-list > li .comment-reply");
for (let i = 0; i < replybtns.length; i++) {
let replybtn = replybtns[i];
let replybtncp = replybtn.cloneNode(true);
let cc = replybtn.parentElement.querySelectorAll('.children div.comment-content');
let lastcc = cc[Object.keys(cc)[Object.keys(cc).length - 1]];
lastcc.appendChild(replybtncp);
}
</code></pre>
<p>This copies all reply links of all level 1 nested comments and appends them to the last comment.</p>
<p>Is this code okay? Is it really that simple? I tested it with Firefox and Chrome, and it seems to work. I know that it appends the reply link only to the last element. I did that on purpose to make it simpler.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T23:32:54.840",
"Id": "507975",
"Score": "0",
"body": "Welcome to Code Review! Your post looks good, hope you get some good answers!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T20:31:46.693",
"Id": "257199",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"wordpress"
],
"Title": "Copy the reply button to each comment thread in WordPress. Converted from jQuery to JavaScript"
}
|
257199
|
<p>I have a requirement to fetch data for different types of Users (Customers, Publishers etc) for three different timelines (retro, current, and past), all have different URLs. There is a scheduler which will run at the different interval (for example 2 minute for retro data, 5 minutes for current data and 10 minutes for Future Dated Data). I have attached an image for better understanding.</p>
<p><a href="https://i.stack.imgur.com/AMlvm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AMlvm.png" alt="enter image description here" /></a></p>
<pre><code> interface IDataPublisher {
void GetUrl();
void Publish();
}
interface ITimeLineGrabber {
TimeSpan GetTimeSpanForNextRun();
}
abstract class BasePublisher : IDataPublisher, ITimeLineGrabber, BackgroundService
{
private readonly ILogger<BasePublisher> _logger;
public BasePublisher (ILogger<BasePublisher> logger)
{
_logger = logger;
}
public abstract string GetUserType();
public abstract string GetDataType();
public abstract TimeSpan GetTimeSpanForNextRun();
public abstract string GetUrl();
public override async Task StartAsync(CancellationToken cancellationToken)
{
await base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var userType = GetUserType();
var dataType = GetDataType();
TimeSpan timeSpan = GetTimeSpanForNextRun();
while (!stoppingToken.IsCancellationRequested)
{
try
{
// Do Something with userType and dataType
await Task.Delay(timeSpan , stoppingToken);
}
catch (Exception ex)
{
_logger.LogError($"Error - {ex.Message}", DateTimeOffset.Now);
}
}
}
public sealed class CustomerRetroPublisher: BasePublisher
{
public override string GetUserType()
{
return "Customer";
}
public override string GetDataType()
{
return "Retro";
}
public override Timespan GetTimeSpanForNextRun()
{
return Timespan.FromMinutes(2); // read from config file..
}
public override string GetUrl()
{
return "CustomerRetroUrl";
}
}
</code></pre>
<p>but this will end up with 12 different classes and loads of code will be duplicated/ over complicated. I have a feeling there must be a simple approach to all this. Just wondering what could be the best approach for my requirement.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T23:30:10.047",
"Id": "507973",
"Score": "0",
"body": "Welcome to Code Review! Looks like you already got some answers, great, hope you enjoy your stay!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:00:33.203",
"Id": "508029",
"Score": "0",
"body": "Your interface `IDataPublisher` defines a method `Publish()`, but I cannot see this method in your implementation of the interface. Is there something missing?"
}
] |
[
{
"body": "<p>It seems not a good idea to hard code the different constants. I would inject them through the constructor (I am using properties instead of <code>Get</code>-methods):</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public sealed class Publisher : interfaces\n{\n public void Publisher (string userType, string dataType, Timespan interval, string url)\n {\n UserType = userType;\n DataType = dataType;\n Interval = interval;\n Url = url;\n }\n\n public string UserType { get; }\n public override string DataType { get; }\n public override Timespan Interval { get; }\n public override string Url { get; }\n}\n</code></pre>\n<p>Then create a factory</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static class PublisherFactory\n{\n public static Publisher CreateCustomerRetroPublisher()\n {\n return new Publisher("Customer", "Retro", Timespan.FromMinutes(2), "CustRetroUrl");\n }\n\n ...\n}\n</code></pre>\n<p>If you need different behaviors for different publishers, you can inject them this way as well. For instance, inject services for timeline-specific behavior (through a <code>ITimelineService</code>) and user type-specific behavior (through a <code>IUserService</code>). Like this you can combine the different behavior types in different ways. 3 timeline services + 4 user services = 7 services is better than 12 different classes.</p>\n<p>The constructor would then have additional parameters</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public void Publisher (string userType, string dataType, Timespan interval, string url,\n ITimelineService timeLineService, IUserService userService)\n</code></pre>\n<p>The services can be assigned to private fields, as they do not need to be visible publicly.</p>\n<p>See also: <a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow noreferrer\">Composition over inheritance (Wikipedia)</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T22:18:24.940",
"Id": "507970",
"Score": "2",
"body": "This is better than [the approach I suggested](https://codereview.stackexchange.com/a/257204/169088) if the OP doesn't need these types to be modeled as actual C# objects, and only requires string identifiers for use by the scheduling system. It's also better if this type is going to be e.g. serialized for an event bus, or something similar, since it offers a lightweight object focused exclusively on capturing the data necessary to handle the message."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T21:59:11.127",
"Id": "257202",
"ParentId": "257200",
"Score": "5"
}
},
{
"body": "<p>This looks like a good opportunity for a generic interface. E.g.,</p>\n<pre class=\"lang-cs prettyprint-override\"><code>interface IDataTimeType<T> where T : IDataType \n{\n T RootData { get; }\n}\n</code></pre>\n<p>Then, your time types can be implemented with generics:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>class Retro<T> : IDataTimeType<T>\n{\n Retro(T rootData) \n {\n RootData = rootData;\n }\n T RootData { get; }\n}\n</code></pre>\n<p>And instantiated like e.g.,</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var data = new Data1();\nvar dataTime = new Retro<Data1>(data);\n</code></pre>\n<p>The interfaces should focus on what interaction points you need to maintain with the objects, not what types each object is; you can use <code>Object.GetType()</code> for that:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var dataTimeType = dataTime.GetType().Name;\nvar dataType = dataTime.RootData.GetType().Name;\n</code></pre>\n<blockquote>\n<p><strong><em>Note:</em></strong> I’d recommend against such general identifiers as <code>Type1</code> and <code>IDataType</code>, but I’m maintaining them for consistency with your question. Regardless, I assume those are just meant to illustrate the concept while abstracting the question from the specifics of your data model.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T23:31:16.317",
"Id": "507974",
"Score": "3",
"body": "Welcome to Code Review! Your post looks good, enjoy your stay!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T22:09:14.897",
"Id": "257204",
"ParentId": "257200",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T21:22:20.200",
"Id": "257200",
"Score": "5",
"Tags": [
"c#",
"inheritance",
"interface"
],
"Title": "Best approach for the Design Pattern for multiple schedulers using interface and abstract class"
}
|
257200
|
<p>I created a tic-tac-toe using java and I would like to know if there are any practices that I can improve and make the code cleaner and more performative</p>
<pre><code>import java.util.Scanner;
public class Main {
public static boolean test(String[] values){
//Check diagonals
if((values[0].equals("X") && values[4].equals("X") && values[8].equals("X")) || (values[0].equals("0") && values[4].equals("0") && values[8].equals("0"))){
System.out.print(values[0] + " win");
return true;
}
if((values[2].equals("X") && values[4].equals("X") && values[6].equals("X")) || (values[2].equals("0") && values[4].equals("0") && values[6].equals("0"))){
System.out.print(values[2] + " win");
return true;
}
//Check verticals
for(int x = 0;x < 9;x+=3){
if((values[0+x].equals("X") && values[1+x].equals("X") && values[2+x].equals("X")) || (values[0+x].equals("0") && values[1+x].equals("0") && values[2+x].equals("0"))){
System.out.print(values[0+x] + " win");
return true;
}
}
//Checks horizontal
for(int x = 0;x < 3;x++){
if((values[0+x].equals("X") && values[3+x].equals("X") && values[6+x].equals("X")) || (values[0+x].equals("0") && values[3+x].equals("0") && values[6+x].equals("0"))){
System.out.print(values[0+x] + " win");
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
String[] game = {" ", " ", " ", " ", " ", " ", " ", " ", " "};
String[] players = {"X", "0"};
for(int x = 0;x < 9;x++){
System.out.print(players[x%2] + ": ");
int currentPlay = read.nextInt();
while(currentPlay < 1 || currentPlay > 9 || game[currentPlay -1] != " "){
System.out.print("Invalid, play again: ");
currentPlay = read.nextInt();
}
if(x % 2 == 0){
game[currentPlay -1] = "X";
}
else{
game[currentPlay -1] = "0";
}
System.out.printf("%s | %s | %s\n%s | %s | %s\n%s | %s | %s\n", game[0], game[1], game[2], game[3], game[4], game[5], game[6], game[7], game[8]);
if(test(game)){
break;
}
if(!test(game) && x == 8){
System.out.print("Tie");
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I hate this sort of hard-coded testing - there is usually a better approach to represent our data.</p>\n<p>A few thoughts come to mind.</p>\n<ol>\n<li>You don't stop players playing into an already occupied cell.</li>\n<li>Why not use a 2-d array (actually an array of arrays)? Then you can more naturally scan rows, columns, and even diagonals.</li>\n<li>If you score X as 1 and O as -1, then a winning row, column or diagonal adds up to 3 (X wins) or -3 (O wins).</li>\n<li>If you initialise the cells to an appropriate value, I think you can also detect a hung game early - for example if you initialise to 4, then any row, column or diagonal with a sum < 4 but not 3 or -3 is unwinnable. If they're all unwinnable, there's no point making further plays. (I need to think this through a bit more!)</li>\n<li>I thought it through more carefully. If X is 1, O is -1 and an empty cell is 4 (for example), then a line summing to 3 is a win for X; summing to -3 is a win for O; 4 is an unwinnable line as it must have an X, an O and a blank cell; other values are undecided lines. If there are 8 unwinnable lines, then the match is a draw.]</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T11:32:09.070",
"Id": "257231",
"ParentId": "257207",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>..are any practices that I can improve and make the code cleaner..</p>\n</blockquote>\n<p>There are!</p>\n<h2>Don't over-enigeer</h2>\n<p>While you can create all fancy strategies to check tic-tac-too rules; I think it is best to keep it as simple as possible. So checking rows, columns and diagonals hard-coded is, imho, not too bad here.</p>\n<h2>Don't use <code>String</code> for state</h2>\n<p>You should never use a <code>String</code> to encode state. Better to use an <code>enum</code></p>\n<p>For example:</p>\n<p><code>enum State { X, O, EMPTY }</code></p>\n<pre><code>State[] board \n</code></pre>\n<p>Then you can use <code>==</code> instead of the verbose <code>equals()</code>, increasing readability.</p>\n<pre><code> if (board[3] == State.X)\n</code></pre>\n<h2>Consider using a 2D array</h2>\n<p>You could encode the board as a 2d array, for readability as well. This won't improve your big if-statement.</p>\n<h2>Consider extracting the 'player'</h2>\n<pre><code> public static boolean test(State[] board, State p){\n //Check diagonals\n if((board[0] == p && board[4] == p && board[8] == p) || {\n System.out.print(p + " win");\n return true;\n }\n...\n\n test(board, State.X);\n test(board, State.O);\n</code></pre>\n<h2>Split code to methods with one-single-responsibility</h2>\n<p><code>test</code> is responsible for checking the entire board. You should not <code>print</code> there; the printing is another responsibility.</p>\n<p>So the <code>test</code> should get rid of all the <code>System.out</code>'s</p>\n<pre><code> public static boolean test(State[] board, State p){\n //Check diagonals\n if((board[0] == p && board[4] == p && board[8] == p) || {\n return true;\n }\n</code></pre>\n<p>You could do this, elsewhere:</p>\n<pre><code> if (test(board, State.X)) {\n System.out.println(State.X + " won!");\n }\n</code></pre>\n<h2>Don't do too much</h2>\n<p>A player that didn't move, cannot win. So you should only have to check one player each time, instead of both players. You keep track of the current player, so you should only check that player after it made it's move.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:01:48.973",
"Id": "257233",
"ParentId": "257207",
"Score": "1"
}
},
{
"body": "<p>Thanks for sharing your code.</p>\n<p>Your code is a <em>procedural</em> approach to the problem.</p>\n<p>There is nothing wrong with procedural approaches in general, but Java is an object oriented (OO) programming language and if you want to become a good Java programmer then you should start solving problems in an OO way.</p>\n<p>But OOP doesn't mean to "split up" code into random classes.</p>\n<p>The ultimate goal of OOP is to reduce code duplication, improve readability and support reuse as well as extending the code.</p>\n<p>Doing OOP means that you follow certain principles which are (among others):</p>\n<ul>\n<li>information hiding / encapsulation</li>\n<li>single responsibility</li>\n<li>separation of concerns</li>\n<li>KISS (Keep it simple (and) stupid.)</li>\n<li>DRY (Don't repeat yourself.)</li>\n<li>"Tell! Don't ask."</li>\n<li>Law of demeter ("Don't talk to strangers!")</li>\n</ul>\n<p>The most obvious problem in your code is the code duplication. You have lots of "sections" that do the same.\nIn a first step you could extract the duplicated code into <em>parameterized methods</em> sticking to the procedural approach like this:</p>\n<pre><code> public class Main {\n private static boolean isOwningThreeInLine(\n String player\n , String[] board\n , int[] positions){\n boolean isOwningLine = true;\n for(int position : positions)\n isOwningLine = isOwningLine && \n player.equals(board[position]);\n return isOwningLine;\n }\n public static boolean test(String[] values){\n //Check diagonals\n if(isOwningThreeInLine("X",values, {0,4,8})\n || (isOwningThreeInLine("0",values, {0,4,8})){\n System.out.print(values[0] + " win");\n return true;\n }\n if(isOwningThreeInLine("X",values, {2,4,6})\n || (isOwningThreeInLine("0",values, {2,4,6})){\n System.out.print(values[2] + " win");\n return true;\n }\n</code></pre>\n<p>This shows, that the converted code still is duplicated with only the definition of the <em>line</em> changing. So we could collect the <em>line definitions</em> in a <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Collection.html\" rel=\"nofollow noreferrer\">collection</a> and loop over them like this:</p>\n<pre><code> public class Main {\n private static final Collection<int[]> lineDefinitions = Arrays.asList(//\n new int[]{0,4,8},\n new int[]{2,4,6} /* more of that for the rows and columns*/)\n private boolean isOwningThreeInLine(String player, String[] board, int[] positions){\n boolean isOwningLine = true;\n for(int position : positions)\n isOwningLine && player.equals(board[position]);\n return isOwningLine;\n }\n public static boolean test(String[] values){\n for(int[] line : lines ) {\n if(isOwningThreeInLine("X",values, line)\n || (isOwningThreeInLine("0",values, line)){\n System.out.print(values[line[0]] + " win");\n return true;\n }\n }\n \n</code></pre>\n<p>And since lines now are <em>objects</em> in a collection this is your first <em>object oriented</em> solution despite we didn't even created a separate <em>class</em> for the <em>line</em> reperesentation.</p>\n<p>The benefit is, that you no longer have to distinguish between "strait lines" and "diagonals", they both are nothing else that entries in the <code>lines</code> collection.</p>\n<p>Of cause you could the same for the <em>player</em>:</p>\n<pre><code> public class Main {\n private static final Collection<String> players = Arrays.asList("X", "0");\n private static final Collection<int[]> lineDefinitions = Arrays.asList(//\n new int[]{0,4,8},\n new int[]{2,4,6} /* more of that for the rows and columns*/)\n private boolean isOwningThreeInLine(String player, String[] board, int[] positions){\n boolean isOwningLine = true;\n for(int position : positions)\n isOwningLine && player.equals(board[position]);\n return isOwningLine;\n }\n public static boolean test(String[] values){\n for(String player : players) {\n for(int[] line : lines ) {\n if(isOwningThreeInLine(player,values, line)){\n System.out.print(player + " win");\n return true;\n }\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:17:53.417",
"Id": "257235",
"ParentId": "257207",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-15T23:39:06.880",
"Id": "257207",
"Score": "3",
"Tags": [
"java",
"tic-tac-toe"
],
"Title": "How can I better test whether the player won in my tic-tac-toe?"
}
|
257207
|
<p>A while ago, I got this question as a part of an interview test which asked to write a function to find the biggest number in a vector and write all the unit tests required to show that the <em>code works under any circumstance</em> using any language or pseudo-code.</p>
<p>To the best of my knowledge, one would need a testing framework in order to do that, so I wrote this and I got a rejection email a couple of hours later.</p>
<pre><code>#include <cassert>
#include <vector>
int largest (std::vector<int> vec ) {
int max = vec[0];
for (int i=1; i<vec.size(); i++)
if (vec[i] > max)
max = vec[i];
return max;
}
void test (std::vector<int> vec, int i) {
assert (largest (vec) == i);
}
int main() {
std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,112 };
test (vec, 112);
test (vec, 7);
return 0;
}
</code></pre>
<p>I have <strong>zero experience</strong> in professional software development and I used C++ since I find it easy to compile and run.</p>
<p>What did I do wrong? What should I have written? Any input would be great.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T12:12:30.283",
"Id": "508197",
"Score": "3",
"body": "If you're applying for a job in software development and you have no experience, it's probably a good idea to read up on some basic standards for professional software development. In this case, I'd look up a popular unit-test framework for C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T10:45:28.077",
"Id": "508288",
"Score": "0",
"body": "*under any circumstances* would solve Turing's Halting Problem. You'd earn a Nobel Prize for that. Maybe they wanted to hear \"but you can try your best\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T13:36:07.763",
"Id": "508320",
"Score": "0",
"body": "@tofro This is irrelevant for the question but where I applied, you could have a Nobel and still be unemployed applying for work ."
}
] |
[
{
"body": "<p>A function that returns the largest value in a vector would certainly have to check if the vector is actually non-empty. You aren't handling that case and are just assuming "the first" element is the biggest...if there is no "first" element, your program will crash in Debug builds or invoke UB in Release builds.</p>\n<p>Also, were there restrictions not mentioned here? Why not use the STL?:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(const auto iter = std::max_element(std::cbegin(vec), std::cend(vec)); iter != std::cend(vec)) {\n //iter now contains a const_iterator containing the largest element...\n} else {\n //The vector was empty.\n //iter now contains std::cend(vec);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:00:12.420",
"Id": "508111",
"Score": "0",
"body": "Why not use the STL? Perhaps that line length has something to do with it, rendering the function almost unreadable..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:43:01.583",
"Id": "508121",
"Score": "1",
"body": "@AnnoyinC Maybe to a novice C programmer. A Modern C++ programmer with knowledge of how the language is designed to be used doesn't care."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T01:10:10.867",
"Id": "257209",
"ParentId": "257208",
"Score": "8"
}
},
{
"body": "<p>A few things to consider / be careful of:</p>\n<ul>\n<li>Pass by reference (and probably an immutable one at that) - so you are not copying the vector AND you are showing that you are only using methods that don't have an effect of changing the vector. e.g</li>\n</ul>\n<pre><code>int largest (std::vector<int> const & vec ) {\n</code></pre>\n<ul>\n<li><p>Boundary cases (empty vector should give what value for <code>largest</code>?)</p>\n</li>\n<li><p>Consider one of the xUnit frameworks (such as cppunit; it doesn't matter which one, just use one) - then you can write simple asserts in a way that debugs easier (expected value first, tested value second, when the test fails the error is value doesn't match expect).</p>\n</li>\n</ul>\n<pre><code>CPPUNIT_ASSERT_EQUAL( 112, largest(vec) );\n</code></pre>\n<ul>\n<li>Need lots of different test inputs: reverse order, negative numbers, same number, repeated tests (to confirm same inputs same outputs).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T02:05:19.287",
"Id": "257210",
"ParentId": "257208",
"Score": "6"
}
},
{
"body": "<p>Unit tests are great, and perfectly suited to self-contained functions such as this. However, <code>assert()</code> is <em>not</em> a testing tool. It's more use as a kind of "magic comment" to tell our readers what we believe to be true (and sometimes to help optimise our code).</p>\n<p>One of the great problems of <code>assert()</code> is that its diagnostics are weak. On failure, it prints the test that evaluated false, but doesn't show any of the values that contributed to the failure.</p>\n<p>I would recommend using one of the many test frameworks (as you hint at in the question) which provide functions or macros such as <code>EXPECT_EQ()</code>, <code>EXPECT_NE()</code>, etc. They are constructed for writing tests, and usually output the actual and expected values to help with diagnosis.</p>\n<p>Another problem with <code>assert()</code> is that when it fails, it's a sign that your program is broken and should be terminated before it causes further damage. What we want is something that records the error, and perhaps terminates that single test, but continues with the other tests in the suite to give us more of that valuable diagnostic information. Again, using a standard test framework would solve that for you.</p>\n<p>If you insist on writing your own comparison function, it isn't hard to add the features I've mentioned. As a prospective colleague, I'd prefer to work with someone who can make good use of existing tools rather than reinvent the wheel - that makes their work easier to read and modify as well as less time-consuming to initially write.</p>\n<p>The choice of tests is puzzling. The very first test I would write would be one that accepts an empty vector. Think also of other boundary cases - a single-element vector would probably be next.</p>\n<p>Consider the test here:</p>\n<blockquote>\n<pre><code>std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,112 };\ntest (vec, 112);\n</code></pre>\n</blockquote>\n<p>We could make this test pass with this (wrong) function:</p>\n<pre><code>int largest(const std::vector<int>& vec) {\n return vec.back();\n}\n</code></pre>\n<p>But our test would not detect the error.</p>\n<hr />\n<p>Some aspects of the function itself are cause for concern:</p>\n<ul>\n<li>Assumption that "number" in the question necessarily means <code>int</code>.</li>\n<li>Passing <code>std::vector</code> by value, rather than by const ref.</li>\n<li>Failure to deal appropriately with empty vectors.</li>\n<li>Nested flow-control (<code>if</code>/<code>for</code>) without braces.</li>\n<li>Failure to take advantage of Standard Library functions (e<code>std::max_element()</code>).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T08:05:11.090",
"Id": "257217",
"ParentId": "257208",
"Score": "7"
}
},
{
"body": "<p>I'm not a C++ developer, and can't comment on the details of the code. But I can comment on the test cases and the general style of the code.</p>\n<p>A good test should be enough to recreate the code from reading just the test cases. Especially when you get the task to make sure <em>the code works under any circumstance</em>.</p>\n<p><strong>Successful test cases</strong></p>\n<p>Let's have a look at your first test case:</p>\n<pre><code>std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,112 };\ntest (vec, 112);\n</code></pre>\n<p>You have a vector with a max number 112, and you test for that. If I were to implement the most simple way of accepting your test I would do this (using pseudocode):</p>\n<pre><code>return 112;\n</code></pre>\n<p>Let's change add another test to avoid that implementation:</p>\n<pre><code>std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,113 };\ntest (vec, 113);\n</code></pre>\n<p>Now I can't just return 112, I have to actually do something else. I would use either of these as my implementation:</p>\n<pre><code>return vec.lastElement();\nreturn vec[7];\n</code></pre>\n<p>More test cases needed to fix those problems. I could go on, but I think you understand. I think the following test cases could be a good base:</p>\n<pre><code>{ 111 }\n{ 7, 50, 16, 8, 25, 9, 12, 112 }\n{ 7, 50, 16, 8, 113, 25, 9, 12 }\n{ 114, 7, 50, 16, 8, 25, 9, 12 }\n{ -1, -2, -3 }\n{ -1, 0, 1 }\n{ -333, 0 }\n{ 0, 123456 }\n</code></pre>\n<p>That's a good start, now we have a lot of test cases with numbers. But we're still missing one important test:</p>\n<pre><code>std::vector<int> vec = { };\n</code></pre>\n<p>I have no idea what you want to be returned in this case, but it is a valid case that needs to be handled.</p>\n<p><strong>Naming tests</strong></p>\n<p>Now we have 10 tests for that simple function. But we need to look at the code to see what the test is testing, and it might not be obvious in all cases. It would be better to have a name for each test that explains what the test is testing in plain English. This is easier with testing frameworks, but a comment would also make the intention clear.</p>\n<p><strong>Indent</strong></p>\n<p>Looking at your code I struggle to see where the functions begin and end. Make sure to indent properly.</p>\n<p><strong>Is this a failing test?</strong></p>\n<p>Your second test is:</p>\n<pre><code>std::vector<int> vec = { 7, 50, 16, 8, 25, 9, 12,112 };\ntest (vec, 7);\n</code></pre>\n<p>What is this testing? My understanding is that 7 shouldn't be returned, failing this test. I don't understand why this is added, please explain in a comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T10:42:26.600",
"Id": "508003",
"Score": "0",
"body": "I can't make a 1-char edit, but in the case where you test 113, you are still calling test() with 112, which seems like an mistake?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T10:47:01.697",
"Id": "508004",
"Score": "0",
"body": "@Korosia it's a mistake that have now been fixed. Thank you for pointing it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T10:49:03.890",
"Id": "508005",
"Score": "0",
"body": "Great. Other than that, good answer! +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T11:26:39.297",
"Id": "508019",
"Score": "0",
"body": "@Polygorial Thank you for your valuable input, I literally know nothing about testing (it was not taught in my college) so my idea was to test all elements of the vector that's why there is `test (vec,7)`, it was a programming job and was caught off guard with the question and failed, I am still trying to find a way to implement what you've said."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T11:56:09.110",
"Id": "508027",
"Score": "0",
"body": "@user10191234 no problems. Testing is a pretty big topic in itself, don't get discouraged by not knowing that much about it yet. For unit tests I suggest reading a bit about TDD or Test Driven Development, it will give you an idea about how to think about when developing using tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T11:56:17.090",
"Id": "508028",
"Score": "1",
"body": "@user10191234 when you create automatic tests the goal is that all tests should pass, you test for the expected result only. Note that the expected result can be an exception as well, the important thing is that it's tested and the test succeeds when it gets that exception. I think you should look into a test framework since it's much easier to write tests using one."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T09:00:23.440",
"Id": "257220",
"ParentId": "257208",
"Score": "11"
}
},
{
"body": "<p>In a practical scenario, a good unit test should cover all edge cases. Hence, you should test the empty list, and you should test the cases where the largest element is at the beginning, at the end, and somewhere in the middle of the vector. There might be even more reasonable test-cases. There is, however, the possibility that you have been confronted with a <em>trick question</em>.</p>\n<p>Strictly speaking, the task to "write all the unit tests required to show that <em>the code works under any circumstance</em>" is impossible. Consider the following code:</p>\n<pre><code>const size_t N = 10;\n\nint largest(std::vector<int> a)\n{\n if (a.size() > N)\n return a.at(0);\n\n int candidate = a.at(0);\n for (size_t i=1; i < a.size(); ++i) {\n if (a[i] > candidate) {\n candidate = a[i];\n }\n }\n return candidate;\n}\n</code></pre>\n<p>This function works perfectly for all vectors that are no longer than 10 elements, however, fails for almost all vectors that have more than 10 elements. You might say: "okay, so I have to include vectors that have to have at least 11 elements." In this case, however, I could set <em>N</em> to 100 or 1000. The point here being, with just a finite number of unit tests and without inspecting the code, it is impossible to <em>prove</em> that the code is correct. I can always give you a function that works for all unit tests and fails for all other inputs. In short:</p>\n<blockquote>\n<p>a test can only show the presence of an error, never the absence of errors.</p>\n</blockquote>\n<p>Depending on the type of person you have been dealing with, this <em>might</em> have been the "correct" answer. Without asking, you will probably never know.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T16:52:33.490",
"Id": "257309",
"ParentId": "257208",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "257220",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T00:01:34.953",
"Id": "257208",
"Score": "9",
"Tags": [
"c++",
"beginner",
"unit-testing",
"interview-questions"
],
"Title": "Unit test for a maximum-finding function"
}
|
257208
|
<p>(using GNU sed)</p>
<p>I want to grab some output from xrandr and leave out everything but the resolution and offset.</p>
<p>Input:</p>
<pre><code>eDP1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 290mm x 160mm
1366x768 60.02*+
1280x720 59.74
...
640x360 59.84 59.32 60.00
HDMI1 connected primary 2560x1440+1366+0 (normal left inverted right x axis y axis) 610mm x 350mm
3840x2160 30.00 + 25.00 24.00 29.97 23.98
2560x1440 59.95*
...
720x400 70.08
</code></pre>
<p>Desired output:</p>
<pre><code>1366x768+0+0
2560x1440+1366+0
</code></pre>
<p>This is my current command:</p>
<pre><code>xrandr | sed -e '/^\ /d' -e 's/.*\(\<.*x[0-9]*+[0-9]*+[0-9]*\).*/\1/'
</code></pre>
<p>The first expression deletes all the lines that begin with spaces, leaving</p>
<pre><code>eDP1 connected 1366x768+0+0 (normal left inverted right x axis y axis) 290mm x 160mm
HDMI1 connected primary 2560x1440+1366+0 (normal left inverted right x axis y axis) 610mm x 350mm
</code></pre>
<p>Then the second expression find the resolution/offset and throws away everything else.</p>
<p>How could I make the regex cleaner?</p>
|
[] |
[
{
"body": "<p>Cleaner is very much in the eye of the beholder.</p>\n<p>Your regex is fine - although for the digits part - I would use <code>\\d+</code> because you expect at least 1 digit. And <code>\\<</code> only works in GNU sed (not on OSX for instance).</p>\n<p>Alternative you can look at it differently .. e.g only print the lines you care about, and on those lines drop everything you don't care about).</p>\n<pre><code>sed -n -e '/connected/ { s/ (.*$//; s/^.*ected //; s/^primary //; p; }'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T10:55:48.517",
"Id": "257228",
"ParentId": "257212",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "257228",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T02:42:48.060",
"Id": "257212",
"Score": "0",
"Tags": [
"regex",
"sed"
],
"Title": "Grabbing resolution and offset from xrandr"
}
|
257212
|
<p>Just out of curiosity, I have this code lying around a personal project in which I will generate lots of dummy customer data.</p>
<p>Here's the code:</p>
<pre><code>faker = Faker()
# Faker.seed(random.randint(0, sys.maxsize))
async def get_random_customer_login(count: int, user: CustomerLogin_PydanticIn) -> list:
data = []
for i in range(count):
plain_email = user.plain_email
user_ip = user.user_ip
user_id = user.user_id
client_id = user.client_id
result = user.result
fail_cause = user.fail_cause
process = user.process
user_agent = user.user_agent
device_token = user.device_token
event_timedate = user.event_timedate
if plain_email is None:
plain_email = await get_random_email()
if user_ip is None:
user_ip = await get_random_ip_address()
if user_id is None:
user_id = uuid.uuid4()
if client_id is None:
client_id = await get_random_client_id()
if result is None:
result = await get_random_result()
if 'AUTHENTICATION_SUCCESS' not in result:
fail_cause = await get_random_fail_cause()
if fail_cause is None:
fail_cause = await get_random_fail_cause()
if process is None:
process = await get_random_ub_process()
if user_agent is None:
user_agent = await get_random_user_agent()
if device_token is None:
device_token = uuid.uuid4()
if event_timedate is None:
event_timedate = await get_random_utc_timestamp()
customer_login = CustomerLogin_PydanticIn(
event_timedate=event_timedate,
user_id=user_id,
device_token=device_token,
user_ip=user_ip,
user_agent=user_agent,
client_id=client_id,
process=process,
result=result,
fail_cause=fail_cause,
plain_email=plain_email)
data.append(customer_login)
return data
async def get_random_email() -> str:
return faker.ascii_company_email()
async def get_random_ip_address() -> str:
return faker.ipv4_public()
async def get_random_ub_process() -> str:
return faker.random_element(elements=PROCESS_LIST)
async def get_random_client_id() -> str:
return faker.random_element(elements=CLIENT_ID_LIST)
async def get_random_result() -> str:
return faker.random_element(elements=RESULT_LIST)
async def get_random_fail_cause() -> str:
return faker.random_element(elements=FAILURE_CAUSE_LIST)
async def get_random_user_agent() -> str:
return faker.user_agent()
async def get_random_utc_timestamp() -> datetime.datetime:
return pytz.utc.localize(faker.date_time_this_century())
</code></pre>
<p>Basically, this function takes in a <code>count</code> of dummy data to be created, and the <code>CustomerLogin</code> pydantic object. The catch is the function will assign some randomly generated value of fields in <code>CustomerLogin</code> that are not provided.</p>
<p>Anyway, this code works. However, I think there's a lot of room to optimize and should I set faker seed?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T09:18:34.673",
"Id": "507994",
"Score": "0",
"body": "There is not much room for performance improvement, no, since all you are doing is a series of \"if X is not set, assign this value to it\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T16:39:04.903",
"Id": "508068",
"Score": "0",
"body": "You can probably extract all the variables that reference random objects to be created in a common get_random(element) function, that will call to faker.random_element(elements=element), so you don't have to do it so many times"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:12:20.643",
"Id": "508075",
"Score": "0",
"body": "Hi. I thinking more of a way to avoid the numerous if-else statements for the `CustomerLogin` pydantic model. Is there a way that I can for loop through them, check the values, and assign generated values if none provided?"
}
] |
[
{
"body": "<p>Since most of your checks are simply checking that a value hasn't already been provided, you can use the <code>or</code> operator to remove most of the if statements. e.g.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> print(None or "I've used the 'or' operator")\nI've used the 'or' operator\n</code></pre>\n<p>Since the value left of the <code>or</code> is <code>None</code> the right-hand side is evaluated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-22T00:26:20.347",
"Id": "257493",
"ParentId": "257213",
"Score": "0"
}
},
{
"body": "<p>I can't come up with many performance improvements, but I have a couple of suggestions for you.</p>\n<p><strong>Dummy variable in the <code>for</code> loop</strong></p>\n<p>You have a <code>for</code> loop that goes</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(count):\n # ...\n</code></pre>\n<p>but you do nothing with <code>i</code> because you just want to execute the function <code>i</code> times.\nA very idiomatic way to say you don't <em>need</em> the variable is by writing</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(count):\n</code></pre>\n<p>It saves people the time of looking for the usage of <code>i</code> inside the loop.</p>\n<p><strong>One item per line, end line with comma on long lists</strong></p>\n<p>You have a long list of kwargs that you pass in to <code>CustomerLogin_PydanticIn</code>, and in those cases it is better to have a kwarg per line and ending every line with a comma. You <em>almost</em> do this, you are just missing the last line:</p>\n<pre class=\"lang-py prettyprint-override\"><code>customer_login = CustomerLogin_PydanticIn(\n event_timedate=event_timedate,\n # ...\n plain_email=plain_email,\n)\n</code></pre>\n<p>This apparently tiny change will be more git friendly if/when you need to add/remove kwargs.</p>\n<p><strong>Short circuiting</strong></p>\n<p>Finally, for the sake of completeness (as this was already mentioned in other answers) you can use short-circuiting for the <code>None</code> checks:</p>\n<pre class=\"lang-py prettyprint-override\"><code>plain_email = user.plain_email\nif plain_email is None:\n plain_email = await get_random_email()\n</code></pre>\n<p>becomes</p>\n<pre class=\"lang-py prettyprint-override\"><code>plain_email = user.plain_email or await get_random_email()\n</code></pre>\n<p><strong>Double fail cause..?</strong></p>\n<p>Your code reads:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if result is None:\n result = await get_random_result()\n\n if 'AUTHENTICATION_SUCCESS' not in result:\n fail_cause = await get_random_fail_cause()\n if fail_cause is None:\n fail_cause = await get_random_fail_cause()\n</code></pre>\n<p>In particular, you do <code>fail_cause = await get_random_fail_cause()</code> and if <code>fail_cause</code> is <code>None</code>, you do <em>the exact same line</em> again, but only once more.\n<em>What if</em> <code>fail_cause</code> is still <code>None</code>? Maybe you know that <code>get_random_fail_cause</code> doesn't return two <code>None</code>s in a row?\nAssuming you don't know that for sure, you would probably write a <code>while</code> loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>fail_cause = None\nwhile fail_cause is None:\n fail_cause = await get_random_fail_cause()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-09T07:01:48.977",
"Id": "528136",
"Score": "1",
"body": "thanks a lot for this. I have learned something new."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-09T07:49:07.417",
"Id": "528139",
"Score": "0",
"body": "@akuani my pleasure!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T06:40:27.097",
"Id": "259783",
"ParentId": "257213",
"Score": "2"
}
},
{
"body": "<h3>Pydantic models</h3>\n<p>I am presuming the CustomerLogin_PydanticIn is a Pydantic model.</p>\n<p>You can iterate over a Pydantic model to get the names and values of its fields.\nWe can do this to build a dict, <code>missing</code>, that maps fields in <code>user</code> with <code>None</code> values\nto functions that generate random replacement values. The functions have a standard\nname format, "random_(field_name)", so they can be looked up using <code>globals()</code>.</p>\n<p><code>new_attrs</code> uses the <code>missing</code> dict to create a dict mapping empty fields to\nreplacement values.</p>\n<p>Field 'fail_cause' is handled separately. Note, the logic for <code>fail_cause</code> may need to be fixed. For example, it doesn't handle the case where user.result has a value\nindicating failure but <code>fail_cause</code> is <code>None</code>.</p>\n<p>Lastly, <code>user.copy</code> is used with the <code>update</code> parameter to create a new CustomerLogin_PydanticIn.</p>\n<pre><code>async def get_random_customer_login(count: int, user: CustomerLogin_PydanticIn) -> list:\n # map missing user attrs to functions that generate random attr values\n missing = {}\n for attr, value in user:\n if value is None and attr != 'fail_cause':\n missing[attr] = globals()[f"random_{attr}"] \n \n data = []\n for _ in range(count):\n new_attrs = {attr:func() for attr, func in missing.items()}\n \n if 'result' in new_attrs and 'AUTHENTICATION_SUCCESS' not in new_attrs['result']:\n fail_cause = await get_random_fail_cause()\n if fail_cause is None:\n fail_cause = await get_random_fail_cause()\n new_attrs['fail_cause'] = fail_cause\n \n data.append(user.copy(update=new_attrs))\n \n return data\n\nasync def random_client_id() -> str:\n return faker.random_element(elements=CLIENT_ID_LIST)\n\nasync def random_device_token():\n return uuid.uuid4()\n\nasync def random_event_timedate() -> datetime.datetime:\n return pytz.utc.localize(faker.date_time_this_century())\n\nasync def random_fail_cause() -> str:\n return faker.random_element(elements=FAILURE_CAUSE_LIST)\n\nasync def random_plain_email() -> str:\n return faker.ascii_company_email()\n\nasync def random_process() -> str:\n return faker.random_element(elements=PROCESS_LIST)\n\nasync def random_result() -> str:\n return faker.random_element(elements=RESULT_LIST)\n\nasync def random_user_agent() -> str:\n return faker.user_agent()\n\nasync def random_user_id() -> str:\n return uuid.uuid4()\n\nasync def random_user_ip() -> str:\n return faker.ipv4_public()\n</code></pre>\n<p>Note, this code hasn't been tested.</p>\n<h3>faker.seed()</h3>\n<p><code>faker</code> uses <code>random.Random</code> in the standard library. An instance of <code>random.Random</code> initializes its seed from the time or a system random source. So setting a seed is not necessary. However, for testing it may be helpful to set the seed to a known value so as to get the same sequence of random values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T07:06:32.260",
"Id": "259785",
"ParentId": "257213",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259785",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T03:39:46.423",
"Id": "257213",
"Score": "3",
"Tags": [
"python",
"performance"
],
"Title": "Generate dummy customer data"
}
|
257213
|
<h3>Objective:</h3>
<ul>
<li>Create a function called <code>wordsAndSpaces</code> that splits a string on groups of spaces, preserving each group of space characters as a single token.<br>
Example: <code>wordsAndSpaces "extra spaces"</code> gives <code>["extra", " ", "spaces"]</code><br></li>
</ul>
<h3>Rules:</h3>
<ul>
<li>Input strings will contains only alphanumeric characters and space characters (no need to handle special characters)</li>
<li>Only Prelude functions are allowed (no imports e.g. <code>Data.List.Split</code>)</li>
</ul>
<h3>Notes:</h3>
<ul>
<li>I'm looking specifically for feedback on how I can break thought patterns I have developed from working in imperative languages. My code likely has the telltale signs of a recovering Java programmer :)</li>
</ul>
<pre><code>wordsAndSpaces :: String -> [String]
wordsAndSpaces = wordsAndSpaces' []
wordsAndSpaces' :: [String] -> String -> [String]
wordsAndSpaces' tokens [] = tokens
wordsAndSpaces' tokens (char : xs)
| shouldAddToLastToken char tokens = wordsAndSpaces' (addToLastToken char tokens) xs
| otherwise = wordsAndSpaces' (tokens ++ [[char]]) xs
shouldAddToLastToken :: Char -> [String] -> Bool
shouldAddToLastToken c tokens
| null tokens = False
| otherwise =
(isSpace c && (isSpace . last . last) tokens)
|| ((not . isSpace) c && (not . isSpace . last . last) tokens)
addToLastToken :: Char -> [String] -> [String]
addToLastToken char tokens = init tokens ++ [last tokens ++ [char]]
isSpace :: Char -> Bool
isSpace = (== ' ')
</code></pre>
|
[] |
[
{
"body": "<p>The big thing that jumped out to me was how you seem to be treating Haskell lists like Java... Arrays? (I haven’t used Java since... 2006?) If you’re repeatedly fiddling with the elements at the end of lists, you’re probably doing something wrong. I’m not sure what the complexity of this all is, but I think it might be something like <span class=\"math-container\">\\$\\mathcal{O}(m^2n^2)\\$</span> where <span class=\"math-container\">\\$m\\$</span> is the length of the original string and <span class=\"math-container\">\\$n\\$</span> is the number of tokens. Haskell lists are linked lists, finding arbitrary elements (of which the <code>last</code> is one) is an <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> operation, as is appending any element to the tail of a list (<code>++</code>).</p>\n<p>I think largely as you gain familiarity with the Prelude you’ll begin to intuit the shape of efficient Haskell algorithms. Now that’s not to say Haskell doesn’t also have arrays, but we tend to use them differently. (How exactly that is being way out of the scope of this question.)</p>\n<p>In this case the concept you're looking for is a <code>span</code>. That is, the part of a list at the front that matches a predicate, and then the rest. In this case we care about the predicates <code>isSpace</code> and <code>not . isSpace</code>.</p>\n<pre><code>-- REPL session, if you're not familiar with REPLs yet coming from Java, check out GHCi\n> span isSpace " word word"\n(" ","word word")\n> span (not . isSpace) "wordword word word"\n("wordword"," word word")\n</code></pre>\n<p><code>span</code> is in the Prelude, but it’s worth taking a crack at implementing it yourself to start building an intuition for living in Linked List World. Try it before you move on and I start to really blow your mind.</p>\n<hr>\n<p>Here’s a solution using <code>span</code>. Spoiler’d so you can figure it out first.</p>\n<blockquote class=\"spoiler\">\n<p> <pre><code>wordsAndSpaces :: String -> [String]\nwordsAndSpaces [] = []\nwordsAndSpaces cs@(c:_) = case isSpace c of\n True -> let (w, rest) = span isSpace cs in w : wordsAndSpaces rest\n False -> let (w, rest) = break isSpace cs in w : wordsAndSpaces rest\n -- break p = span (not . p), just a convenient name</code></pre></p>\n</blockquote>\n<hr>\n<p>In that solution you might notice how both tines of the fork (as it were) are very, very similar. Generally this is a hint that a handy library function exists or there’s some common trick that has a deeply unintuitive category theoretical name and/or requires a flash of abstractly reasoned insight to recognize. Luckily in this case you would just have to know about <code>Data.List.groupBy :: (a -> a -> Bool) -> [a] -> [[a]]</code>.</p>\n<p>Coming from outside the Prelude <code>groupBy</code> doesn’t fit your criteria for usage in this practice problem, but as with <code>span</code> it’s something worth knowing for <em>the way we think about decomposing problems</em>. If you didn’t immediately understand what <code>groupBy</code> is or does from its type, that’s more than alright for a beginner, but give it a think before reading on.</p>\n<hr>\n<p><code>groupBy</code> breaks a list into sublists based on which stretches of values are like one another. This probably makes most sense when you look at an example.</p>\n<pre><code>> groupBy (==) [1,1,2,2,2,3,4,5,5,5,5]\n[[1,1],[2,2,2],[3],[4],[5,5,5,5]]\n\ngroupBy :: (a -> a -> Bool) -> [a] -> [[a]]\nisSpace :: (a -> Bool)\n</code></pre>\n<p>So the question is, how do we turn the unary predicate <code>isSpace</code> into a binary predicate to pass to <code>groupBy</code>? The first step to recognize is that the <code>Bool</code> return values mean different things. <code>isSpace</code> says whether or not a character is a space, <code>groupBy</code>’s predicate is asking whether two things are <em>the same</em>. So we can test the result of isSpace on two elements for equality.</p>\n<pre><code>predicate :: Char -> Char -> Bool\npredicate c d = isSpace c == isSpace d\n</code></pre>\n<p>But it turns out we even do <em>that</em> so frequently that there's a name for it also, <code>Data.Function.on :: (b -> b -> c) -> (a -> b) -> a -> a -> c</code>. Used like—</p>\n<pre><code>predicate = (==) `on` isSpace\n</code></pre>\n<p><code>on</code> takes a binary operation (<code>b -> b -> c</code>) and a unary operation (<code>a -> b</code>) and <em>lifts</em> the binop to work on <code>a</code>s, whatever those may be. <code>groupBy</code> is a good example, sorts are another where you might do something like <code>compare `on` color</code>, if <code>color</code> had a type like <code>Shape -> Color</code>. We would like to sort <code>Shape</code>s by <code>Color</code>, so you use a higher order function (<code>on</code>) to build a function to do that! Try to implement <code>on</code>.</p>\n<hr>\n<p>So, here's how a Haskeller would write <code>wordsAndSpaces</code>.</p>\n<blockquote class=\"spoiler\">\n<p> <pre><code>wordsAndSpaces = groupBy ((==) `on` isSpace)</code></pre></p>\n</blockquote>\n<p>With that (probably, hopefully, shocking) motivating example, now try to write <code>groupBy</code>. Think back to the solution using <code>span</code>, consider its symmetries, and try to go one level up the abstraction stack. Ultimately Haskell coding is about solving the smallest part of a problem that you can, recognizing which higher order function can plumb that into solving a slightly larger problem, then repeating that process over and over again until you reach the end.</p>\n<p>In this case (though I’ve kind of meandered), first we had to have figured out how to say whether or not something is a space. Next you figure out identifying a single stretch of spaces or not-spaces. Then the trick is categorizing <em>all</em> of the maybe-or-not-spaces. Each step in the path is something small and tackle-able on its own, and we try to consider the most general possible solution to it so that we <em>don't have to</em> think about the whole problem at once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-04T22:13:56.607",
"Id": "510922",
"Score": "0",
"body": "I really like how you described the method of tackling problems in Haskell -- start with something simple and concrete, then plug those simple solutions into higher order functions until you get the generalized solution! You have a great teaching style -- thank you for sharing principles, and not just code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T06:53:28.500",
"Id": "257287",
"ParentId": "257214",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257287",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T04:22:15.060",
"Id": "257214",
"Score": "1",
"Tags": [
"beginner",
"strings",
"haskell",
"recursion",
"reinventing-the-wheel"
],
"Title": "String tokenizer"
}
|
257214
|
<p>I want to write an extension method for getting Sunday Date based on weekOffset and current date. For example if weekOffset value is 1 that means next week sunday date and if weekOffset is 2 that means next to next week's Sunday date.</p>
<p>I have come up with below code</p>
<pre><code>private static List<string> GetWeekRange(this DateTimeOffset date, int weekOffset = 0)
{
var sundayDate = new DateTimeOffset(date.Year, date.Month, date.Day, 0, 0, 0, date.Offset).AddDays(weekOffset * 7 - (int) new DateTimeOffset(date.Year, date.Month, date.Day, 0, 0, 0, date.Offset).DayOfWeek);
var saturdayDate = new DateTimeOffset(weekStartDate.Year, weekStartDate.Month, weekStartDate.Day, 0, 0, 0, weekStartDate.Offset).AddDays(7).AddMilliseconds(-1);
return new List<string> { weekStartDate.ToString("o"), weekEndDate.ToString("o") };
}
</code></pre>
<p>I was wondering if there can be a better way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T07:26:33.420",
"Id": "507990",
"Score": "1",
"body": "You should perhaps be clear about your definition of \"better\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:21:50.000",
"Id": "508031",
"Score": "1",
"body": "This code does not compile. Apparently you have mixed up naming with `sundayDate` & `weekStartDate` and `saturdayDate` & `weekEndDate`. FIX YOUR CODE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:33:22.007",
"Id": "508032",
"Score": "0",
"body": "@RickDavin Sorry, Fixed now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:43:44.263",
"Id": "508036",
"Score": "0",
"body": "You also have a logic bug that does not account for DST. Bottom line is this method only works as long as a week does not have a DST transition. That is the input `date` has an `Offset` property that is fixed for the week being observed. Last week, my local Offset was -06:00. This week it is -05:00."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:50:13.580",
"Id": "508039",
"Score": "0",
"body": "Spring Forward for me was 3 days ago. This returns the wrong start date for me: `GetWeekRange(DateTimeOffset.Now.AddDays(-7), 0)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T13:37:05.820",
"Id": "508045",
"Score": "1",
"body": "Welcome to Code Review! Changing the code in the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again."
}
] |
[
{
"body": "<p>I think your code could be more succinctly and usefully (ie don't return string) written as:</p>\n<pre><code> private static DateTimeOffset[] GetWeekRange(this DateTimeOffset d, int weekOffset = 0)\n {\n var weekStartDate = new DateTimeOffset(d.Date, d.Offset).AddDays(weekOffset * 7 - (int)d.DayOfWeek);\n var weekEndDate = weekStartDate.AddDays(7);\n return new [] { weekStartDate, weekEndDate };\n }\n</code></pre>\n<p>But then given that end is so easily calc'd from start, maybe just return start, forget the array</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T07:19:20.610",
"Id": "257216",
"ParentId": "257215",
"Score": "0"
}
},
{
"body": "<p>My comments to the OP mention there is a flaw in the method if the week in question has a DST transition. The UTC offset for the <code>DateTimeOffset</code> is constant for the week, that is to say that both the Start and End dates must have the same UTC offset, which may not be desired. Unless you were to account for a time zone, you will have to accept this flaw.</p>\n<p>I would suggest you could have phrased the question better. And the same thinking could also go into your variable naming. You really aren't trying to find Sunday's start. Rather you are trying to find the start of a "week". If you pass in 1 for your <code>weekOffset</code>, then the start of the week is Monday, not Sunday. Thus the variable naming of <code>sundayDate</code> really should be <code>startDate</code> or something like that since it does not have to be Sunday.</p>\n<p>There is no constraint on the <code>int weekOffset</code> parameter. Since a <code>DateTimeOffset</code> also has an <code>Offset</code> property (for UTC offset), I paused and had to slowly read to see what purpose was served by <code>weekOffset</code>. This is cleaned up better in my version below where I use a <code>DayOfWeek</code> enum instead. As a enum, it serves as a constrait but also is more direct that it serves as the beginning of a "week".</p>\n<p>There is no need to substract a millisecond to get the week End date. Why a millisecond? Why not 1 tick? Better yet, why bother at all? Generally one accepts that one week's End is another week's Start. The convention is therefore to have the Start be inclusive (i.e. <code>>=</code>) and the End be exclusive (i.e. <code><</code>) when filtering is applied to see if a given <code>DateTime</code> falls within that "week".</p>\n<p>Your variable naming could go a long way to clear up any confusion. It is a relative rookie mistake to return strings. As the other answer says, you could either return an array of <code>DateTimeOffset</code> or really just return the start of the week since you know the end of that week is just 7 days away. Let's go further. Let's return a tuple with named values, and let's have those names clear up the confusion.</p>\n<pre><code> public static (DateTimeOffset InclusiveStartDate, DateTimeOffset ExclusiveEndDate) GetWeekRange(this DateTimeOffset date, DayOfWeek weekStartingDay = DayOfWeek.Sunday)\n {\n date = new DateTimeOffset(date.Year, date.Month, date.Day, 0, 0, 0, date.Offset);\n var offsetDays = ((int)weekStartingDay * 7) - (int)date.DayOfWeek;\n var startDate = date.AddDays(offsetDays);\n return (startDate, startDate.AddDays(7));\n }\n</code></pre>\n<p>Any developer using this clearly sees that there is an <code>InclusiveStartDate</code> and an <code>ExclusiveEndDate</code>. Furthermore, instead of the <code>weekOffset</code> being an <code>int</code>, where one could pass in bad values like <code>-999</code>, I pass in a <code>DayOfWeek</code> enumerated value.</p>\n<p>To see it in action:</p>\n<pre><code>static void Main(string[] args)\n{\n var date = DateTimeOffset.Now;\n DisplayWeekRange(date, DayOfWeek.Sunday);\n DisplayWeekRange(date.AddDays(-7), DayOfWeek.Sunday);\n\n Console.WriteLine("\\nPress ENTER key to close.");\n Console.ReadLine();\n}\n\nprivate static void DisplayWeekRange(DateTimeOffset date, DayOfWeek weekStartingDay)\n{\n var weekRange = date.GetWeekRange(weekStartingDay);\n Console.WriteLine($"Input Date: {date}");\n Console.WriteLine($"Week Starting Day: {weekStartingDay}");\n Console.WriteLine($" Inclusive Start: {weekRange.InclusiveStartDate}");\n Console.WriteLine($" Exclusive End : {weekRange.ExclusiveEndDate}");\n}\n</code></pre>\n<p>And here is some sample output:</p>\n<pre><code>Input Date: 3/16/2021 8:47:24 AM -05:00\nWeek Starting Day: Sunday\n Inclusive Start: 3/14/2021 12:00:00 AM -05:00\n Exclusive End : 3/21/2021 12:00:00 AM -05:00\nInput Date: 3/9/2021 8:47:24 AM -05:00\nWeek Starting Day: Sunday\n Inclusive Start: 3/7/2021 12:00:00 AM -05:00\n Exclusive End : 3/14/2021 12:00:00 AM -05:00\n\nPress ENTER key to close.\n</code></pre>\n<p>The second example shows the flaw with DST Transition. I am in US Central and just 3 days ago we had the Spring Forward to DST. This week's range is correct. However, last week's range should really show a UTC offset of <code>-06:00</code> since last week was Standard time. Again, this flaw is not a logic bug as much as a design bug. Without knowing what time zone I am using, I cannot account for DST transitions. So a future version could maybe include that.</p>\n<p>Also, anytime there is a question of time zones, times, etc., I always refer you to:</p>\n<p><a href=\"https://nodatime.org/\" rel=\"nofollow noreferrer\">https://nodatime.org/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T13:52:45.910",
"Id": "257241",
"ParentId": "257215",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T07:07:10.053",
"Id": "257215",
"Score": "0",
"Tags": [
"c#",
"performance",
"datetime",
"extension-methods",
"asp.net-core"
],
"Title": "Extension method to get the Sunday date from current date based on weekOffset"
}
|
257215
|
<p>I'm trying to implement execvp () using execv (). I don't know if the code is the best implementation.</p>
<p>my code:</p>
<pre><code>#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
extern char **environ;
int my_execvp(char *file, char *argv[])
{
char *p, *colon, *pathseq = getenv("PATH");
size_t len;
if(strchr (file, '/'))
return execv(file, argv);
if (pathseq == NULL) {
len = confstr(_CS_PATH, (char *) NULL, 0);
pathseq = (char *) alloca(1 + len);
pathseq[0] = ':';
(void) confstr (_CS_PATH, pathseq + 1, len);
}
len = strlen(file) + strlen(pathseq) + 2;
for(p = pathseq; p && *p; p = colon)
{
char b[len];
colon = strchr(p, ':');
if(colon)
{
memcpy(b, p, (size_t) (colon - p));
b[colon++-p] = 0;
}
else
strcpy(b, p);
strcat (b, "/");
strcat (b, file);
if(!access(b, F_OK)) {
execv(b, argv);
fprintf(stderr, "an error occurred in execv\n");
abort();
}
}
errno = ENOENT;
return -1;
}
int main()
{
/* "ls / -l" */
char *arg[] = {"ls", "/", "-l", NULL};
my_execvp (arg[0], arg);
return 0;
}
</code></pre>
<p>And the question I have, is it a good implementation? How could it be improved or write a better implementation?</p>
|
[] |
[
{
"body": "<p>The implementation is non-conformant.</p>\n<ol>\n<li>No handling of undefined <code>PATH</code>. Quoting <code>man execp</code>:</li>\n</ol>\n<blockquote>\n<p>search path is the path specified in the environment by\n``PATH'' variable. If this variable is not specified, the <strong>default path\nis set according to the <code>_PATH_DEFPATH</code></strong> definition in <paths.h></p>\n</blockquote>\n<p>Once <code>confstr</code> returns <code>0</code>, check <code>errno</code>, and act accordingly.</p>\n<ol start=\"2\">\n<li><p>Calling <code>abort</code> on <code>execv</code> failure is plain wrong. At least return what <code>execv</code> returns.</p>\n</li>\n<li><p>Calling <code>access</code> is also incorrect. If the file exists, but doesn't have correct permissions, <code>execvp</code> shall continue searching.</p>\n</li>\n</ol>\n<p>As a side note, <code>access</code> is very rarely useful. Consider calling <code>execvp</code> blindly, and testing <code>errno</code> upon return.</p>\n<ol start=\"4\">\n<li><p>Final <code>errno = ENOENT;</code> is also non-compliant. <code>execvp</code> sets <code>ENOENT</code> if the file does not exist in any path. If it was found at least once, and fails to execute, the <code>errno</code> shall be <code>EACCES</code>.</p>\n</li>\n<li><p><code>execvp</code> is not supposed to <code>fprintf</code> anything.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:54:38.093",
"Id": "257254",
"ParentId": "257222",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T09:26:07.677",
"Id": "257222",
"Score": "1",
"Tags": [
"beginner",
"c",
"reinventing-the-wheel",
"file"
],
"Title": "A better implementation of the `execvp` call: the code implements `execvp`"
}
|
257222
|
<p>A Java service that connects to MongoDB in production, but opened connection count is too much. It affects on MongoDb performance, so I have come up with a solution that provides only one <code>MongoClient</code> instance so which will reduce the connections.</p>
<p>Here is my code, is it a good way to provide a singleton object from 3rd party library?</p>
<pre><code>import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
public class MongoClientFactory {
private static volatile MongoClient instance = null;
private MongoClientFactory() {}
public static MongoClient getInstance(String connectionString) {
if (instance == null) {
synchronized(MongoClientFactory.class) {
if (instance == null) {
instance = MongoClients.create(connectionString);
}
}
}
return instance;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:53:24.560",
"Id": "508062",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:55:59.397",
"Id": "508064",
"Score": "1",
"body": "Thanks for the warning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:01:43.527",
"Id": "508073",
"Score": "0",
"body": "There's only one review applicable for a singleton: don't. See https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern for an introduction."
}
] |
[
{
"body": "<p>I am not expert in singleton but does the connectionString really change over the life of the application? Usually (I might be wrong) this string is declared with the <code>final</code> keyword.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T14:46:40.117",
"Id": "508051",
"Score": "0",
"body": "because of different environment like test, prod and local, for different connection string"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T14:55:35.050",
"Id": "508052",
"Score": "0",
"body": "Yes but once the application is launch you are probably not going to change the URL ? For me the url should be inside a porperties file, which is different for every env and so you can change your singleton to be build inside static block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:46:42.567",
"Id": "508059",
"Score": "0",
"body": "yes, just change the function signature"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T13:56:40.570",
"Id": "257242",
"ParentId": "257226",
"Score": "1"
}
},
{
"body": "<p>There are already links on this page to reasons why singletons should not be used. I will not repeat those.</p>\n<p><em>is it a good way to provide a singleton object from 3rd party library?</em></p>\n<p>No. Your singleton has an undocumented internal state which affects the processing of the input parameters. On the first invocation, the <code>getInstance(String connectionString)</code> methods returns a connection to the database requested by the caller. On subsequent invocations it returns a connection to the database requested by the first caller, regardless of what connection string is provided to it. You could document it but it doesn't fix the issue of this being a very error prone solution: your method does something unexpected if something that cannot be verified during run time happened before it was called.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T10:51:06.733",
"Id": "257336",
"ParentId": "257226",
"Score": "2"
}
},
{
"body": "<p>With your code you'll get <code>getInstance(database1) == getInstance(database2)</code> which is obviously wrong, this points to a problem with your API. Using a singleton (poorly) is the likely cause here. There's good reason why singletons are discouraged.</p>\n<p>For your problem you really should have one instance created in your <code>main</code> that's then passed through to all objects that need it and the instance is then kept alive. In general what you're looking for is called <a href=\"https://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow noreferrer\">Dependency Injection</a> and there are several frameworks to make it easier, for example dagger and guice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T11:24:08.310",
"Id": "257338",
"ParentId": "257226",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T10:50:23.440",
"Id": "257226",
"Score": "1",
"Tags": [
"java",
"singleton"
],
"Title": "Singleton MongoClient instance provider"
}
|
257226
|
<p>I have done some programming tasks as a part of my candidacy for a web development apprenticeship. Unfortunately, my application was rejected as the hiring manager "didn't like my codes." I called up their office but no one was able to provide sufficient feedback for me.</p>
<p>If any of you could tell me what I could have misunderstood or what I could have done correctly, I pretty much appreciate it.</p>
<p><strong>The Tasks I worked with</strong></p>
<p>Write a program that shows the numbers from 1 to a specified limit (e.g. 100).</p>
<p>The numbers should be translated as follows: 1. For multiples of 3 return "Fizz" 2. For multiples of 5 return "Buzz" 3. For multiples of 3 and 5 return "FizzBuzz" 4. If none of the other rules apply, return the number itself</p>
<p>Unit tests are optional, but would be a plus.</p>
<p><strong>My Solution</strong></p>
<pre class="lang-java prettyprint-override"><code>public class FizzBuzz {
//a class *variable*, not a class
private static int counter;
//checking if a multiple of 3
private static boolean isFizz(int i) {
return i % 3 == 0; //no need for if
}
//checking if a multiple of 5
private static boolean isBuzz(int i) {
return i % 5 == 0; //no need for if
}
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
System.out.println(i);
if (i % 5 == 0 && i % 3 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0){
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
@Test public void testFizzBuzz(){
assertEquals("fizz", fizzBuzz(i == 3));
assertEquals("buzz", fizzBuzz(i == 5));
assertEquals("fizzbuzz", fizzBuzz(i == 15));
assertEquals("2", fizzBuzz(i == 2));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T11:24:53.917",
"Id": "508017",
"Score": "2",
"body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T16:34:30.407",
"Id": "508343",
"Score": "0",
"body": "What does your compiler show given above source code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T22:19:56.357",
"Id": "508468",
"Score": "0",
"body": "See my own answer below"
}
] |
[
{
"body": "<p>You don't use counter, isFizz() or isBuzz(), testFizzBuzz() calls to a fizzBuzz method which doesn't appear to exist. (Passing a boolean argument which seems illogical).</p>\n<p>Your code is formatted well, but the points above mean that a reviewer would doubt your competence.</p>\n<p>Have you shown us all your code? If not, why not?</p>\n<p>Did you compile, run and test your code? If not, why not?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T13:21:48.237",
"Id": "508043",
"Score": "0",
"body": "Have you shown us all your code? If not, why not?\nYes I have.\n\nDid you compile, run and test your code? If not, why not?\nYes I have and I confirmed that it fired correctly on my side."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T13:40:33.673",
"Id": "508047",
"Score": "2",
"body": "I don't like to accuse anyone of falsehoods, but that simply can't be the case - that code will not compile, for multiple reasons. Let's start at the first one that my IDE detected, that there is no variable 'i' to test in your test. If I fix that, there's no fizzBuzz(boolean) method.\nIf you don't understand why we're objecting to the code and why the hiring manager rejected it, you need to spend a lot more time learning Java.\nIf the code as presented did indeed compile and run, I think you must have a very strange toolchain!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:07:32.457",
"Id": "508053",
"Score": "0",
"body": "Yeah, seems to me like I have a very strange toolchain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T22:18:57.830",
"Id": "508467",
"Score": "0",
"body": "See my answer below."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T11:16:23.830",
"Id": "257230",
"ParentId": "257227",
"Score": "4"
}
},
{
"body": "<p>Super short review;</p>\n<ul>\n<li>Your code should be mostly in nicely named methods, not <code>main</code></li>\n<li>You call <code>System.out.println(i);</code> twice, which means you do not follow the fizzbuzz rules</li>\n<li><code>counter</code> is not used, and I am not sure it should have been declared <code>static</code></li>\n<li>Why write a test for <code>isFizz</code>/<code>isBuzz</code> and then never actually use them, this looks bizarre to an interviewer</li>\n</ul>\n<p>Also, FizzBuzz is a super common interview question. Do some googling, do some youtubing, you will learn a ton.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T22:12:02.137",
"Id": "508465",
"Score": "0",
"body": "Thanks for the \"well-mannered\" response. See my answer below."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T13:01:14.163",
"Id": "257240",
"ParentId": "257227",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T10:52:00.743",
"Id": "257227",
"Score": "2",
"Tags": [
"java",
"fizzbuzz"
],
"Title": "Fizzbuzz questions - job interview rejected"
}
|
257227
|
<p>In R, the function <strong>dpois</strong> (the poison distribution) can be used as <code>dpois(x,theta)</code> with both <code>x</code> and <code>theta</code> being vectors. However, in Rcpp, it can't be used like that. Can anyone suggest some function to replace the loop in the following <strong>dtpoi0</strong> function.</p>
<pre><code>#include <algorithm>
#include <RcppArmadillo.h>
using namespace Rcpp;
using namespace arma;
// [[Rcpp::depends("RcppArmadillo")]]
// [[Rcpp::export]]
imat misy(const ivec& x) {
const int s1 = std::min(x(0), x(1));
const int s2 = std::min(x(0), x(2));
const int s3 = std::min(x(1), x(2));
imat missy(3, 1, fill::zeros);
for (int i = 0; i <= s1; ++i) {
for (int j = 0; j <= s2 and i + j <= x(0); ++j) {
for (int k = 0; k <= s3 and i + k <= x(1) and j + k <= x(2); ++k) {
missy = join_rows(missy, ivec{i, j, k});
}
}
}
missy.shed_col(0);
return (missy);
}
// [[Rcpp::export]]
double dtpoi0(const ivec& x, const vec& theta) {
imat missy = misy(x);
double fvalue = 0.0;
missy.each_col([&](ivec& v) {
ivec u=join_cols(x - v(uvec{0, 0, 1}) - v(uvec{1, 2, 2}), v);
double prod = 1;
for (int i = 0; i < (int (u.n_elem)); ++i) {
prod *= R::dpois(u(i), theta(i), 0);
}
fvalue += prod;
});
return fvalue;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-07T08:28:58.607",
"Id": "511116",
"Score": "0",
"body": "There is no need to do that, as the act of compiling can sometimes \"vectorize\" for you, so it is seldomly advantageous to have vectorised variants of functions in C++."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T12:29:51.087",
"Id": "257237",
"Score": "0",
"Tags": [
"r",
"rcpp"
],
"Title": "Is there a way for Rcpp's dpois function where I can send a vector `theta` as param?"
}
|
257237
|
<h2>Context</h2>
<p>In an Angular application, I have three <code><select></code> boxes that are fed from the database with a relatively small data set. These boxes are part of a filter <code>Component</code> that is displayed next to a server-side data table. The component outputs the filter asynchronously to the parent component, which then pipes into the table, invokes server, filters out SQL etc.</p>
<p>Focusing on the scope, when the control is loaded, I want to invoke the server with three <code>GET</code> invocations. Until they complete, I want to display a spinner.</p>
<p>Since I am using a library of controls, part of the code is already done. I want to ask here if I am handling the <code>Observable</code>s correctly from the Angular point of view</p>
<h2>Code I wrote so far</h2>
<p>The code works</p>
<pre><code>export class MyComponent implements OnInit, OnDestroy {
public filterLoading$: BehaviorSubject<boolean>;
public select1: Observable<string[]>;
public select2: Observable<string[]>;
public select3: Observable<string[]>;
private filterLoadingSub$?: Subscription;
constructor(private remoteService: RemoteService) {
this.select1 = remoteService.getFirst();
this.select2 = remoteService.getSecond();
this.select3 = remoteService.getThird();
this.filterLoading$ = new BehaviorSubject<boolean>(true);
}
ngOnInit(): void {
this.filterLoadingSub$ = forkJoin([this.select1, this.select2, this.select3])
.subscribe(() => this.filterLoading$.next(false))
;
}
ngOnDestroy(): void {
if (!!this.filterLoadingSub$) {
this.filterLoadingSub$.unsubscribe();
}
}
}
</code></pre>
<p>Explanation:</p>
<ul>
<li><code>selectX</code> are bound to the front end with <code><option *ngFor="let x of (selectX | async)" ...></code></li>
<li>The subject <code>filterLoading$</code> is used to display the spinner. Actually my custom accordion handles it for me <code><acme-filter-panel isLoaded="!(filterLoading$ | async)></code></li>
<li>Then I used <code>forkJoin</code> operator to wait for the completion of all three calls. I don't care about the last returned valued, only that the three have completed. But this leads to a <code>Subscription</code></li>
<li>Under the philosophy of <em>dispose your own garbage</em>, every time I hit a <code>Subscription</code> I always write code to unsubscribe. However, these are just HTTP calls that return only once when invoked.</li>
</ul>
<p><strong>I truly understand that I am not handling error logic</strong>, but really that goes beyond the scope of the question</p>
<h2>Questions</h2>
<p>My question is about two aspects.</p>
<p>Apart from moving code from constructor to <code>ngOnInit</code>, on reasons of symmetry, am I writing too much code or is there some simplification I can use to say Angular to <em>unlock</em> the spinner when all of the three invocations occurred?</p>
<p>Is it always necessary to always unsubscribe from subscriptions? Or are there cases in which a <em>dangling</em> subscription harms none? I learned that subscriptions use memory, so I deem necessary to clean up resources whenever possible, even if modern machines have gigabytes of RAM.</p>
<p>More in general, is it possible to write this piece in a more concise way? For three data sets I had to instantiate a fourth member, which is actually needed to monitor the spinner, and a fifth member used only on destruction to clean up. I often work with Observables & co.</p>
|
[] |
[
{
"body": "<p>It is in theory not necessary to unsubscribe all subscriptions. For example if you call the backend with the Angular HttpClient then you will get an observable, that will automaticly complete after it emits the first result. As soon as it is completed, the observable is gone and does not strain your ressources anymore.<br />\nThat means, if the Observable will complete itself in a timely manner, then you do not have to unsubscribe.</p>\n<p>BUT: In most cases you have to dig a bit deeper to see that an observable will complete itself. That means the reader of your code will not easily know if you forgot the unsubscribe or if it could be skipped. Therefore i personaly decided for safety (but more code) and unsubscribe always.</p>\n<p>Not unsubscribing will result in unnecessary memory consumption and/or can create unexpected sideeffects. The function that should be executed at emits, is stored at the Subject. That means even when your component is long ago destroyed, the function will still "live" at the Subject. And will be executed at each emit...</p>\n<p>But you could make unsubscribing a bit nicer with a <code>Subscription</code> Object</p>\n<pre><code>private subscriptions: Subscription = new Subscription();\n...\nthis.subscriptions.add( myOberservable.subscribe(value => doMagic(value)) );\nthis.subscriptions.add( myOtherOberservable.subscribe(value => doMoreMagic(value)) );\n...\nthis.subscriptions.unsubribe() // will unsubscribe all added subscriptions at once\n</code></pre>\n<p>About the general question of implementing the spinner. If you always want a spinner, you could attach it in an interceptor, activating the spinner before the call is fired and deactivated as soon as you get a respond.<br />\nOr using a central method for backend calls and doing the the toggle there.<br />\nIn both cases you would need a spinner service that needs to remember how often it was "activated", so that if 3 calls are triggered at once, the first response does not deactivate the trigger.</p>\n<p>May ways are possible, it depends a bit on your use case and your general architecture.</p>\n<p>But your specific example i would write in the following way:</p>\n<pre><code>export class MyComponent implements OnInit, OnDestroy {\n\n private subscriptions: Subscription = new Subscription();\n private filterLoading$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(true);\n\n ngOnInit(){\n this.subscriptions.add(this.callAll().subscribe(() => this.toggleSpinner()));\n }\n\n ngOnDestroy(){\n this.subscriptions.unsubscribe();\n }\n \n private callAll():Observable[]{\n const listOfCalls: Observable[] = [\n remoteService.getFirst(),\n remoteService.getSecond(),\n remoteService.getThird(),\n ];\n return forkJoin(listOfCalls);\n }\n\n private toggleSpinner():void{\n this.filterLoading.next(false)\n }\n}\n</code></pre>\n<p>Its nearly the same way you used. Only a few changes.</p>\n<ol>\n<li>If there is no need to declare something public, then its private.</li>\n<li>I make use of the "Subscription" Object, even if in this example there is just one subscription to be stored. I try to be consisten with solutions. Also it makes it easier to extend the component when a second subscription is needed.</li>\n<li>I like to hide code behind methods. That way someone reads the methodname and then can decide if he/she is interested in the details or not.</li>\n</ol>\n<p>All in all its more code. But i think its easier to understand. And in my experience, code is read quite more often then writen. And "read" really means "reading and understanding". And thats an very expensive task. :-)</p>\n<p>As always, the solution totaly depends on the context. So, choose the things that suit you well and skip the rest. :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T10:28:33.200",
"Id": "508286",
"Score": "0",
"body": "You just triple-confirmed about how good of an idea is to write good, clean, easy to understand and maintainable code versus cheap code that *just works*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T10:30:12.917",
"Id": "508287",
"Score": "0",
"body": "It is also interesting to see that both a single `Observable` and an array of Observables (`Observable[]`) offer a subscribe method, which is probably what I was looking for in my very beginning. About *publicity* of some members, they have to be bound on the template, and if they are not public they are not accepted by the transpiler. I am working on Angular since just 2 months."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T13:06:36.743",
"Id": "508310",
"Score": "0",
"body": "(no... I suggested an edit because you used forkJoin correctly in callAll, which returns a single observable from an array of those)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T09:00:56.653",
"Id": "257332",
"ParentId": "257243",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257332",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T13:59:20.490",
"Id": "257243",
"Score": "0",
"Tags": [
"typescript",
"angular-2+",
"rxjs"
],
"Title": "Handling a spinner for multiple REST calls"
}
|
257243
|
<blockquote>
<p>Write a recursive version of the function <strong>reverse(s)</strong>, which reverses the string <strong>s</strong> in place.</p>
</blockquote>
<p>I'm studying K&R and wrote a code for the question.</p>
<pre><code>void reverse(char s[], int n) // The seconde argument should be always 1.
{ // The function should be always called as reverse(s, 1);
int temp;
int len;
len = strlen(s);
if ((len + 1) / 2 > n)
reverse(s, n + 1);
temp = s[n-1];
s[n-1] = s[(len - 1) - (n-1)];
s[(len - 1) - (n-1)] = temp;
}
</code></pre>
<p>The second argument <code>n</code> says reverse() is currently called at n-th times. The function works as if it sets an axis of symmetry at <code>s[(strlen(s) + 1) / 2]</code>(since integer division is truncated, it's not always symmetric by the axis but the function behaves as if truncation doesn't happen and it is exactly an symmetric axis) and accordingly change <code>s[n - 1]</code> with <code>s[(strlen(s) - 1) - (n - 1)]</code> and vice versa. The function stops its recursive call when the index of the axis is larger than n.<br/><br/>
I saw other solutions(<a href="https://github.com/anotherlin/tcpl/blob/master/chapter_4/exercise_4-13.c" rel="nofollow noreferrer">this</a> and <a href="https://codereview.stackexchange.com/questions/39891/recursive-reverse-function">this</a>). I think they used nice idea for the question. But I wonder how you think about mine. Thanks for reading!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T17:01:35.367",
"Id": "508345",
"Score": "1",
"body": "\"second argument n says reverse() is currently called at n-th times\" is unclear with the comment \"The seconde argument should be always 1\"."
}
] |
[
{
"body": "<p>To be honest, this is a bad way to solve the problem - recursion with <code>strlen()</code> is not a good idea. There was a recent discovery that Rockstar Games had their loading screens in GTA5 extended by several minutes due to their JSON parser calling <code>strlen()</code> on a string repeatedly.</p>\n<p>Instead, when handling strings in a recursive manner that requires knowledge of the length of the string, one should pass that length alongside the pointer.</p>\n<p>On the topic of length, you're storing the length of the string in a variable with type <code>int</code> rather than the <code>size_t</code> that <code>strlen()</code> returns. There are two problems with this - the first is that <code>int</code> is signed and <code>size_t</code> is unsigned, and the second is that <code>size_t</code> is often larger than <code>int</code>, especially with modern 64-bit systems defining the former as <code>uint64_t</code> and the latter as <code>int32_t</code>.</p>\n<p>Lastly, you could avoid a lot of mental overhead by using two pointers instead - one to the beginning of the string, and one to the end of the string. You would then stop the recursion when the beginning is no longer before the end.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T02:28:59.970",
"Id": "508141",
"Score": "0",
"body": "Thanks for explaining with many informative reasons and even with real world problem. By the way I don't understand your second paragraph. `one should pass that length alongside the pointer.` Did you mean I should use `strlen()` only once before the recursive function call and insert that return value into the actual parameter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T10:22:05.583",
"Id": "508185",
"Score": "2",
"body": "That sounds correct."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T18:20:54.553",
"Id": "257263",
"ParentId": "257247",
"Score": "4"
}
},
{
"body": "<p><strong>Bug: short string</strong></p>\n<p>Consider <code>reverse("", 1)</code>. Code attempts <code>s[-1]</code> which leads to <em>undefined behavior</em> (UB).</p>\n<pre><code>len = 0;\ns[(len - 1) - (1-1)] // UB\n</code></pre>\n<p><strong>Bug: long string</strong></p>\n<p>Pedantic: Code fails for <em>huge</em> strings longer than <code>INT_MAX</code>. Use <code>size_t</code>, not <code>int</code>.</p>\n<p><strong>Alternative</strong></p>\n<pre><code>// left points to left-most character\n// right points to right-most + 1 character\nstatic void rev(unsigned char *left, unsigned char *right) {\n if (left < right) {\n unsigned char temp = *--right;\n *right = *left;\n *left = temp; \n rev(left + 1, right);\n }\n}\n \nvoid reverse(char s[], int n) {\n rev(s, s + strlen(s));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T16:47:42.400",
"Id": "257355",
"ParentId": "257247",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257263",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:17:19.907",
"Id": "257247",
"Score": "0",
"Tags": [
"c",
"strings",
"recursion"
],
"Title": "A recursive function to reverse string"
}
|
257247
|
<p><strong>Note: This is my first post for a code review, so any feedback on what other info would be helpful to post (if any) would be much appreciated!</strong></p>
<p>React component: Social.js</p>
<p>The component has an input of 4 properties:</p>
<ul>
<li>dark: Boolean - if dark is supplied, the component renders white icons for contrast against a dark background</li>
<li>facebook: String - if facebook url is supplied, the component renders the facebook icon, else no icon at all</li>
<li>twitter: String - if twitter url is supplied, the component renders the twitter icon, else no icon at all</li>
<li>instagram: String - if instagram url is supplied, the component renders the instagram icon, else no icon at all</li>
</ul>
<p><strong>If only 1 social media url is supplied, the text "<em>Follow us on:</em> " is rendered along with the single icon</strong></p>
<pre><code>let count = 0;
function countProp (prop) {
if (prop !== undefined) {
if (prop.url !== ``) {
count++;
}
}
return prop;
}
const Social = props => {
count = 0;
let facebook = countProp(props.facebook);
let twitter = countProp(props.twitter);
let instagram = countProp(props.instagram);
return (
<>
<div className="social">
{ (count == 1) ? <span>Follow us on:</span> : `` }
{ (!props.dark) ?
( (facebook.url !== ``) ?
<a href={facebook.url}>
<img src="./assets/social/facebook.svg" alt="facebook"></img>
</a>
: null )
: ( (facebook.url !== ``) ?
<a href={facebook.url}>
<img src="./assets/social/facebook_white.svg" alt="facebook"></img>
</a>
: null ) }
{ (!props.dark) ?
( (twitter.url !== ``) ?
<a href={twitter.url}>
<img src="./assets/social/twitter.svg" alt="twitter"></img>
</a>
: null )
: ( (twitter.url !== ``) ?
<a href={twitter.url}>
<img src="./assets/social/twitter_white.svg" alt="twitter"></img>
</a>
: null ) }
{ (!props.dark) ?
( (instagram.url !== ``) ?
<a href={instagram.url}>
<img src="./assets/social/instagram.svg" alt="instagram"></img>
</a>
: null )
: ( (instagram.url !== ``) ?
<a href={instagram.url}>
<img src="./assets/social/instagram_white.svg" alt="instagram"></img>
</a>
: null ) }
</div>
<style type="text/css"> {
`
.social {
display: flex;
flex-wrap: wrap;
align-content: center;
justify-content: center;
}
.social img {
max-height: 25px;
margin: 0 15px;
}
`
}
</style>
</>
)};
export default Social;
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>consider using The strict equality operator (===) over the abstract equality operator (==) , see <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">== VS ===</a></p>\n</li>\n<li><p>avoid nested <code>if</code> blocks using <code>optional chaining</code> , it can get pretty messy if you have a lot of nested properties, it's a relatively new feature but you can always use <a href=\"https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining\" rel=\"nofollow noreferrer\">a babel plugin</a>.</p>\n</li>\n<li><p>consider a different aproach to styling ( i recommend <a href=\"https://styled-components.com/\" rel=\"nofollow noreferrer\">styled-components</a> ), adding styles like that would affect other components on the same page.</p>\n</li>\n<li><p>since the images urls' are hardcoded , use an object to toggle <code>dark mode</code></p>\n</li>\n<li><p>keep your code <a href=\"https://medium.com/jl-codes/dry-vs-wet-code-589c564aa5aa\" rel=\"nofollow noreferrer\">DRY</a> , you can use an Array of social media names and loop through it to display the icons</p>\n</li>\n<li><p>for counting the <code>props</code> , you could use <code>Object.keys</code> or if you have other props to pass along the social media icons, use <code>Array.filter</code> to check how many are there and grab the resulting array's <code>length</code></p>\n</li>\n</ul>\n<p>snippet of the end result :</p>\n<pre><code>import styeld from "styled-components";\n\nconst Wrapper = styled.div`\n .social {\n display: flex;\n flex-wrap: wrap;\n align-content: center;\n justify-content: center;\n }\n\n .social img {\n max-height: 25px;\n margin: 0 15px;\n }\n`;\n\nconst icons = {\n darkMode: {\n facebook: "facebook_white",\n twitter: "twitter_white",\n instagram: "instagram_white"\n },\n\n lightMode: {\n facebook: "facebook",\n twitter: "twitter",\n instagram: "instagram"\n }\n}\n\nconst options = ["facebook", "twitter", "imstagram"];\n\nconst Social = props => {\n // check for dark mode\n const mode = props.dark ? "darkMode" : "lightMode";\n\n // count social media icons \n const count = option.filter(option => props[option]?.url ? true : false).length();\n\n return (\n <Wrapper>\n <div className="social">\n {/* show the text if there's at least one social media is supplied */}\n {count > 1 ? <span>Follow us on:</span> : ``}\n\n {\n // loop through the social media array to display the ones available in props\n options.map(option => props[option]?.url \n ? <a href={props[option]?.url}>\n <img src={`./assets/social/${icons[mode].facebook}.svg`} alt={option} /> \n </a> \n : null)\n }\n\n </div>\n </Wrapper>\n\n )\n};\n\nexport default Social;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T19:10:31.557",
"Id": "257452",
"ParentId": "257248",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:22:54.210",
"Id": "257248",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "Dynamic social media component w/ dark mode"
}
|
257248
|
<p>I am trying to understand the best way to write this. This is part of my organization work so can't disclose it fully here like why such requirement. So Apologies for that.</p>
<p>I have <strong>ListA</strong> and <strong>ListB</strong>.</p>
<pre><code>val ListA: List[((String, String), Int)] = List(
(("A", "B"), 1),
(("C", "D"), 2),
(("E", "F"), 5),
(("E", "F"), 4),
(("E", "F"), 3)
)
val ListB: List[(String, String)] = List(
("A", "B"),
("E", "F")
)
</code></pre>
<p>We need to search id in <strong>ListA</strong> that contain <strong>ListB</strong> element. For example tuple ("A", "B") is present in ListA with (("A", "B"), 1), . so output would be <strong>List(1)</strong>. This process would repeat again once we fetch first match. if no match is found then <strong>List(0)</strong> would be output. Also both lists are sorted on priority. ListB drives the main priority and after that in case of repeating values the List A does it. And lists are already ordered.
I wrote this.</p>
<pre><code>val result = ((for {
a <- ListB
m <- ListA.filter(_._1 == a).map(_._2)
} yield m):::List(0)).slice(0,1)
</code></pre>
<p>slice is used because we need List with first match. as <strong>ListB</strong> is already sorted on priority. Also We are going to repeat this process again by removing already matched id from <strong>ListA</strong>. But for now please ignore like how we remove these elements and re-iterate.</p>
<p>So new iteration would be on</p>
<pre><code>val ListA: List[((String, String), Int)] = List(
// (("A", "B"), 1), This will not be part of second iteration as we already matched it in first iteration.
(("C", "D"), 2),
(("E", "F"), 5),
(("E", "F"), 4),
(("E", "F"), 3)
)
val ListB: List[(String, String)] = List(
("A", "B"),
("E", "F")
)
</code></pre>
<p><strong>Output of</strong></p>
<ul>
<li>iteration 1 is <strong>List(1)</strong></li>
<li>iteration 2 is <strong>List(5)</strong></li>
<li>iteration 3 is <strong>List(4)</strong></li>
<li>iteration 4 is <strong>List(3)</strong></li>
<li>iteration 5 is <strong>List(0)</strong></li>
</ul>
<p>I would just like to understand that</p>
<p>"Is it right way to code where we search one list element in another".</p>
<p>"Do we have some scala library that can be used here like ListA.filter(ListB.contains(_._1)) --> this needs us to write full filter case method so it wont work like this"</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T10:11:23.147",
"Id": "508184",
"Score": "0",
"body": "Welcome to CR! Could you explain the reasoning behind the exact way this filtering is supposed to work? I have a hard time seeing why an iterative solution is necessary at all. That's all why we require some _review context_. As it stands you're providing a very algorithmic explanation of the desired output, with no context as to why that's necessary. Readers might be able to suggest a better way of providing the desired, or an equivalent result, when they can actually know how the algorithm is going to be used in the end. If it's an exercise please provide the exact wording."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T13:59:50.460",
"Id": "508212",
"Score": "0",
"body": "ferada is correct. On this site, we review real, complete, working code. We don't discuss best practices and we don't review stubs or pseudo code (which is what this feels like to me). I guarantee that, as written, this question will get closed, and soon, if it is not brought up to standards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T09:38:13.973",
"Id": "508279",
"Score": "0",
"body": "Hey Ferada, the thing is its something related to my organization so I can't disclose use case. Requirements or the use case looks into multiple priorities as both lists are sorted on different level of preferences. I did it using (listB.flatMap(x=> listA.filter(_._1 == x).map(_._2)) :+ 0).head ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T11:05:36.810",
"Id": "508291",
"Score": "0",
"body": "Hey @Donald, I am really sorry if I I have asked question on wrong platform. I would definitely improve on this. I thought we can ask questions on best practices which is present in this reference document. I had gone through https://codereview.stackexchange.com/help/on-topic"
}
] |
[
{
"body": "<p>Apart from my comment, I'd suggest using <code>Set</code> for, well sets, since operations will likely be quicker, but more importantly, they're more correct wrt. what operations can be done on them.</p>\n<pre><code>val setB: Set[(String, String)] = ListB.toSet\n\nval filtered: List[((String, String), Int)] =\n ListA.filterNot(x => setB.contains(x._1))\n\nval result: List[Int] =\n filtered.map(_._2)\n</code></pre>\n<p><strong>This returns a different result.</strong> As I wrote in my comment I don't quite understand the reasoning behind the algorithm and if it's a real requirement that it's going to be iterative like this, you'll likely have to use the implementation you have right now, i.e. via <code>for</code>.</p>\n<p>Also splitting the computation into multiple steps might help with understanding what's going on (especially in a debugger), that's also why I copied over the type signatures as you did.</p>\n<del>\n*If the exact same output is desired*, that'd be this then:\n<pre><code>val result = ((for {\n m <- ListA.filter(x => setB.contains(x._1)).map(_._2)\n} yield m):::List(0)).slice(0,1)\n</code></pre>\n</del>\nNevermind, the same result requires to walk through the list as in the original post.\n<hr />\n<ul>\n<li>Also variables shouldn't start with an upper case, c.f. <code>setB</code> instead of <code>SetB</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T09:46:56.343",
"Id": "508281",
"Score": "0",
"body": "m <- ListA.filter(x => setB.contains(x._1)).map(_._2), Here if ListB is lets say ( (\"E\", \"F\"),(\"A\", \"B\")).. the answer would still be same but we want order to be taken care of. First priority to ListB and second priority to ListA in case of repeat values. Answer in this case should be like 5,4,3,1,0. I did it using (listB.flatMap(x=> listA.filter(._1 == x).map(._2)) :+ 0).head ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T09:54:35.790",
"Id": "508282",
"Score": "0",
"body": "I removed the last section. In that case I don't think there's anything to fix other than making the code less dense and introducing some better variable names."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T10:14:35.323",
"Id": "257294",
"ParentId": "257249",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:27:24.520",
"Id": "257249",
"Score": "0",
"Tags": [
"scala"
],
"Title": "filtering element of one List from another in Scala with different tuple structure"
}
|
257249
|
<p>I previously posted this question in Stack Overflow, but I was told to post it here as my code is already working and I'm just trying to optimize it. Background: I'm developing a Game Boy emulator, and because most of it is done, I'm currently trying to optimize everything as much as I can.</p>
<p>There's this operation the graphics processor does where it fetches 16 bits worth of graphics data (which encode a row of 8, 2bpp color pixels) to push into a queue.</p>
<p>The data is arranged in a low and high byte pattern, given a position, we mask and shift the corresponding bit in the low and high bytes equally to form a 2 bit number that represents a shade or color. (we also need to shift the high byte's corresponding bit left by 1 to make it the MSB)</p>
<p>The operation visually looks something like this:</p>
<pre><code>Given high = 0xff, low = 0x00
Let position = 0
high, low = 0b11111111 0b00000000
^ ^
+----------+-> n = 0b10
1 0
Let position = 1
high, low = 0b11111111 0b00000000
^ ^
+----------+-> n = 0b10
1 0
...
</code></pre>
<p>And the actual binary manip operation might look something like this</p>
<pre><code>n = ((low >> (7 - position)) & 1) | (((high >> (7 - position)) & 1) << 1)
</code></pre>
<p>Other than calculating <code>(7 - position)</code> once and storing it in a variable, there's not much room left for optimization.</p>
<p>I was wondering if there's some compiler intrinsic I could use, or if there's a more optimized way of doing this I'm not identifying. Take into account that the high and low bytes don't necessarily have to be in separate variables, they could just be a single 16-bit integer, I've seen similar operations in assembly/intrinsics such as <code>blend</code>, or packed integer operations.</p>
<p>Anyways, thanks in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:03:53.543",
"Id": "508113",
"Score": "0",
"body": "Welcome to the Code Review Community. The name code review is important, to optimize code we need to see the actual code. This question is off-topic on `Code Review` as well as `Stack Overflow` without the actual code to be reviewed. I sorry, but one line of hypothetical code doesn't give us anywhere near enough code to help you. If you could supply 3 or 4 functions or an entire class we might be able to help you optimize the code. Have you profiled the code to see where you are spending the most amount of time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:18:23.977",
"Id": "508115",
"Score": "0",
"body": "@pacmaninbw \"to optimize code we need to see the actual code\". We have a line of actual code?! Additionally the length of code is not a determiner for if something is on or off topic. [1](//codereview.meta.stackexchange.com/q/364) [2](//codereview.meta.stackexchange.com/q/466) [3](//codereview.meta.stackexchange.com/a/1588) [4](//codereview.meta.stackexchange.com/q/6649) The question would be better with more code, yes. But the question isn't off-topic, unless you've found some AoC rule I've never seen before."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:10:18.403",
"Id": "508123",
"Score": "1",
"body": "([interleave bits](https://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableObvious)?) `fetches 16 bits worth of graphics data (which encode a row of 8, 2bpp color pixels) to push into a queue` I'd like to see where this data comes from, and where it goes to - source code welcome. What is the requirement: Some bit pattern deep down in the bowels of the machine? Appropriate output from a colour table?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T07:29:49.577",
"Id": "508160",
"Score": "1",
"body": "When we have a description that says \"_might look something like this_\", there's an implication that we're not looking at the real code. What would be better would be to show a complete function; that would give a lot more context (the types of all the variables, for a start, and the accompanying comments). A _great_ question would also include the unit tests and the benchmark code. I'm pretty sure it would be possible to add the extra information without invalidating Emily's existing answer, and it would rescue this interesting problem from the risk of deletion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T07:35:54.640",
"Id": "508162",
"Score": "1",
"body": "Missing information (that we might know with more context): what's the access pattern for this function? Are we computing all eight results from the same byte pair before moving on to the next, or are we accessing the pairs in more random sequence?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T16:42:50.740",
"Id": "508344",
"Score": "0",
"body": "I used the phrase \"Might look something like this\" to imply that there might not be a single algorithm for this, nor my one is be the best, but that code there is pulled straight from my PPU code. (see [link](https://github.com/Lycoder/Geebly/blob/9a1bab06b586861337468eb9ecc31834ad099585/src/devices/ppu/fifo.hpp#L89))\nAlso, I don't think sharing documentation is \"on-topic\", as it would make this question more like homework other than a concrete question about an **specific** formula. Anyways, here's some info: [link](https://www.huderlem.com/demos/gameboy2bpp.html)"
}
] |
[
{
"body": "<p>At the risk of this question being closed as off topic, I find this problem interesting and will hazard an answer.</p>\n<p>I believe that the best answer here is simply a lookup table. You only have 16 bits of input domain, so you could make a LUT with 2^16 entries, each entry giving the 8 colours as output. This will cost you around 64-512 KByte of memory depending on how you encode the output. For an emulator this seems affordable even on low end systems. I would expect this to be at least 8 times faster than your code because you're getting all colours in parallel + you're not doing a bunch of bit arithmetic so I wouldn't be surprised if this was even faster than that. Ideally you've baked your active palette into the LUT (or prebaked LUTs for all palettes) so that the LUT provides direct RGB tuples that you can blit onto the screen without further massaging.</p>\n<p>If half a meg of RAM is too much (I don't know what you're running this on), you can swizzle the nibbles around so that you have the first byte with the first 4 pixels and the second byte with the last two pixels (e.g. turn 0xABCD into 0xAC, 0xBD). Then you can use a 256 entry LUT with 4 colour as output and run each swizzled byte through it separately. Conceivably this LUT would cost between 256 bytes or 1KB depending again on how you encode the output. Even with the swizzle, this should be faster than your original code as you're getting all the colours in parallel.</p>\n<p>Swizzle is relatively cheap:</p>\n<pre><code>Given two bytes A, B\n\nX = (A & 0xF0) | ((B & 0xF0) >> 4)\nY = ((A & 0x0F) << 4) | (B & 0x0F)\n</code></pre>\n<p>Note that even though you're still doing some binary ops, you're getting several pixels in parallel through the LUT.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T00:21:28.853",
"Id": "257276",
"ParentId": "257250",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "257276",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:32:04.867",
"Id": "257250",
"Score": "-1",
"Tags": [
"c++",
"performance"
],
"Title": "Optimizing a bit manipulation formula"
}
|
257250
|
<p>I am attempting to implement a converter which can convert two dimensional array (using Boost.MultiArray library) into <a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#Tables" rel="nofollow noreferrer">markdown table</a>.</p>
<p><strong>The experimental implementation</strong></p>
<pre><code>#include <boost/multi_array.hpp>
template<typename T>
concept is_multi_array = requires(T x) {
x.shape();
boost::multi_array(x);
};
class Converter
{
public:
enum Alignment
{
Default,
Left,
Center,
Right
};
template<is_multi_array T>
static auto to_markdown_table(const T& input, Alignment alignment = Alignment::Default)
{
// Retrieve row and column
int row_length = input.shape()[0];
int column_length = input.shape()[1];
std::vector<Alignment> alignments;
for (size_t i = 0; i < column_length; i++)
{
alignments.push_back(alignment);
}
return to_markdown_table(input, alignments);
}
template<is_multi_array T>
static auto to_markdown_table(const T& input, std::vector<Alignment> alignments)
{
std::list<std::string> output;
// Retrieve row and column
int row_length = input.shape()[0];
int column_length = input.shape()[1];
output.push_back(to_table_header(input));
output.push_back(to_table_cell_alignments(input, alignments));
for (size_t row = 1; row < row_length; row++)
{
output.push_back(to_table_row(input, row));
}
return output;
}
private:
const static char cell_separator = '|';
/// <summary>
/// Generate table header
/// </summary>
/// <param name="input">input two dimensional boost::multi_array</param>
/// <returns>The header row of table</returns>
template<is_multi_array T>
static auto to_table_header(const T& input)
{
return to_table_row(input, 0);
}
/// <summary>
/// Generate the row of cell alignments
/// </summary>
/// <param name="input">input two dimensional boost::multi_array</param>
/// <param name="alignments">alignment settings</param>
/// <returns>The alignment settings row of table</returns>
template<is_multi_array T>
static auto to_table_cell_alignments(const T& input, std::vector<Alignment> alignments)
{
std::string output(1, cell_separator);
// Retrieve row and column
int row_length = input.shape()[0];
int column_length = input.shape()[1];
for (size_t column = 0; column < column_length; column++)
{
switch (alignments[column])
{
case Converter::Default:
output += "-" + std::string(1, cell_separator);
break;
case Converter::Left:
output += ":-" + std::string(1, cell_separator);
break;
case Converter::Center:
output += ":-:" + std::string(1, cell_separator);
break;
case Converter::Right:
output += "-:" + std::string(1, cell_separator);
break;
default:
output += "-" + std::string(1, cell_separator);
break;
}
}
return output;
}
template<is_multi_array T>
static auto to_table_row(const T& input, const int row)
{
std::string output(1, cell_separator);
// Retrieve row and column
int row_length = input.shape()[0];
int column_length = input.shape()[1];
for (size_t column = 0; column < column_length; column++)
{
output += input[row][column] + std::string(1, cell_separator);
}
return output;
}
};
</code></pre>
<p><strong>Test cases</strong></p>
<pre><code>// Create a 2D array that is 3 x 4
typedef boost::multi_array<std::string, 2> array_type;
typedef array_type::index index;
int row = 10;
int column = 4;
array_type A(boost::extents[row][column]);
// Assign values to the elements
int values = 1;
for (index i = 0; i != row; ++i)
for (index j = 0; j != column; ++j)
A[i][j] = std::to_string(values++);
for (index i = 0; i != row; ++i)
{
for (index j = 0; j != column; ++j)
{
std::cout << A[i][j] << "\t";
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << "to_markdown_table function output" << std::endl;
for (auto& element : Converter::to_markdown_table(A, Converter::Alignment::Center))
{
std::cout << element << std::endl;
}
</code></pre>
<p>The output of the above tests:</p>
<pre><code>1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
25 26 27 28
29 30 31 32
33 34 35 36
37 38 39 40
to_markdown_table function output
|1|2|3|4|
|:-:|:-:|:-:|:-:|
|5|6|7|8|
|9|10|11|12|
|13|14|15|16|
|17|18|19|20|
|21|22|23|24|
|25|26|27|28|
|29|30|31|32|
|33|34|35|36|
|37|38|39|40|
</code></pre>
<p><a href="https://godbolt.org/z/vrahd8" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>If there is any possible improvement, please let me know.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T15:46:11.983",
"Id": "257253",
"Score": "0",
"Tags": [
"c++",
"strings",
"array",
"boost",
"c++20"
],
"Title": "Boost.MultiArray Based Two Dimensional Array to Markdown Table Converter Implementation in C++"
}
|
257253
|
<p>I have a piece of bash code that works fine.</p>
<pre><code>for thing in "$things"; do
output=$(my_program "$thing" 2>&1)
if [[ $? -eq 0 ]]; then
echo "$(echo "$output" | tail -1)"
else
echo "$(echo "$output" | tail -1)" 1>&2
fi
done
</code></pre>
<p>The idea is to echo the last line of the output from the subcommand to stdout if it worked and to stderr if it didn't work.</p>
<p>Is there a better way to achieve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T13:21:33.427",
"Id": "508509",
"Score": "0",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
}
] |
[
{
"body": "<p>Don't quote <code>$things</code>:</p>\n<pre><code>for i in "1 2 3 4"; do\n echo "i=$i"\ndone\ni=1 2 3 4\n# Better is\nfor i in 1 2 3 4; do\n echo "i=$i"\ndone\ni=1\ni=2\ni=3\ni=4\n</code></pre>\n<p>When <code>my_program</code> is written well, errors are written to stderr and normal output to stdout. Your bash code is working well, so the program already uses the right returncode.<br />\nCan you change the <code>my_program</code>? When you can add an option <code>-s</code> (silent/summary), the program can make sure only 1 line is written to stdout (when OK) or stderr (when NOK):</p>\n<pre><code>for thing in ${things}; do\n my_program -s "${thing}"\ndone\n</code></pre>\n<p>Or without for-loop</p>\n<pre><code>printf "%s\\n" ${things} | xargs -L1 -I{} my_program -s "{}"\n</code></pre>\n<p>When you can't change <code>my_program</code>, or you don't want to, move the special handling to a function and remove the additional <code>echo</code> commands:</p>\n<pre><code>tail_my_program() {\n output=$(my_program $* 2>&1)\n if (( $? == 0 )); then\n tail -1 <<< "${output}"\n else\n tail -1 <<< "${output}" >&2\n fi\n}\n\nfor thing in ${things}; do\n tail_my_program "${thing}"\ndone\n</code></pre>\n<p>Your original solution and my function have a small bug: When <code>my_program</code> writes something to stdout after writing an error message to stderr, the stdout message is selected after an <code>exit 1</code>. This might never happen.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T11:39:22.110",
"Id": "257436",
"ParentId": "257255",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T16:05:20.487",
"Id": "257255",
"Score": "0",
"Tags": [
"bash"
],
"Title": "Tail program output to stdout or stderr"
}
|
257255
|
<p>I'm new to C++ and decided to implement a simple program that checks if a string is a pangram (i.e. the string contains all the English alphabet letters). It's my first program in C++ and I have some background with interpreted programming languages like Python and R.</p>
<p>I want to know what are the common beginners mistakes I'm making in this implementation, whether I'm following good practices, what I should avoid etc.</p>
<h2>The Code</h2>
<pre><code>#include<iostream>
#include<string>
#include<vector>
#include <algorithm>
bool isPangram(std::string str) {
std::transform(str.begin(), str.end(), str.begin(), ::toupper); // Transforming a string to upper case
std::vector<bool> hash_table(26, false); // a hash_table that maps the index of a letter from the alphabet
// and a boolean saying if the string contains this element
int index;
for(auto c: str){
if(isalpha(c))
// Checks if the element in the string is in the alphabet
index = c - 'A';
hash_table[index] = true;
std::cout << index << std::endl;
};
if(std::any_of(hash_table.begin(), hash_table.end(), [](bool v) { return !v; })) {
// if any of the items in the array evaluates to false
// means that the string don't contain all the elements
// in the alphabet,hence, it's not a pangram
return false;
}
return true;
};
int main() {
std::string str = "We promptly judged antique ivory buckles for the next prize";
if (isPangram(str)){
std::cout << "Yes" << std::endl;
}
else {
std::cout << "No" << std::endl;
};
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T16:59:51.907",
"Id": "508072",
"Score": "17",
"body": "For a beginner, it's amazing I'm not seeing the most-most common mistakes of: No STL; C as C++; `using namespace std;`; You even have an appropriate use of `std::vector<bool>`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:46:10.983",
"Id": "508128",
"Score": "0",
"body": "@Casey, thank you! I went after some C++ good practices before implementing this code, but, i knew that i wouldn't get everything right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:27:08.330",
"Id": "508166",
"Score": "1",
"body": "@Casey: Arguably, for a table that's known to only need 26 elements, it would be worth the 26 bytes for a `vector<char>` instead of 26/8 bytes to hold 0 / 1 values for a present/absent status. So although `vector<bool>` is the obvious choice for a container here, the requirement that it be specialized as a bit-vector (https://isocpp.org/blog/2012/11/on-vectorbool) is actually *not* ideal for this use-case. Also given the small fixed size, `std::array<bool, 26>` would be good here. (For a beginner's first C++ program, though, this is more than fine, and not \"wrong\" per-se.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:34:08.460",
"Id": "508167",
"Score": "0",
"body": "@PeterCordes Yeah, hence \"Appropriate\", I personally would have used a `std::bitset` as it is a known length and fixed length. I would go as far to say a `uint32` and bit-twiddling would have been a considerable alternative. But only in rare cases where performance was warranted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:56:59.267",
"Id": "508175",
"Score": "0",
"body": "@Casey: yeah, bitset is decent, although for long strings, [setting a bit could be more expensive than a cached store to an array index](https://codereview.stackexchange.com/questions/257256/#comment508170_257262). (Depending on how smart your compiler is, e.g. using x86 `bts dst, src` to implement `dst |= 1<<src` or doing it manually.) Unfortunately standard library `isalpha ` and `toupper` aren't fast enough for the data dependency to probably matter, but the overall throughput cost can matter. And for short strings being very fast to clear initially and check at the end is great. :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T09:09:08.787",
"Id": "508177",
"Score": "0",
"body": "@Casey: Out of curiosity, GCC -O3 codegen for AArch64 is pretty nice https://godbolt.org/z/1v9KP1 (after fixing the `if(){}` braces and moving toupper into the loop after isalpha), but neither toupper nor isalpha inline. (For ASCII it's super cheap to turn a char into a 0..25 index into the alphabet, or detect that it's non-alphabetic, with OR + SUB and a compare/branch. [What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa?](//stackoverflow.com/a/54585515), but ASCII isn't the only 8-bit charset, although non-UTF8 8-bit charsets are less and less relevant)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T21:32:32.390",
"Id": "508251",
"Score": "2",
"body": "The `isalpha()` may check the local which opens it up to a lot of other characters not in the English language. Thus you may get letters that our outside `'A' -> 'Z'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T23:17:24.520",
"Id": "508375",
"Score": "0",
"body": "@Casey `using namespace std` just turns C++ into a more human language in which you can just use the darn words without `simon says std::`. The usability advantage of `using namespace std` outweighs the theoretical problems, like your program clashing with future versions of the library that introduce more identifiers. Worrying about the distant future is a fool's errand; you can whack name clash moles on the head as they pop up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T10:02:52.217",
"Id": "508405",
"Score": "0",
"body": "Actually some compilers do through an error if the main function has a return type but no return statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T14:51:30.977",
"Id": "508428",
"Score": "0",
"body": "@Kaz> I have seen so many real bugs in real applications coming from this \"theoritical\" problem, that I just see your comment as misguided (and no, name clashes do not always pop up, they can also change the behavior of your program without even generating a warning). If you want the convenience, you can name types explicitly with `using std::string;`"
}
] |
[
{
"body": "<ul>\n<li><p>The sequence</p>\n<pre><code> if (condition) {\n return false;\n }\n return true;\n</code></pre>\n<p>is a long way to say</p>\n<pre><code> return !condition;\n</code></pre>\n</li>\n<li><p><code>std::all_of</code> seems more natural than <code>std::any_of</code>, which implies double negation.</p>\n</li>\n<li><p><code>std::toupper</code> is declared in <code><cctype></code>. Make sure to explicitly <code>#include</code> it.</p>\n</li>\n<li><p>In programming, <code>hash_table</code> has very special meaning. I strongly recommend to rename it to <code>present</code> or something like that.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:51:16.747",
"Id": "508132",
"Score": "0",
"body": "Thank you, @vnp, I've thought about using `std::all_of` but for me it seemed that `std::any_of`` was the more efficient way, i did not knew that any_of implied a double negation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T09:15:23.437",
"Id": "508178",
"Score": "1",
"body": "Strictly speaking this *is* a hash table, with the identity function as a hash and a hard-coded load factor of 1. But it's still not a good name since it doesn't convey useful information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T16:56:10.820",
"Id": "257258",
"ParentId": "257256",
"Score": "10"
}
},
{
"body": "<p>Here are a number of things that may help you improve your program.</p>\n<h2>Make sure you have all required <code>#include</code>s</h2>\n<p>The code uses <code>toupper</code> but doesn't <code>#include <cctype></code>.</p>\n<h2>Eliminate spurious semicolons</h2>\n<p>The code has a number of spurious semicolons immediately after closing braces. They don't bother the compiler but they will bother any other programmer who looks at your code.</p>\n<h2>Check your <code>if</code> statements for proper braces</h2>\n<p>It appears from the indentation in the <code>if</code> statement in the <code>isPangram</code> routine is not what you intended to write. The only thing that is currently associated with the <code>if</code> statement is <code>index = c - 'A';</code> -- all of the lines after that are executed in every case.</p>\n<h2>Initialize variables before use</h2>\n<p>The <code>index</code> variable, as mentioned above, may or may not actually get initialized to anything as it's currently written. That leads to <em>undefined behavior</em> of your program, which is not a good thing. Best practice is to initialize variables when they are declared.</p>\n<h2>Return <code>boolean</code> values directly</h2>\n<p>The <code>isPangram</code> ends with this strange construct:</p>\n<pre><code>if(std::any_of(hash_table.begin(), hash_table.end(), [](bool v) { return !v; })) {\n return false;\n}\nreturn true;\n</code></pre>\n<p>Here's a much more direct way to do that:</p>\n<pre><code>return std::all_of(hash_table.begin(), hash_table.end(), [](bool v){return v;});\n</code></pre>\n<p>Similarly, within <code>main</code>, I'd write this:</p>\n<pre><code>std::cout << (isPangram(str) ? "Yes" : "No" ) << '\\n';\n</code></pre>\n<h2>Consider a more efficient approach</h2>\n<p>Consider that the the <code>transform</code> must necessarily visit every letter. We then make another pass through with the main loop. It is possible to do everything in a single pass.</p>\n<h2>Don't use std::endl unless you really need to flush the stream</h2>\n<p>The difference between <code>std::endl</code> and <code>'\\n'</code> is that <code>std::endl</code> actually flushes the stream. This can be a costly operation in terms of processing time, so it's best to get in the habit of only using it when flushing the stream is actually required. It's not for this code.</p>\n<h2>Eliminate <code>return 0</code> at the end of main</h2>\n<p>When a C++ program reaches the end of <code>main</code> the compiler will automatically generate code to return 0, so it is not necessary to explicitly write that. Some people prefer to do so for style reasons, but it's important to know that it's not required by the standard.</p>\n<h2>Consider using <s><code>std::span</code></s><code>std::accumulate</code></h2>\n<p>If your compiler is C++20 capable, this would be a good use of <code>std::accumulate</code> (not <code>std::span</code> as I originally wrote). This version is faster than <a href=\"https://quick-bench.com/q/-B7bLMm24sikZyGigsmdW8Qdsik\" rel=\"nofollow noreferrer\">anything so far</a>.</p>\n<pre><code>// helper function for isPangram_accum\nconstexpr uint_fast32_t charToMask(const unsigned char c){ \n // can't use non-const toupper in constexpr function\n unsigned index{(c | 0x20u) - 'a'};\n return index < 26 ? ~(1u << index) : ~0;\n}\n\nbool isPangram_accum(const std::string& str) {\n uint_fast32_t present{(1u << 26) - 1};\n constexpr auto letterMask = [](uint_fast32_t collection, char ch) {\n if (collection)\n collection &= charToMask(ch);\n return collection;\n };\n return std::accumulate(str.begin(), str.end(), present, letterMask) == 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:56:00.077",
"Id": "508082",
"Score": "0",
"body": "`std::isalpha` also requires `<cctype>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:57:03.187",
"Id": "508083",
"Score": "1",
"body": "Perhaps `std::string_view` would be more appropriate than `std::span`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T18:39:52.573",
"Id": "508087",
"Score": "0",
"body": "Just for S&Gs I implemented your more efficient suggestion: The `std::string` declaration, the `std::vector<bool>` declaration, an optional-for-readability lambda declaration, a call to `std::transform`, a call to `std::all_of`. Done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:47:43.997",
"Id": "508129",
"Score": "0",
"body": "Hey @Edward! Thank you for your contribuition i'll have a look at span and those annoying semicolons and all the other things you've pointed out!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T11:47:13.857",
"Id": "508294",
"Score": "0",
"body": "Wouldn't you want `charToMask` to return `~0` aka `-1` for the non-letter case, to leave all the bits set when you `&` together all the masks? I would have maybe used `|` to combine `1UL << index`, especially since you called it \"present\", although your way does have the advantage of making an early-out on `present == 0` even more efficient on many CPUs. Note that `1U` isn't guaranteed to be a 32-bit type, so `1U << 16` or more could overflow on implementations with 16-bit int."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T11:51:11.303",
"Id": "508296",
"Score": "0",
"body": "I would have used `uint32_t` because many compilers / C libraries, including unfortunately x86-64 glibc, [unwisely](https://stackoverflow.com/questions/36961100/how-should-the-uint-fastn-t-types-be-defined-for-x86-64-with-or-without-the-x) make `uint_fast32_t` a 64-bit type, which as I mentioned in my answer will make auto-vectorization worse. Speaking of which, out-of-range chars could be mapped to a different bit-position (like 0 or 26) instead of to not changing the bitmap. \n That could let smart compilers use a saturating subtract instead of a compare/AND."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T13:12:14.383",
"Id": "508313",
"Score": "0",
"body": "@PeterCordes: good point on returning `~0`. That was a bug I've now fixed. Thanks also for your other useful points and comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T13:27:45.640",
"Id": "508318",
"Score": "0",
"body": "You're still missing portability to implementations where int is 16-bit. Use `~(1UL << index : ~0UL` to fix that, and in the initializer. (Or like in my answer, explicit casts to the exact type you want, like `uint32_t(1) << index`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T19:35:16.233",
"Id": "508357",
"Score": "0",
"body": "Would using a simple table-lookup not work better? Just change that one function: `constexpr auto charToMask(unsigned char c) noexcept { constexpr auto table= []{ std::array<unsigned char, 1u + (unsigned char)-1> r; for (unsigned i = 0; i < r.size(); ++i) r[i] = std::min<unsigned>((c | 0x20) - 'a', 26); return r; }(); return 1 << table[c]; }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T07:56:42.643",
"Id": "508397",
"Score": "0",
"body": "The 2nd and 3rd point can be combined together: Use a linter or formatter to ensure consistent coding style / convention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T18:48:18.850",
"Id": "508452",
"Score": "0",
"body": "@Deduplicator: not really; and the bit-shift can actually auto-vectorize (see my answer) but a LUT would defeat that. If compilers do a good job, `1UL<<index` is pretty cheap, even with clamping. Also, you'd need to keep that LUT somewhere, or initialize it every time you use it. Maybe it could give a minor speedup for long strings, if the pure bit-manipulation is a bit slower, but it would make startup overhead worse."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T19:42:51.227",
"Id": "508453",
"Score": "0",
"body": "@PeterCordes You know the LUT is a compile-time constant? And stashing 256 byte somewhere should not be such a burden. Whether one lookup (byte for a byte) versus bitwise-or + subtract + clamp is a bargain, or auto-vectorizing steals the show, I don't know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T19:55:29.663",
"Id": "508456",
"Score": "0",
"body": "@Deduplicator: Yeah, but the first access might miss in cache. Or actually, GCC decides to write `table` to the stack before using it, since it's in automatic storage. Even at -O2 or -O3 https://godbolt.org/z/qWh6zz (init from mov-immediate or copy from .rodata respectively). But C++ doesn't let us make it `static` in that scope. (We could make it file-scope.) Also, if you're optimizing for x86, might want to have the table hold `unsigned` `1<<idx` constants to allow memory-source OR, instead of load + BTS. (Or worse, legacy `shl reg,cl` 3 uops on Intel, then an OR. GCC10 does use BTS.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T20:03:21.080",
"Id": "508457",
"Score": "0",
"body": "(Only some of the elements will be \"hot\", but yeah with that many elements probably uint8_t shift counts would be better than uint32_t masks. I was forgetting the point of the LUT was to avoid range-checking. Still questionable whether it's worth doing; only for really large strings, and when you can't get the pangram check to vectorize.)"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:07:49.623",
"Id": "257259",
"ParentId": "257256",
"Score": "18"
}
},
{
"body": "<p>There's a problem hidden here:</p>\n<blockquote>\n<pre><code>std::transform(str.begin(), str.end(), str.begin(), ::toupper);\n</code></pre>\n</blockquote>\n<p>The problem is quite subtle (more subtle the missing include of <code><cctype></code> or misspelling of <code>std::toupper</code>). It's that <code>std::toupper()</code> accepts a positive <code>int</code>, and plain <code>char</code> may be signed or unsigned.</p>\n<p>Promoting signed <code>char</code> to <code>int</code> may result in a negative value, but we need a positive value, usually achieved by converting to <code>unsigned char</code> and allowing that to promote to a (positive) int.</p>\n<p>For a safe version, we have to write</p>\n<pre><code>std::transform(str.begin(), str.end(), str.begin(),\n [](unsigned char c) { return std::toupper(c); });\n</code></pre>\n<p>Similarly, we need to replace</p>\n<blockquote>\n<pre><code>for(auto c: str){\n if(isalpha(c))\n</code></pre>\n</blockquote>\n<p>with</p>\n<pre><code>for (unsigned char c: str) {\n if (std::isalpha(c))\n</code></pre>\n<hr />\n<p>Another portability bug lurks here:</p>\n<blockquote>\n<pre><code> if(isalpha(c))\n // Checks if the element in the string is in the alphabet\n index = c - 'A';\n</code></pre>\n</blockquote>\n<p>There's no guarantee that the host character set contains all upper-case letters in any particular sequence. Of particular note, on EBCDIC systems, <code>'Z'-'A'</code> is significantly more than 25 (it's 37 if I remember correctly), and we'll write outside the bounds of <code>hash_table</code>.</p>\n<p>For portable code, we need to change how we store the values - perhaps use a bitset of length <code>UCHAR_MAX</code>, or perhaps a <code>std::set</code>. Then test whether there are any <code>std::isalpha()</code> characters not present.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:56:22.487",
"Id": "508133",
"Score": "0",
"body": "Thank you ! That is a really subtle problem, i need to study more on the data structures/tpyes that c++ provides. as close friend said to me: \"C++ gives you enough rope to hang yourself\" you need to know how to use the language correctly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:35:54.883",
"Id": "508168",
"Score": "1",
"body": "I was curious what exactly would happen with negative args to `std::toupper`. According to https://en.cppreference.com/w/cpp/string/byte/toupper, *If the value of ch is not representable as `unsigned char` and does not equal EOF, the behavior is undefined.*. So a value sign-extended to a negative `int` would indeed cause UB. A plausible implementation of toupper (on a system with 8-bit char) could be using the `int` to index a 257-char lookup table, with the `[-1]` index having something for EOF=-1. More-negative indices could even go off into an unmapped earlier page."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:46:52.040",
"Id": "257261",
"ParentId": "257256",
"Score": "8"
}
},
{
"body": "<p>This is good use of the standard library, and the code is quite good for a beginner.</p>\n<p>The main thing that sticks out to me (aside from the points mentioned in the other answers) is that you are passing the input string to your function by value, which creates an unnecessary copy of the string for a function that should just need to read the string and return a boolean. Normally, such a function would accept its argument as a <code>const</code> reference, but the call to <code>std::transform</code> prevents this (at least, the <code>const</code> part of it). The call to <code>std::transform</code> isn't really needed anyway (and results in another, unnecessary loop through each letter), since you can call <code>toupper</code> in your <code>for</code> loop.</p>\n<p>I would also suggest using a <code>std::unordered_set<std::string::value_type></code> instead of a <code>std::vector<bool></code>. This will allow you to call <code>std::unordered_set::insert()</code> in your <code>for</code> loop, which only adds the letter if it isn't already in the <code>std::unordered_set</code>. Then, instead of calling <code>std::any_of</code> at the end (a loop through possibly all 26 elements of the <code>std::vector<bool></code>) you can call the constant-time <code>std::unordered_set::size()</code> to determine if the set contains all 26 letters.</p>\n<p>Here's how it would look:</p>\n<pre><code>bool isPangram(const std::string& str) {\n std::unordered_set<std::string::value_type> hash_table;\n\n for (auto c : str) {\n if (isalpha(c)) {\n hash_table.insert(::toupper(c));\n };\n };\n\n return hash_table.size() == 26;\n};\n</code></pre>\n<p>Finally, if you do use your original code it would be best to use the proper type for <code>index</code>: not <code>int</code>, but the <code>size_type</code> of the container your are indexing (i.e. <code>std::vector<bool>::size_type</code> for your original container).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:59:49.080",
"Id": "508084",
"Score": "2",
"body": "`std::vector<bool>` often trips people up because despite its name, **`std::vector<bool>` is not a standard container**, having a subtly different interface, and performance issues, too. Although counter-intuitive, `std::vector<char>` is almost always a better choice for storing booleans."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:05:42.440",
"Id": "508114",
"Score": "5",
"body": "Using a `std::unordered_set` here is very inefficient. The `vector<bool>` is better, but best would be a `std::bitset<26>`, and then you can call [`std::bitset::all()`](https://en.cppreference.com/w/cpp/utility/bitset/all_any_none) to check if all letters of the alphabet are present."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T00:02:22.767",
"Id": "508134",
"Score": "0",
"body": "Hey @Null, thanks for your contribuition. I've seen some people using pointers to iterate through things in C++, that's really new to me and i've seem some posts in SO about using pointers just when you really need them. Do you think it would be more useful passing a string pointer sas argument to the `isPangram` function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:00:02.613",
"Id": "508165",
"Score": "0",
"body": "@TobySpeight `std::vector<bool>` is often faster in my testing. See https://codereview.stackexchange.com/q/117880/39848"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:41:45.360",
"Id": "508170",
"Score": "0",
"body": "@Edward: Yup, `vector<bool>` has is place, and that place is for large data sets, like a prime sieve or something. For *this* case, `std::bitset<32>` could be good to enable quick checking (setting is only quick on systems that have something like x86's `bts reg, reg` to implement `reg |= 1<<reg` efficiently), or `std::array<char, 26>` (where memory indexing makes setting cheap, without any data dependency between elements. i.e. setting an `A` doesn't have to wait for a store to `arr['B'-'A']` to complete.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:44:09.367",
"Id": "508171",
"Score": "0",
"body": "On some non-x86 microarchitectures, even `std:array<int,26>` could be better, more likely to allow higher throughput commit to L1d cache from the store buffer without needing an internal RMW cycle in the L1d cache to modify a byte in a word if the store buffer couldn't merge multiple writes to the same word into one commit. [Are there any modern CPUs where a cached byte store is actually slower than a word store?](https://stackoverflow.com/q/54217528)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:49:20.750",
"Id": "508172",
"Score": "0",
"body": "Modern x86 CPUs have byte granularity for cache writes so `char` would definitely be best, to make checking all 26 bytes cheaper. (One or two SIMD loads to get all the data back. Probably pad to `array<char,32>` so the compiler can check all 32 bytes for non-zero with one AVX1 `vptest ymm` (maybe after setting `array[26..31]` to one? hmm, non-trivial to handle the padding), or SSE2 maybe two overlapping 16-byte loads that span the whole 26 bytes, ANDing them together, then check that they're all non-zero. Anyway, storing a `1` is cheap, esp on ISAs with indexed addressing modes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:50:48.987",
"Id": "508173",
"Score": "0",
"body": "\"instead of calling `std::any_of` at the end (a loop through possibly all 26 elements of the `std::vector<bool>`) you can call the constant-time\"… technically O(26)=O(1) "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T08:51:57.173",
"Id": "508174",
"Score": "1",
"body": "Edward and @TobySpeight: forgot to link Howard Hinnant's comments on when a bit-vector is useful - https://isocpp.org/blog/2012/11/on-vectorbool. He agrees that `vector<bool>` was a poor choice of name for it, but it has its uses, and a standard library with good specializations for it can go fast checking or counting many bits at once for stuff like `std::find`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T11:52:45.910",
"Id": "508196",
"Score": "1",
"body": "@Occhima A `const` reference for the argument makes a little more sense than a pointer in this case, but a pointer would be better than passing by value since it also would avoid the unnecessary string copy. For discussions about pointers vs. references see [Pointer vs. Reference](https://stackoverflow.com/q/114180/3964927) and [When to use references vs. pointers](https://stackoverflow.com/q/7058339/3964927)."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:49:16.113",
"Id": "257262",
"ParentId": "257256",
"Score": "3"
}
},
{
"body": "<p>Note that your entire strategy of assuming 26 alphabetic upper-case characters, and that they're between 'A' and 'Z', breaks if there are any high-8-bit accented characters in a non-UTF-8 8-bit character set. So the locale-aware <code>toupper</code> and <code>isalpha</code> are just slower for probably no benefit.</p>\n<p>Several comments have discussed using a "better" data structure for your set of seen letters, because <a href=\"https://en.cppreference.com/w/cpp/container/vector_bool\" rel=\"nofollow noreferrer\"><code>std::vector<bool></code> is unfortunately required</a> to be specialized as a bit-vector. (Good data structure for some things, especially <em>large</em> bitsets, bad choice of name to expose it in ISO C++, as <a href=\"https://isocpp.org/blog/2012/11/on-vectorbool\" rel=\"nofollow noreferrer\">Howard Hinnant argues</a>). For this use-case of only 26 elements, it's slower than necessary.</p>\n<p>The two good choices here for efficiency (and clean concise code) are:</p>\n<ul>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/utility/bitset\" rel=\"nofollow noreferrer\"><code>std::bitset<26></code></a> - very cheap to init and check (and convenient with <code>bitset.all()</code>), relatively cheap to update on most ISAs. (Better than <code>std::vector<bool></code> because the template can specialize itself for the known size being <= one unsigned long or whatever chunk size the library uses. So the compiler will have an easier time being sure it can just keep one integer in a register and OR bits into it.)</p>\n<p>std::bitset is so cheap to check, literally just an integer compare for a small bitset (smaller than the bitness of the machine you're compiling for, which is usually at least 32 these days), you could even consider an early-out check every iteration if you expect very long strings where all 26 letters appear far before the end of the string. (Maybe unroll by 4 so you check every 4 chars).</p>\n<p>With an ASCII-only replacement for isalpha and toupper, some compilers (e.g. clang and ICC) can even auto-vectorize the bit shift / OR, effectively checking 2 to 4 characters in parallel for only somewhat more than the cost of one. (Or even 8 characters in parallel if you replace std::bitset with <code>uint32_t</code> to avoid the silly compiler widening to 64-bit integer elements. Or even 16 with AVX-512)</p>\n</li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array<bool,26></code></a> - Unlike <code>vector<char></code>, no dynamic allocation required (it doesn't indirect to separately allocated storage: the object <em>is</em> the array, which is totally fine for a small fixed size like 26). Less cheap than bitset to init and check (especially if the compiler doesn't do a smart job), but even cheaper to update for each char of the string, especially on CPUs like modern x86 where a byte store is extremely cheap, <a href=\"https://stackoverflow.com/questions/54217528/are-there-any-modern-cpus-where-a-cached-byte-store-is-actually-slower-than-a-wo\">not even an internal word-RMW when committing to L1d cache</a>, although non-x86 CPUs will often do more store coalescing in their store buffer making byte stores still fairly cheap, and likely not a bottleneck unless you <em>seriously</em> optimize the isalpha and toupper checks. (It will hit in cache every time because the array is tiny).</p>\n<p>In theory a smart compiler could check for all 26 byte elements of being set fairly efficiently, with two partially-overlapping SIMD 16-byte loads and a SIMD AND (then on x86 for example, pcmpeqb against 0 / pmovmskb to check for any elements that matched a zero). But in practice GCC is dumb and fully unrolls 1 byte at a time compare/branching.</p>\n</li>\n</ul>\n<h2>The clean portable way, not optimizing for ASCII-only</h2>\n<p>Still only using narrow <code>char</code>, though, not <code>wchar_t</code> and not using UTF-8 aware stuff. non-UTF8 charsets other than ASCII are increasingly rare these days.</p>\n<p>Probably a good idea to just use <code>toupper(c) - 'A'</code> and manually check if that's unsigned <code><= 25</code>, instead of using isalpha: on a POSIX system for example, if LOCALE or LC_ALL aren't <code>"C"</code> (the POSIX locale, pure ASCII), <code>isalpha</code> can also return true for allow accented characters whose upper-case codepoint is also outside the 'A'..'Z' range. For example in a locale like ISO-8859-1 or probably also Windows-1252, somewhere from 0x80 to 0xff.</p>\n<pre><code>bool isPangram(const std::string &str) // note: const-ref arg\n{\n static_assert('Z'-'A' == 25, "we assume a charset where letters are contiguous");\n std::bitset<26> present(false);\n //std::array<bool, 26> present = {0};\n\n for(unsigned char c: str){ // note: unsigned char instead of auto to work around legacy C unsigned-char value range in int arg requirements\n if(isalpha(c)) { // FIXME: isalpha can return true for high-8-bit c\n auto index = toupper(c) - 'A';\n present[index] = true; \n // std::cout << index << '\\n';\n }\n }\n\n return present.all(); // nice semantic meaning of "all present"\n //return std::all_of(present.begin(), present.end(), [](bool v){return v;});\n};\n</code></pre>\n<p>(Compiles and runs, with complete <code>#include<></code> list and an improved main, <a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tQVvQAZPLUwA5YwCNMxEAFYAnKQAOqBYXW0eoYmgj5%2BanRWNvZGTi4eisqYqgEMBMzEBEHGppyJKhG0aRkEUXaOziAAzAAciumZ2SF5Cg2l1uWxlbUAlIqoBsTIHADkUlXWyIZY4lU66q3EmMxGs9jiAAwAguOT05izOovWwGubWwD0F7u0UwYzcwBuyUTEZ9s3d1gA1IcOhEoCO8dpIJrd9r85hliMwAJ7Az4Qw5sYAkQgIVZVdYfUF7e6YSE6AxqViEeFY86I/GE5CqWFeA4Uj7bByofTfPAKAAKImAMKMEDQtFa31a6BAIGOol%2BkgAbIsepSAOyybbfdWi9JqZAAfWYCiUmQgYBGAC0TQBaE1bE2QgAiszt30krlIMskAHcCfqFMZvd9kAgMoDvh6EM4CewCARnApvhkCUK1MADAMFFJJIqqqqthrNeKQP8CIDDnK1t8vEslPRqGwlFmc3mrmKJdC4X82aw3WWsRWq1oCPbfiqNuIlQ7s5S1RqaMQIAZhXhgDZ0AGg8QAyBNcRFSq8xqrt9aKgY1uF35l5hV4GMhzhTHmKvUFR48TUN8iKGSABrePEAbaN87DAMwyCwt8OjfOeS4rhaN4bo8bAGASMKiAS1h3oOGTAN8SwAI4GHgSxGAO6bTvuHJUBAnJsF4QaCj0PTDo2FH7swb53lgAAeQ5EAYXgMnOyBMRa3zWiaszSAeFzfPOi6XugPR8QJzgMd8ol%2BAAXpgOoEMaIw2iMTEcnGCiksACAEKw4FGCQBKYFQVB4MgeADt8s5/jC4HWNxJzfHQ3xcTUspug4xIBqgRheHg7Bxh6JBKO5JDfEWIYeui3wAOI6Do5ysfulaYNWQKuNIPmYFx4iuE6jofsQyGSb85H5d8h4tigAyDochycRVhI9RJrg6LQEmTs1eZjg6zWTVOuYaksBCDLQfZFQOAB0bCsBADbSUezkEkoRgiNq3wkSIfnPu6m0rcVGZ5dJC1LfmrasKwOrPhAhXFWtTjANY21ul963mADvylVVdoQKy7KPLu0iPcQy2PJJk0NsqE45uch4I8KHLoFxbqIaS6BreqeAvkTeDoG6VM8Zyd5g9IGxrWtLoQ%2Bc1ikjY6rtV4zBEYc0EKWuGSkNDrDlvqLl4DqUYxsQtNyReK6YQGiofCq93qm1BAK6o1nfFsDA6AAkibboAFTHgQFv%2BQQ4YbjUFpFiLxCAgoa1a61Mn2wSaJ/bQbDfPg6AjSMg7xcQv4eQAqgAKgAYhaNSnQYrBqM7sIxvGtIDlerugfLcYiLCHpwqF4XHrQFrxwnKdOy78Hu5qMWsN8FWckCzVCyr8FASwiW1RISo6BsXGSKOY1zeqPf533tFBjqtNDqwA8EqJJrMKNUnazJzOs64SUbgvzBONqpPfAA6q3oYwl4R8F6osYpcoqAemJIxbyMbrJafqDPM6Q%2BHlywmk0hJZqONmInyXvjN08ZWB0WYDAni3UqhOlnugfSYCRhWk/iaXcGN0azUPOxIgFpniqDRNpOKGUpi8gvlsQC6V7aGwAGoAA1JBujrO%2BbKkERCrhNjlT22xDzfDjuGSi21vjPDdgEYOqAioyOcOBWg%2B0DbMIQGw9hFpXCcC4SlcKaAooxWfugd8kdEqaPVOLfqcwjznFsZyHkoh%2BR6gUNLHUxjorsGIFQBW5hrKCjoCKdqUocJSHlLrdWOxNbNWbAQAsqVMBAjmD2bAN0By1lYPWFG3drAECqJIXSKVCBHXvrVSeO9vbxkeKgKm3xZTcGdoQUU746HSlIagchLwqFKM0Z1UMVMtB%2BT5iKIpLSCAiJ2M1WcSsYJz3XJubccMvZ5i6XjFBaD4weLwDLOWzhFbCTydPfcVxyayVpmtJQQpFK7Q6ThGSQj%2BFvh6cgduzxlrWN9pRNZGoxwsRat7IG9AqplXxmtJybsSo1W2brBqU8gW71FAgcmg4ZIAHkABK/kXzMG%2BBsHZ8YjzdNQPfDyVcLQnzPs5EyL9ozOA/EGZaXhiRqE6RBAAshi1h/llo/OQArbUQc%2Bb2z%2BRRMRAj26BwcLFLKOUPzvi6W814eBtLcMHOwfUEcMpbA4ZIB%2BiEFan3YBaBQqKqBd1OflIs5Thy5W2YRegRTdLUQhTcugdzUGQSuVC1ojUamcBjhYOxkEvxp1XE4RpzSXZSqOt%2Bb0ryKGqs0swQoX43aYGmflGa01xyzTzO1ZJqSdDpMyfQIctrmBeBOXmSBIKpmbW2gGw8VaKloNqhAINIbvXOllCJb4nATkzSnrNApp1%2Ba0GkQCr2YTdZ%2BUWEODMl8CSVkil4Ky4E%2BD3GAPnY6eACLoTqcQcCYVkDfjlR5H5NguKDkrGqg4khJABpqfCg4zV2poHCr26i3JeT8ggAqSECd3RvqqsNDM3wtwZioHWA4Q1aAZh2mcmS1sOBHkwB6Lm6FwT4lXBhcJZFTmLtqki90K6%2Bzrs3d8bd6Bd2rn3Yewx57L3JWvRVO9CttJ3WzC1Q8sGcnvuI4kiUX6upzB6r%2BlxfIViAeicB0D9V4MQafVB90AmlDgcQ0%2BtGECUlPSqUQ5kIIJgviwE5FcEAdQ6iCrKazTExy5RHsHByHRMHWdszqJp9msY%2B1RXGemYY03ysghbc1AxWDoFtlG8xflrHtTbLCGm95lhPhfPbYLCt8DIDTmmdyadrIWgXP%2BV6%2BcHBZ29FhD8eASIBiihcPgtJKS4lwz8Q4NWjAFIVrQNaCBgS2MDMkb8Opjw6m0v%2BBQwT7zPRAIljs%2BhuyynLJE6EDm4mnOs0YfRNQ8AyM4EOHURgjCy1QI%2BAwOo/DbagEKEUm3tt4Atg5uUq2X0ofckREUnBZQpQq0RvMd3JA7ZkQa2qh3jusFO%2Bgc7l3AfXZCYOAHO3HsyllNCMFcoLRfYhjtQ8whPvfc%2BiUPAQd/7OGEF4GJeZHj7dB0dvU2gLt4Cu9TwmmZa0ampwdunyAoqYDwjqTA0UagQBZ98MHF2UnjdQIzq7jEX2HkpVLyi8ZaCnoqxOggg2GPfCl17SBYAwDi9ss8I6ChhuC7wML6nunYlTRM%2BYcmRkhAgBGK4b%2BpgRgbG/qgF3uUZByDaYMYYMoqicG/gQF3XvGKkHDI%2BSoANvxuFlGtVwrhZR6KVJwJUNQNhKlcBsDYrpWAu%2B4N/IwXAC%2BkA9170gPuRjfwUCADYpAI%2Be6d3AWAMBEAdRMb48glBvGmJcA8zgnANh5CcunWMlAHCR%2B/v8QOJ6Xdh9IMYki9AMW0GsnP0gWAjqiHYDv/ASwUjPEb230gFVkjElGDXgpygd%2BkgcDCE9egsDL/DwrcvIww99BoPQJgNgDgHgfgEALhYQUQFAOQOQIQPABwRvSAPoMlQoc/C0DFKodSMUR0CQf3GQLPdSI6IYPrNBIMBQL0V6Agg0TAbgdSKgY8IrWgErVgC0CHMlBQBvJIFIDQCAcwJoXIS/bQMoGIOIUIXwfwOgPg0Q8IAIIQioFwFoTgwoYoRofQHIQQJQAoVINoWQroeQ%2BoEoSQlobQjoYQyoTgPoBQAYIYYAvoYvV3d3HfOvWzC0JpAMCAnCUfNaZmfbCAXAQgZKcYPICCddIfEPTMCCaAmQcPOfaPWPLAFwBPEAbgKoNabgZI7gGoQHSQTgdwF0Z3EYUvUgcvJUJUNaHI7gPPSQEo7gdwJUCopUKvRwl3BvJvFvGI0gDvbvTqVlAgfvYJXvSoLhK8fwvQ//RgFgQ/EAj0O%2BD/Wwl3N3Roi/OvcYA1axZw1wh5QdTgLwso6ItvWI1LePOYgosvMAyQNaHPVwSQCop9fPF0J9EKavb3ZoxQVo1vKPPoRPZI1I9IzIzInIvIuwqoBwpYl494oyY4yQEEmvOvPYj40gWRPwDQbgIAA%3D%3D%3D\" rel=\"nofollow noreferrer\">on the Godbolt compiler explorer</a>. Along with some experiments for pure-ASCII, and a manually-vectorized function with SSE2 intrinsics to check a <code>std::array<bool,26></code> for being all non-zero. Clang's bitmap update is clever for x86-64: With EAX holding the <code>toupper</code> return value: <code>dec al</code> / <code>bts r15, rax</code>. <code>'A'</code> is ASCII 65, and the <a href=\"https://www.felixcloutier.com/x86/bts\" rel=\"nofollow noreferrer\"><code>bts</code> instruction</a> (bit test-and-set, like <code>dst |= 1<<src</code>) with a reg destination masks the bit-index by <code>&63</code>, like <code>%64</code>, so <code>c-'A'</code> is equivalent to <code>c-1</code> as a shift count in x86 asm. I don't know why clang thinks using a partial register, AL, is a good idea. Other compilers do worse.)</p>\n<p>This also shows other improvements mentioned in other answers:</p>\n<ul>\n<li><p><code>const std::string &</code> by-reference arg, which we <em>don't</em> modify. Instead we do <code>toupper</code> inside the loop, and only for alphabetic characters. If you're used to Python, "applying" something to a whole list can be faster than looping manually, but that's because of Python interpreter overhead, where you want to get into a compiled C loop in the Python interpreter. C++ always compiles to native machine code, so you can mostly loop as fast as any <code>std::</code> template function can. (In theory template functions could use tricks like manual SIMD vectorization, but in practice that's unlikely. However, C library functions like <code>memcmp</code> or <code>strchr</code> <em>are</em> often hand-written in asm, so that's one case where you have fast building blocks that you can't replicate with portable C++, only with intrinsics like x86 <code>_mm_cmpeq_epi8</code> to do 16 byte-compares in parallel.)</p>\n</li>\n<li><p><code>unsigned char</code> because <code>toupper</code> and <code>isalpha</code> expect their arg in an <code>int</code> (because those functions date back to early C before function prototypes even existed). But they expect the character code to have the value-range of <code>unsigned char</code>. Perhaps a good way to remember this is to imagine that they're implemented by using the <code>int</code> arg as an index into a table of character attributes for the current locale (which is actually true on many libc implementations), so a negative <code>int</code> from sign-extending a signed <code>char</code> would be a problem. That won't happen if your characters are purely ASCII; those are always positive-valued <code>char</code>s, but in general don't assume that. On many ABIs (including the mainstream x86 ones), <code>char</code> is signed. (Fun fact: ARM C/C++ implementations use unsigned <code>char</code>, so your code wouldn't have this problem there.)</p>\n</li>\n<li><p><code>{}</code> after the inner <code>if()</code> so the if also controls <em>using</em> the index. I also moved the declaration of <code>index</code> into that scope because there's no need for it outside.</p>\n</li>\n<li><p>static_assert to check that 'Z'-'A' == 25. Non-ASCII / non-UTF-8 character sets are possible in portable C++, but actually making your code slower because of the possibility isn't something you always want to do. But if possible, you can avoid silent failure there.</p>\n</li>\n</ul>\n<h2>ASCII-only</h2>\n<p>Neither of <code>isalpha</code> and <code>toupper</code> will inline, with gcc / glibc / libstdc++. That's normal; non-ASCII locales may have accented characters. But just for fun since we're not handling modern UTF-8 anyway, lets see how fast we can go for ASCII. And because the whole strategy of 26 slots revolves around plain ASCII, not accented upper-case characters.</p>\n<p>It only takes a couple operations to check it for being alphabetic, by turning it into an index into the alphabet and checking if that's in the 0..25 range (<a href=\"https://stackoverflow.com/questions/54536362/what-is-the-idea-behind-32-that-converts-lowercase-letters-to-upper-and-vice/54585515#54585515\">see this SO answer: set the lower-case bit, then one sub / unsigned compare as a range check</a>). In our case, we actually want that index, so this is perfect. Turns out the check can even auto-vectorize decently, especially with AVX2, allowing compilers to check multiple characters at once. (You can still see asm for the scalar version in a clean-up loop after the vectorized version.)</p>\n<p>(Instead of benchmarking, I actually just wanted to look at the asm; turns out clang has some neat tricks up its sleeve and without AVX2 for variable-shift with a per-element shift count, it adds a value into the exponent of a float <code>1.0</code> and does float->int conversion to get a per-element <code>1<<idx</code>, I think. Other compilers just give up and use scalar. Clang also seems to be doing an integer multiply as part of the vectorization, and I don't know what that's about. Haven't fully reverse engineered how it vectorized, and IDK whether it's a real speedup :P)</p>\n<pre><code>// I also tried unsigned int for most of these; compilers widen sooner for that\n// clang isn't usefully getting more work done before widening, but GCC might be\n\n// returns idx, valid. if valid, idx is in [0..25]\ninline std::pair<unsigned char,bool> ascii_letteridx(unsigned int c)\n{\n // strictly ASCII, *not* other 8-bit charsets.\n // the original didn't work for UTF-8 multi-byte accented characters anyway, but non-UTF8 8-bit charsets still exist\n unsigned char lcase = c|0x20;\n unsigned char alpha_idx = lcase - 'a'; // 0..25 for alphabetic. Will wrap for characters below 'a', or above 25 for > 'z'\n return {alpha_idx, alpha_idx <= unsigned('z'-'a')};\n}\n\n\n// auto-vectorizes with clang. And with AVX2, also GCC and ICC.\n// The if() version does very nicely with AVX-512, but compilers do worse with bool << n\nbool isPangram_ascii_compilerfriendly(const std::string &str)\n{\n //std::bitset<26> present(false);\n uint32_t bitmap = 0; // avoid 64-bit so clang auto-vectorizes without widening past 32-bit.\n\n for(unsigned char c: str){\n auto idx = ascii_letteridx(c);\n //if (idx.second) // clang / ICC auto-vec even with the if\n {\n //present[idx.first] = true;\n // shift / OR of a 0 as a no-op for non-alphabetic is better than putting a CMOV on the critical path\n // and enables GCC to auto-vectorize, at least with AVX2 for variable-shift\n bitmap |= uint32_t(idx.second) << idx.first; // 1UL << would be 64-bit and make auto-vectorization worse.\n }\n }\n\n std::bitset<26> present = bitmap;\n return present.all(); // bitmap == (1UL << 26) - 1;\n};\n</code></pre>\n<p>These comments are <em>not</em> a recommendation for how to write code, just leftover notes after looking at how it compiles with gcc, clang, and ICC, for various x86 targets (e.g. <code>-march=sandybridge</code>, <code>-march=haswell</code> (includes AVX2), <code>-march=skylake-avx512</code>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T15:23:05.400",
"Id": "508217",
"Score": "0",
"body": "A [quick benchmark](https://quick-bench.com/q/hepHGb8DTsomvxWrEvuDLayGC-4) shows that compared to the original, the `bitset` version is 18 million times faster and the `vector<bool>` equivalent is 1400 times faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T15:31:41.397",
"Id": "508218",
"Score": "0",
"body": "@Edward: That smells fishy, like constant-propagation after inlining for the compile-time constant string. But on your link, I'm seeing `BM_isPangram3` (bitset) as 1.9x faster than `BM_isPangram2` (`vector<bool>` with toupper inside the loop, manual isalpha. Oh, good point, `isalpha` would return true for high-8-bit accented chars in 8-bit charsets! So this whole strategy is only safe for ASCII anyway.) And 570x faster than `BM_isPangram1` (`vector<bool>` with fully original method). I'd believe 2x for startup / check overhead, and 570x is somewhat plausible, oh you left in printing!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T15:40:58.943",
"Id": "508222",
"Score": "0",
"body": "Yes, I left in printing from the original. If we remove it (making all routines more similar) we the `bitset` version is 17,000 times faster and the `vector<bool>` version is 1.4 times faster. Note, too, that I have used a longer test string that actually contains two pangrams."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T15:41:22.137",
"Id": "508223",
"Score": "0",
"body": "@Edward: oh, and according to the QuickBench assembly output after I removed printing from pangram1 (https://quick-bench.com/q/umLvnM-7VzOkmjJA7CMLEmAFBBw), BM_isPangram3 spent all its time in an empty loop, adding `-1` (0xfff...fff) to RBX). You need some Benchmark::DoNotOptimize in there to consume the result and defeat CSE across iterations, because `isPangram3` can inline into it. (The other 2 didn't inline and so actually got called, so another option would just be to put `__attribute__((noinline, noclone))` on pangram3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T15:50:29.427",
"Id": "508224",
"Score": "0",
"body": "@Edward: here's a valid version, where the bitset work isn't optimized away or hoisted out of the loop `bitset` 2.3x faster than #2 `vector<bool>`: https://quick-bench.com/q/3qu88BxW3Un0YU7_wTO7TN6gjIk I had to use `benchmark::DoNotOptimize(result);` in the BM_ loop to make sure it actually called it every time. (I also made the functions `noinline`, which is kind of the opposite of what we want for the perf record output from the asm dump: better to have them inline into the loop.) I guess there's no way to pass `-march=native` or whatever on QuickBench :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T16:02:31.300",
"Id": "508225",
"Score": "1",
"body": "Also interesting is that LLVM's `libc++` also gives a performance boost over GNU's `libstdc++`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T16:05:16.770",
"Id": "508226",
"Score": "0",
"body": "@Edward: Oh yeah, I had meant to try libc++, it's often more compiler-friendly (or at least clang-friendly). I see it's a lot faster for bitset (like 172ms vs. 645ms or whatever units), and also about twice as fast for vector<bool>. So the relative advantage of bitset increases, as well as being a lot faster in an absolute sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-19T17:11:20.923",
"Id": "508444",
"Score": "1",
"body": "Instead of returning a char/bool pair, wouldn't returning `min(tolower(x)-'a',26)` be faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-16T11:14:02.333",
"Id": "519391",
"Score": "0",
"body": "@HagenvonEitzen: Yeah that's another possibility, doing a `cmp` / `cmov` on the index-into-alphabet. That would let compilers use `bts` to implement `bitmap |= uint32_t(1) << idx;`, instead of manual shift and OR. Or with SIMD, unsigned min is a single instruction in SSE4.1 / AVX: [`pminud`](https://www.felixcloutier.com/x86/pminud:pminuq)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T13:57:58.277",
"Id": "257300",
"ParentId": "257256",
"Score": "4"
}
},
{
"body": "<p>Another comment says "Initialize variables before use".\nI would turn that around and say something like:</p>\n<p><strong>Avoid declaring a variable without initialization</strong></p>\n<p>The problem occurs in:</p>\n<pre><code>int index; // Could change to index=0;\nfor(auto c: str){\n if(isalpha(c))\n // Checks if the element in the string is in the alphabet\n index = c - 'A';\n hash_table[index] = true; \n std::cout << index << std::endl;\n\n};\n</code></pre>\n<p>But the solution isn't to initialize index with 0 (or -1), but to move the declaration until you can initialize it as follows:</p>\n<pre><code>for(auto c: str){\n if(isalpha(c))\n // Checks if the element in the string is in the alphabet\n const int index = c - 'A';\n hash_table[index] = true; \n std::cout << index << std::endl;\n\n};\n</code></pre>\n<p>The reason for moving the declaration is that <code>index</code> will have a smaller scope so it is easier to keep track of (for programmers) - and by making it <code>const</code> you don't have to check if it is changed anywhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T13:02:34.317",
"Id": "257340",
"ParentId": "257256",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "257259",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T16:21:06.263",
"Id": "257256",
"Score": "18",
"Tags": [
"c++",
"strings"
],
"Title": "A C++ program to check if a string is a pangram"
}
|
257256
|
<p>I just got started coding in Java and I just made my first project. I was wondering if someone would review my code and show me the things I can improve in it. I am eager to learn and would appreciate any advice.</p>
<p>Here is the code:</p>
<pre><code>package snake.app;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import javax.swing.JPanel;
public class Main {
public static void main(String[] args) {
new GameFrame();
}
}
import javax.swing.JFrame;
public class GameFrame extends JFrame{
public GameFrame() {
this.add(new GamePanel());
this.setTitle("Snake");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(true);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
public class GamePanel extends JPanel implements ActionListener{
public enum Direction {
Right,
Left,
Up,
Down
}
static final int screenWidth = 600;
static final int screenHeight = 600;
static final int unitSize = 25;
static final int gameUnits = (screenWidth * screenHeight) / unitSize;
static final int delay = 75;
private boolean running = true;
private Snake snake;
private Apple apple;
private Timer timer;
private Random random;
public GamePanel() {
timer = new Timer(delay, this);
timer.start();
random = new Random();
this.setPreferredSize(new Dimension(screenWidth, screenHeight));
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addKeyListener(new Adapter());
startGame();
}
public void startGame() {
running = true;
snake = new Snake();
apple = new Apple();
}
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkCollisions();
}
repaint();
}
public void move() {
for (int i = snake.length; i > 0; i--) {
snake.XPositions[i] = snake.XPositions[i - 1];
snake.YPositions[i] = snake.YPositions[i - 1];
}
switch(snake.direction) {
case Right:
snake.XPositions[0] += unitSize;
break;
case Left:
snake.XPositions[0] -= unitSize;
break;
case Up:
snake.YPositions[0] -= unitSize;
break;
case Down:
snake.YPositions[0] += unitSize;
break;
}
}
public void checkCollisions() {
checkBodyCollision();
checkWallCollision();
checkAppleCollision();
}
private void checkBodyCollision() {
for (int i = 0; i < snake.length; i++) {
for (int j = 0; i < snake.length; i++) {
if (snake.XPositions[i] == snake.XPositions[j] && snake.YPositions[i] == snake.YPositions[j]) {
if (i != j) {
running = false;
}
}
}
}
}
private void checkWallCollision() {
if (snake.XPositions[0] > screenWidth) {
running = false;
} else if (snake.XPositions[0] < 0) {
running = false;
} else if (snake.YPositions[0] > screenHeight) {
running = false;
} else if (snake.YPositions[0] < 0) {
running = false;
}
}
public void checkAppleCollision() {
for (int i = 0; i < snake.length; i++) {
if (snake.XPositions[i] == apple.XPosition && snake.YPositions[i] == apple.YPosition) {
apple = new Apple();
snake.length++;
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
drawGrid(g);
drawSnake(g);
drawApple(g);
}
private void drawGrid(Graphics g) {
for (int i = 0; i < screenHeight / unitSize; i++) {
g.drawLine(i * unitSize, 0, i * unitSize, screenHeight);
g.drawLine(0, i * unitSize, screenWidth, i * unitSize);
}
}
private void drawSnake(Graphics g) {
g.setColor(Color.GREEN);
for (int i = 0; i < snake.length; i++) {
g.fillRect(snake.XPositions[i], snake.YPositions[i], unitSize, unitSize);
}
}
private void drawApple(Graphics g) {
g.setColor(Color.RED);
g.fillRect(apple.XPosition, apple.YPosition, unitSize, unitSize);
}
public class Apple {
public int XPosition;
public int YPosition;
public Apple() {
XPosition = random.nextInt((int)(screenWidth / unitSize)) * unitSize;
YPosition = random.nextInt((int)(screenHeight / unitSize)) * unitSize;
}
}
public class Snake {
private final int startXPosition = (int) (gameUnits / 2);
private final int startYPosition = (int) (gameUnits / 2);
private final int[] XPositions = new int[gameUnits];
private final int[] YPositions = new int[gameUnits];
private int length = 10;
private Direction direction;
public Snake() {
createRandomDirection();
createBodyPartPositions();
}
private void createRandomDirection() {
int i = 1;
switch (i) {
case 1:
direction = Direction.Right;
break;
case 2:
direction = Direction.Left;
break;
case 3:
direction = Direction.Up;
break;
case 4:
direction = Direction.Down;
break;
}
}
private void createBodyPartPositions() {
if (direction == Direction.Right) {
for (int i = this.length; i > 0; i--) {
XPositions[i] = ((startXPosition + i) * unitSize);
}
} else if (direction == Direction.Left) {
for (int i = 0; i < this.length; i++) {
XPositions[i] = ((startXPosition - i) * unitSize);
}
} else if (direction == Direction.Up) {
for (int i = this.length; i > 0; i--) {
YPositions[i] = ((startYPosition + i) * unitSize);
}
} else if (direction == Direction.Down) {
for (int i = 0; i < this.length; i++) {
YPositions[i] = ((startYPosition - i) * unitSize);
}
}
}
}
public class Adapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_RIGHT:
if (snake.direction != GamePanel.Direction.Left) {
snake.direction = GamePanel.Direction.Right;
}
break;
case KeyEvent.VK_LEFT:
if (snake.direction != GamePanel.Direction.Right) {
snake.direction = GamePanel.Direction.Left;
}
break;
case KeyEvent.VK_UP:
if (snake.direction != GamePanel.Direction.Down) {
snake.direction = GamePanel.Direction.Up;
}
break;
case KeyEvent.VK_DOWN:
if (snake.direction != GamePanel.Direction.Up) {
snake.direction = GamePanel.Direction.Down;
}
break;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This is very readable. I noticed you had a XKCD random number generator there...</p>\n<pre><code>int i = 1;\n</code></pre>\n<p>I'm aware that the time signal is not related to keypress timings (e.g. you might make a direction change but not actually move for up to 75ms). In principle I guess you can tap the arrow keys and not move the snake if you do it quick enough, is that right? Also the amount you move for e.g. a 200ms keypress is actually a bit random depending on how it interacts with the timer.</p>\n<p>If your snake speed needed to be lower than 75ms the delays and discontinuities this might be noticeable in the gameplay.</p>\n<p>I'd be edgy about a class called Adapter when even the subclass has more information in its name. Maybe DirectionAdapter?</p>\n<p>Your use of the <code>running</code> value as a substitute for return values in various functions was a surprise compared to calling them and responding to the result. won't give you a lot of options for control flow.</p>\n<p>Apples can appear under the snake and score instant points which seems a shame.</p>\n<p>You have clearly structured and thought about your approach and it's a great start!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:37:02.787",
"Id": "257265",
"ParentId": "257260",
"Score": "4"
}
},
{
"body": "<p>Beside all hints that you might gather from PMD, Findbugs and Checkstyle?</p>\n<p>I would suggest to review the design. The inheritance of GamePanel is</p>\n<blockquote>\n<p>GamePanel extends JPanel implements ActionListener</p>\n</blockquote>\n<p>whearat inheritance is meant to be used for something that "is" something, and fields are used to use for something that "has" something.</p>\n<p>From design I would expect that the GamePanel <em>have</em> a ActionListener but I would not expect the GamePanel to <em>be</em> a ActionListener.</p>\n<hr />\n<blockquote>\n<p>public class Adapter extends KeyAdapter</p>\n</blockquote>\n<p>I support what cefn says about the classname. I am always happy if the Classname describe itself, like self-explained-classnames or speaking-classnames. Well <code>Adapter</code> is speaking but ambiguous, I would love to see a more specific speaking-classname.</p>\n<hr />\n<pre><code>private void checkWallCollision() {\n if (snake.XPositions[0] > screenWidth) {\n running = false;\n</code></pre>\n<p>Since your class is non-final you allow inheritance and might be able to override basic behaviour. The you better use <code>setRunning(false);</code> to be able to override this basic state-information.</p>\n<hr />\n<blockquote>\n<p>random = new Random();</p>\n</blockquote>\n<p>Well you might get trouble by a Gambling Authority. You might better use:</p>\n<blockquote>\n<p>random = new SecureRandom();</p>\n</blockquote>\n<hr />\n<p><code>GamePanel.move();</code> have code that should be part of the Snake-Object. Because currently the game moves the snake, this is unusual from the point-of-view of the mother nature. Mother nature would mention that snakes are able to (and usually) move themselves, sure, limited by the environmental situation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T19:52:24.997",
"Id": "257454",
"ParentId": "257260",
"Score": "1"
}
},
{
"body": "<p>Just one additional aspect not yet mentioned by the other answers so far.</p>\n<p>Don't use wildcard imports as in</p>\n<pre><code>import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n</code></pre>\n<p>They look so convenient, but there's a risk. Why? It creates possible ambiguities that you can't control.</p>\n<p>Imagine that e.g. in Java20 a new class <code>javax.swing.KeyAdapter</code> gets introduced. Then writing the symbol <code>KeyAdapter</code> no longer clearly denotes the java.awt.event.KeyAdapter class, but might as well refer to the new class <code>javax.swing.KeyAdapter</code>, probably breaking your program. And you can't know now what gets added into future Java versions.</p>\n<p>If you explicitly import exactly the classes you want to use, that problem will never arise. And decent IDEs (e.g. Eclipse) can manage all the import statements for you so you don't need to fear any extra work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-20T21:31:48.367",
"Id": "257456",
"ParentId": "257260",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T17:43:52.400",
"Id": "257260",
"Score": "5",
"Tags": [
"java",
"beginner",
"snake-game"
],
"Title": "Java GUI Snake game"
}
|
257260
|
<p>I wrote some functions to compress and decompress a list of ints using <a href="https://en.wikipedia.org/wiki/Elias_gamma_coding" rel="nofollow noreferrer">Elias gamma encoding</a>:</p>
<pre class="lang-py prettyprint-override"><code>def _reverseBits(number: int) -> int:
rev = 0
while number:
rev = rev << 1
if number & 1:
rev = rev ^ 1 # bitwise ^ 1 is faster than arithmetic + 1
number = number >> 1
return rev
def compress(numbers: List[int]) -> int:
r'''Calculate the elias gamma encoded bitstream representation of the input list of numbers.
>>> compress([5]) == 0b10100
True
>>> compress([15]) == 0b1111000
True
>>> compress([5, 15]) == 0b10100010100
True
'''
bitstream = 0
bitstream_length = 0
previous_number = 0
for number in numbers:
delta = number - previous_number # store deltas, much smaller numbers
N = delta.bit_length() - 1
encoded_number = _reverseBits(delta) << N # reversed bitstream won't have leading zeroes problem in int container
bitstream += encoded_number << bitstream_length
bitstream_length += (N * 2 + 1)
previous_number = number
return bitstream
def decompress(bitstream: int) -> List[int]:
r'''Convert the elias-encoded bitstream into a list of numbers.
>>> decompress(0b10100010100)
[5, 15]
'''
numbers = []
cumulative_sum = 0
while bitstream:
N = 1
while bitstream & 1 == 0: # count Elias leading zeroes
bitstream = bitstream >> 1
N += 1
mask = (1 << N) - 1
number = _reverseBits(bitstream & mask)
number = number << N - number.bit_length()
cumulative_sum += number
numbers.append(cumulative_sum)
bitstream = bitstream >> N
return numbers
</code></pre>
<p>But it's very slow on huge input lists</p>
<pre><code>start = 5000
size = int(4e6)
numbers = [i for i in range(start, start + size + 1)]
</code></pre>
<p>I started a test with a four-million size input list, all elements sequential, it took 13 minutes to encode and decode on my laptop.</p>
<p>I've thought about parallelising what I already have, but I don't think there's anywhere I can actually work it in.</p>
<p>Please could you help me review my algorithm and see if there are ways to improve or rework it to make my compress and decompress methods faster?</p>
<p>Or potentially, this might be the limit of Elias gamma encoding in Python...</p>
<hr />
<p>I have also noticed a problem with mine, that memory does not seem to be freed after it finishes. <code>tracemalloc.get_traced_memory()</code> after running it shows a memory usage higher than the encoded int.</p>
<hr />
<p>Elias gamma encoding encodes numbers like this</p>
<pre><code>+--------+---------------+
| Number | γ encoding |
+--------+---------------+
| 1 | 1 |
| 2 | 0 10 |
| 3 | 0 11 |
| 4 | 00 100 |
| 5 | 00 101 |
| 6 | 00 110 |
| 7 | 00 111 |
| ... | |
| 15 | 000 1111 |
| 16 | 0000 1 0000 |
| ... | |
| 31 | 0000 1 1111 |
| 32 | 00000 10 0000 |
</code></pre>
<p>The leading zeroes inform the decoder how many of the following bits are part of the current number. So numbers of the input list are concatenated into a bitstream, and can be unambiguously decoded back into the same list of numbers. <code>[1, 4, 3]</code> encodes to <code>1 00100 011</code>.</p>
<p>I am storing the bitstream in reverse inside of a python <code>int</code>, reversed so that there's no problems with the leading zeroes of the int container.</p>
<p>Even though the bit sequences in the table look large because of the leading zeroes, my compression only encodes the difference between the current list element and the previous (<a href="https://en.wikipedia.org/wiki/Delta_encoding" rel="nofollow noreferrer">delta encoding</a>), so that most of the time the number to encode and concatenate is much smaller than the actual list element.</p>
<p>My methods intentionally only work with sorted lists.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:17:27.827",
"Id": "508089",
"Score": "0",
"body": "Why are you creating numbers instead of (bit)strings?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:23:05.787",
"Id": "508090",
"Score": "0",
"body": "Out of curiosity: Is it really \"compressing\" for the numbers in the range you're testing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:26:54.083",
"Id": "508091",
"Score": "0",
"body": "@Manuel hugely, for example the 4 million element list was compressed to 277x smaller. More modest lists, for example of 469 elements, achieve 184x compression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:35:03.920",
"Id": "508094",
"Score": "1",
"body": "Ah yes, you're encoding deltas. Which in your test are almost all 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:41:58.240",
"Id": "508095",
"Score": "0",
"body": "@Manuel i used `int` instead of `str` or `bitarray` because it uses up way less memory. It was also way faster for inputs <500 elements, but I haven't actually compared speeds on gigantic inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:36:05.137",
"Id": "508127",
"Score": "0",
"body": "Hmm, I just realized you mentioned `bitarray`. That should only take slightly more memory than `int`. How much way more memory than `int` did it take for you?"
}
] |
[
{
"body": "<p>Rather strange to encode as a number instead of a (bit)string. And the way you do it takes quadratic time in the size of your list (because both the <code>+</code> and the <code><<</code> in <code>bitstream += encoded_number << bitstream_length</code> are linear). You could do it in linear time by building a string and then turning it into a number at the end.</p>\n<p>This should take only a few seconds for your large test (removing the docstring just for brevity here):</p>\n<pre><code>def compress(numbers: List[int]) -> int:\n bitstream = []\n previous_number = 0\n for number in numbers:\n delta = number - previous_number # store deltas, much smaller numbers\n N = delta.bit_length() - 1\n encoded_number = bin(delta)[:1:-1] + '0' * N\n bitstream.append(encoded_number)\n previous_number = number\n bitstream.reverse()\n return int(''.join(bitstream), 2)\n</code></pre>\n<p>For decompression, I'd accordingly first turn the number into a string and then work with that.</p>\n<p>Optimized version should take less than a second:</p>\n<pre><code>def compress(numbers: List[int]) -> int:\n bitstream = []\n append = bitstream.append\n memo = {}\n lookup = memo.get\n previous_number = 0\n for number in numbers:\n delta = number - previous_number # store deltas, much smaller numbers\n if not (encoded_number := lookup(delta)):\n N = delta.bit_length() - 1\n memo[delta] = encoded_number = bin(delta)[:1:-1] + '0' * N\n append(encoded_number)\n previous_number = number\n bitstream.reverse()\n return int(''.join(bitstream), 2)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:03:53.167",
"Id": "508099",
"Score": "0",
"body": "How \"small\", and what times did you get for both? In my own testing, mine's always faster, even when the list only has a single number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:09:41.433",
"Id": "508101",
"Score": "0",
"body": "When I tried with strings before, I was using string concatenation. I had no idea building a list of strings like this would be so fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:12:48.837",
"Id": "508102",
"Score": "0",
"body": "\"100 ms faster\" doesn't say much, what were the times? Btw I improved it a little further now. String concatenation the way I guess you tried might [become quadratic](https://stackoverflow.com/q/44487537/14265373), too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:13:42.323",
"Id": "508103",
"Score": "0",
"body": "The times were 360 for int, 270 for str, for my 469 element set"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:14:19.510",
"Id": "508104",
"Score": "0",
"body": "I now reverse the list instead of using a reverse iterator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:19:08.820",
"Id": "508105",
"Score": "0",
"body": "This is totally awesome. It's super fast, I'll test how much memory it consumes next. My previous pitfall on attempting a solution like this was totally because I used string concatenation instead of a list of strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:26:32.847",
"Id": "508106",
"Score": "0",
"body": "Why is my int solution quadratic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:28:34.457",
"Id": "508107",
"Score": "0",
"body": "@theonlygusti Because both operations in `bitstream += encoded_number << bitstream_length` are linear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T21:29:44.520",
"Id": "508108",
"Score": "0",
"body": "Why aren't bitshifting or addition linear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:23:31.720",
"Id": "508117",
"Score": "0",
"body": "They are, that's what I said."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:29:11.200",
"Id": "508118",
"Score": "0",
"body": "Oh sorry, I meant constant"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T22:31:51.057",
"Id": "508119",
"Score": "0",
"body": "It's because they're linear size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T23:16:56.630",
"Id": "508125",
"Score": "0",
"body": "@theonlygusti Added a further optimized version."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:53:56.983",
"Id": "257268",
"ParentId": "257264",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "257268",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:08:01.987",
"Id": "257264",
"Score": "2",
"Tags": [
"python"
],
"Title": "speed up Elias gamma compression"
}
|
257264
|
<p>I'm trying to solve the N-Puzzle problem using IDA* algorithm with a Manhattan heuristic. I already implemented the algorithm from the pseudocode in this Wikipedia page (<a href="https://en.wikipedia.org/wiki/Iterative_deepening_A*" rel="nofollow noreferrer">link</a>).</p>
<p>Here's my code so far :</p>
<pre class="lang-py prettyprint-override"><code>class Node():
def __init__(self, state, manhattan):
self.state = state
self.heuristic = manhattan
def __str__(self):
return f"state=\n{self.state}\nheuristic={int(self.heuristic)}"
def __eq__(self, other):
return np.array_equal(self.state, other.state)
def customSort(node):
return node.heuristic
def nextnodes(node):
zero = np.where(node.state == 0)
y,x = zero
y = int(y)
x = int(x)
directions = []
if y > 0:
directions.append((y - 1, x))
if x > 0:
directions.append((y, x - 1))
if y < constant.SIZE2 - 1:
directions.append((y + 1, x))
if x < constant.SIZE2 - 1:
directions.append((y, x + 1))
arr = []
for direction in directions:
tmp = np.copy(node.state)
goal = np.where(constant.GOAL_STATE == tmp[direction])
tmp[direction], tmp[zero] = tmp[zero], tmp[direction]
tile1_score = manhattan_distance(direction, goal)
tile2_score = manhattan_distance(zero, goal)
arr.append(Node(tmp, node.heuristic - tile1_score + tile2_score))
arr.sort(key=customSort)
return arr
def manhattan_distance(a, b):
return abs(b[0] - a[0]) + abs(b[1] - a[1])
def count_distance(number, state1, state2):
position1 = np.where(state1 == number)
position2 = np.where(state2 == number)
return manhattan_distance(position1, position2)
def manhattan_heuristic(state):
distances = [count_distance(num, state, constant.GOAL_STATE) for num in constant.SIZE]
return sum(distances)
def search(path, g, threshold):
node = path[-1]
f = g + node.heuristic
if f > threshold:
return f
if np.array_equal(node.state, constant.GOAL_STATE):
return True
minimum = float('inf')
for n in nextnodes(node):
if n not in path:
path.append(n)
tmp = search(path, g + 1, threshold)
if tmp == True:
return True
if tmp < minimum:
minimum = tmp
path.pop()
return minimum
def solve(initial_state):path = solve(initial_state)
initial_node = Node(initial_state, manhattan_heuristic(initial_state))
threshold = initial_node.heuristic
path = [initial_node]
while 1:
tmp = search(path, 0, threshold)
if tmp == True:
print(f"GOOD!")
return path
elif tmp == float('inf'):
print(f"WRONG!")
return False
threshold = tmp
</code></pre>
<p>You can call the <code>solve()</code> function (and create some needed global variables) like this:</p>
<pre class="lang-py prettyprint-override"><code>def define_goal_state(n):
global GOAL_STATE
global SIZE
global SIZE2
global ZERO
m = [[0] * n for i in range(n)]
dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
x, y, c = 0, -1, 1
for i in range(n + n - 2):
for j in range((n + n - i) // 2):
x += dx[i % 4]
y += dy[i % 4]
m[x][y] = c
c += 1
GOAL_STATE = np.array(m)
SIZE = range(1, len(GOAL_STATE) ** 2)
SIZE2 = len(GOAL_STATE)
ZERO = np.where(GOAL_STATE == 0)
initial_state = np.array([8 7 3],[4 1 2],[0 5 6])
define_goal_state(len(initial_state))
path = solve(initial_state)
</code></pre>
<p>My implementation of the Wikipedia pseudocode is working and I get pretty fast results in a 8-Puzzle problem. But it gets really slow with a 15-Puzzle problem and above.
Regarding the <code>solve()</code> and the <code>search()</code> functions I think I respect almost identically the pseudocode. I also optimized my <code>nextnodes()</code> function to count only the tile that has been moved, not all tiles every time. Should be good here.</p>
<p>So where's the catch ? Why is my implementation taking so long ?
Does anyone have a clue ?</p>
|
[] |
[
{
"body": "<p>The code does not compile as it is:</p>\n<ul>\n<li>The <code>solve</code> function's signature contains unnecessary code\n<pre><code>def solve(initial_state):path = solve(initial_state)\n</code></pre>\n</li>\n<li>A NumPy array cannot be initialized like <code>np.array([8 7 3],[4 1 2],[0 5 6])</code></li>\n<li>Globals are not initialized</li>\n<li><code>constant.GOAL_STATE</code> is not defined</li>\n</ul>\n<h2>Review</h2>\n<ul>\n<li>In the method <code>search</code>, checking <code>if n not in path</code> is an expensive operation that can be optimized using a set or a dictionary. This drops the runtime on my machine by 70%. A dictionary seems to be a good option since it keeps insertion order (if Python >= 3.7) and can be used as a queue.</li>\n<li><code>manhattan_heuristic</code> uses many times <code>np.where</code>, it can be optimized. An option is to iterate through the puzzle and when an element is different from the goal, calculate the difference. Converting <code>GOAL_STATE</code> to a dictionary will also improve the performance, instead of calling <code>position1 = np.where(state1 == number)</code> every time.</li>\n<li><code>nextnodes</code> also uses <code>np.where</code> two times which can be avoided. For example, instead of calling <code>zero = np.where(node.state == 0)</code> every time, <code>Node</code> can contain the coordinates of zero as a class property.</li>\n<li><strong>Naming</strong>: variable <code>SIZE</code> and <code>SIZE2</code> are confusing because one is a generator and the other is the size of the puzzle. Consider giving more meaningful names.</li>\n<li><strong>Globals</strong>: try to reduce the use of globals as much as possible as it makes the code hard to test.</li>\n</ul>\n<p><strong>Note</strong>: this is not a comprehensive review, I think there is still room for improvements, I hope you will get more reviews.</p>\n<p>Runtime after the improvements:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Puzzle</th>\n<th>Original</th>\n<th>Improved</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>3x3</td>\n<td>0.696 s</td>\n<td>0.097 s</td>\n</tr>\n<tr>\n<td>4x4</td>\n<td>7.021 s</td>\n<td>0.549 s</td>\n</tr>\n</tbody>\n</table>\n</div><h2>Reworked code:</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from time import perf_counter as pc\n\nimport numpy as np\n\nGOAL_STATE = [[]]\nGLOBAL_STATE_DICT = {}\nN = 0\n\n\nclass Node:\n def __init__(self, state, manhattan, zero_pos):\n self.state = state\n self.heuristic = manhattan\n self.zero_pos = zero_pos\n\n def __str__(self):\n return f"state=\\n{self.state}\\nheuristic={int(self.heuristic)}"\n\n def __eq__(self, other):\n return np.array_equal(self.state, other.state)\n\n def __repr__(self):\n return f"state=\\n{self.state}\\nheuristic={int(self.heuristic)}"\n\n def __hash__(self):\n return hash(self.state.tobytes())\n\n\ndef customSort(node):\n return node.heuristic\n\n\ndef nextnodes(node):\n zero = node.zero_pos\n\n r, c = map(int, zero)\n directions = ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1))\n nodes = []\n for direction in directions:\n if 0 <= direction[0] < N and 0 <= direction[1] < N:\n tmp = np.copy(node.state)\n goal = GLOBAL_STATE_DICT[tmp[direction]]\n\n tmp[direction], tmp[zero] = tmp[zero], tmp[direction]\n\n dir_goal_distance = manhattan_distance(direction, goal)\n goal_zero_distance = manhattan_distance(goal, (r, c))\n\n nodes.append(Node(tmp, node.heuristic - dir_goal_distance + goal_zero_distance, direction))\n return sorted(nodes, key=customSort)\n\n\ndef manhattan_distance(a, b):\n return abs(b[0] - a[0]) + abs(b[1] - a[1])\n\n\ndef manhattan_heuristic(state):\n distance = 0\n for i in range(N):\n for j in range(N):\n num = state[i][j]\n if num != GOAL_STATE[i][j] and num != 0:\n goal = GLOBAL_STATE_DICT[num]\n distance += manhattan_distance((i, j), goal)\n return distance\n\n\ndef search(path, g, threshold):\n node = list(path.keys())[-1]\n\n f = g + node.heuristic\n\n if f > threshold:\n return f\n if np.array_equal(node.state, GOAL_STATE):\n return True\n\n minimum = float('inf')\n for n in nextnodes(node):\n if n not in path:\n path[n] = None\n tmp = search(path, g + 1, threshold)\n if tmp == True:\n return True\n if tmp < minimum:\n minimum = tmp\n path.popitem()\n\n return minimum\n\ndef solve(initial_state):\n zero = np.where(initial_state == 0)\n initial_node = Node(initial_state, manhattan_heuristic(initial_state), zero)\n threshold = initial_node.heuristic\n # The dictionary keeps insertion order since Python 3.7 so it can be used as a queue\n path = {initial_node: None}\n while 1:\n tmp = search(path, 0, threshold)\n if tmp == True:\n print("GOOD!")\n return path.keys()\n elif tmp == float('inf'):\n print("WRONG!")\n return False\n threshold = tmp\n\n\n\ndef define_goal_state(n):\n global GOAL_STATE\n global N\n global GLOBAL_STATE_DICT\n\n m = [[0] * n for i in range(n)]\n dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]\n x, y, c = 0, -1, 1\n for i in range(n + n - 2):\n for j in range((n + n - i) // 2):\n x += dx[i % 4]\n y += dy[i % 4]\n m[x][y] = c\n c += 1\n\n GOAL_STATE = np.array(m)\n N = len(GOAL_STATE)\n GLOBAL_STATE_DICT = {m[r][c]: (r, c) for r in range(N) for c in range(N)}\n\n\ntests = {'3x3': np.array([[8, 7, 3], [4, 1, 2], [0, 5, 6]]),\n '4x4': np.array([[13, 2, 10, 3],\n [1, 12, 8, 4],\n [5, 0, 9, 6],\n [15, 14, 11, 7]])}\n\nfor name, puzzle in tests.items():\n define_goal_state(len(puzzle))\n print('Puzzle:\\n', puzzle)\n t0 = pc()\n path = solve(puzzle)\n t1 = pc()\n print(f'{name} depth:{len(path)} runtime:{round(t1 - t0, 3)} s')\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-15T13:29:29.110",
"Id": "512026",
"Score": "0",
"body": "Sorry for the delay. Your answer is really helpful, I managed to speed up my IDA algo a little bit. It is still slow on difficult configurations. I can speed it up by changing the heuristic : manhattan seems to be pretty slow."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-17T07:06:01.510",
"Id": "257288",
"ParentId": "257267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257288",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:46:58.797",
"Id": "257267",
"Score": "2",
"Tags": [
"python",
"algorithm",
"pathfinding",
"a-star",
"sliding-tile-puzzle"
],
"Title": "How can I speed up my IDA* algorithm for N-puzzle?"
}
|
257267
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.