body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Which of these variations do you think is the best way to write a function that returns True based on multiple conditions?</p>
<p>Variation 1:</p>
<pre><code>def is_trial_plan(order):
return (
"shipping" not in order
and order["amount"] == 0
and order["description"] == "Affiliate"
)
</code></pre>
<p>Variation 2:</p>
<pre><code>def is_trial_plan(order):
if (
"shipping" not in order
and order["amount"] == 0
and order["description"] == "Affiliate"
):
return True
</code></pre>
<p>Variation 3:</p>
<pre><code>def is_trial_plan(order):
if (
"shipping" not in order
and order["amount"] == 0
and order["description"] == "Affiliate"
):
return True
return False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T18:16:42.147",
"Id": "496121",
"Score": "3",
"body": "I hope you're aware that the second version is not equivalent to the others... In case the condition doesn't hold it returns `None`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T20:22:46.510",
"Id": "496128",
"Score": "3",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. This question is off-topic"
}
] |
[
{
"body": "<p>I personnaly prefer var1 as the function name is in "isSomething...." form i'll assume all conditions to be true.</p>\n<p>I may prefer other versions if other cases of multiples conditions arise in the function.</p>\n<p>If there is multiples more conditions and if theirs reading cost is high (for example reading from file/parsing,db.., you may prefer return multiple false to avoid evaluation even if this augment code size.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T20:22:58.060",
"Id": "496129",
"Score": "1",
"body": "Please dont answer questions that are off-topic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T20:44:26.383",
"Id": "496133",
"Score": "0",
"body": "sorry, i just joined codereview and didn't though that question was off-topic, i'll care more in future"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T21:27:39.240",
"Id": "496137",
"Score": "0",
"body": "Not a problem, you can find a lot of information in the [help]. If you feel a question is off-topic it's best to not answer, and instead flag it for closure. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T18:15:46.220",
"Id": "251916",
"ParentId": "251914",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T18:00:15.407",
"Id": "251914",
"Score": "-3",
"Tags": [
"python"
],
"Title": "Python explicit or implicit boolean return"
}
|
251914
|
<p>Would you help me? I want to make this code efficient and simple.</p>
<p><a href="https://programmers.co.kr/learn/courses/30/lessons/67260" rel="nofollow noreferrer">Original Link</a></p>
<p>Frodo, a backcountry explorer, came to explore an underground cave with n rooms during his expedition. All rooms are numbered 0 through n-1. There are many, the only entrances are connected with 0 rooms. Each room is connected to each other by passages that allow passage in both directions, but there is only one passage directly connecting the two different rooms. There is only one shortest path between any two different rooms, and there is no case where it is impossible to move between any two rooms.</p>
<p>Having obtained a map of this underground cave prior to his expedition, Frodo planned his expedition as follows:</p>
<ol>
<li><p>You must visit every room at least once.</p>
</li>
<li><p>Certain rooms must be visited first before visiting. <br>
2.1. This means that you must visit Room B before visiting Room A. <br>
2.2. There is no or only one room that must be visited first in order to visit a room. <br>
2.3. For two or more different rooms, there is never the same room that must be visited first. <br>
2.4 A room is not a room that must be visited first and a room that must be visited later.</p>
</li>
</ol>
<p><br>Among the above plans, 2.2, 2.3 and 2.4 mean that the pair of two rooms that must be visited in order is unique in the form of A → B (visit A first and then B). In other words, Frodo made a visit plan so that the order of visit would not be arranged as follows.</p>
<p>A → B, A → C (visit order order = [...,[A,B],...,[A,C],...]) The room to visit after visiting A is B Two or more with and C
The room to visit before visiting A in the form X → A, Z → A (visit order order = [...,[X,A],...,[Z,A],...]) Two or more with X and Z
A → B → C (visit order arrangement order = [...,[A,B],...,[B,C],...), like B, after visit A and before visit C at the same time</p>
<p>Also, you do not have to visit the room you need to visit first and the room you will visit later, so you can visit room A and then visit another room and then visit room B.</p>
<p>When the number of rooms n, a two-dimensional array path containing the number of two rooms connected by each of the corridors in the cave, and a two-dimensional array order containing the visit order set by Frodo are given as parameters, Frodo can explore all rooms according to the rules. Complete the solution function to return whether it exists. <strong>It's source is kakao intern coding test.</strong></p>
<p>I/O example:</p>
<p>n path order ---> result</p>
<p>9,[[0,1],[0,3],[0,7],[8,1],[3,6],[1,2],[4,7],[7,5]],[[8,5],[6,7],[4,1]] --->true</p>
<p><strong>this is my code. I used stack. And when frodo arrived at room A, which is needed to visit Room B, then I added rooms on dictionary that can only be accessed after arriving Room B. It could have some errors, but I/O case correct rate was about 0.95/1</strong></p>
<pre><code>def check(a,route,res,path):
if a in res:
p=res[a]
del[res[a]]
if a not in res:
for c in path:
if p in c:
for j in c:
if j!=p :
if j in route:
if p not in route[j]:
route[j].append(p)
else:
route[j]=[p]
return None
def solution(n, path, order):
res=dict(order)
warn=[]
for i in order:
if i[1] not in warn:
warn.append(i[1])
route={}
for i in range(n):
for j in path:
if i in j:
for k in j:
if k in warn or i==k:
pass
else:
if i in route:
route[i].append(k)
else:
route[i]=[k]
for j in range(len(order)):
stack=[]
visited=set()
stack.append(0)
visited.add(0)
while len(stack)!=0:
a=stack.pop()
visited.add(a)
check(a,route,res,path)
if a in route:
for i in route[a]:
if i not in visited:
stack.append(i)
if len(visited)==n:
return True
return False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T19:30:49.893",
"Id": "496126",
"Score": "3",
"body": "if your question is from a programming challenge, please provide a link to the source."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T06:36:37.550",
"Id": "496159",
"Score": "0",
"body": "[link](https://programmers.co.kr/learn/courses/30/lessons/67260)_italic_ **bold**"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T18:10:27.860",
"Id": "251915",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Graph: A backcountry explorer"
}
|
251915
|
<p><strong>Question description</strong></p>
<p>I am currently developing an RPG to gain programming experience. An RPG consists of many individual components such as the combat system, quest system and the item system. I decided to develop an item system first, before I develop the other parts.</p>
<p>I have made some philosophical thoughts on the question of how items can be mapped in object oriented code so that the code is easily understandable and suitable for further development. I would like to present my current status here and ask you whether my item concept is suitable for further development, or whether I have made design mistakes that lead to poor results in further development.</p>
<p>First of all, I took care of consumable items like food and potions.</p>
<p><strong>Short description of my Item concept and the code</strong></p>
<p>All items, whether they are items of equipment or can be consumed, have general values such as a name, a price, and can be assigned to a category. Therefore there is a corresponding base class.</p>
<p><strong>Item.java</strong></p>
<pre><code>public class Item {
protected String name;
protected String category;
protected int price;
public Item(String name, String category, int price) {
this.name = name;
this.category = category;
this.price = price;
}
public Item(String name, String category) {
this(name, category, 0);
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public int getPrice() {
return price;
}
}
</code></pre>
<p>Consumable Items are special: They can be consumed und then unfold an effect on the being that consumes an Item. I decided to create an interface that says that.</p>
<p><strong>Consumable.java</strong></p>
<pre><code>public interface Consumable {
public void unfoldEffect(Character character);
}
</code></pre>
<p>There are two ressources a player has: He has health and energy. The amount of health points decides how much blows he can take before he dies. The amount of energy decides how strong his attacks will be. And so there are items that fill up health and energy. Both are represented in different classes that are based on the Item-class and the Consumable-Interface.</p>
<p><strong>HealthItem.java</strong></p>
<pre><code>// can be food (bread, water) or healing potions or stuff like that
public class HealthItem extends Item implements Consumable {
private int healthPoints;
public HealthItem(String name, String category, int price, int healthPoints) {
super(name, category, price);
this.healthPoints = healthPoints;
}
public int getHealthPoints() {
return healthPoints;
}
public void unfoldEffect(Character character) {
character.regenerateHealthPoints(healthPoints);
}
}
</code></pre>
<p>And the enery-item-class:</p>
<p><strong>EnergyItem.java</strong></p>
<pre><code>public class EnergyItem extends Item implements Consumable {
private int energyPoints;
public EnergyItem(String name, String category, int price, int energyPoints) {
super(name, category, price);
this.energyPoints = energyPoints;
}
public int getEnergyPoints() {
return energyPoints;
}
public void unfoldEffect(Character character) {
character.regenerateEnergyPoints(energyPoints);
}
}
</code></pre>
<p>And of course there has to be a class that represents characters that can act in the game. These class is the base class for human players and NPCs.</p>
<p><strong>Character.java</strong></p>
<pre><code>public class Character {
// could be an orc, animal, human and what the imagination has to offer
private String species;
// not every char must have a name. E. g. pigs usually dont have names
private String name;
private int healthPoints;
private int healthPointsMax;
private int energyPoints;
private int energyPointsMax;
public Character(String species, String name, int healthPoints, int healthPointsMax ,int energyPoints, int energyPointsMax) {
this.species = species;
this.name = name;
this.healthPoints = healthPoints;
this.healthPointsMax = healthPointsMax;
this.energyPoints = energyPoints;
this.energyPointsMax = energyPointsMax;
}
public Character(String species, String name, int healthPoints, int energyPoints) {
this(species, name, healthPoints, healthPoints, energyPoints, energyPoints);
}
public Character(String species, int healthPoints, int energyPoints) {
this(species, null, healthPoints, energyPoints);
}
public String getName() {
return name;
}
public int getHealthPoints() {
return healthPoints;
}
public int getHealthPointsMax() {
return healthPointsMax;
}
public int getEnergyPoints() {
return energyPoints;
}
public int getEnergyPointsMax() {
return energyPointsMax;
}
public void regenerateHealthPoints(int healthPoints) {
if (this.healthPoints + healthPoints > this.healthPointsMax) {
this.healthPoints = healthPointsMax;
} else {
this.healthPoints += healthPoints;
}
}
public void regenerateEnergyPoints(int energyPoints) {
if (this.energyPoints + energyPoints > energyPointsMax) {
this.energyPoints = energyPointsMax;
} else {
this.energyPoints += energyPoints;
}
}
}
</code></pre>
<p>The game output will be printed to the console. So there also should be a class that handles some recurring output tasks.</p>
<p><strong>Display.java</strong></p>
<pre><code>public class Display {
public static void health(Character character) {
System.out.println("health points: " + character.getHealthPoints() + " / " + character.getHealthPointsMax());
}
public static void energy(Character character) {
System.out.println("energy points: " + character.getEnergyPoints() + " / " + character.getEnergyPointsMax());
}
public static void healthAndEnergy(Character character) {
health(character);
energy(character);
}
public static void basicDetails(Item item) {
System.out.println("name: " + item.getName());
System.out.println("category: " + item.getCategory());
System.out.println("price: " + item.getPrice());
}
public static void details(HealthItem item) {
basicDetails(item);
System.out.println("health bonus: " + item.getHealthPoints());
}
public static void details(EnergyItem item) {
basicDetails(item);
System.out.println("energy bonus: " + item.getEnergyPoints());
}
}
</code></pre>
<p>And here is a test class that tests my program.</p>
<p><strong>ItemTestMain.java</strong></p>
<pre><code>public class ItemTestMain {
public static void main(String[] args) {
// Create Items
HealthItem bred = new HealthItem("bred", "food", 0, 20);
EnergyItem manaPotion = new EnergyItem("mana potion", "potion", 0, 50);
// create character
Character klaus = new Character("Man", "Klaus Dieter", 5, 100, 20, 50);
Display.healthAndEnergy(klaus);
// Let the character consume items
System.out.println("The Character consumes: ");
Display.details(bred);
bred.unfoldEffect(klaus);
Display.healthAndEnergy(klaus);
System.out.println("The Character consumes: ");
Display.details(manaPotion);
manaPotion.unfoldEffect(klaus);
Display.healthAndEnergy(klaus);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T20:22:21.777",
"Id": "496219",
"Score": "0",
"body": "Without doing a full review, what you're trying to build here with classes and inheritance, would be better modeled using an [Entity-Component-System](https://en.wikipedia.org/wiki/Entity_component_system). As that would easily allow for a single item to have multiple effects. Your code also looks quite clean and good to me."
}
] |
[
{
"body": "<p>A rpg is not an easy project to start but good luck and it's probably a good training for OO.</p>\n<p>When your item system will be more elaborated you'll probably be interested in using a factory pattern as it can help a lot while using loot table (and random generation?).</p>\n<p>Will you allow inventory (limited in space, with item of different size, weight), character inventory relative to body part (weapons, armors, jewelry....) do they need specific requirements? (level, statistics...). All those things you need to think carefully before coding.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T20:19:02.987",
"Id": "496217",
"Score": "0",
"body": "This...really is more of a comment, isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T19:34:54.780",
"Id": "496511",
"Score": "0",
"body": "probably, i just did'nt have right to comment when i did post this answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T19:46:31.540",
"Id": "251920",
"ParentId": "251919",
"Score": "0"
}
},
{
"body": "<h1>Avoid needless Inheritance</h1>\n<p>Actually <strong>never use Inheritance</strong> when you just want to share some code. Purpose of Inheritance is not a code reuse. Inheritance is meant to model <strong>Is-A</strong> relationship. And you don't need to model Is-A relationship very often. Code sharing is a side effect of this. Composition is a way better technique of code reuse. Take a look at this quick draft of what Composition based <code>Consumable</code> might look like.</p>\n<pre><code>public class Consumable {\n\n private final List<Effect> effects;\n\n public Consumable(final List<Effect> effects) {\n this.effects = new ArrayList<>(effects);\n }\n\n public void useOn(Character character) {\n for (Effect effect : this.effects) {\n effect.affect(character);\n }\n }\n\n}\n\npublic interface Effect {\n void affect(Character character);\n}\n\npublic class HealthGain implements Effect {\n private final int amount;\n\n public HealthGain(final int amount) {\n this.amount = amount;\n }\n\n public void affect(final Character character) {\n character.regenerateHealthPoints(this.amount);\n }\n\n}\n\npublic class EnergyGain implements Effect {\n private final int amount;\n\n public EnergyGain(final int amount) {\n this.amount = amount;\n }\n\n public void affect(final Character character) {\n character.regenerateEnergyPoints(this.amount);\n }\n\n}\n\npublic static void main(String[] args) {\n final Consumable lesserHealingPotion = new Consumable(List.of(\n new HealthGain(10) \n ));\n final Consumable uberRestorationPotion = new Consumable(List.of(\n new HealthGain(1000),\n new EnergyGain(1000)\n ));\n}\n</code></pre>\n<h1>Keep your features separate</h1>\n<p>The thing that both buying and using an item works with an item does not mean that both of these features have to be implemented by a single Item class. Each and every such feature will only bloat your Item and you will end up with gigantic class where each feature uses only part of it.. Instead of having a single <code>Item</code> consider having a representation for each domain in which an item figures. Such as <code>Merchandise</code> for shopping, <code>Consumable</code> for use or <code>Equipment</code> for use in combat. By keeping them separate you can easily add related behavior such as limited use, cooldowns or durability without cluttering the class too much.</p>\n<h1>Avoid static functions</h1>\n<p>Static functions cause a very strong coupling and as a result make testing needlessly difficult. Especially in the context of display you wouldn't be able to substitute the <code>Display</code> for any test-friendly implementation. Take a look at this example.</p>\n<pre><code>public class Display {\n void show(Displayable displayable) {\n // ...\n }\n}\n\ninterface Displayable {\n String asText();\n}\n\nclass Merchandise implements Displayable {\n \n // ...\n \n @Override\n public String asText() {\n final StringBuilder builder = new StringBuilder();\n builder.append("name: " + this.name);\n builder.append("category: " + this.category);\n builder.append("price: " + this.price);\n return builder.toString();\n }\n\n}\n</code></pre>\n<h1>Test your code</h1>\n<p>Take a look at some testing libraries such as <a href=\"https://junit.org/junit5/docs/current/user-guide/\" rel=\"nofollow noreferrer\">JUnit</a> so that you can properly test your code.</p>\n<p>PS: Take those examples with a grain of salt. They are mean to show that there are many ways to build a program and what actually works for any use case can be discovered only by digging in.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T15:22:06.050",
"Id": "251950",
"ParentId": "251919",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251950",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T19:17:01.173",
"Id": "251919",
"Score": "6",
"Tags": [
"java",
"object-oriented",
"console",
"role-playing-game"
],
"Title": "RPG item, character, and display"
}
|
251919
|
<p>I wrote a script that places documents to the folders they should be (based on my preferences of course).
It even creates the folder if it doesn't exists.</p>
<p>Here's how it works:</p>
<ol>
<li>You run de script by clicking on it. (idk if I should let this run in the background constantly, I don't use it that much)</li>
<li>Checks the selected directory for files with a "-" in their name.
(Physics- Homework.docx)</li>
<li>It checks the targeted directory (where my folder hierarchy is meant to be) if there's a folder named after the file's name before the "-" part. ("Physics- Homework.docx" goes to a folder named "Physics")</li>
<li>If there isn't a folder, it creates one. If there is a folder, it just moves the file inside</li>
</ol>
<p>So Like I said in the first step, you have to click to run this, I would love to make it automatic, but I don't want it to run in the background just to move a file twice in a week or so. I would love to know if there's another cool way to achieve this automatic way of working.</p>
<p>My idea (to achieve what I said above) was to create a ".bat" file that runs Word and the script at the same time (this time script keeps running in the background once started), next to script's based functionality, it would also check for the apps running in the background and when Word is closed, it performs the file movement and closes itself. But I don't know if this is a great idea or if it can be done in much simpler way.</p>
<p>I want to know what I could've done better. Since the code is relatively short, I feel like I have done a great job, but I believe that there's always room for improvement.</p>
<p>Here's the code:</p>
<pre><code>import shutil
import os
Dir = "D:/OneDrive/Documents/" # Where are the files? Add "/" at the end of your directory.
TragetDir = "D:/OneDrive/Documents/school/6a9/" # Where are the target folders? Add "/" at the end of your directory.
FileNames = glob.glob(Dir + "*-*") # scans the dir with the selected character (*[selected character]*), searches directly for the name now.
StartIndex = len(Dir) # The chars of the Dir are useless
for x in range(len(FileNames)): # Each file gets moved one by one
Index = FileNames[x].find("-") # I always create my files using: "class + "-" + topic" way
SFolder = FileNames[x][StartIndex:Index] # My folders are always named after the subject, so "Math- exam 1.docx" should be placed in a folder named "Math"
try: #tries to make a target dir
os.makedirs(TragetDir + SFolder)
except: #if the directory already exists just skips this process
pass
shutil.move(FileNames[x], TragetDir + SFolder) # moves to the target folder
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>For automation, I think you can look for Task Scheduler in windows (as you mention <code>*.bat</code>, I imagine <a href=\"https://www.schakko.de/2020/03/15/how-to-add-a-cron-job-scheduled-task-on-windows/\" rel=\"nofollow noreferrer\">cron isn't an option</a>.</p>\n</li>\n<li><p>And just add a job daily (or weekly, etc.) to run your script and forget about that.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T20:34:03.353",
"Id": "496130",
"Score": "0",
"body": "Thanks for sharing this with me, I didn't know about the the scheduled tasks on Windows (at least that it was open for users). This is quiete cool actually to know.\n\nHowever I aim for that \"I saved the file and it directly moved to the targeted folder\" approach. And there's no option in it to start a program, when another one is closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T20:41:16.627",
"Id": "496132",
"Score": "0",
"body": "in this case the option to use a bat script with after word is closed seem better (i don't think you want to reverse engeenering word to detour it)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T20:19:55.830",
"Id": "251923",
"ParentId": "251921",
"Score": "0"
}
},
{
"body": "<p>A few changes I would make:</p>\n<ul>\n<li>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>.</li>\n<li>Use the modern, high-level <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> instead of a combination of the <code>os</code> module, <code>glob</code>, and <code>shutil</code>.</li>\n<li>Be careful when using a bare <code>except:</code>, or <code>except Exception:</code>, see <a href=\"https://stackoverflow.com/q/54948548\">https://stackoverflow.com/q/54948548</a>.</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>import pathlib\n\ndocs_dir = pathlib.Path('')\ntarget_dir = pathlib.Path('')\n\nfor file in docs_dir.glob('*-*'): # Each file gets moved one by one\n subject_name, file_name = str(file.name).split('-', maxsplit=1)\n subject_dir = target_dir.joinpath(subject_name)\n \n subject_dir.mkdir(exist_ok=True)\n file.rename(subject_dir.joinpath(file_name))\n</code></pre>\n<p>As an aside, it may be worth considering using a folder just for unsorted school-related files. It would be so easy to add a non-schoolwork file which contains a <code>'-'</code> to your documents folder, and have it moved unintentionally by the program.</p>\n<p>You wrote in a comment:</p>\n<blockquote>\n<p>However I aim for that "I saved the file and it directly moved to the targeted folder" approach.</p>\n</blockquote>\n<p>If that's the case, you should look into file system watchers/watchdogs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T20:41:29.153",
"Id": "251966",
"ParentId": "251921",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T20:03:16.533",
"Id": "251921",
"Score": "4",
"Tags": [
"python",
"file-system"
],
"Title": "File mover based on document name"
}
|
251921
|
<p>As the title says, I have created an alternative class to imitate AsyncTask class (deprecated) with Thread and Handler classes but i feel uncomfortable to use it.(the app works fine with my class) Can you guys tell me is it ok or not? I feel like there is nothing changed. The reason i want to stop using AsyncTask is memoryleak issue.</p>
<pre><code>import android.os.Handler;
public class BackgroundTask
{
protected Handler localHandler;
protected Thread localThread;
public void execute()
{
this.localHandler = new Handler();
this.onPreExecute(); //onPreExecute Method
this.localThread = new Thread(new Runnable()
{
@Override
public void run()
{
BackgroundTask.this.doInBackground(); //doInBackground Method
BackgroundTask.this.localHandler.post(new Runnable()
{
@Override
public void run()
{
BackgroundTask.this.onPostExecute(); //onPostExecute Method
}
});
}
});
this.localThread.start();
}
public void cancel()
{
if(this.localThread.isAlive())
this.localThread.interrupt();
}
protected void onPreExecute()
{
}
protected void doInBackground()
{
}
protected void onPostExecute()
{
}
}
</code></pre>
<p>Example for use (I can interrupt the Thread when i want so this must be solving the leak issue but i want this code to be seen by some other programmers too.)</p>
<pre><code>public class HttpPostUserScore extends BackgroundTask
{
private final Context context;
private Exception taskException;
private final String point;
public HttpPostUserScore(Context context, String point)
{
this.context = context;
this.point = point;
}
@Override
protected void doInBackground()
{
try
{
OkHttpClient client = new OkHttpClient();
FormBody.Builder formBuilder = new FormBody.Builder();
formBuilder.add("token", User.loggedUser.getToken());
formBuilder.add("score", this.point);
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder().url(this.context.getString(R.string.user_score_api_url_body)).post(requestBody).build();
Response response = client.newCall(request).execute();
Log.println(Log.WARN, "ScorePost Response", response.body().string());
}
catch (Exception e) { this.taskException = e; }
}
@Override
protected void onPostExecute()
{
if(this.taskException != null)
Log.println(Log.ERROR, "ScorePost Error", this.taskException.getMessage());
else
Toast.makeText(this.context, this.point + " Points Added!", Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p>I have examined some codes from Facebook's android login api. They are still using AsyncTask for asynchronous programming. Is it a big deal or not?</p>
|
[] |
[
{
"body": "<pre class=\"lang-java prettyprint-override\"><code> public void execute()\n {\n this.localHandler = new Handler();\n this.onPreExecute(); //onPreExecute Method\n\n this.localThread = new Thread(new Runnable()\n {\n @Override\n public void run()\n {\n BackgroundTask.this.doInBackground(); //doInBackground Method\n BackgroundTask.this.localHandler.post(new Runnable()\n {\n @Override\n public void run()\n {\n BackgroundTask.this.onPostExecute(); //onPostExecute Method\n }\n });\n }\n });\n this.localThread.start();\n }\n</code></pre>\n<p>This part would be much easier to read using method references:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public void execute()\n{\n localHandler = new Handler();\n onPreExecute();\n\n localThread = new Thread(this::backgroundExecutor)\n localThread.start();\n}\n\nprotected void backgroundExecutor() {\n doInBackground();\n \n localHandler.post(this::onPostExecute)\n}\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> this.localHandler = new Handler();\n this.onPreExecute(); //onPreExecute Method\n</code></pre>\n<p>One should only use <code>this</code> if it is necessary to differentiate between a local and a member variable. And that should only be necessary in setters and the constructor. You can remove <code>this</code> and remove a lot of noise with it.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> this.localHandler = new Handler();\n this.onPreExecute(); //onPreExecute Method\n</code></pre>\n<p>Comment on <em>why</em> you're doing something, not <em>what</em> you're doing. This comment tells me nothing the code on the left doesn't tell me.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> if(this.localThread.isAlive())\n this.localThread.interrupt();\n</code></pre>\n<p>One should only use curly-braces to make the scopes easily visible and minimize possible scope errors.</p>\n<hr />\n<p>Your code has a few problems when it comes to threading. Invoking <code>execute</code> multiple times will reset the local state and will yield inconsistent and potentially unknown results, as <code>localHandler</code> and <code>localThread</code> are getting overwritten with every call (imagine <code>execute</code> being called from multiple threads). That will also impact <code>cancel</code>, as it will only be called on the last run thread. Additionally, calling <code>interrupt</code> might or might not actually end the thread. There is no failsafe way to end a thread except killing the JVM.</p>\n<p>Your implementation has similar issues, as it shares state using class members, which means that multiple invocations will lead to lost state and possible confusions (three invocations, the last two fail, but the first one is the last to finish).</p>\n<p>What you're trying to do is not easy. I'd recommend looking at the implementation of the <code>AsyncHandler</code> class and getting ideas what they were doing. Depending in your use-case, for example if you have a lot of background actions, you might want instead to utilize a thread-pool, to minimize constantly spinning up threads.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T20:44:13.503",
"Id": "251967",
"ParentId": "251925",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251967",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T21:58:55.313",
"Id": "251925",
"Score": "3",
"Tags": [
"java",
"android",
"asynchronous"
],
"Title": "Alternative class to imitate AsyncTask class (deprecated) with Thread and Handler classes"
}
|
251925
|
<h1> Objective</h1>
<p>Determine whether a given word is contained in a 2D Array word search.</p>
<h1> Question</h1>
<h2>1. What are the time and space complexities of the current algorithm?</h2>
<h3>Time complexity</h3>
<p>Linear: <span class="math-container">\$O(2(r * n))\$</span></p>
<p>There are iterations through the outer and inner loops for the rows and columns occurring twice, once for the horizontal search, and once for the vertical search.</p>
<h3>Space complexity</h3>
<p>Constant: <span class="math-container">\$O(1)\$</span></p>
<p>The only data stored is the <code>currentSearch</code> string that will not grow based on the size of the word search.</p>
<h2>2. How can the time complexity be optimized?</h2>
<ul>
<li>If the <code>currentSearchIndex == 0</code>, skip rows/columns that do not contain the first character of the word that is being searched for.</li>
</ul>
<h1> Implement</h1>
<ol>
<li>Iterate through the 2D Array for the word to find both horizontally and vertically.</li>
<li>Horizontally: Outer loop iteration is rows, inner loop iteration is columns</li>
<li>Vertically: Outer loop iteration is columns, inner loop iteration is rows</li>
</ol>
<h2>Sample</h2>
<p><em>Input</em></p>
<pre class="lang-kotlin prettyprint-override"><code>findWord(
arrayOf(
arrayOf("b", "r", "n"),
arrayOf("a", "s", "h"),
arrayOf("z", "x", "y")
),
"ash"
)
</code></pre>
<p><em>Output</em></p>
<p><code>true</code></p>
<h2>Code</h2>
<pre class="lang-kotlin prettyprint-override"><code>fun findWord(wordSearch: Array<Array<String>>, word: String): Boolean {
checkArgErrors(wordSearch, word)
return horizSearch(wordSearch, word) || vertSearch(wordSearch, word)
}
fun horizSearch(wordSearch: Array<Array<String>>, word: String): Boolean {
for (r in wordSearch) {
var currentSearch = ""
var currentSearchIndex = 0
for (c in r) {
if (word.substring(currentSearchIndex, currentSearchIndex + 1).equals(c.toString())) {
currentSearch += c
currentSearchIndex++
if (currentSearch.equals(word))
return true
} else {
currentSearch = ""
currentSearchIndex == 0
}
}
}
return false
}
fun vertSearch(wordSearch: Array<Array<String>>, word: String): Boolean {
for (cIndex in 0 .. wordSearch[0].size - 1) {
var currentSearch = ""
var currentSearchIndex = 0
for (rIndex in 0 .. wordSearch.size - 1) {
println("c:${wordSearch[rIndex][cIndex]}")
val currentChar = word.substring(currentSearchIndex, currentSearchIndex + 1)
if (currentChar.equals(wordSearch[rIndex][cIndex].toString())) {
currentSearch += currentChar
currentSearchIndex++
if (currentSearch.equals(word)) return true
} else {
currentSearch = ""
currentSearchIndex == 0
}
}
}
return false
}
fun checkArgErrors(wordSearch: Array<Array<String>>, word: String) {
val exception =
if (wordSearch.size == 0 || wordSearch[0].size == 0) "The word search cannot be empty."
else if (word.isEmpty()) "Cannot search for an empty word."
else if (word.length > wordSearch[0].size || word.length > wordSearch.size)
"The word is too long to search for within the word search."
else null
if (exception != null)
throw IllegalArgumentException(exception)
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T01:19:34.073",
"Id": "251927",
"Score": "2",
"Tags": [
"array",
"complexity",
"search",
"kotlin"
],
"Title": "2D Array Word Search: Complexity and Optimization"
}
|
251927
|
<p>This question is a follow up question to the <a href="https://codereview.stackexchange.com/questions/251647/product-of-all-but-one-number-in-a-sequence/251893">Product of all but one number in a sequence</a>.</p>
<p>I am posting a new code here with taking into consideration the suggestions of [Edward], [CiaPan], [chux], [superb rain] and others. Please advise how the code efficiency can be improved.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
//without division, with O(n) time, but extra space complexity as suggested
//return new array on the heap
int *find_product_arr(const int *nums, int arr_size)
{
int *new_arr = (int *)malloc(sizeof(int)*arr_size);
int mult_prefix=1; //product of prefix elements
int mult_suffix=1; //product of suffix elements
//left most element special handling
new_arr[0]=1;
//swipe up
for(int i=1; i<arr_size; i++) {
mult_prefix *= nums[i-1];
new_arr[i] = mult_prefix;
}
//swipe down
for(int j=arr_size-2; j>=0; j--) {
mult_suffix *= nums[j+1];
new_arr[j] *= mult_suffix;
}
return new_arr;
}
int main(void)
{
/*Given an array of integers, return a new array such that each element at index i of the
new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24] */
int nums[] = {1, 2, 2, 4, 6};
int size = sizeof(nums)/sizeof(nums[0]);
int *products = find_product_arr(nums, size); //get a new array
for (int i = 0; i < size; i++)
printf("%d ", *(products+i) );
free(products); //release heap memory
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T08:37:40.133",
"Id": "496293",
"Score": "1",
"body": "Revised code posted here: https://codereview.stackexchange.com/questions/251991/product-of-all-but-one-number-in-a-sequence-follow-up-2"
}
] |
[
{
"body": "<p>This "new" vs. "original" array seems a bit unclear to me. This is C, so you have to define very carefully. The strdup() states at the very top:</p>\n<blockquote>\n<p>Memory for the new <em>string</em> is obtained with malloc(3), and can be\nfreed with free(3).</p>\n</blockquote>\n<p>Maybe it is the "find_" in <code>find_product_arr()</code> that is misleading.</p>\n<p>And then - after correctly returning that new array(-pointer) -\nwhy:</p>\n<p><code>*(products+i)</code> and not</p>\n<p><code>products[i]</code> ?</p>\n<p>This is like telling your new boss: <em>OK, I made that function allocate like strdup(), but for me it still is just a pointer, whose memory I have to manage.</em></p>\n<p>I minimalized <code>nums[]</code> and wrapped 12 loops around the function call (I gave it a new name). To "close' the loop I had to use <code>memcpy()</code>. If the <code>free()</code> is after the looping, then <code>products</code> gets a new address in every iteration.</p>\n<pre><code>int nums[] = {1,2,1};\nint size = sizeof(nums) / sizeof(nums[0]);\n\nint *products;\nint loops=12;\nwhile (loops--) {\n\n products = dup_product_arr(nums, size);\n\n for (int i = 0; i < size; i++)\n printf("%d ", products[i]);\n printf("\\n");\n\n memcpy(nums, products, sizeof(nums));\n free(products);\n}\n</code></pre>\n<p>The output:</p>\n<pre><code>2 1 2 \n2 4 2 \n8 4 8 \n32 64 32 \n2048 1024 2048 \n2097152 4194304 2097152 \n0 0 0 \n0 0 0 \n0 0 0 \n0 0 0 \n0 0 0 \n0 0 0 \n</code></pre>\n<p>So this overflow problem exists...but then again that multiply-all-rule is a bit exotic. Is it meant to run on floating point numbers? Close to 1.0?</p>\n<hr />\n<p>The combined <strong>swipe-up and swipe-down</strong> algorithm is very nice. But otherwise, because of unclear specification or over-interpretation, I don't like the result that much.</p>\n<p>In an interview situation I hope there was the possibility to clear this "new array" question, and then I would prefer like:</p>\n<pre><code> int nums[] = {1, 2, 2, 4, 6}; \n int size = sizeof(nums)/sizeof(nums[0]);\n int prods[size];\n swipe_product_into(nums, size, prods);\n</code></pre>\n<p>i.e. the function receives two arrays and the size. Both arrays are "allocated" automatically in main, without malloc/free.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T10:49:21.337",
"Id": "251938",
"ParentId": "251929",
"Score": "3"
}
},
{
"body": "<p>The algorithm is optimal, and any perceived inefficiency in expression should not faze the compiler at least. So, it will all be about optimizing for readability and maintenance.</p>\n<h3>Naming</h3>\n<p>There are three factors for choosing names:</p>\n<ul>\n<li>Being <strong>consistent</strong> (with the rest of the code, and the field's jargon),</li>\n<li>being <strong>concise</strong> (all else being equal, less is more), and</li>\n<li>being <strong>descriptive</strong>.</li>\n</ul>\n<p>Infrequent use and big scope call for more descriptive identifiers, even if conciseness suffers. Properly choosing what to describe and being precise about it is crucial.</p>\n<ol>\n<li><p><code>find_product_arr()</code> is a miss-nomer. There is no finding about it, but calculation, or derivation. And if <code>product</code> is pluralized, the awkward abbreviation for array can also be dropped, as it is implied. Thus, better name it like <code>derive_products()</code>.</p>\n</li>\n<li><p><code>arr_size</code> is also a bad one. Where is <code>arr</code>? <code>new_arr</code> might be an implementation-detail, not that the user should look or care, as it is not part of the public interface. A simple <code>count</code> would be best, <code>count_nums</code> would also serve.</p>\n</li>\n<li><p><code>new_arr</code> also doesn't describe anything relevant. I would call it <code>result</code>, <code>res</code>, or just <code>r</code>. I prefer the shortest as it is a very common identifier in my code.</p>\n</li>\n<li><p><code>mult_prefix</code> and <code>mult_suffix</code> suffer from a far over-broad scope. <a href=\"//stackoverflow.com/questions/27729930/is-declaration-of-variables-expensive\">The compiler might not care, but we do</a>. Tightening the scope to just the relevant for-loop lets us rename both to <code>mult</code>.</p>\n</li>\n<li><p>Be precise: Do you have a <code>size</code> (what is the unit of measurement? Bytes is common), or a <code>count</code>.</p>\n</li>\n</ol>\n<h3>Allocating memory</h3>\n<pre><code>int *new_arr = (int *)malloc(sizeof(int)*arr_size);\n</code></pre>\n<ol start=\"6\">\n<li><p>The above line uses <code>sizeof(TYPE)</code>, which is error-prone as it repeats information manually derived from the left hand side. Use <code>sizeof *pointer</code> and let the compiler figure it out.</p>\n</li>\n<li><p>"<em><a href=\"//stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc\">Do I cast the result of malloc?\n</a></em>"<br />\nNo, not in C, as it is superfluous and error-prone.</p>\n</li>\n<li><p>Always check the result of <code>malloc()</code>. It <em>can</em> fail.</p>\n</li>\n</ol>\n<p>Fixed code:</p>\n<pre><code>int* r = malloc(count * sizeof *r);\nif (!r && count)\n return 0; // or die("alloc() failed in ABC.\\n"); which should call vfprintf and abort\n</code></pre>\n<h3>Use indexing when you mean it</h3>\n<pre><code>printf("%d ", *(products+i) );\n</code></pre>\n<ol start=\"9\">\n<li>I really wonder why you didn't use normal indexing <code>products[i]</code> instead of <code>*(products+i)</code> in <code>main()</code> like everywhere else.</li>\n</ol>\n<h3>The rest</h3>\n<ol start=\"10\">\n<li><p>In a definition, marking the absence of parameters with <code>void</code> is not needed. Make of it what you will.</p>\n</li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code> since C99. Not sure you should care.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T08:10:49.110",
"Id": "496290",
"Score": "0",
"body": "Thank you as always. I will edit the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:47:22.523",
"Id": "496355",
"Score": "0",
"body": "BTW: Changed the long-form suggestion for the return value to `result`, as that looks better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T11:04:01.513",
"Id": "251939",
"ParentId": "251929",
"Score": "4"
}
},
{
"body": "<p>You could eliminate the special case here:</p>\n<blockquote>\n<pre><code>//left most element special handling\nnew_arr[0]=1;\n\n//swipe up \nfor(int i=1; i<arr_size; i++) {\n mult_prefix *= nums[i-1];\n new_arr[i] = mult_prefix;\n}\n</code></pre>\n</blockquote>\n<p>by assigning before multiplying, and bringing index 0 into the loop:</p>\n<pre><code>//swipe up \nfor(int i=0; i<arr_size; i++) {\n new_arr[i] = mult_prefix;\n mult_prefix *= nums[i];\n}\n</code></pre>\n<p>A similar transformation also applies to the downward sweep (so that each iteration only accesses <code>nums[i]</code>, making it easier to reason about).</p>\n<p>There is a cost associated with the simplification: an extra multiply, and risk of overflow (technically Undefined behaviour, even though we don't use the final value).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T07:51:34.980",
"Id": "496287",
"Score": "0",
"body": "I have edited the code. Thanks pal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:51:17.793",
"Id": "496335",
"Score": "1",
"body": "Of course, that means one multiply more. And thus increased likelihood of overflow, which is UB, even if probably handled in a benign way. I should have found this simplification too ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T13:45:08.173",
"Id": "251946",
"ParentId": "251929",
"Score": "4"
}
},
{
"body": "<p>The code is much improved from the previous version. Well done! Here are a few more things that may help you further improve your code.</p>\n<h2>Don't cast result of <code>malloc</code></h2>\n<p>The <code>malloc</code> call returns a <code>void *</code> and one of the special aspects of C is that such a type does not need to be cast to be converted into another pointer type. So for example, this line:</p>\n<pre><code>int *new_arr = (int *)malloc(sizeof(int)*arr_size);\n</code></pre>\n<p>could be shortened to this:</p>\n<pre><code>int *new_arr = malloc(arr_size * sizeof *new_arr);\n</code></pre>\n<p>Note also that we don't need to repeat <code>int</code> here. This makes it easier to keep it correct if, for example, we wanted to change to <code>long *</code>.</p>\n<h2>Check the return value of <code>malloc</code></h2>\n<p>If the program runs out of memory, a call to <code>malloc</code> can fail. The indication for this is that the call will return a <code>NULL</code> pointer. You should check for this and avoid dereferencing a <code>NULL</code> pointer (which typically causes a program crash).</p>\n<h2>Eliminate special handling</h2>\n<p>Instead of this:</p>\n<pre><code>//left most element special handling\nnew_arr[0]=1;\n\n//swipe up \nfor(size_t i=1; i<arr_size; i++) {\n mult_prefix *= nums[i-1];\n new_arr[i] = mult_prefix;\n}\n\n//swipe down\nfor(long j=arr_size-2; j>=0; j--) {\n mult_suffix *= nums[j+1];\n new_arr[j] *= mult_suffix;\n}\n</code></pre>\n<p>Here's how I'd write it:</p>\n<pre><code>static const int multiplicative_identity = 1;\n// calculate product of preceding numbers for each i\nfor (size_t i = arr_size; i; --i) {\n *result++ = prod;\n prod *= *nums++;\n}\nprod = multiplicative_identity;\n// calculate product of succeeding numbers for each i, \n// starting from the end, and multiply by current index\nfor (size_t i = arr_size; i; --i) {\n *(--result) *= prod;\n prod *= *(--nums);\n}\nreturn result;\n</code></pre>\n<p>There are a couple of things worth noting here. First, is that there is no need for a special case when written this way. Second, the use of pointers simplifies the code and makes it more regular. Third, many processors have a special instruction for looping down and/or checking for zero which tends to make counting down ever so slightly faster than counting up. Fourth, there is no reason not to use the passed value <code>nums</code> as a pointer since the pointer is a local copy (even though the contents are not). In this particular case, since we increment the pointer to the end, moving the other direction is trivially simple since the pointers are already where we need them for both <code>result</code> and <code>nums</code>.</p>\n<h2>Consider a generic version</h2>\n<p>What if we wanted to create a similar function, but one that does the sum instead of the product? It's not at all needed for this project, but worth thinking about because of both the mathematics and the code. You will see that I called the constant <code>multiplicative_identity</code>. Simply put, an <em>identity element</em> of an operation over a set is the value that, when combined by the operation with any other element of the set yields the same value. So for example, <span class=\"math-container\">\\$n * 1 = n\\$</span> for all real values of <span class=\"math-container\">\\$n\\$</span> and <span class=\"math-container\">\\$n + 0 = n\\$</span> for all real values of <span class=\"math-container\">\\$n\\$</span>. This suggests a generic routine:</p>\n<pre><code>int* exclusive_op(const int* nums, size_t arr_size, int (*op)(int, int), int identity)\n{\n int* result = malloc(arr_size * sizeof(int));\n if (result == NULL || arr_size == 0) {\n return NULL;\n }\n int prod = identity;\n // calculate op of preceding numbers for each i\n for (size_t i = arr_size; i; --i) {\n *result++ = prod;\n prod = op(prod, *nums++);\n }\n prod = identity;\n // calculate op of succeeding numbers for each i, \n // starting from the end, and multiply by current index\n for (size_t i = arr_size; i; --i) {\n --result;\n *result = op(*result, prod);\n prod = op(prod, *(--nums));\n }\n return result;\n}\n</code></pre>\n<p>Now we can define functions with which to use this generic version:</p>\n<pre><code>int add(int a, int b) { \n return a+b;\n}\n\nint mult(int a, int b) { \n return a*b;\n}\n\nint multmod3(int a, int b) { \n return (a*b)%3;\n}\n\nint summod3(int a, int b) { \n return (a+b)%3;\n}\n\nstruct {\n int (*op)(int, int); \n int identity;\n} ops[] = {\n { mult, 1 },\n { add, 0 },\n { multmod3, 1 },\n { summod3, 0 },\n};\n</code></pre>\n<p>Using that array of <code>struct</code>s, we could produce the same effect as your <code>find_product_arr</code> by using this wrapper function:</p>\n<pre><code>int *generic(const int *nums, size_t arr_size) {\n return exclusive_op(nums, arr_size, ops[0].op, ops[0].identity);\n}\n</code></pre>\n<p>As you can see with the last two functions, this works with <em>any</em> operation that is both associative and that has an identity value.</p>\n<h2>Create some test code</h2>\n<p>How do you know if your results are correct? One way to do that is to write some test code. As I commented on your earlier code, it wasn't very efficient but was obviously correct. That is a nice foundation on which to create test code to make sure that your new version still produces correct results. Here's one way to do that. First, we need a way to compare the returned result against a known correct version:</p>\n<pre><code>bool compare(size_t size, const int* result, const int* expected)\n{\n for (size_t i = 0; i < size; ++i) {\n if (result[i] != expected[i]) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n<p>Now we can get fancy with colors and a test array:</p>\n<pre><code>#define RED "\\033[31m"\n#define GREEN "\\033[32m"\n#define WHITE "\\033[39m"\n\nint main(void)\n{\n struct {\n size_t array_size;\n int in[5];\n int expected[5];\n } test[] = {\n { 5, { 1, 2, 3, 4, 5 }, { 120, 60, 40, 30, 24 } },\n { 4, { 1, 2, 3, 4, 5 }, { 24, 12, 8, 6, 0 } },\n { 3, { 1, 2, 3, 4, 5 }, { 6, 3, 2, 0, 0 } },\n { 2, { 1, 2, 3, 4, 5 }, { 2, 1, 0, 0, 0 } },\n { 1, { 1, 2, 3, 4, 5 }, { 1, 0, 0, 0, 0 } },\n { 1, { 0, 2, 3, 4, 5 }, { 1, 0, 0, 0, 0 } },\n { 5, { 1, 2, 2, 4, 5 }, { 80, 40, 40, 20, 16 } },\n { 5, { 9, 2, 2, 4, 5 }, { 80, 360, 360, 180, 144 } },\n { 5, { 0, 2, 0, 4, 5 }, { 0, 0, 0, 0, 0 } },\n { 5, { 7, 2, 0, 4, 5 }, { 0, 0, 280, 0, 0 } },\n { 5, { -1, -1, -1, -1, -1 }, { 1, 1, 1, 1, 1 } },\n { 4, { -1, -1, -1, -1, -1 }, { -1, -1, -1, -1, -1 } },\n { 2, { INT_MAX, INT_MIN, 0, 0, 0 }, { INT_MIN, INT_MAX, 0, 0, 0 } },\n };\n const size_t test_count = sizeof(test)/sizeof(test[0]);\n\n const char* function_names[] = { "original", "find_product_arr", "generic" };\n int *(*functions[])(const int*, size_t) = { original, find_product_arr, generic };\n const size_t function_count = sizeof(functions)/sizeof(functions[0]);\n\n for (size_t i = 0; i < test_count; ++i) {\n for (size_t j = 0; j < function_count; ++j) {\n int *result = functions[j](test[i].in, test[i].array_size);\n bool ok = compare(test[i].array_size, result, test[i].expected);\n printf("%s: %20.20s { %lu, {",\n (ok ? GREEN " OK" WHITE: RED "BAD" WHITE),\n function_names[j],\n test[i].array_size\n );\n dump(test[i].in, test[i].array_size);\n printf("}, {");\n dump(test[i].expected, test[i].array_size);\n printf("} }");\n if (ok) {\n printf("\\n");\n } else {\n printf(", got " RED "{" );\n dump(result, test[i].array_size);\n printf("}" WHITE "\\n");\n }\n free(result);\n }\n }\n}\n</code></pre>\n<p>Is it overkill? Probably, but if I saw such code associated with a function like yours, I'd be much more likely to both use it as is with confidence and also to modify it or write a new version with the expectation of being able to test it quickly and accurately.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T21:41:15.440",
"Id": "251971",
"ParentId": "251929",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251946",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T04:17:36.350",
"Id": "251929",
"Score": "5",
"Tags": [
"c",
"interview-questions"
],
"Title": "Product of all but one number in a sequence - Follow Up"
}
|
251929
|
<p>I have two arrays of objects. One has an id property with a list of ids and the second has an object with a unique id property. I want to filter the ids in the second array with the first list and get the data.</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 data1 = [{
name: 'A',
ids: [1, 2, 3]
}, {
name: 'B',
ids: [4, 5, 6]
}, {
name: 'C',
ids: [7, 8, 9]
}]
const data2 = [{
id: 1,
color: 'red'
}, {
id: 2,
color: 'black'
}, {
id: 3,
color: 'blue'
}, {
id: 4,
color: 'yellow'
}, {
id: 5,
color: 'green'
}, {
id: 6,
color: 'pink'
},
{
id: 7,
color: 'orange'
}, {
id: 8,
color: 'white'
}, {
id: 9,
color: 'teal'
}
]
const arrayToObject = (array) =>
array.reduce((obj, item) => {
obj[item.id] = item
return obj
}, {})
console.log(arrayToObject(data2))
const newData = data1.map(item => {
return {
name: item.name,
data: item.ids.map(i => arrayToObject(data2)[i])
}
})
console.log(newData)</code></pre>
</div>
</div>
</p>
<p>Expected Output:</p>
<pre><code>[
{
"name": "A",
"data": [
{
"id": 1,
"color": "red"
},
{
"id": 2,
"color": "black"
},
{
"id": 3,
"color": "blue"
}
]
},
{
"name": "B",
"data": [
{
"id": 4,
"color": "yellow"
},
{
"id": 5,
"color": "green"
},
{
"id": 6,
"color": "pink"
}
]
},
{
"name": "C",
"data": [
{
"id": 7,
"color": "orange"
},
{
"id": 8,
"color": "white"
},
{
"id": 9,
"color": "teal"
}
]
}
]
</code></pre>
<p>I did manage to achieve this, but I guess there might be a better clean and performant solution. Please advice me on that.</p>
<p>P.S: I am also open to using lodash.</p>
|
[] |
[
{
"body": "<h2>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> to reduce search complexity</h2>\n<p>Currently your method is rather complex at <span class=\"math-container\">\\$O(n^2)\\$</span>. The reason is that for each Id you iterate each item to locate the one with the Id you want.</p>\n<p>You can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\"><code>Map</code></a> to reduce the complexity. <code>Map</code> uses a hash to locate items, you can add each id to a map linking ids to each category.</p>\n<p>Then just iterate the items array using the map to locate the correct category and add the item.</p>\n<p>The result is achieved in a time complexity of <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<p>The example shows how this can be implemented.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const categories = [{name: 'A', ids: [1, 2, 3]}, {name: 'B', ids: [4, 5, 6]}, {name: 'C', ids: [7, 8, 9]}]\nconst items = [{ id: 1, color: 'red'}, { id: 2, color: 'black'}, { id: 3, color: 'blue'}, { id: 4, color: 'yellow'}, { id: 5, color: 'green'}, { id: 6, color: 'pink'},{ id: 7, color: 'orange'}, { id: 8, color: 'white'}, { id: 9, color: 'teal'}];\n\n\nfunction categorizeById(cats, items) {\n const idMap = new Map();\n const result = cats.map(cat => {\n const category = {name: cat.name, data: []};\n cat.ids.forEach(id => idMap.set(id, category));\n return category ;\n },[]);\n items.forEach(item => idMap.get(item.id).data.push({...item}));\n return result;\n}\nconsole.log(categorizeById(categories, items));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T06:25:21.667",
"Id": "251933",
"ParentId": "251931",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251933",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T05:31:25.353",
"Id": "251931",
"Score": "1",
"Tags": [
"javascript",
"array",
"lodash.js"
],
"Title": "Compare two arrays of objects and get the objects based on ids"
}
|
251931
|
<p>This question is a follow up question to the <a href="https://codereview.stackexchange.com/questions/251894/xor-linked-list-implementation">XOR linked list implementation</a>.</p>
<p>I am posting a new code here with taking into consideration the suggestions of Toby Speight and Deduplicator. Please advise how the code efficiency can be improved.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
struct StNode {
int value;
uintptr_t both;
};
typedef struct StNode StHexNode;
StHexNode *add(StHexNode *lastNode, int value)
{
StHexNode *newNode = malloc(sizeof(struct StNode));
newNode->value = value;
//latest node's [both]=pointer value pointing previous node:
newNode->both = (uintptr_t)lastNode;
//calculating previous node [both]:
lastNode->both = (uintptr_t)newNode ^ lastNode->both;
return newNode;
}
StHexNode *get(StHexNode *headNode, unsigned int index)
{
StHexNode *prevNode;
StHexNode *currNode;
uintptr_t tmp;
//cur=1, prev=0
currNode = (struct StNode *) ((headNode->both) ^ 0);
prevNode = headNode;
for(int i=2; i<=index; i++)
{
tmp = (uintptr_t)prevNode;
prevNode = currNode;
currNode = (struct StNode *) (currNode->both ^ tmp);
}
return currNode;
}
int free_list(StHexNode *headNode)
{
StHexNode *prevNode;
StHexNode *currNode;
uintptr_t tmp;
int ctr=0;
//case: there is a only head node in the list
if(headNode->both == 0)
{
free(headNode);
return ++ctr;
}
//prev=head, curr=second_node
currNode = (struct StNode *) ((headNode->both) ^ 0);
prevNode = headNode;
while(currNode->both != (uintptr_t)prevNode)
{
tmp = (uintptr_t)prevNode;
free(prevNode);
ctr++;
prevNode = currNode;
currNode = (struct StNode *) (currNode->both ^ tmp);
}
//last node
free(currNode);
ctr++;
return ctr;
}
int main(void)
{
unsigned int i;
//I named first node as headNode, and last node as tailNode
//create head node with both=0 since there is no previous node to it
StHexNode *headNode = malloc(sizeof(struct StNode));
StHexNode *tailNode = headNode; //last node pointer in the list
//lets add 100 nodes after head
//special handling of both value at head node
for(headNode->both = 0, i=100; i<200; i++)
{
tailNode = add(tailNode, i);
//printf("last node value:%d\n", tailNode->value);
}
//get index=50 node value
StHexNode *iNode = get(headNode, 50);
printf( "result: %d\n", iNode->value);
//free memory
printf("we released %d list\n", free_list(headNode));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T10:24:40.727",
"Id": "496169",
"Score": "3",
"body": "Any reason you didn't take Deduplicator's advice to use `sizeof *newNode` as argument to `malloc()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T10:25:34.670",
"Id": "496170",
"Score": "4",
"body": "I still see no function to release the resources."
}
] |
[
{
"body": "<h1>Don't use a different name for a <code>struct</code> and its <code>typedef</code></h1>\n<p>Why is <code>struct StNode</code> typedef'ed to <code>StHexNode</code>? What does the <code>Hex</code> mean here, I don't see anything hexadecimal or hexagonal in the rest of the code? You can use exactly the same name for a <code>struct</code> as for its <code>typedef</code>, so I would just use that:</p>\n<pre><code>typedef struct StNode StNode;\n</code></pre>\n<p>You can also combine the <code>typedef</code> with the <code>struct</code> definition:</p>\n<pre><code>typedef struct StNode {\n ...\n} StNode;\n</code></pre>\n<h1>Use <code>typedef</code>s consistently</h1>\n<p>I see you use <code>StHexNode</code> in some places, and <code>struct StNode</code> in others. Be consistent and only use the typedef'ed variant.</p>\n<h1>Avoid repeating type names if possible</h1>\n<p>In this line:</p>\n<pre><code>StHexNode *newNode = malloc(sizeof(struct StNode));\n</code></pre>\n<p>Besides the inconstent use of the typedef, you repeat the type twice. That makes this error prone (if you make a mistake on the right side it will compile without errors but it will probably be wrong), and if you ever have to change the type of the variable <code>newNode</code>, you would have to do it in at least two places. It is better to avoid repeating the type name, but instead repeat the variable name:</p>\n<pre><code>StNode *newNode = malloc(sizeof(*newNode));\n</code></pre>\n<h1>Prefer using compound assignment operators to avoid repetition</h1>\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/language/operator_assignment#Builtin_compound_assignment\" rel=\"nofollow noreferrer\">compound assignment operators</a> if possible to save some typing, and also avoiding possible mistakes. For example, instead of:</p>\n<pre><code>lastNode->both = (uintptr_t)newNode ^ lastNode->both;\n</code></pre>\n<p>Prefer:</p>\n<pre><code>lastNode->both ^= (uintptr_t)newNode;\n</code></pre>\n<h1>Simplifying <code>get()</code></h1>\n<p>You can simplify the function <code>get()</code> somewhat. In particular, when looping over the elements of a list, try to start at index <code>0</code>, and avoid making the start and end special cases. You can do this here like so:</p>\n<pre><code>StNode *get(StNode *headNode, unsigned int index)\n{ \n StNode *currNode = headNode;\n uintptr_t prev = 0;\n \n for (int i = 0; i < index; i++)\n {\n uintptr_t next = currNode->both ^ prev;\n prev = (uintptr_t)currNode;\n currNode = (StNode *)(next);\n }\n\n return currNode;\n}\n</code></pre>\n<p>Note that you could even avoid the declaration of <code>currNode</code> if you change the name of <code>headNode</code> to <code>currNode</code>, but I would personally keep it as it is above, as it makes the role of the parameter and the local variable more clear.</p>\n<h1>Simplifying <code>free_list()</code></h1>\n<p>The same goes for <code>free_list()</code>: you should not need to make a list of one element a special case. Also, why is <code>free_list()</code> calculating the number of elements of a list that will have been deleted by the time it returns?</p>\n<pre><code>void free_list(StNode *headNode)\n{\n StNode *currNode = headNode;\n uintptr_t prev = 0;\n \n while (currNode)\n {\n uintptr_t next = currNode->both ^ prev;\n prev = (uintptr_t)currNode;\n free(currNode);\n currNode = (StNode *)(next);\n }\n}\n</code></pre>\n<h1>Use a unique and consistent naming scheme</h1>\n<p>If you want to use your XOR linked list in a real program, consider that names like <code>StNode</code> and <code>get()</code> are very generic and will likely conflict with other parts of a larger project. Maybe you need a binary tree implementation as well for example, and how are you going to name its function to retrieve an element at a given index? To solve this issue in C, come up with a unique prefix that you can use for all the struct and function names. For example, prefix everything with <code>xllist_</code>:</p>\n<pre><code>typedef struct xllist_node {\n ...\n} xllist_node;\n\nxllist_node *xllist_add(xllist_node *lastNode, int value);\nxllist_node *xllist_get(xllist_node *headNode, usigned int index);\nvoid xllist_free(xllist_node *headNode);\n</code></pre>\n<p>Of course you can argue about what the prefix should be exactly. I find something like <code>xor_linked_list</code> or <code>XorLinkedList</code> a bit too verbose, so <code>xllist</code> is a compromise: it still has <code>list</code> clearly in the name, and if you don't know what <code>xl</code> is you can look it up, and once you have seen what it means it is easy to remember that <code>xl</code> stands for <code>XOR linked</code> I hope.</p>\n<h1>Create a <code>struct</code> representing the whole list</h1>\n<p>You have a <code>struct</code> for a node, but not one for the whole list. That means the caller of your functions has to manually allocate the first list element, and it needs to keep track of both the head and tail node. It is much better if you create a <code>struct</code> representing the list:</p>\n<pre><code>typedef struct xllist {\n xllist_node *head;\n xllist_node *tail;\n} xllist;\n</code></pre>\n<p>And then pass a pointer to this <code>struct</code> to functions like <code>xllist_get()</code>, <code>xllist_add()</code> and <code>xllist_free()</code>, like so:</p>\n<pre><code>xllist_node *xllist_add(xllist *list, int value) {\n xllist_node *newNode = malloc(sizeof(*newNode));\n newNode->both = (uintptr_t)xllist->tail;\n newNode->value = value;\n\n if (xllist->tail) {\n // Append it to the existing tail node\n xllist->tail->both ^= (uintptr_t)newNode;\n xllist->tail = newNode;\n } else {\n // The list was empty\n xllist->head = newNode;\n xllist->tail = newNode;\n }\n\n return newNode;\n}\n</code></pre>\n<p>And you use it like so in <code>main()</code>:</p>\n<pre><code>xllist myList = {NULL, NULL}; // declare an empty list\n\nfor (int i = 100; i < 200; i++)\n{\n xllist_add(&myList, i);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:59:26.483",
"Id": "252019",
"ParentId": "251932",
"Score": "2"
}
},
{
"body": "<p>Updated version after applying advice from G. Sliepen.</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\ntypedef struct StNode {\n int value;\n uintptr_t both;\n} StNode; \n\n//keep track of linked list head and tail\ntypedef struct xllist {\n //I named first node as headNode, and last node as tailNode\n StNode *head;\n StNode *tail;\n} xllist;\n\nStNode *xllist_add(xllist *list, int value)\n{\n StNode *newNode = malloc(sizeof *newNode); \n newNode->value = value;\n if(list->head == NULL)\n {\n //very first node\n list->head = newNode;\n list->tail = newNode;\n list->head->both = 0;\n return newNode;\n }\n \n list->tail->both ^= (uintptr_t)newNode;\n newNode->both = (uintptr_t)list->tail;\n list->tail = newNode;\n \n return newNode;\n}\n\nStNode *xllist_get(xllist *list, unsigned int index)\n{ \n StNode *currNode = list->head;\n uintptr_t prev=0;\n \n for(int i=0; i<index; i++)\n {\n uintptr_t next = currNode->both ^ prev;\n prev = (uintptr_t)currNode;\n currNode = (StNode *)next;\n }\n return currNode;\n}\n\nvoid xllist_free(xllist *list)\n{\n StNode *currNode=list->head;\n uintptr_t prev=0, next;\n \n while(currNode)\n {\n next = prev ^ (uintptr_t)currNode->both;\n prev = (uintptr_t)currNode;\n free(currNode);\n currNode = (StNode *)next;\n \n }\n \n}\n\nint main(void) \n{\n unsigned int i; \n xllist myList = {NULL, NULL};\n \n //lets xllist_add 100 nodes after head\n //special handling of both value at head node\n for(i=100; i<200; i++)\n {\n xllist_add(&myList, i);\n }\n \n //xllist_get index=50 node value\n StNode *iNode = xllist_get(&myList, 50);\n printf( "result: %d\\n", iNode->value);\n \n //free memory\n xllist_free(&myList);\n \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:34:07.357",
"Id": "496439",
"Score": "1",
"body": "I would still rename `StNode` to `xllist_node`, again to have a consistent prefix and to avoid possible conflicts with other data structures that have nodes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:36:56.160",
"Id": "496440",
"Score": "0",
"body": "got it. Important thing is I got the concept. will very appreciated if you review my codes in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:38:50.217",
"Id": "496441",
"Score": "1",
"body": "Sure, just post new questions here on CodeReview and I and others will have a look at it :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:06:29.077",
"Id": "252037",
"ParentId": "251932",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "252019",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T06:15:59.723",
"Id": "251932",
"Score": "5",
"Tags": [
"c",
"linked-list"
],
"Title": "XOR linked list implementation - Follow Up"
}
|
251932
|
<h2>Story</h2>
<p>Niñez friends from Kakao Elementary School meet a stream with stepping stones on an autumn picnic with Ms. Ryan and are about to cross over to the other side. Ms. Ryan made the following rules so that Niñez and his friends can safely cross the river:</p>
<ul>
<li>Stepping stones are placed in a row, and the number of times a kid may step on a stone is written on each stone.</li>
<li>The number on the stone decreases by one each time a kid steps on them.</li>
<li>When the number of stepping stones reaches 0, you can no longer step on them.</li>
<li>A kid can jump, skipping several stones. The maximum number of stones that a kid may skip is given as a parameter k.</li>
<li>If a kid jumps, you always jump to the nearest stepping stone that isn't 0.</li>
</ul>
<p>The friends of Niñez are on the left side of the stream, and they must arrive across the right side of the stream to be counted as crossing the stepping stone.</p>
<p><strong>How many kids can cross the river, given an array of initial values on the stones and the parameter k?</strong></p>
<h2>Constraints</h2>
<ul>
<li>The number of Ninez friends who must cross the stepping stone is considered to be unlimited.</li>
<li>The stones array has a size of at least 1 and has a maximum length of 200,000.</li>
<li>The initial value of each element in the stones array is a natural number between 1 and 200,000,000.</li>
<li>k is a natural number greater than or equal to 1 and less than or equal to the length of the stones.</li>
</ul>
<h2>Code review question</h2>
<p>How should i revise my code? this is Kakao intern code test. I used loop to change stone numbers when stepped and repeat many times . It returns how many people could cross the river.</p>
<p><a href="https://programmers.co.kr/learn/courses/30/lessons/64062" rel="nofollow noreferrer">Original challenge (in Korean)</a></p>
<h2>Example</h2>
<pre><code>stones = [2, 4, 5, 3, 2, 1, 4, 2, 5, 1]
k=3
</code></pre>
<p>After the first kid crosses, the stones have the following values:</p>
<pre><code>stones = [1, 3, 4, 2, 1, 0, 3, 1, 4, 0]
</code></pre>
<p>The second kid makes it, making two jumps:</p>
<pre><code>stones = [0, 2, 3, 1, 0, 0, 2, 0, 3, 0]
</code></pre>
<p>The third kid makes it, making four jumps:</p>
<pre><code>stones = [0, 1, 2, 0, 0, 0, 1, 0, 2, 0]
</code></pre>
<p>Now it takes a jump of 4 stones to get to the other side, which is larger than k = 3. So the answer for this input is three kids, or simply <code>3</code>.</p>
<pre><code>def solution(stones, k):
num=len(stones)
answer=0
for count in range(max(stones)):
stat=-1
for i in range(num):
if stat==i-1:
if stones[i]==0:
for j in range(i+1,num):
if stones[j]==0:
if j-stat>=k:
return answer
else:
pass
elif stones[j]!=0:
stat=j
stones[j]-=1
break
elif stones[i]!=0:
stat=i
stones[i]-=1
if stat+k>=num:
answer+=1
elif stat+k<num:
return answer
return answer
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T07:28:37.490",
"Id": "496160",
"Score": "0",
"body": "Can you provide a link to the programming challenge?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T08:08:57.120",
"Id": "496161",
"Score": "2",
"body": "@aryanParekh while it isn't very noticeable it does contain [a link](https://programmers.co.kr/learn/courses/30/lessons/64062) at the end of the description/question, before the example input"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T08:32:32.917",
"Id": "496162",
"Score": "0",
"body": "Ah yes sorry I missed that, my bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T11:39:59.060",
"Id": "496174",
"Score": "0",
"body": "@AryanParekh sorry, I'm new here. I will do better next time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T12:07:25.137",
"Id": "496176",
"Score": "0",
"body": "@sherloock You're doing everything fine! I missed the link you provided, my mistake not yours"
}
] |
[
{
"body": "<h2>Try to avoid nested if and for loops</h2>\n<p>The structure of your code is a bunch of nested <code>for</code> and <code>if-elif-else</code> statements. Try to find a way to compact those by restructuring your code or logic. Some examples:</p>\n<p>No need to use <code>elif</code> if <code>else</code> suffices.</p>\n<pre><code>if stones[i]==0:\n # code\nelif stones[i]!=0:\n # more code\n</code></pre>\n<p>Can be rewritten as:</p>\n<pre><code>if stones[i]==0:\n # code\nelse: # you can place a comment here like: stones[i]!=0 \n # more code\n</code></pre>\n<p>Combine if statements with <code>and</code> or <code>or</code>:</p>\n<pre><code>if stat==i-1:\n if stones[i]==0:\n</code></pre>\n<p>Can be rewritten as:</p>\n<pre><code>if stat==i-1 and stones[i]==0:\n</code></pre>\n<p>No need to state and <code>else</code> if it does nothing:</p>\n<pre><code>else:\n pass\n</code></pre>\n<p>Can be omitted.</p>\n<h2>Try to use Python code style PEP8 and meaningfull variable naming</h2>\n<p>See <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. Some examples in your code that can be improved for consistent readability by other Pythonistas:</p>\n<p>Use spaces around operators and comparisons. These (unrelated) lines:</p>\n<pre><code>num=len(stones)\nrange(i+1,num)\nif j-stat>=k:\n pass\n</code></pre>\n<p>Becomes:</p>\n<pre><code>num = len(stones) # spaces around '='\nrange(i+1, num) # space after ',' in function arguments\nif j - stat >= k: # spaces around '-' and '>='\n pass\n</code></pre>\n<p>Use meaningfull function and variable names</p>\n<ul>\n<li><code>solution()</code> -> <code>num_kids_crossing_river()</code></li>\n<li><code>answer</code> -> <code>num_kids</code> or simply <code>kids</code></li>\n<li><code>i</code> -> <code>current_stone</code></li>\n<li><code>k</code> -> <code>max_leap</code></li>\n<li>Etc.</li>\n</ul>\n<h2>Use docstrings and comments to clarify your code</h2>\n<p>Document your code. Place documentation below your function definition (a "docstring") like this:</p>\n<pre><code>def num_kids_crossing_river(stones, max_leap)\n""" Return the number of kids that can pass the array of stones. \n <<some more text here; like in the text from the exercise>>\n\n Args:\n stones (list(int)): initial values on the stones.\n max_leap (int): maximum number of stones a kid can jump over/skip.\n\n Returns:\n int: the number of kids that can cross the river.\n</code></pre>\n<p>Use comments to document what you are doing, as far as it isn't clear from the code itself. Document the algorithm/idea and not the code itself.</p>\n<p>For example:</p>\n<pre><code># Maximum number of iterations is the maximum number on the stones\nfor count in range(max(stones)):\n etc.\n</code></pre>\n<h2>Most importantly: rethink the problem</h2>\n<p>All of the above can be used to improve your code and coding style, but it does not really optimise your code. One important step in coding is to first <em>think</em> about what you are about to code and <em>how</em> to code it.</p>\n<p>If you look at the example, you see that the numbers in the stone array decrease, until there are k or more zero's next to eachother.</p>\n<p>So an other way to formulate the problem is: how many times can I subtract 1 from an array until I have k or more zero's next to eachother?</p>\n<p>Now suppose <code>k = 0</code> (no jumps). And <code>stones = [5, 6, 7]</code>. You can see/imagine that the number of kids that can pass is 5.</p>\n<p>Now suppose <code>k = 1</code> and the same <code>stones</code>. You can see/imagine that the number of kids that can pass is 6. The 5 becomes 0 first, but you can skip it. Next, the 6 becomes 0.</p>\n<p>What we can do, is to iterate over the stones, and check each "window" of k stones. And check the maximum value in that window. After that number of steps, that window is all 0 and the game stops. So we need to find the window that first gets to 0.</p>\n<p>So now we can rephrase the problem again, more in mathematical terms: what is the minimum value of the maximum value of all sequential windows of stones with length k?</p>\n<p>Illustrated with the example give in the problem statement: <code>k = 3; stones = [2, 4, 5, 3, 2, 1, 4, 2, 5, 1]</code></p>\n<pre><code>[2, 4, 5, 3, 2, 1, 4, 2, 5, 1]\n+-------+ # maximum = 5 for this window\n +-------+ # maximum = 5 for this window\n +-------+ # maximum = 5 for this window\n +-------+ # maximum = 3 for this window\n +-------+ # maximum = 4 for this window\n +-------+ # maximum = 4 for this window\n +-------+ # maximum = 5 for this window\n +-------+ # maximum = 5 for this window\n</code></pre>\n<p>Now the minimum value of all those maximum values is 3, which is the answer.</p>\n<p>You can see that the value of 3 exactly appears in the piece that goes 0 first and where the fourth kid is stuck.</p>\n<p>Here, I give you two implementations. One uses basic Python concepts, like your code. The second uses the (intermediate level Python concept) list comprehensions.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def min_max_of_subsection(array, k):\n \"\"\" Returns the minimum value of the maximum value of each subsection of length k in array.\n\n Args:\n array (list): an array of values (can be anything that has an order)\n k (int): length of the sub section\n\n Returns:\n value from array\n \"\"\"\n max_subsection = []\n for array_index in range(len(array) - k + 1):\n max_subsection.append(max(array[array_index:array_index + k]))\n return min(max_subsection)\n\n\ndef min_max_of_subsection2(array, k):\n \"\"\" Returns the minimum value of the maximum value of each subsection of length k in array.\n\n Args:\n array (list): an array of values (can be anything that has an order)\n k (int): length of the sub section\n\n Returns:\n value from array\n \"\"\"\n return min(max(array[idx:idx+k]) for idx in range(len(array) - k + 1))\n\nprint(min_max_of_subsection([2, 4, 5, 3, 2, 1, 4, 2, 5, 1], 3))\nprint(min_max_of_subsection2([2, 4, 5, 3, 2, 1, 4, 2, 5, 1], 3))\n</code></pre>\n<p><a href=\"https://tio.run/##7VNBboMwELzzihUnW6GRQtoLUg/9Qq8oQk4wYAE2sk1FXk/XNk1AatM@oJYQZuydmd0Rw9U2Sh7nueQV9EIWPZsKVRVmPBt@sUJJwrRm1wRamkWAK45jeOd21NKAbbgrEv3YwwfrRg6qCiCbtiBnlwbupA7quKxtAy0ICV5jH3mBN12bIOWWPwHSCWNpBmy56uo9twFyQfDM8QhbEbJGfWahYcZdVrrkmt7IWiBCOp5Fe3GLvmAxFiws/d1dhD4qrfqg/zUJ/3YjW7X2CvnJ45XS4XYhZMkn16dmsuYE1cNUKTyhpx0c6E1qS7Znw8BlSRANFfmKMFuT76A90dCp9u5dMGTLRqMo@jHn9D/o34LeDnYJRJRThs8Ox@8Tx/3DpDGEQaM58v3flqcJPCfwksAxAdwf/GfqkcMJUSR4UJ/@hWCePwE\" rel=\"nofollow noreferrer\" title=\"Python 3 – Try It Online\">Try it online!</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T11:38:33.803",
"Id": "496173",
"Score": "0",
"body": "thanks, I learned a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T11:45:41.077",
"Id": "496175",
"Score": "0",
"body": "@sherloock : thanks. If, after a few days, this is the review you’re most happy with, please consider accepting it as an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T11:26:40.667",
"Id": "496306",
"Score": "0",
"body": "okay!! I uploaded new question, Cheapest route If you have time help me"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T08:30:31.920",
"Id": "251935",
"ParentId": "251934",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251935",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T06:34:51.937",
"Id": "251934",
"Score": "4",
"Tags": [
"python-3.x",
"programming-challenge"
],
"Title": "This is Crossing river code"
}
|
251934
|
<p>I made a small python script to create an audio sound used as stimuli. It's one of my first uses of <code>super()</code>, and I do not know if I did it right. I'm looking for any improvement in both optimization and style you could suggest.</p>
<pre><code>import pyaudio
import numpy as np
class SoundStimuli:
def __init__(self, fs=44100, duration=1.0):
self.fs = fs
self.duration = duration
self.t = np.linspace(0, duration, int(duration*fs), endpoint=False)
self.signal = None
def play(self):
if self.signal is None:
print ('WARNING: No audio signal to play.')
return
p = pyaudio.PyAudio()
# for paFloat32 sample values must be in range [-1.0, 1.0]
stream = p.open(format=pyaudio.paFloat32,
channels=1,
rate=self.fs,
output=True)
# play. May repeat with different volume values (if done interactively)
stream.write(self.signal)
stream.stop_stream()
stream.close()
p.terminate()
def convert2float32(self):
self.signal = self.signal.astype(np.float32)
def plot_signal(self, ax, **plt_kwargs):
if self.signal is None:
print ('WARNING: No audio signal to plot.')
return
ax.plot(self.t, self.signal, **plt_kwargs)
def plot_signal_fft(self, ax, **plt_kwargs):
fft_freq = np.fft.rfftfreq(self.t.shape[0], 1.0/self.fs)
fft = np.abs(np.fft.rfft(self.signal))
ax.plot(fft_freq, fft, **plt_kwargs)
class ASSR(SoundStimuli):
def __init__(self, fc, fm, fs=44100, duration=1.0):
super().__init__(fs, duration)
self.fc = fc
self.fm = fm
def classical_AM(self):
self.assr_amplitude = (1-np.sin(2*np.pi*self.fm*self.t))
self.signal = self.assr_amplitude * np.sin(2*np.pi*self.fc*self.t).astype(np.float32)
def DSBSC_AM(self):
self.assr_amplitude = np.sin(2*np.pi*self.fm*self.t)
self.signal = self.assr_amplitude * np.sin(2*np.pi*self.fc*self.t).astype(np.float32)
def plot_signal(self, ax, amplitude_linestyle='--', amplitude_color='crimson', **plt_kwargs):
super().plot_signal(ax, **plt_kwargs)
ax.plot(self.t, self.assr_amplitude, linestyle=amplitude_linestyle, color=amplitude_color)
</code></pre>
<p>The class <code>ASSR</code> is imported in a second script where the stimuli is created:</p>
<pre><code>sound = ASSR(fs=44100, duration=1.0, fc=1000, fm=40)
sound.classical_AM()
</code></pre>
<p>However, I do not play it using the <code>.play()</code> method because it looks like <code>pyaudio</code> doesn't accept the <code>PyAudio</code> and <code>stream</code> to be open/close outside the scope of <code>.write()</code>. And since I do not want to open a new stream every time I play a sound, I ended up using <code>.play()</code> to test the sound; and then create in the main program where <code>ASSR</code> is imported a new audio stream with different <code>.write(sound.signal)</code> calls.</p>
<pre><code># Initialize audio stream
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32,
channels=1,
rate=sound.fs,
output=True)
# Do stuff
stream.write(sound.signal)
# Do stuff
stream.write(sound.signal)
stream.stop_stream()
stream.close()
p.terminate()
</code></pre>
|
[] |
[
{
"body": "<p>A lot of things here are already good, like:</p>\n<ul>\n<li><code>fs</code>, <code>duration</code> and <code>t</code> being members on <code>SoundStimuli</code></li>\n<li>The choice of which things to initialize in the first <code>__init__</code> (mostly)</li>\n</ul>\n<p>Things that could be improved:</p>\n<ul>\n<li><code>SoundStimuli</code> is arguably <code>SoundStimulus</code></li>\n<li><code>self.signal</code> should not be an optional member variable; the base class should be made effectively abstract and the signal should be returned from a getter or property whose base implementation raises <code>NotImplementedError</code>.</li>\n<li>In <code>play</code>, the absence of a signal should be fatal, so you should naively access <code>self.signal</code>, and let any exceptions fall through to the caller</li>\n<li>After <code>p.open</code>, wrap the rest in a <code>try</code>, and put the <code>close()</code> in a <code>finally</code></li>\n<li><code>convert2float</code> is not a great idea - it replaces a member with a different version of the same member. That means that before this is called, the instance is by definition in an invalid state, which should be avoided.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T15:10:09.667",
"Id": "251949",
"ParentId": "251936",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251949",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T09:01:48.667",
"Id": "251936",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Generate simple sinusoidal sounds and plot signal/fft"
}
|
251936
|
<p>I am just looking to improve my indentation on my current code. I'd be happy to hear any reviews and improvements.</p>
<pre><code>public class DataAccess
{
public List<ComplaintModel> GetComplaint(string _OrderNumber)
{
throw new NotImplementedException();
}
public void InsertComplaint(
DateTime _Date,
string _OrderNumber,
string _CustomerName,
string _CustomerContactName,
string _Telephone,
string _Email,
string _CustomerReference,
string _Product,
string _PackSize,
string _BatchNumber,
DateTime _BestBeforeDate,
string _QuantityInvolved,
string _Details,
string _Comments)
{
using(MySqlConnection conn = new MySqlConnection(ConnectionString.ConnString))
{
List<ComplaintModel> complaint = new List<ComplaintModel>();
complaint.Add(new ComplaintModel { Date = _Date,
OrderNumber = _OrderNumber,
CustomerName = _CustomerName,
CustomerContactName = _CustomerContactName,
Telephone = _Telephone,
Email = _Email,
CustomerReference = _CustomerReference,
Product = _Product,
PackSize = _PackSize,
BatchNumber = _BatchNumber,
BestBeforeDate = _BestBeforeDate,
QuantityInvolved = _QuantityInvolved,
Details = _Details,
Comments = _Comments});
conn.Execute(@"INSERT INTO customer_complaints
(date_taken, order_number, customer_name, customer_contact, telephone, email, customer_reference, product, pack_size, batch_lot_number,
best_before_date, quantity_involved, details, comments)
VALUES (@Date, @OrderNumber, @CustomerName, @CustomerContactName, @Telephone, @Email, @CustomerReference, @Product, @PackSize, @BatchNumber,
@BestBeforeDate, @QuantityInvolved, @Details, @Comments)", complaint);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:34:47.967",
"Id": "496310",
"Score": "1",
"body": "2 more things, Object-Modeling (passing a model to the `InsertComplaint` method. Secondly, using `ORM`. If you use an ORM like Dapper and Entity Framework, then your work would be much simpler and you would avoid most of SQL-Injections risks."
}
] |
[
{
"body": "<p>There are two places where I would use <code>var</code>:</p>\n<pre><code>var conn = new MySqlConnection(ConnectionString.ConnString)\nvar complaint = new List<ComplaintModel>();\n</code></pre>\n<p>You no longer have to put braces around a using block, saving you one indentation level:</p>\n<pre><code>using var conn = new MySqlConnection(ConnectionString.ConnString);\n</code></pre>\n<p>Don't put the first parameter at the end of the line and the rest on a new line. Put the first parameter on a new line as well:</p>\n<pre><code>complaint.Add(new ComplaintModel {\n Date = _Date,\n ...\n</code></pre>\n<p>If you start the Query string on a new line, you can move it back one indentation level:</p>\n<pre><code>conn.Execute(\n @"INSERT INTO customer_complaints\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T21:38:03.680",
"Id": "496224",
"Score": "3",
"body": "Be careful with removing braces from `using` statements. While in this scenario it doesn't hurt, there might be other scenarios where it leads to unexpected results, for example [this question](https://stackoverflow.com/q/61761053/3502980) that I've answered a while back"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T13:22:03.413",
"Id": "251942",
"ParentId": "251941",
"Score": "5"
}
},
{
"body": "<p>Dennis_E has some good advice, but there are two items I would do differently.</p>\n<ol>\n<li><p>The SQL insert statement looks fine as-is. The code reads just fine, but I would declare a private constant in the class to store the statement.</p>\n</li>\n<li><p>Put the curly braces for your object initializer on their own lines as well:</p>\n<pre><code>complaint.Add(new ComplaintModel \n{\n Date = _Date,\n OrderNumber = _OrderNumber,\n CustomerName = _CustomerName,\n CustomerContactName = _CustomerContactName,\n Telephone = _Telephone,\n Email = _Email,\n CustomerReference = _CustomerReference,\n Product = _Product,\n PackSize = _PackSize,\n BatchNumber = _BatchNumber,\n BestBeforeDate = _BestBeforeDate,\n QuantityInvolved = _QuantityInvolved,\n Details = _Details,\n Comments = _Comments\n});\n</code></pre>\n</li>\n</ol>\n<p>Some additional observations unrelated to indentation:</p>\n<ul>\n<li><p>Rename your parameters to camelCase instead of PascalCase with leading underscores. The idiomatic naming convention in C# would be <code>quantityInvolved</code> rather than <code>_QuantityInvolved</code>.</p>\n<p>It might sound insignificant, but reaching for the shift key and/or the underscore key slows down your typing speed. It is "death by a thousand paper cuts." One tiny little decrease in speed by itself doesn't matter. Multiply that by the hundreds of times each day you do this while typing code and it adds up.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T14:46:40.013",
"Id": "496185",
"Score": "0",
"body": "Totally agree with the underscore aha! :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T06:31:34.093",
"Id": "496278",
"Score": "0",
"body": "The General Naming Conventions also discourage the use of underscores (_) : https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions\nI personally like the _ on members to distinguish from function and class scope, but that's a personal preference. The coreFx (net core) Coding Guidelines Agree: https://github.com/dotnet/runtime/blob/master/docs/coding-guidelines/coding-style.md so not even MS is consistent"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T14:44:12.003",
"Id": "251948",
"ParentId": "251941",
"Score": "3"
}
},
{
"body": "<p>You have a method with fourteen parameters, this is way too many. The names of these parameters also don't follow the one usually used in C#: camelCased, and no underscore prefix.</p>\n<p>Why not construct a <code>ComplaintModel</code> and pass that to <code>InsertComplaint()</code>?</p>\n<hr />\n<p><code>DataAccess</code> is IMHO a far too generic name. You'll be tempted to fill this with dozens of methods, centralizing all of your database logic there, and it will just become unmanageable. Consider having a "ComplaintsService" for instance where you just have the methods related to complaints, or even go full <a href=\"https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs\" rel=\"nofollow noreferrer\">CQRS</a>.</p>\n<hr />\n<p>Do not pointlessly abbreviate names. I can live with <code>conn</code> (though I'd prefer <code>mySqlConnection</code>), but <code>ConnString</code> is pointless. I get that you did this to avoid issues with the class named <code>ConnectionString</code>, but then you should change that class's name.</p>\n<hr />\n<p>Give things proper names: <code>List<ComplaintModel> complaint</code> is wrong because it is literally a list of complaints, and thus it should be called <code>complaints</code>.</p>\n<hr />\n<p>I'm not a fan of inline SQL when it becomes lengthy. I'm a fan of embedding .SQL scripts and then reading them <a href=\"https://codereview.stackexchange.com/questions/214250/retrieving-the-ids-of-entries-to-be-deleted-from-a-table\">using a QueryRetriever</a>. The advantage is that such .SQL scripts also become color-coded in Visual Studio (though I wish there was a way to have different extensions based on the type of query, e.g. SQL Server vs. MySql vs Oracle etc.).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:54:55.147",
"Id": "252038",
"ParentId": "251941",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "251942",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T12:53:54.737",
"Id": "251941",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Indentation for c# functions"
}
|
251941
|
<p>This is a follow up to my question <a href="https://codereview.stackexchange.com/questions/251154/c-number-guessing-game">here</a>. Well, it ain't exactly a follow-up, but more like my next project after the last one</p>
<p>I created a tic tac toe game using object-oriented programming</p>
<p>You all already know how the tic tac toe works so I won't be wasting your time by explaining to you how it works</p>
<p>I'm looking for feedback on absolutely everything that could make me a better programmer, especially a better C++ programmer, also how to use class, function better, and how to use OOP correctly, and these:</p>
<ul>
<li>Optimization</li>
<li>Bad practice and good practice</li>
<li>Code structure</li>
<li>Functions and variable naming</li>
<li>Bugs</li>
<li>Improving class and function usage</li>
<li>How to correctly use OOP</li>
<li>Oh, also how to add comment properly</li>
<li>etc</li>
</ul>
<p><strong>Thank you very much!</strong></p>
<p><em>I'm using Visual Studio Community 2019 ver 16.7.7</em></p>
<p><strong>Globals.h</strong></p>
<pre><code>#ifndef GUARD_GLOBALS_H
#define GUARD_GLOBALS_H
namespace
{
enum class Players : char
{
PLAYER_X = 'X',
PLAYER_O = 'O'
};
}
#endif // !GUARD_GLOBALS_H
</code></pre>
<p><strong>board.h</strong></p>
<pre><code>#ifndef GUARD_BOARD_H
#define GUARD_BOARD_H
#include "player.h"
class Board
{
private:
char board[9];
// This is suppose to be a place to put the score
// But I don't know how to implement it yet
int scoreX{};
int scoreO{};
public:
Board();
void printBoard() const;
void markBoard(const size_t& choseNum, const char& player, bool& inputPass);
char checkWin(bool& isDone, int& countTurn);
void printWinner(bool& isDone, int& countTurn);
};
#endif // !GUARD_BOARD_H
</code></pre>
<p><strong>board.cpp</strong></p>
<pre><code>#include "board.h"
#include <iostream>
// To set the board with numbers
Board::Board()
{
int j{ 1 };
for (int i = 0; i < 9; i++)
{
board[i] = '0' + j++;
}
}
void Board::printBoard() const
{
system("cls");
std::cout << " | | " << "\n";
std::cout << " " << board[0] << " | " << board[1] << " | " << board[2] << "\tPlayer X: " << scoreX << "\n";
std::cout << "___|___|__" << "\tPlayer O: " << scoreO << "\n";
std::cout << " | | " << "\n";
std::cout << " " << board[3] << " | " << board[4] << " | " << board[5] << "\n";
std::cout << "___|___|__" << "\n";
std::cout << " | | " << "\n";
std::cout << " " << board[6] << " | " << board[7] << " | " << board[8] << "\n";
std::cout << " | | " << "\n\n";
}
// To change the board to which the player choose the number
void Board::markBoard(const size_t& choseNum, const char& player, bool& inputPass)
{
char checkNum = board[choseNum - 1];
// To check if the number that the player choose is available or not
if (checkNum != (char)Players::PLAYER_X && checkNum != (char)Players::PLAYER_O)
{
// To check if the number that the player input
if (choseNum >= 1 && choseNum <= 9)
{
board[choseNum - 1] = player;
inputPass = true;
}
else
{
std::cout << "CHOOSE THE AVAILABLE NUMBER!\nTRY AGAIN: ";
}
}
else
{
std::cout << "SPACE HAS ALREADY BEEN OCCUPIED\nTry again: ";
}
}
/*
There is probably a better way to do this. But, I don't know how tho
Maybe someday I could improve the checking for win but right now
this is good enough
Also, there are a lot of magic number here such as 8, 2, 6 and 7.
I've tried to remove the magic number but I don't know how.
*/
// Check the board if there is player with parallel set or not
char Board::checkWin(bool &isDone, int &countTurn)
{
/*
I use middleboard and initialize it to board[4] because in order
for a player to win diagonally they have to acquire the
middle board first. So, I initialize middleboard to board[4]
hoping it could remove the magic number
and I initialize i to 0 and j to 8 because the checking is
begin from the top left corner-middle-bottom right corner
if it false then I add add 2 to i and substract 2 from j
because now the checking is top right corner-middle-bottom left corner
*/
// Check diagonal win
size_t middleBoard = board[4];
for (size_t i = 0, j = 8; i <= 2 && j >= 6; i+=2, j-=2)
{
// If all the board is occupied by the same player then the same player win
if (middleBoard == board[i] && board[i] == board[j])
{
//This is suppose to add score, but I don't know how to implement it yet
board[middleBoard] == (char)Players::PLAYER_X ? scoreX++ : scoreO++;
isDone = true;
return middleBoard; // To return the character of the player who won
}
}
/*
I initialize initialNum to 0 as a starting point for the checking.
Initilialized i to 1 and j to 2
The checking is like this, top left corner-middle top-top right corner
If it false then the I add 3 to initialNum to make middle left as the
starting point, then add 3 to i and j so it the next checking is
middle left-middle-middle right, and so on
*/
// Check horizontal win
size_t initialNum = 0;
for (size_t i = 1, j = 2; i <= 7 && j <= 8; i += 3, j += 3)
{
if (board[initialNum] == board[i] && board[i] == board[j])
{
board[initialNum] == (char)Players::PLAYER_X ? scoreX++ : scoreO++;
isDone = true;
return board[initialNum];
}
else
{
initialNum += 3;
}
}
/*
I reset the initialNum to 0 and initialized i to 3 and j 6 so
the first check will be like this: top left corner-middle left-bottom left corner
if it fails then i add 1 to initialNum, i, and j, so the next check will be
middle top-middle-middle bottom and so on
*/
// Check vertical win
initialNum = 0;
for (size_t i = 3, j = 6; i <= 5 && j <= 8; i++, j++)
{
if (board[initialNum] == board[i] && board[i] == board[j])
{
board[initialNum] == (char)Players::PLAYER_X ? scoreX++ : scoreO++;
isDone = true;
return board[initialNum];
}
else
{
initialNum++;
}
}
// If the countTurn is 8 then there're no place to occupy anymore, thus a draw
if (countTurn == 8)
{
isDone = true;
return 'D'; // As a check for printWinner() function
}
countTurn++;
}
// To print who's the winner or draw
void Board::printWinner(bool& isDone, int& countTurn)
{
if (checkWin(isDone, countTurn) == 'D')
{
std::cout << "It's a Draw!\n";
}
else
{
std::cout << "Congratulations!\nPlayer " << checkWin(isDone, countTurn) << " won the game!\n";
}
}
</code></pre>
<p><strong>player.h</strong></p>
<pre><code>#ifndef GUARD_PLAYER_H
#define GUARD_PLAYER_H
#include "Globals.h"
#include "board.h"
class Board;
class Player
{
private:
char mainPlayer;
char secondPlayer;
char turnPlayer = mainPlayer;
public:
void choosePlayer(bool &choosePass);
void movePlayer(Board& myBoard);
void switchPlayer();
};
#endif // !GUARD_PLAYER_H
</code></pre>
<p><strong>player.cpp</strong></p>
<pre><code>#include "player.h"
#include "board.h"
#include <iostream>
#include <random>
// To give a choice for the player if they want to be X or O
void Player::choosePlayer(bool& choosePass)
{
char chosePlayer;
std::cout << "Do you want to be player X or O? ";
while (!choosePass)
{
std::cin >> chosePlayer;
// If the player type X uppercase or lowercase then they will be
// X and the computer will be O, vice versa
if (chosePlayer == 'x' || chosePlayer == 'X')
{
mainPlayer = (char)Players::PLAYER_X;
secondPlayer = (char)Players::PLAYER_O;
choosePass = true;
}
else if (chosePlayer == 'o' || chosePlayer == 'O')
{
mainPlayer = (char)Players::PLAYER_O;
secondPlayer = (char)Players::PLAYER_X;
choosePass = true;
}
else
{
std::cout << "Invalid choice\n Try again: ";
}
}
}
// To make a player choose a number to which they want to occupy
void Player::movePlayer(Board &myBoard)
{
size_t choseNum;
bool inputPass = false;
/*
I make it turnPlayer != mainPlayer because if I make it
turnPlayer == mainPlayer then the computer will make the first move
I don't know why. Probably should find out the why. But it'll do for now
*/
// If turnPlayer is not mainPlayer then it's the player's move
if (turnPlayer != mainPlayer)
{
std::cout << "Player " << mainPlayer << " choose a number: ";
while (!inputPass)
{
if (std::cin >> choseNum)
{
myBoard.markBoard(choseNum, mainPlayer, inputPass); //Go to markBoard function in board.cpp
}
else
{
std::cout << "Invalid input type (Type only number)\nTry again: ";
std::cin.clear(); // To clear the input so
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // the player can input again
}
}
}
// If the turnPlayer is mainPlayer then it's the computer's move
else
{
while (!inputPass)
{
// To make a random move for the computer
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(1, 9);
choseNum = distrib(gen);
myBoard.markBoard(choseNum, secondPlayer, inputPass);
}
}
}
// To change turn, if the player finishes then the computer will make the move
void Player::switchPlayer()
{
turnPlayer = (turnPlayer == mainPlayer) ? secondPlayer : mainPlayer;
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include "board.h"
#include "player.h"
int main()
{
Board myBoard;
Player mainPlayer;
int countTurn{ 0 };
bool choosePass = false;
bool isDone = false;
myBoard.printBoard(); // To print the initial board with numbered spaces
while (!isDone)
{
if (!choosePass)
{
mainPlayer.choosePlayer(choosePass);
}
mainPlayer.movePlayer(myBoard);
myBoard.printBoard();
mainPlayer.switchPlayer();
myBoard.checkWin(isDone, countTurn);
}
myBoard.printWinner(isDone, countTurn);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T14:32:42.800",
"Id": "496182",
"Score": "1",
"body": "I'd really like to answer this question but it doesn't seem quite ready for review. This comment makes it off-topic `// This is suppose to be a place to put the score // But I don't know how to implement it yet`. There are also 4 compiler errors for me in board.cpp where this code is `(char)Players::PLAYER_X ?` (hint there is a problem with `Players` here). Does this game compile and run for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T15:38:42.533",
"Id": "496187",
"Score": "0",
"body": "@SirBroccolia Does the game work as expected for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T15:46:53.743",
"Id": "496188",
"Score": "0",
"body": "@pacmaninbw actually it compiles and runs perfectly for me, what is the issue? Is it because of `system('cls')`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T16:33:02.207",
"Id": "496191",
"Score": "0",
"body": "There is no class called Players, it is Player. I'm using visual studio 2019 professional."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T16:35:08.533",
"Id": "496192",
"Score": "0",
"body": "@pacmaninbw I'm using vs 2019 too, I'm facing no errors. I might've fixed something small in a hurry, which file and line does it come from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T16:58:09.567",
"Id": "496193",
"Score": "0",
"body": "No longer complaining it was in board.cpp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:16:49.590",
"Id": "496205",
"Score": "1",
"body": "Welcome to Code review, this code is not ready for review yet because of this statement `// This is suppose to be a place to put the score // But I don't know how to implement it yet` as such, it's off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:31:19.767",
"Id": "496210",
"Score": "0",
"body": "@theProgrammer The code actually works perfectly, that is something he would like to add in the future"
}
] |
[
{
"body": "<h1>Should there be <code>Globals.h</code>?</h1>\n<p>I disagree. <code>Globals.h</code> has a single <code>enum</code> that is only meaningful to your <code>Player</code> class. So why create a new Header? Why can't <code>enum class Players</code> just be in <code>Player.cpp</code>? That is the only file that ever accesses the contents of <code>Players</code>. I believe the best thing to do here is to create an <strong>anonymous namespace in <code>Player.cpp</code></strong> and let it remain there.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>// Player.cpp\nnamespace {\n enum class Players { ... };\n}\n</code></pre>\n<p>Also, <a href=\"https://rules.sonarsource.com/cpp/RSPEC-1000\" rel=\"noreferrer\"><strong>be careful while using an unnamed namespace in a header file</strong></a></p>\n<hr />\n<h1>Use <a href=\"https://en.cppreference.com/w/cpp/locale/tolower\" rel=\"noreferrer\">std::tolower</a></h1>\n<p>instead of comparing with both cases of a character, use <a href=\"https://en.cppreference.com/w/cpp/locale/tolower\" rel=\"noreferrer\"><code>std::tolower</code></a> to directly convert a character into lowercase. This would convert</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cin >> chosePlayer;\n\nif (chosePlayer == 'x' || chosePlayer == 'X') {...}\nelse if (chosePlayer == 'o' || chosePlayer == 'O') {...}\nelse {...}\n</code></pre>\n<p>Into</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cin >> chosePlayer;\nchosePlayer = std::tolower(chosePlayer, std::locale());\n\nif (chosePlayer == 'x' ) {...}\nelse if (chosePlayer == 'o') {...}\nelse {...}\n</code></pre>\n<p><sup> <code>#include <locale></code> </sup></p>\n<ul>\n<li>Note that on entering anything > 1 character, the code will accept the first one. For example, if the user enters <code>cplusplus</code>, <code>chosePlayer</code> is now set to <code>c</code>.</li>\n</ul>\n<hr />\n<h1>Use the <code>enum class</code> you created</h1>\n<p>You created an <code>enum</code> removing the magic <code>x</code> and <code>o</code>. Why are you still using them here?</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (chosePlayer == 'x' ) \nelse if (chosePlayer == 'o')\n</code></pre>\n<p>Use the values of <code>enum class Players</code> here.</p>\n<hr />\n<h1>Use an <code>enum</code> here</h1>\n<p>While some might disagree, I think an <code>enum</code> is better compared to <code>enum class</code> here. The reason being you don't have to constantly cast the values to <code>char</code> whenever you want to compare an <code>enum</code> and <code>char</code> type. <br>If it's only going to be visible in a single <code>.cpp</code> file like I earlier mentioned, you're most probably not going to have name conflicts.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Player : char { PLAYER_1 = 'x', PLAYER_2 = 'o' };\n</code></pre>\n<h1>From <code>Player::chosePlayer()</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>void Player::choosePlayer(bool& choosePass)\n{\n char chosePlayer;\n std::cout << "Do you want to be player X or O? ";\n\n while (!choosePass)\n {\n std::cin >> chosePlayer;\n // If the player type X uppercase or lowercase then they will be\n // X and the computer will be O, vice versa\n if (chosePlayer == 'x' || chosePlayer == 'X')\n {\n mainPlayer = (char)Players::PLAYER_X;\n secondPlayer = (char)Players::PLAYER_O;\n choosePass = true;\n }\n else if (chosePlayer == 'o' || chosePlayer == 'O')\n {\n mainPlayer = (char)Players::PLAYER_O;\n secondPlayer = (char)Players::PLAYER_X;\n choosePass = true;\n }\n else\n {\n std::cout << "Invalid choice\\n Try again: ";\n }\n }\n}\n</code></pre>\n<p>If you want to indicate whether the inputted values are good or bad, why are you passing a reference to a <code>bool</code> variable? Why not return <code>true</code> if the input is good, and <code>false</code> if the input isn't?\nPassing by reference implicitly passes a pointer, so you are actually passing a pointer to a bool variable in the function. You will <strong>have</strong> to pass by reference if you go with your current logic, but the thing is</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>sizeof(bool) == 2\nsizeof(bool*) == 8\n</code></pre>\n<p>For that reason, and for simplicity, I believe simply returning <code>True</code> or <code>False</code> will be better</p>\n<hr />\n<h1>Checking for a winner</h1>\n<p>Your current algorithm of checking for a winner is very long and hard to read. There are better ways. <a href=\"https://stackoverflow.com/questions/1056316/algorithm-for-determining-tic-tac-toe-game-over\">This thread will provide a lot of useful information about them</a>. The simplest of all</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>constexpr int NB_WIN_DIR = 8;\nconstexpr int N = 3; // please think of a better name \n\nconstexpr int wins[NB_WIN_DIR][N] {\n {0, 1, 2}, // first row\n {3, 4, 5}, // second row\n {6, 7, 8}, // third row\n {0, 3, 6}, // first col\n {1, 4, 7}, // second col\n {2, 5, 8}, // third col\n {2, 4, 6}, // diagonal\n {0, 4, 8}, // antidiagonal\n};\n\nfor (int i = 0; i < NB_WIN_DIR ;i++)\n{\n if (board[wins[0]] == board[wins[1]] and board[wins[1]] == board[wins[2]]) \n return board[wins[0]];\n}\n</code></pre>\n<hr />\n<h1>When should you pass by <code>const&</code>?</h1>\n<p>I see a <code>const bool&</code> and <code>const size_t&</code> function arguments. <br>\nWhen you <strong>should</strong> pass as a constant reference</p>\n<ul>\n<li>When you want to avoid copies for large objects</li>\n</ul>\n<p>As I said earlier, passing by reference implicitly passes a pointer. But the problem is</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>sizeof(bool) == 2\nsizeof(bool*) == 8\n\nsizeof(size_t) == 8 // depending on your machine, sometimes 4\nsizeof(size_t*) == 8 \n</code></pre>\n<p>So at best, it's doing you no good at all, and possibly is doing more <strong>bad</strong>. A simple rule of thumb, you don't have to pass primitive types like <code>int, char, double, float</code> by <code>const&</code>, however, do pass by reference if you have something like <code>std::vector</code>.</p>\n<p>Don't get me wrong, you <strong>should</strong> pass by reference if a function should be modifying the original value of an object. But if this isn't the intent, only use it for large objects.</p>\n<hr />\n<h1>Re-think your code structure</h1>\n<p>I really dislike this class</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Player\n{\nprivate:\n char mainPlayer;\n char secondPlayer;\n char turnPlayer = mainPlayer;\n\npublic:\n void choosePlayer(bool &choosePass);\n void movePlayer(Board& myBoard);\n void switchPlayer();\n};\n</code></pre>\n<p>Your <code>Player</code> class doesn't hold any information about a single player. All your member functions modify the values of your <code>board</code>. All of this actually belongs to your <code>Board</code> class. A player is actually just a <code>char</code>, either <code>o</code> or <code>x</code>. It literally holds no other information than that. What you should do is simply represent a player using an enum like you already do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Player { ... };\n\nclass Board{ \n Player human;\n Player bot; \n};\n</code></pre>\n<p>the <code>bot</code> would be the computer who is playing against you, and <code>human</code> would be the actual user.</p>\n<p>What think <strong>should</strong> be represented using a class is a simple move. A move has two things.</p>\n<ul>\n<li>The square</li>\n<li>The player</li>\n</ul>\n<p>Everywhere in your program, you have passed around these two separately, why not create a simple <code>struct</code> that would hold it?</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Move {\n int square;\n Player player;\n}\n</code></pre>\n<p>I wrote out a very basic example of how this game can be re-structured.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Game\n{\n private:\n struct Move {\n Player player;\n int square;\n\n Move(const int square, const Player player)\n : square(square), player(player)\n {}\n };\n\n enum Player {\n PLAYER_1, PLAYER_2, NONE \n };\n\n template < typename T, size_t N > using array = std::array < T, N >;\n\n\n array < char, NB_SQ > board;\n Player human;\n Player bot;\n\n short int turns; // number of total moves played\n \n\n \n void computer_move();\n Move input_move() const;\n void make_move(const Move& move);\n bool validate_move(const Move& move);\n\n Player check_win() const;\n bool check_draw() const;\n\n void print_board() const;\n void new_game(); // choose whether the player plays 'x' or 'o' here\n \n public:\n void mainloop(){\n for (;;) {\n const Move& move = input_move();\n make_move(move);\n computer_move();\n\n if (check_win()) // ...\n if (check_draw()) // ...\n\n }\n }\n \n Game() { new_game(); }\n\n};\n</code></pre>\n<pre><code>int main() {\n Game game;\n game.mainloop();\n}\n</code></pre>\n<hr />\n<h1>About <code>system("cls")</code></h1>\n<p>Your current program will not work on operating systems that aren't windows. On most other systems, the word is <code>clear</code>. To make this more portable you can use an <a href=\"https://docs.microsoft.com/en-us/cpp/preprocessor/hash-ifdef-and-hash-ifndef-directives-c-cpp?view=msvc-160\" rel=\"noreferrer\">#ifdef</a> statement to check for the operating system</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void clear_screen()\n{\n#ifdef _WIN32\n system("cls");\n#else \n system("clear");\n#endif\n}\n</code></pre>\n<h2><a href=\"https://stackoverflow.com/questions/228617/how-do-i-clear-the-console-in-both-windows-and-linux-using-c/228628\">Read more</a></h2>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:00:08.727",
"Id": "496202",
"Score": "2",
"body": "I'm having flashbacks of the film \"WarGames\", in that, number of players should be the first input asked and valid for 0, 1, or 2 players. :) But that might require a redesign."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T22:06:31.203",
"Id": "496228",
"Score": "0",
"body": "@Casey Aryan may be a bit too young to remember the film \"WarGames\". I think he was born in the 21st century."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T03:07:19.063",
"Id": "496266",
"Score": "1",
"body": "@pacmaninbw that' what i said earlier, the film is 23 years older than me."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T17:46:18.690",
"Id": "251957",
"ParentId": "251943",
"Score": "6"
}
},
{
"body": "<h2>Overall Observations</h2>\n<p>The code in <code>main()</code> is well sized, nice and tight, very readable. The only down side to <code>main()</code> is the comment which really isn't necessary.</p>\n<p>There seems to be mutual dependencies between Board and Player, in software design this is known as a tight coupling and it generally indicates a bad design.</p>\n<p>I only see one instance of the Player class and I would expect to see 2 instances, one for each player.</p>\n<p>Keep working on your object designs to remove tight coupling, and try to follow the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> programming principles. Learn some object oriented design patterns such as composition.</p>\n<p>SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.</p>\n<ol>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open–closed Principle</a> - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a> - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">Interface segregation principle</a> - states that no client should be forced to depend on methods it does not use.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">Dependency Inversion Principle</a> - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.</li>\n</ol>\n<h2>Turn on a High Level of Warning, Don't Ignore Warnings</h2>\n<p>There are 2 warnings when I compile and both warnings indicate possible logic problems in the code.</p>\n<p>One warning is possible loss of data on this line:</p>\n<pre><code> return middleBoard; // To return the character of the player who won \n</code></pre>\n<p>in <code>Board::checkwin()</code>. This warning is because the code is returning a variable declared as <code>size_t</code> as a <code>char</code>.</p>\n<p>The second warning is also about <code>Board::checkwin()</code>, the warning is <code>not all control paths return a value</code> which is issued on the last line of the function. This may be the more serious of the 2 warning since it definitely indicates possible logic problems in the code.</p>\n<h2>Prefer C++ Style Casts Over Old C Style Casts</h2>\n<p>The following line of code is using an old C style cast:</p>\n<pre><code> board[initialNum] == (char)Players::PLAYER_X ? scoreX++ : scoreO++;\n</code></pre>\n<p>C++ has it's own casts that provide better warnings and compiler errors, these are <code>static casts</code> and <code>dynamic casts</code>. Static casts occur at compile time and provide possible errors or warnings if the cast is not type safe. On the line of code above a static cast is more appropriate.</p>\n<pre><code> board[initialNum] == (static_cast<char>(Players::PLAYER_X)) ? scoreX++ : scoreO++;\n</code></pre>\n<h2>Prefer Self Documenting Code Over Comments</h2>\n<p>There are too many comments in the code. One of the things that new programmers are not aware of is the maintenance of code, the code you write may be in use for 20 or more years and it is quite possible that you won't be working for the company that long. If there are a lot of comments in the code the comments must be maintained as well as the code itself, and this can double the amount of work to be done. It is better to write self documenting code using clear variable, class and function names. Use comments for design decisions or high level abstractions. If a function requires a special flow state it in a comment block preceding the function.</p>\n<h2>DRY Code</h2>\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well. The function <code>Board::checkWin()</code> contains redundant code in the 3 loops that check for wins. There are multiple ways to fix this and a good one has been suggested in another answer.</p>\n<h2>Complexity</h2>\n<p>The function <code>Board::checkWin()</code> is too complex (does too much). Rather than returning a character <code>Board::checkWin()</code> should return a boolean value indicating if it is a win or not. Other functions should implement updating the board with the proper characters. The complexity of this function has lead to the warning <code>not all control paths return a value</code>.</p>\n<h2>Magic Numbers</h2>\n<p>There are Magic Numbers in the <code>Board::checkWin()</code> function in each of the loops that check if there is a win, it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T03:28:02.063",
"Id": "496267",
"Score": "0",
"body": "I had 12 warnings including the two you have mentioned, intellisense warnings are extremely noisy sometimes"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T22:47:07.393",
"Id": "251977",
"ParentId": "251943",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251957",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T13:23:04.720",
"Id": "251943",
"Score": "5",
"Tags": [
"c++",
"object-oriented",
"game",
"tic-tac-toe"
],
"Title": "C++ OOP Tic Tac Toe"
}
|
251943
|
<p>I use <a href="https://www.borgbackup.org" rel="nofollow noreferrer">BorgBackup</a> to handle backups for my personal computer.
The following is a bash script that creates backups of my system to various different targets.
I have little experience with bash and hope to get some pointers regarding best practices and possible security issues/unanticipated edge cases.</p>
<p>One specific question is about the need to unset environment variables (in particular BORG_PASSPHRASE) like I have seen people doing (for example <a href="https://blog.andrewkeech.com/posts/170719_borg.html" rel="nofollow noreferrer">here</a>)
From my understanding this should not be necessary because the environment is only local.</p>
<p>Ideally I would also like to automatically ensure the integrity of the Borg repositories. I know there is <code>borg check</code> which I could run from time to time, but I am not sure if this is even necessary when using <code>create</code> which supposedly already makes sure the repository is in a healthy state?</p>
<p>Some notes regarding the code below:</p>
<ul>
<li><code>noti</code> is a very simple script for notifications with i3status but could be replaced with anything else</li>
<li>Some paths and names are replaces with dummies</li>
<li>I can not exit properly on errors of <code>borg create</code> because I backup /etc where some files have wrong permissions and BorgBackup will throw errors</li>
<li>The TODO comments in the code are things I may want to look into at some time, but the code works for now</li>
</ul>
<p>Bash script:</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
# User data backup script using BorgBackup with options for different target repositories
# usage: backup.sh <targetname>
# Each target must have a configuration file backup-<targetname>.conf that provides:
# - pre- and posthook functions
# - $repository - path to a valid borg repository or were one should be created
# - $backup - paths or exclusion paths
# - $pruning - borg pruning scheme
# Additional borg environment variables may be provided and will not be overwritten.
# Output is logged to LOGFILE="$HOME/.local/log/backup/<date>"
# INSTALLATION
# Place script and all target configs in $HOME/.local/scripts
# $HOME/.config/systemd/user/borg-backup.service
# ```
# [Unit]
# Description=Borg User Backup
# [Service]
# Environment=SSH_AUTH_SOCK=/run/user/1000/keyring/ssh
# ExecStart=%h/.local/scripts/backup.sh target1
# Nice=19
# IOSchedulingClass=2
# IOSchedulingPriority=7
# ```
#
# $HOME/.config/systemd/user/borg-backup.timer
# ```
# [Unit]
# Description=Borg User Backup Timer
# [Timer]
# OnCalendar=*-*-* 8:00:00
# Persistent=true
# RandomizedDelaySec=10min
# WakeSystem=false
# [Install]
# WantedBy=timers.target
# ```
# $ systemctl --user import-environment PATH
# reload the daemon
# $ systemctl --user daemon-reload
# start the timer with
# $ systemctl --user start borg-backup.timer
# and confirm that it is running
# $ systemctl --user list-timer
# you can also run the service manually with
# $ systemctl --user start borg-backup
function error () {
RED='\033[0;91m'
NC='\033[0m'
printf "${RED}%s${NC}\n" "${1}"
notify-send -u critical "Borg" "Backup failed: ${1}"
noti rm "BACKUP"
noti add "BACKUP FAILED"
exit 1
}
## Targets
if [ $# -lt 1 ]; then
echo "$0: Missing arguments"
echo "usage: $0 targetname"
exit 1
fi
case "$1" in
"target1"|"target2"|"target3")
target="$1"
;;
*)
error "Unknown target"
;;
esac
# TODO abort if specified target is already running
# exit if borg is already running, maybe previous run didn't finish
#if pidof -x borg >/dev/null; then
# error "Backup already running."
#fi
## Logging and notification
# notify about running backup
noti add "BACKUP"
# write output to logfile
log="$HOME/.local/log/backup/backup-$(date +%Y-%m-%d-%H%M%S).log"
exec > >(tee -i "$log")
exec 2>&1
echo "$target"
## Global Prehook
# create list of installed software
pacman -Qeq > "$HOME/.local/log/package_list.txt"
# create list of non backed up resources
ls -R "$HOME/misc/" > "$HOME/.local/log/resources_list.txt"
# create list of music titles
ls -R "$HOME/music/" > "$HOME/music/music_list.txt"
## Global Config
# set repository passphrase
export BORG_PASSCOMMAND="cat $HOME/passwd.txt"
compression="lz4"
## Target specific Prehook and Config
CONFIGDIR="$HOME/.local/scripts"
source "$CONFIGDIR"/backup-"$target".conf
# TODO make non mandatory and only run if it is defined
prehook || error "prehook failed"
## Borg
# TODO use env variables in configs instead?
# export BORG_REPO=$1
# export BORG_REMOTE_PATH=borg1
# borg create ::'{hostname}-{utcnow:%Y-%m-%dT%H:%M:%S}' $HOME
SECONDS=0
echo "Begin of backup $(date)."
borg create \
--verbose \
--stats \
--progress \
--compression $compression \
"$repository"::"{hostname}-{utcnow:%Y-%m-%d-%H%M%S}" \
$backup
# || error "borg failed"
# use prune subcommand to maintain archives of this machine
borg prune \
--verbose \
--list \
--progress \
"$repository" \
--prefix "{hostname}-" \
$pruning \
|| error "prune failed"
echo "End of backup $(date). Duration: $SECONDS Seconds"
## Cleanup
posthook
noti rm "BACKUP"
echo "Finished"
exit 0
</code></pre>
<p>Example configuration file:</p>
<pre class="lang-bsh prettyprint-override"><code>backup="$HOME
--exclude $HOME/movie
--exclude $HOME/.cache
--exclude $HOME/.local/lib
--exclude $HOME/.thumbnails
--exclude $HOME/.Xauthority
"
pruning="--keep-daily=6 --keep-weekly=6 --keep-monthly=6"
repository="/run/media/username/DRIVE"
prehook() { :; } # e.g. mount drives/network storage
posthook() { :; } # unmount ...
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T16:49:09.987",
"Id": "251952",
"Score": "4",
"Tags": [
"bash"
],
"Title": "Bash script for user backups with BorgBackup"
}
|
251952
|
<p>There is a task to create site-blog on PHP. I have made some classes, but my Senior reviewed them and said that approach is bad and <em>"best practicies"</em> need to be used. What did he mean? Any advises on how to improve my code. There are classes for database, user, posts and archive.
IDK how to specify my question, there is no error messages or smth, but what may be 'best practicies'?</p>
<p><strong>Working with database</strong></p>
<pre><code><?php
/**
* Class DB
*/
class DB
{
private $source;
function connect()
{
global $config;
if(!is_null($this->source))
return true;
$this->source = mysql_connect($config['db']['host'], $config['db']['user'], $config['db']['pass']);
if(!$this->source)
{
die('Could not connect: ' . mysql_error());
}
if(!mysql_select_db($config['db']['db'], $this->source))
{
die('Could not select: ' . mysql_error());
}
$this->q("SET NAMES 'utf8'");
$this->q('SET collation_connection = "utf8_general_ci"');
return true;
}
function q($query)
{
return mysql_query($query, $this->source);
}
function select($query)
{
$res = $this->q($query);
if(!$res)
return null;
$result = array();
while(($r = mysql_fetch_assoc($res)) !== false)
{
$result[] = $r;
}
return $result;
}
}
</code></pre>
<p><strong>User</strong></p>
<pre><code><?php
class User extends DB
{
public function __construct()
{
session_start();
$this->connect();
}
public function auth($login, $pass)
{
$login = htmlspecialchars($login);
$pass = htmlspecialchars($pass);
$auth = $this->select('select * from user where login="' . $login . '" and pass="' . $pass . '"');
if(count($auth) > 0)
{
$_SESSION['authorized'] = 1;
}
else
$_SESSION['authorized'] = 0;
}
public function checkAuth()
{
if($_SESSION['authorized'] == 1)
{
return true;
}
else
return false;
}
}
</code></pre>
<p><strong>For posting</strong></p>
<pre><code><?php
class Post extends DB
{
public $id = 0;
public $params = array();
public function __construct($id = 0)
{
$this->connect();
$this->id = (int)$id;
if($this->id > 0)
{
$this->params = $this->select('select * from post where id=' . $this->id);
if(is_array($this->params))
$this->params = $this->params[0];
}
}
public function Add($params)
{
if($this->id != 0)
return false;
if(!$params['name'])
return false;
if(!$params['message'])
return false;
if($this->q("insert into post (name, date, message) values ('{$params['name']}', NOW(), '{$params['message']}')"))
return true;
return false;
}
public function Update($params)
{
if($this->id == 0)
return false;
if(!$params['name'])
return false;
if(!$params['message'])
return false;
if($this->q("update post set name = '{$params['name']}', message = '{$params['message']}' where id=" . $this->id))
return true;
return false;
}
/**
* @param string $select
* @param string $where
* @param string $order
* @param int $limit
* @param int $offset
* @return self[]
*/
public function GetList($select = '*', $where = '', $order = '', $limit = 0, $offset = 0)
{
$return = array();
$res = $this->select('select ' .
$select . ' from post ' .
($where ? ' WHERE ' . $where : '') .
($order ? ' ORDER BY ' . $order : '') . ' ' .
($limit ? ' LIMIT ' . ($offset ? $offset . ', ' . $limit : $limit) : '') // LIMIT 10; LIMIT 50, 10
);
if(!$res)
return $return;
foreach($res as $item)
{
$return[] = new self($item['id']);
}
return $return;
}
public function Delete()
{
if($this->q("delete from post where id=" . $this->id))
return true;
return false;
}
public function getArchive()
{
$monthNames = array(1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December');
$archiveList = $this->select('SELECT DATE_FORMAT(date, "%Y") year, DATE_FORMAT(date, "%c") month from post group by year, month ORDER BY year desc, month desc');
if(!empty($archiveList))
{
foreach($archiveList as $k => $item)
{
$archiveList[$k]['month_name'] = $monthNames[$item['month']];
}
}
return $archiveList;
}
}
</code></pre>
<p><strong>Posts archive</strong></p>
<pre><code><?php
class Post extends DB
{
public $id = 0;
public $params = array();
public function __construct($id = 0)
{
$this->connect();
$this->id = (int)$id;
if($this->id > 0)
{
$this->params = $this->select('select * from post where id=' . $this->id);
if(is_array($this->params))
$this->params = $this->params[0];
}
}
public function Add($params)
{
if($this->id != 0)
return false;
if(!$params['name'])
return false;
if(!$params['message'])
return false;
if($this->q("insert into post (name, date, message) values ('{$params['name']}', NOW(), '{$params['message']}')"))
return true;
return false;
}
public function Update($params)
{
if($this->id == 0)
return false;
if(!$params['name'])
return false;
if(!$params['message'])
return false;
if($this->q("update post set name = '{$params['name']}', message = '{$params['message']}' where id=" . $this->id))
return true;
return false;
}
/**
* get list of posts
* @param string $select
* @param string $where
* @param string $order
* @param int $limit
* @param int $offset
* @return self[]
*/
public function GetList($select = '*', $where = '', $order = '', $limit = 0, $offset = 0)
{
$return = array();
$res = $this->select('select ' .
$select . ' from post ' .
($where ? ' WHERE ' . $where : '') .
($order ? ' ORDER BY ' . $order : '') . ' ' .
($limit ? ' LIMIT ' . ($offset ? $offset . ', ' . $limit : $limit) : '') // LIMIT 10; LIMIT 50, 10
);
if(!$res)
return $return;
foreach($res as $item)
{
$return[] = new self($item['id']);
}
return $return;
}
public function Delete()
{
if($this->q("delete from post where id=" . $this->id))
return true;
return false;
}
public function getArchive()
{
$monthNames = array(1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December');
// get all years and month when posts were made
$archiveList = $this->select('SELECT DATE_FORMAT(date, "%Y") year, DATE_FORMAT(date, "%c") month from post group by year, month ORDER BY year desc, month desc');
if(!empty($archiveList))
{
foreach($archiveList as $k => $item)
{
$archiveList[$k]['month_name'] = $monthNames[$item['month']];
}
}
return $archiveList;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T18:26:14.917",
"Id": "496200",
"Score": "0",
"body": "Are you really using `mysql_connect`? What PHP version are you running? I am finding it hard to believe that you could write such code in 2020"
}
] |
[
{
"body": "<p>I really hope that you are trolling us, but if you are not trolling and this is a real code, then I must say that <strong>it should absolutely never be used.</strong> This might have been acceptable 25 years ago, but even then there are too many issues with this code.</p>\n<ul>\n<li>use of old <code>mysql_*</code> API (you know this API is not available anymore, right?)</li>\n<li>SQL injection,</li>\n<li>cleartext passwords,</li>\n<li>HTML escaping the data going into the database,</li>\n<li>NO utf8 support,</li>\n<li>questionable <code>returns</code></li>\n<li>false polymorphism</li>\n<li>long array syntax</li>\n<li>implicit code blocks</li>\n<li>unnecessary loops</li>\n<li>poorly named methods</li>\n<li>unnecessary classes</li>\n<li>and more...</li>\n</ul>\n<h1>1. Using <code>mysql_*</code> in 2020</h1>\n<p>As of November 2020, the minimum PHP version you should be using is PHP 7.3. PHP 7.2 is still available but not for long.</p>\n<p>Given that the <code>mysql_*</code> API has been removed a couple of years ago and is no longer available this leads me to think that you might still be using PHP 5. <strong>Don't!</strong>. You are risking security of not only your own system but your users as well.</p>\n<p>Learn about PDO and start using it, preferably with some kind of DB abstraction layer. e.g. <a href=\"https://github.com/paragonie/easydb\" rel=\"noreferrer\">EasyDB</a></p>\n<h1>2. SQL injection</h1>\n<p>You must always bind the data separately. Never concatenate PHP variables into your SQL unless they have been validated against a pre-approved list or hardcoded.</p>\n<p>It would be a waste of time to explain for a millionth time how to use prepared statements, so let me just link you to <a href=\"https://stackoverflow.com/a/60496/1839439\">How can I prevent SQL injection in PHP?</a></p>\n<h1>3. Never store plaintext passwords</h1>\n<p>You should never ever store your users' passwords on the server. You may only store secure hashes such as the ones generated by <a href=\"https://www.php.net/manual/en/function.password-hash.php\" rel=\"noreferrer\"><code>password_hash()</code></a></p>\n<h1>4. Use <code>htmlspecialchars()</code> properly</h1>\n<p>It's in the name: HTML. You should only use this function when displaying the data inside of an HTML document. Learn about XSS and never store the output of <code>htmlspecialchars()</code> in your database; this can only damage your data.</p>\n<h1>5. UTF-8 support</h1>\n<p>Your application should support full UTF-8. Use <code>utf8mb4</code> as your database charset and set it when connecting to your database.</p>\n<p>Pay special attention to how your application handles strings, to make sure that you never confuse byte operations with character operations. Use mbstring extension of string manipulation.</p>\n<h1>5. When to use return</h1>\n<p>Use return when your function should return a value or make an early exit. <strong>Do not use it to return if the function was not provided valid arguments or something can't be executed!</strong> This is what exceptions are for. For example:</p>\n<pre><code> public function Delete()\n {\n if($this->q("delete from post where id=" . $this->id))\n return true;\n\n return false;\n }\n</code></pre>\n<p>This function should not return anything. This function causes side-effects, not return data. If the execution of SQL failed then there should be an exception. With PDO and mysqli this is done automatically for you.</p>\n<p>Also, don't repeat the same thing over and over. If you have multiple conditions why a function might return early then combine them into a single <code>if</code> statement.</p>\n<h1>6. What is polymorphism</h1>\n<p>Polymorphism is when a class can be extended into subclasses that are a special type of the main class. For example, Mercedes-Benz and Volvo truck are special types of Vehicle. <strong>User is not a type of database!</strong> Your user class should never extend the database. The pattern you are looking for is composition.</p>\n<p>Use dependency injection for providing dependant classes. I would also advise using composer autoloading and DI container if you're not using them yet.</p>\n<h1>7. Learn new syntax.</h1>\n<p>Use short array syntax (<code>[]</code>) rather than the old one (<code>array()</code>). Stay on top of the new features. They have been added to PHP for your convenience so that the code can be kept cleaner.</p>\n<p>On the topic of clean code: adopt a coding standard (I recommend familiarizing yourself with PSR) and format your code properly. Avoid implicit code blocks after <code>if</code> statements. Also, use type hinting.</p>\n<p>Avoid unnecessary coding. Don't reinvent the wheel. PHP has so many array functions that if you have to do something with a loop, you should first check if PHP doesn't already have a function for it. Once you adopt PDO, check all the different fetch modes. They help to avoid unnecessary coding/loops in PHP.</p>\n<h1>8. Name stuff properly</h1>\n<p>Methods are actions. They perform some task. They should be named accordingly. What action is <code>auth()</code> or <code>checkAuth()</code>? The name should describe the action.</p>\n<h1>9 DB class</h1>\n<p>Why would you need such class? The only real method there is <code>select()</code> which is just three lines of PDO code. If you use proper DB abstraction layer this becomes a single line. There's no use for such class.</p>\n<p>The subclasses are even worse. Why do you have a method such as <code>GetList()</code> that should abstract SQL, but yet it accepts SQL as a parameter. This makes no sense. Just stick to normal SQL and prepared statements. Absolutely, no reason to have such class in your code.</p>\n<h1>10 Comments</h1>\n<p>This is slightly controversial, but what are you trying to achieve with the doclocks? I know they can be handy when describing a complex method or one that takes complex parameters, but why does the method <code>Post::GetList()</code> have a description <code>get list of posts</code>? PHP lets you specify types for your arguments and return values. What purpose does the docblock server then?</p>\n<p>There's plenty of other issues in that code. Your session handling is something that raises an eyebrow. The whole application logic is very muddy. It seems you are not using namespaces. Your methods signatures are very inconsistent (array in one place vs. named parameters) I could go on for quite some time, but I think your main problem is your PHP version.</p>\n<p>Upgrade PHP to something reasonable, delete this code, and start fresh. But first, please take some courses in web development or spend a few weeks reading online materials and self-studying. Don't start developing code that could potentially be run online until you gain some experience with web development.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:15:06.520",
"Id": "251962",
"ParentId": "251953",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T17:06:00.257",
"Id": "251953",
"Score": "3",
"Tags": [
"php",
"classes"
],
"Title": "Classes for the blog (PHP)"
}
|
251953
|
<p>this code seems fine at once but the problem I see with this code maintainability I can imagine if one will have to add 10 or more routes the function will grow badly.
can we refactor this code for better maintainibility .</p>
<pre class="lang-javascript prettyprint-override"><code>export const getMetaDescription = (pathname) => {
if (pathname.includes("about")) return "About Us | " + BASE_SITE_NAME;
else if (pathname.includes("fees")) return "Our Fees | " + BASE_SITE_NAME;
else if (pathname.includes("legal")) return "Legal Info | " + BASE_SITE_NAME;
else if (pathname.includes("register"))
return "Registration | " + BASE_SITE_NAME;
else if (pathname.includes("login")) return "Login | " + BASE_SITE_NAME;
return BASE_SITE_NAME;
};
</code></pre>
<p>Edit:
i had a similar function which i refactor by using a map (kind of)</p>
<pre class="lang-javascript prettyprint-override"><code>const titles = {
about: "About Us",
login: "Login",
wallet: "Wallet",
profile: "Profile",
beneficiary: "Beneficiary",
};
export const getMetaTitle = pathname => {
for (let key in titles) {
if (pathname.includes(key)) {
return titles[key] + " | " + BASE_SITE_NAME;
}
}
return BASE_SITE_NAME;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:44:38.723",
"Id": "496216",
"Score": "0",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. This question is off-topic and I'm voting to close it"
}
] |
[
{
"body": "<p>I'd make an object whose key is the pathname and whose value is the unique string for that pathname, then iterate through the object to find the matching key:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const BASE_SITE_NAME = 'BASE_SITE_NAME';\nconst descriptions = {\n about: 'About Us',\n fees: 'Our Fees',\n legal: 'Legal Info',\n register: 'Registration',\n login: 'Login',\n};\nconst getMetaDescription = (pathname) => {\n const foundDescriptionKey = Object.keys(descriptions).find(key => pathname.includes(key));\n return foundDescriptionKey\n ? descriptions[foundDescriptionKey] + ' | ' + BASE_SITE_NAME\n : BASE_SITE_NAME;\n};\n\nconsole.log(getMetaDescription('about'));\nconsole.log(getMetaDescription('foobar'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If <code>pathname</code> is directly from the URL in the browser, make sure to call <code>toLowerCase()</code> on it first (just in case, for example, someone types in <code>example.com/ABOUT</code> instead of clicking a link that redirects to <code>/about</code>).</p>\n<p>This is faithful to your original code. But if each of the descriptions correspond to an entirely separate route, it'd be better to just use plain property lookup. For example, if the pathname is <code>/about</code>, extract the <code>about</code> from that and look up that key on the object, instead of iterating.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const BASE_SITE_NAME = 'BASE_SITE_NAME';\nconst descriptions = {\n about: 'About Us',\n fees: 'Our Fees',\n legal: 'Legal Info',\n register: 'Registration',\n login: 'Login',\n};\nconst getMetaDescription = (pathname) => {\n const description = descriptions[pathname.slice(1)];\n return description\n ? description + ' | ' + BASE_SITE_NAME\n : BASE_SITE_NAME;\n};\n\nconsole.log(getMetaDescription('/about'));\nconsole.log(getMetaDescription('/foobar'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The <code>.includes</code> approach is needed only if you have multiple pathnames associated with a single description. Even if you have multiple pathnames associated with a single description, consider using <code>startsWith</code> instead - it'll be more precise and less likely to have collisions. For example, if you have <code>example.com/profile/aboutme</code>, the <code>about</code> would result in <code>About Us</code> being displayed, which would not be desirable.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const BASE_SITE_NAME = 'BASE_SITE_NAME';\nconst descriptions = {\n about: 'About Us',\n fees: 'Our Fees',\n legal: 'Legal Info',\n register: 'Registration',\n login: 'Login',\n profile: 'Profile',\n};\nconst getMetaDescription = (pathname) => {\n const foundDescriptionKey = Object.keys(descriptions).find(key => pathname.slice(1).startsWith(key));\n return foundDescriptionKey\n ? descriptions[foundDescriptionKey] + ' | ' + BASE_SITE_NAME\n : BASE_SITE_NAME;\n};\n\nconsole.log(getMetaDescription('/about'));\nconsole.log(getMetaDescription('/profile/aboutme'));\nconsole.log(getMetaDescription('/foobar'));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T17:24:25.337",
"Id": "496196",
"Score": "0",
"body": "thanks, i had a similar approach in mind and i have updated the question with it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T17:19:13.743",
"Id": "251956",
"ParentId": "251955",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T17:14:42.443",
"Id": "251955",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Function to get title based on pathname"
}
|
251955
|
<p>I am using Java, but coming from a JavaScript background. I have two objects:</p>
<ol>
<li>a list of users</li>
<li>an Iterable of users preferences</li>
</ol>
<p>I am joining them into a new users object that I call <code>newUser</code>, and then adding <code>newUser</code> to a List of <code>User</code> and returning that.</p>
<p>I need to match up users to their user preferences based on a shared id. If I was using JS I would get the id of the user and filter the user preferences based on the same id. I wasn't able to figure that out, so I used a for loop for users and then a foreach loop for users preferences and the used an if statement to find a match.</p>
<pre><code>var users = service.getUsers();
List<User> value = new ArrayList<User>();
var usersPreferences = _userRepo.findAll();
for(int i =0; i < users.size(); i++){
var user = users.get(i);
boolean[] isFound = {false};
usersPreferences.forEach(prefUser -> {
if(prefUser.getId() == user.getId()){
User newUser = new User(user, prefUser);
value.add(newUser);
isFound[0] = true;
}
});
if(!isFound[0]){
User newUser = new User(user);
value.add(newUser);
}
}
return value;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:58:20.913",
"Id": "496251",
"Score": "0",
"body": "https://www.sitepoint.com/java-8-streams-filter-map-reduce/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:28:36.067",
"Id": "496436",
"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": "<pre class=\"lang-java prettyprint-override\"><code> var users = service.getUsers();\n List<User> value = new ArrayList<User>();\n var usersPreferences = _userRepo.findAll();\n</code></pre>\n<p>Personally, I dislike <code>var</code> with a passion because of exactly <em>such</em> usage. I can't see half-the types, so I have to make a few assumptions here.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for(int i =0; i < users.size(); i++){\n</code></pre>\n<p>First, I'm against using single-letter variable names, with the only exception being dimensions. Having said that, you can most likely use a for-each loop here (I'm not seeing the type of <code>users</code>, but I assume that it is a <code>List</code>).</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (User user : users) {\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>List<User> value = new ArrayList<User>();\n</code></pre>\n<p>This variable name could be better, because it doesn't make much sense.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> boolean[] isFound = {false};\n usersPreferences.forEach(prefUser -> {\n if(prefUser.getId() == user.getId()){\n User newUser = new User(user, prefUser);\n value.add(newUser);\n isFound[0] = true;\n }\n });\n if(!isFound[0]){\n User newUser = new User(user);\n value.add(newUser);\n }\n</code></pre>\n<p>Instead of using a lambda, you could use a simple for-each loop:</p>\n<pre class=\"lang-java prettyprint-override\"><code> boolean isFound = false;\n for (UserPreference userPreference : userPreferences) {\n if(prefUser.getId() == user.getId()){\n User newUser = new User(user, prefUser);\n value.add(newUser);\n isFound = true;\n }\n }\n if(!isFound){\n User newUser = new User(user);\n value.add(newUser);\n }\n\n</code></pre>\n<p>Even better would be if you would extract the second loop into its own function, as that would reduce the complexity of your logic:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private User createUserWithPreferences(User user, List<UserPreferences> userPreferences) {\n for (UserPreference userPreference : userPreferences) {\n if (userPreference.getUserId() == user.getId()) {\n return new User(user, userPreference);\n }\n }\n \n return new User(user);\n}\n\nList<User> createdUsers = new ArrayList<>();\n\nfor (User user : users) {\n createdUsers.add(createUserWithPreferences(user, userPreferences);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T20:17:27.027",
"Id": "251965",
"ParentId": "251959",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "251965",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T18:20:34.733",
"Id": "251959",
"Score": "3",
"Tags": [
"java",
"object-oriented"
],
"Title": "Match users to their preferences by ID"
}
|
251959
|
<h1>Story</h1>
<h2><strong><a href="https://programmers.co.kr/learn/courses/30/lessons/67259" rel="nofollow noreferrer">Original link written in korean</a></strong></h2>
<p>Jordi, the architect of a construction company, received a request from a customer for an estimate for the construction of a raceway.
According to the raceway design drawing provided, the raceway site is in the form of an N x N square grid, each grid being 1 x 1.
In the design drawing, the cells in each grid are filled with 0 or 1, where 0 indicates that the cells are empty and 1 indicates that the cells are filled with walls.The starting point of the raceway is the (0, 0) space (top left), and the end point is the (N-1, N-1) space (bottom right).</p>
<p>Jordi must build a raceway so that the car from the starting point (0, 0) can safely reach the destination (N-1, N-1).
A raceway can be constructed by connecting two adjacent blank spaces up, down, left and right, and a raceway cannot be built in a wall with walls.
At this time, a raceway that connects two adjacent blank spaces up and down or left and right is called a straight road.</p>
<p>Also, the point where two straight roads meet each other at right angles is called a corner.
Calculating the construction cost, it costs 100 $ to make a straight road, and 500$ to make a corner.</p>
<p>Jordi needs to calculate the minimum cost required to build a raceway in order to make an estimate.</p>
<h1>I/O Example</h1>
<p><strong>[[0,0,0,0,0,0],[0,1,1,1,1,0],[0,0,1,0,0,0],[1,0,0,1,0,1],[0,1,0,0,0,1],[0,0,0,0,0,0]]</strong></p>
<p><strong>answer=3200</strong></p>
<p><a href="https://i.stack.imgur.com/59drc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/59drc.png" alt="Road" /></a></p>
<p><strong>If you build a raceway like the red one, it costs 3200 won for 12 straight roads and 4 corners.
If you build a raceway like the blue path, it costs a total of 3,500 won for 10 straight roads and 5 corners, and it costs more.</strong></p>
<h1>my question</h1>
<p>My code consumes lots of running time... <strong>my new idea</strong> is making an library. key value of(x,y).
If BFS arrives at (x,y) first time it saves the cost to reach (x,y).
If BFS arrives (x,y) again, and it's cost is compared with value existing. and if it bigger than value, it is not added to BFS how's this idea? i did not use this idea on code because i'm afraid this would take long time too.</p>
<p>and i wonder your idea too there is a hint but i could not understand it</p>
<h1>My code(original code, new idea not used)</h1>
<pre><code>from collections import deque
import copy
def check(a,b,board,n):
#checks if it can be added to queue#
if b=='U':
if a[0][0]>0 and board[a[0][0]-1][a[0][1]]!=1 and [a[0][0]-1,a[0][1]] not in a[3]:
return True
if b=='D':
if a[0][0]<n-1 and board[a[0][0]+1][a[0][1]]!=1 and [a[0][0]+1,a[0][1]] not in a[3]:
return True
if b=='R':
if a[0][1]<n-1 and board[a[0][0]][a[0][1]+1]!=1 and [a[0][0],a[0][1]+1] not in a[3]:
return True
if b=='L':
if 0<a[0][1] and board[a[0][0]][a[0][1]-1]!=1 and [a[0][0],a[0][1]-1] not in a[3]:
return True
return False
def move(a,b):
# append next movement to queue, change direction and add Turn counts
if b==a[1]:
if b=='U':
a[0][0]-=1
return a
if b=='D':
a[0][0]+=1
return a
if b=='R':
a[0][1]+=1
return a
if b=='L':
a[0][1]-=1
return a
else:
if b=='U':
a[2]+=1
a[0][0]-=1
a[1]='U'
return a
if b=='D':
a[2]+=1
a[0][0]+=1
a[1]='D'
return a
if b=='R':
a[2]+=1
a[0][1]+=1
a[1]='R'
return a
if b=='L':
a[2]+=1
a[0][1]-=1
a[1]='L'
return a
def solution(board):
value=[]
n=len(board)
d=0
queue=deque()
# In queue i added elements [current location, Direction,Turn Counts,visited dots in list]
queue.append([[0,0],'R',0,[]])
queue.append([[0,0],'D',0,[]])
while len(queue)!=0:
p=queue.popleft()
#to use differnt lists in case of error in if loop
Up=copy.deepcopy(p)
Down=copy.deepcopy(p)
Right=copy.deepcopy(p)
Left=copy.deepcopy(p)
past=p[0]
Up[3].append(past)
Down[3].append(past)
Left[3].append(past)
Right[3].append(past)
p[3].append(past)
#I thought the cheapest route can not be longer than shortest route+3
if d!=0 and len(p[3])>d+3:
answer = min(value)*100
return answer
if p[0]==[n-1,n-1]:
value.append((len(p[3])-1)+5*p[2])
d=len(p[3])-1
if check(Up,'U',board,n)==True:
queue.append(move(Up,'U'))
if check(Down,'D',board,n)==True:
queue.append(move(Down,'D'))
if check(Right,'R',board,n)==True:
queue.append(move(Right,'R'))
if check(Left,'L',board,n)==True:
queue.append(move(Left,'L'))
answer = min(value)*100
return answer
</code></pre>
<h1>hint(just for reference)</h1>
<p>For the lowest cost with K corners, you can reduce the number of straight roads as much as possible. This is done by making K corners and finding the shortest route from the origin to the destination.</p>
<p>Now we define the state space S as follows:</p>
<ul>
<li>[Vertical coordinate R][Horizontal coordinate C][Number of corners K][Looking direction D] → Shortest distance when arriving at the (R, C) position while making K corners and looking at direction D</li>
</ul>
<p>At this time, it is assumed that the cost of moving one space is 1, and the cost of creating a corner is also 1. Now it finds the shortest route to the origin → destination for all Ks. The BFS search code is written as follows:</p>
<ul>
<li>Based on the last viewed direction, it searches for three cases: turning left, turning right, and going straight.</li>
<li>In the case of left and right rotation, add a corner and change the viewing direction.</li>
<li>In the case of going straight, advance one space in the direction you are looking.</li>
</ul>
<p>After searching for BFS as above, finally K = 1, 2, 3,… at (N – 1, N – 1) position. Find the shortest distance for the case. At this time, it is important to note that the shortest distance obtained here is a value including the number of corners. Therefore, in the shortest distance with K corners, the construction cost can be calculated as follows:</p>
<ul>
<li>(Shortest distance-K) x 100 + K * 500</li>
</ul>
<p>So how big can the K value here? Each grid can have a maximum of 1 corner. If so, the number of corners in an N x N grid should be less than the number of grid cells. Therefore, the number of corners K can be at most N x N.</p>
<h1>p</h1>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:26:22.577",
"Id": "496209",
"Score": "0",
"body": "Can you explain the math behind the score computation? If I divide the red/blue paths into corner vs. straight, the numbers don't add up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T21:16:36.760",
"Id": "496221",
"Score": "1",
"body": "Dynamic programming. Start from the end block and evaluate the minimum cost for each free block linked with it, then propagate until you arriverà to the starting block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T02:10:40.303",
"Id": "496263",
"Score": "0",
"body": "@AustinHastings there is photo below I think it might help you. for example 3×3, 0,0 0,1 0,2 1,2 2,2 it is shortest 4 straight roads and 1corner so 900$"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T02:19:22.587",
"Id": "496264",
"Score": "0",
"body": "@N74 umm I tried to do that... but I wonder how to do that. IF I USE QUEUE would that be shorter than mine???please explain more. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T03:39:17.273",
"Id": "496268",
"Score": "0",
"body": "@AustinHastings I added photo"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T21:52:35.097",
"Id": "496830",
"Score": "0",
"body": "Take look at A* search (A star search)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T10:27:47.427",
"Id": "496859",
"Score": "0",
"body": "@RootTwo how should Ibuild a huristic for this problem? It contains walls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T16:18:05.753",
"Id": "496911",
"Score": "1",
"body": "@sherloock, just use taxi-cab distance. The heuristic can be any estimate as long as it never overestimates the remaining cost. In this case, taxi-cab distance would have zero or one turn. If there are walls in the way, then the path would have more turns and a higher cost. So the taxi-cab distance would never be an overestimate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T16:54:33.153",
"Id": "497069",
"Score": "0",
"body": "@RootTwo okay I will try that too. thanks!! I actually coded with only cost term. Not using huristic term. and If cost on getting dot A by a route is bigger than the past route to dot A, not append it to queue. So by doing this it reduces useless tries. I thought this would reduce more time than using huristic. Am i thinking wrong??"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T18:38:14.797",
"Id": "251960",
"Score": "3",
"Tags": [
"python-3.x",
"programming-challenge"
],
"Title": "Finding cheapest route (turn costs 500, going straight costs 100)"
}
|
251960
|
<p>The whole project would be a bit much to post, but there were a couple of questions that came up while I worked on this project. This is a fully working space invader game I coded in C++ with SDL2. I am an experienced C# developer and first done this in C# using MonoGame and then "ported" it over to SDL2. Platform is Windows 10 using Visual Studio 2019.</p>
<p>1: I do have a class tree where the base class is Object, and other classes such a Player, Enemy, Bullet and Bunker inherit from it. My ObjectManager keeps track of them all and updates, checks collisions and draws them. My ObjectManager holds them in a vector:</p>
<pre><code> std::vector<std::unique_ptr<Object>> m_colliableObjects;
</code></pre>
<p>I'm using a unique_ptr because unlike C# (which uses ptrs too of course) I can't just use the base class in a vector. Now to add an object to this vector, I have this template function:</p>
<pre><code>template<class T>
void addColliableObject(T* co)
{
static_assert(std::is_base_of<Object, T>::value, "T must be Object.");
m_colliableObjects.push_back(std::unique_ptr<T>(co));
}
</code></pre>
<p>To make the registration, each class inheriting "Object" implements a reg function:</p>
<pre><code>void Player::reg()
{
ObjectManager::getInstance()->addColliableObject<Player>(this);
}
</code></pre>
<p>Which must be called from the constructor from all classes that inherit.
Is there a way to implement this function once in the Object base class, so I can also call it straight from the base class constructor? Meanwhile the opposite destroy() function I was able to implement in the base class easily.</p>
<p>2: I always read to use std::string and not wstring. But the windows API in visual studio defaults to UNICODE. Which I can turn off, but what's the best to use? I want to be able to store normal UTF8 strings, Ascii is too limited.</p>
<p>3: I used a unique_ptr to store this struct in the vector so I do not need a copy and move constructor..is this a wise move? Also is ownership clear in this struct? Because Texture is just pointing to a texture which is owned in the Content namespace</p>
<pre><code> struct SpriteFrame
{
SDL_Texture* Texture;
float Time;
std::unique_ptr<SDL_Rect> SourceRect;
SpriteFrame(SDL_Texture* texture, const float time, SDL_Rect* sourceRect)
: Texture(texture), Time(time), SourceRect(sourceRect)
{
}
};
std::vector<std::unique_ptr<SpriteFrame>> m_frames;
</code></pre>
<p>4: Is there any point of a unique_ptr in a namespace class other than showing ownership? Because these variables never go out of the stack I still need to call reset manually:</p>
<pre><code>namespace Content
{
SDL_Texture* getSpriteSheet();
SDL_Texture* getSpaceBackground();
void loadTextures(const std::string& root);
TTF_Font* loadFont(const std::string& name, int size);
TTF_Font* getFont(const std::string& name, int size, bool loadIfNotFound);
void reset();
namespace
{
SDL_Texture* loadTexture(const std::string& root, const std::string& name);
std::unique_ptr<SDL_Texture, SDL_Deleter> Spritesheet;
std::unique_ptr<SDL_Texture, SDL_Deleter> SpaceBackground;
std::map<std::string, std::unique_ptr<TTF_Font, SDL_Deleter>> fonts;
std::string fontToKey(const std::string& name, int size);
}
</code></pre>
<p>}</p>
<p>5: Similar to 4, to ease access to the ObjectManager I implemented a getInstance function. But since the instance member is stored static, I still need to reset/delete it manually again. Is there a better way?</p>
<pre><code>static ObjectManager* getInstance()
{
if (!m_instance)
m_instance.reset(new ObjectManager());
return m_instance.get();
}
static void reset()
{
m_instance.reset();
}
</code></pre>
<p>6: I'm hosting enemies in a nested array. Which works, but it's not C++ 11 of course. Enemy itself is already owned by ObjectManager, but as soon I use unique_ptr for the array the [] operator does not work. But I need to fill the array quiet dynamically as you can see below:</p>
<pre><code>typedef Enemy** EnemyArr;
EnemyArr* m_enemies;
void EnemyManager::createEnemies(const int xCount, const int yCount, const bool initial)
{
this->m_xCount = xCount;
this->m_yCount = yCount;
m_enemies = new EnemyArr[xCount]);
for (int x = 0; x < xCount; ++x)
{
m_enemies[x] = new Enemy*[yCount];
for (int y = 0; y < yCount; ++y)
{
m_enemies[x][y] = new Enemy(this,{
x * Defs::EnemySpacing + Defs::EnemyMarginIn,
y * Defs::EnemySpacing + Defs::EnemyMarginIn });
m_enemies[x][y]->m_ignoreCollision = y < yCount - 1;
}
}
m_currentMoveAmount = 0;
m_moveToRight = 0;
m_reachedPlayer = false;
if (initial)
{
m_moveDelay = Defs::EnemyMoveDelay;
m_shootDelay = Defs::EnemyShootDelay;
}
else
{
m_moveDelay /= Defs::EnemyIncreaseRoundSpeedMult;
m_shootDelay /= Defs::EnemyIncreaseRoundShootSpeedMult;
}
}
</code></pre>
<p>Please let me know if you need more info because the code is quite straight to the point, I just didn't want to post code of 30 files but I'm happy to share whatever you need, the whole project too.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:41:39.517",
"Id": "496214",
"Score": "2",
"body": "Welcome to Code Review. Please post your whole working code as one, You can even provide a link to a GitHub repository and post the main files here, but its important that you post the full code"
}
] |
[
{
"body": "<h1>No need for a template if you use pointers to base class</h1>\n<p>You made <code>addColliableObject()</code> a template, but that is unnecessary. Since it accepts a pointer to an object that should always be derived from <code>Object</code>, you can write this instead:</p>\n<pre><code>void addColliableObject(Object* co)\n{\n m_colliableObjects.push_back(std::unique_ptr<Object>(co));\n}\n</code></pre>\n<p>You can simplify this even further by writing:</p>\n<pre><code>void addColliableObject(Object* co)\n{\n m_colliableObjects.emplace_back(co);\n}\n</code></pre>\n<p>So now that you no longer need to push the derived type, you can just push a pointer to the base class to <code>m_colliableObjects</code> from the constructor of <code>Object</code>. But be aware that the constructor of the base class is called before the derived class, so you can't have anything use the pointer in <code>m_colliableObjects</code> until the constructor of the derived class has finished.</p>\n<p>You can also destroy it in the base class in a similar way. The destructor of the base class is run after the destructor of the derived class.</p>\n<h1>Unicode is not an encoding</h1>\n<p>See <a href=\"https://stackoverflow.com/questions/402283/stdwstring-vs-stdstring\">this question</a> for a discussion about <code>std::string</code> vs. <code>std::wstring</code>. But in short: <code>std::string</code> can hold UTF-8 strings without issues, but it is not Unicode-aware. It just treats everything as bytes. That's perfectly fine in most cases though; for example the SDL_ttf functions to render text also expect UTF-8 strings in the same format. So it all depends on what other functions need to parse your strings. If it's mostly the Windows API, then perhaps using <code>std::wstring</code> is better.</p>\n<h1>Using <code>std::unique_ptr</code></h1>\n<p>Using <code>std::unique_ptr</code> like you do for <code>m_colliableObjects</code> is perfectly fine and exactly what you need here. It will also work fine for <code>m_frames</code>. However, it should not be necessary to store pointers to <code>SpriteFrame</code>s here. With the definition you provided, <code>std::vector<SpriteFrame> m_frames</code> should work as well, without needing to add copy or move constructors. But what you probably noticed is that you cannot do something like this:</p>\n<pre><code>SpriteFrame frame(...);\nm_frames.push_back(frame);\n</code></pre>\n<p>The reason is that the default copy constructor of <code>SpriteFrame</code> is implicitly deleted, with good reason! It contains a <code>std::unique_ptr</code>, and you cannot copy unique pointers, as then they wouldn't be unique anymore. You should not attempt to fix this by creating a copy constructor, but instead you should use <code>std::move</code> to move <code>frame</code> into the vector:</p>\n<pre><code>m_frames.push_back(std::move(frame));\n</code></pre>\n<p>Alternatively, you can emplace a new <code>SpriteFrame</code> directly into the vector:</p>\n<pre><code>m_frames.emplace_back(...);\n</code></pre>\n<p>As for the usefulness of a <code>std::unique_ptr</code>: besides ownership semantic, it also ensures the memory is automatically cleaned up correctly, so it is a good way to manage storage, and is preferably over manual use of <code>new</code> and <code>delete</code>.</p>\n<h1>Avoid the singleton pattern</h1>\n<p>It seems like you are leaning heavily on the singleton pattern. But do you really need them? Instead of having:</p>\n<pre><code>class Foo {\n static Foo *m_instance;\npublic:\n static Foo *getFoo() {\n if (!m_instance)\n m_instance.reset(new Foo);\n \n return m_instance;\n }\n};\n</code></pre>\n<p>You can just write:</p>\n<pre><code>class Foo {\n ...\n};\n\nFoo theFoo;\n</code></pre>\n<p>Here <code>theFoo</code> is a global variable, everyone can access it, and there is only one <code>theFoo</code>. Especially if <code>Foo</code> doesn't depend on other things to be initialized first, this is easy to do. If you can use this, I would recommend it.</p>\n<p>Anyway, in both your code using the singleton pattern, and my example here, you don't need to explicitly reset or delete it, this will be done automatically once the program terminates. Of course, if the order is important, you might have to manually call <code>reset()</code>, or ensure the order is guaranteed in some other way. There are various ways to approach this, but I cannot tell what the best way would be for your project.</p>\n<h1>Use <code>std::vector</code> for variable sized arrays</h1>\n<p>Avoid raw <code>new</code> and <code>delete</code> for creating arrays, use <code>std::vector</code> for that. If you want a 2D array, you could nest <code>std::vector</code>s like so:</p>\n<pre><code>std::vector<std::vector<Enemy>> m_enemies;\n</code></pre>\n<p>But this approach, and yours too, is inefficient. It is much better to have a one-dimensional array so everything is layed out consecutively in memory, and manually calculate the right index given the x and y coordinates. Here is how to create such an array:</p>\n<pre><code>std::vector<Enemy> m_enemies;\n\n// remember the actual dimensions\nsize_t m_xCount;\nsize_t m_yCount;\n\n...\n\nvoid EnemyManager::createEnemies(const int xCount, const int yCount, const bool initial)\n{\n m_xCount = xCount;\n m_yCount = yCount;\n\n for (int y = 0; y < yCount; ++y)\n {\n for (int x = 0; x < xCount; ++x)\n {\n m_enemies.emplace_back(this, {\n x * Defs::EnemySpacing + Defs::EnemyMarginIn,\n y * Defs::EnemySpacing + Defs::EnemyMarginIn });\n\n m_enemies.back().m_ignoreCollision = y < yCount - 1;\n }\n }\n}\n</code></pre>\n<p>And if you later need to access the enemy at location <code>{x, y}</code>, use:</p>\n<pre><code>m_enemies[x + y * m_xCount]\n</code></pre>\n<p>This small calculation is much faster for the CPU to execute than following multiple pointers.</p>\n<p>Again I've shown <code>m_enemies</code> here storing <code>Enemy</code>s directly, it's also possible to make this a <code>std::vector<std::unique_ptr<Enemy>></code> of course.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:31:57.130",
"Id": "496248",
"Score": "1",
"body": "Thanks a lot, this is very useful information! The reason I put SpriteFrame into a unique_ptr was because I need a copy constructor to make it work inside a vector, at least the way I tried to do it. Is it always recommended to define a copy constructor? I'm only using 1 windows API function and that's \"GetModuleFileNameA\" to get the root path for asset loading. Should I rather use the W function and convert to a wide character string for that function only?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:20:26.647",
"Id": "496402",
"Score": "1",
"body": "You should not need to create a copy constructor. I updated the answer with the reasoning for that. As for using only that one API function: keep using `GetModuleFileNameA()`, you can put the result into a `std::string` and that should work. Compile your code with `UNICODE` set, so you will get the UTF-8 variant."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T22:20:06.213",
"Id": "251974",
"ParentId": "251961",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251974",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:05:32.530",
"Id": "251961",
"Score": "4",
"Tags": [
"c++",
"sdl",
"visual-studio"
],
"Title": "C++ SDL2 Space Invader C++ questions"
}
|
251961
|
<p>Bit of a basic question but I was creating a ancestor/family tree app thingy (haven't really worked out the details) and I wrote a small start-up program (seen below) which checks the AppData directory exists and the config file exist (consisting of the number of tree and their respective names).</p>
<p>I was wondering if it's better to include the code that updates the config file at the beginning of runtime EVERY TIME or not since its only there in case the user accidently changes something:</p>
<pre><code>import json
import os
AncestoryDir = os.getenv("APPDATA") + "\Ancestry"
ConfigFile = AncestoryDir + "\CONFIG.ini"
# Make Ancestory Directory
if not os.path.exists(AncestoryDir):
os.makedirs(AncestoryDir)
# Update Config.ini File
CONFIGTree = {"Tree Count": None, "Tree's": []}
for File in os.scandir(AncestoryDir):
if File.is_file():
Tree, Suffix = File.name.split(".")
if Suffix == "json":
CONFIGTree["Tree's"].append(Tree)
CONFIGTree["Tree Count"] = len(CONFIGTree["Tree's"])
with open(ConfigFile, "w") as JSON:
json.dump(CONFIGTree, JSON, indent = 4)
</code></pre>
<p>Main File:</p>
<pre><code>import os
os.system("python Ancestory.py")
#Other Stuff
</code></pre>
<p>As you can see it updates the config file EVERY TIME and im not sure if its worth it. Any thoughts or suggestions are appreciated.</p>
<p>Note:
Please don't tell me about PEP-8, I'm well aware of it and I choose to ignore it out of pure idiocy (my choice)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T21:46:08.100",
"Id": "496226",
"Score": "1",
"body": "Sure, it's your choice, but... there's a reason it exists. A third-party dev looking at `AncestoryDir` with no other context would assume that it's a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T21:48:31.680",
"Id": "496227",
"Score": "2",
"body": "So your request that we _please don't tell you about PEP8_ might go unheeded; all constructive feedback is on-topic."
}
] |
[
{
"body": "<h2>Pathlib</h2>\n<pre><code>AncestoryDir = os.getenv("APPDATA") + "\\Ancestry"\nConfigFile = AncestoryDir + "\\CONFIG.ini"\n\n# Make Ancestory Directory\nif not os.path.exists(AncestoryDir):\n os.makedirs(AncestoryDir)\n</code></pre>\n<p>can reduce to</p>\n<pre><code>ancestry_dir = Path(os.getenv('APPDATA')) / 'Ancestry'\nconfig_file = ancestry_dir / 'CONFIG.ini'\n\nancestry_dir.mkdir(exist_ok=True)\n</code></pre>\n<p>Note:</p>\n<ul>\n<li>pathlib grants you a cleaner, object-oriented method for path manipulation</li>\n<li>it's spelled "ancestry"</li>\n<li>with pathlib there's no need for a separate existence check</li>\n<li>even if you kept your approach, you have an invalid escape <code>\\A</code> that either needs to be double-escaped or exist in a raw string</li>\n</ul>\n<p>pathlib applies to your other code, too. Also it's spelled "Trees", not "Tree's".</p>\n<h2>PEP8</h2>\n<p>Protest thou may, but this actually matters. Coding is a form of communication, and the less we successfully communicate with other coders, the less they're able to help and work with us.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T09:19:53.477",
"Id": "496297",
"Score": "0",
"body": "I can't believe I've been spelling it wrong lol, thanks :). Also 'Path' not defined? Even with pathlib"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:33:13.693",
"Id": "496348",
"Score": "0",
"body": "Can you show your import statement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:33:24.303",
"Id": "496349",
"Score": "0",
"body": "And what version of Python are you running?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:47:33.967",
"Id": "496356",
"Score": "0",
"body": "python version 3.8.6"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T22:28:31.910",
"Id": "251975",
"ParentId": "251963",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T19:17:08.987",
"Id": "251963",
"Score": "2",
"Tags": [
"python",
"performance",
"json"
],
"Title": "Program efficiency vs user experience. Python Ancestor app"
}
|
251963
|
<p>I recently started a project which has a database of rail cars for a train simulator. Im trying to set up a way to filter the data based upon 4 categories "Car Type", "Road Name", "Pack", and "Area of Origin". I was able to get the dropdown menus to work but they way I did it seems a bit cumbersome. Essentially I have 4 Jquery Ajax scripts one for each dropdown menu each tied to their own specific php file to run the query. Is there a way to consolidate these 4 files into perhaps 1 file that does the same thing? Below is my code.</p>
<p><strong>Index.php (The car directory main page)</strong></p>
<pre><code><html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function showType(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","type.php?t="+str,true);
xmlhttp.send();
}
}
function showRoad(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","road.php?r="+str,true);
xmlhttp.send();
}
}
function showPack(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","pack.php?p="+str,true);
xmlhttp.send();
}
}
</script>
<style type="text/css">
#infoPicture{
width: 200px;
height: 113px;
float: left;
}
#infoInfo{
height: 200px;
width: auto;
float: left;
}
</style>
</head>
<body>
<form>
<?php
include ("includes/dbh.inc.php");
//$query = "SELECT * FROM categories WHERE catagoryID = $catagoryID AND catagoryName = $catagoryName";
//Type Dropdown
$type = mysqli_query($conn, "SELECT * FROM types");
echo '<select onchange="showType(this.value)" name"CarTypes">';
echo '<option>' . 'Car Type' . '</option>';
while ($row = mysqli_fetch_array($type)) {
echo '<option value"' . $row['typeName'] .'">' . $row['typeName'] . '</option>';
}
echo '</select>';
//Road Dropdown
$road = mysqli_query($conn, "SELECT * FROM roads");
echo '<select onchange="showRoad(this.value)" name"RoadNames">';
echo '<option>' . 'Road Name' . '</option>';
while ($row = mysqli_fetch_array($road)) {
echo '<option value"' . $row['roadName']. '">' . $row['roadName'] . ' ('.$row['reportingMark']. ')</option>';
}
echo '</select>';
//Pack Dropdown
$pack = mysqli_query($conn, "SELECT * FROM packs");
echo '<select onchange="showPack(this.value)" name"AddonPack">';
echo '<option>' . 'Add on Pack' . '</option>';
while ($row = mysqli_fetch_array($pack)) {
echo '<option value"' . $row['packID'] .'">' . $row['packName'] . '</option>';
}
echo '</select>';
//Origin Dropdown
$origin = mysqli_query($conn, "SELECT * FROM origins");
echo '<select onchange="showOrigin(this.value)" name"Origins">';
echo '<option>' . 'Area of Origin' . '</option>';
while ($row = mysqli_fetch_array($origin)) {
echo '<option value"' . $row['originID'] .'">' . $row['origin'] . '</option>';
}
echo '</select>';
?>
<a href="index.php">Show All</a>
</form>
</code></pre>
<p><strong>Type.php</strong> <em>I only included one of these as all four are essentially the same but with slightly different queries</em></p>
<pre><code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<?php
include_once 'includes/dbh.inc.php';
if(isset($_GET['t'])){
$t = $_GET['t'];
}else{
$t = "Name not set in the GET method";
}
$sql="SELECT * FROM rollingstock WHERE stockType = '".$t."'";
$result = mysqli_query($conn, $sql);
echo '<table border="0">';
if ($result-> num_rows > 0) {
while ($row = $result-> fetch_assoc()) {
//echo '<div class="listing-picture" style="background-color:#bbb">';
echo '<tr><td>';
echo '<img src="images/Coil_2.png"/>';
echo '</td>';
echo '<td width ="500">';
echo $row["stockName"];
echo '<br>';
echo $row["stockPack"];
echo '<br>';
echo $row["stockLink"];
echo '<br>';
echo $row["stockDesc"];
echo '</td></tr>';
}
echo '</table>';
}else{
echo "Nothing Found!";
}
?>
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T22:57:31.420",
"Id": "496234",
"Score": "0",
"body": "Please take the [tour] and read [ask]. Your question title is meant to uniquely describe what your script does. I don't see any jquery in your scripts so that tag is inappropriate. We are not meant to help with adding new features (such as converting your plain js to jquery). Please edit."
}
] |
[
{
"body": "<p>These are my recommendations:</p>\n<ol>\n<li><p>Move your inline javascript listeners to where your other javascript processes are.</p>\n</li>\n<li><p>Move all javascript processes to an external .js file and call it into your index page. This will reduce the code bloat and put similiar code all in one manageable place.</p>\n</li>\n<li><p>Move all styling declarations to an external .css file. Again, keeping things meaningfully grouped will aid in code readability and maintenance.</p>\n</li>\n<li><p>Consistently use mysqli's object-oriented syntax. The syntax is more concise than procedural style.</p>\n</li>\n<li><p>Never directly inject values into query strings. Use prepared statements with bound parameters.</p>\n</li>\n<li><p>When the intent of building a result set is to instantly pass the data to another layer, it is recommended to simply use <code>fetch_all()</code>. And for that matter, wrap the whole result set in <code>json_encode()</code> and just pass that payload back to your ajax call.</p>\n</li>\n<li><p>Do not make it the responsibility of the querying file to generate html. Pass the raw data back to javascript and demand that the markup be constructed by javascript. There are clean ways to do this.</p>\n</li>\n<li><p>There is never a reason to duplicate the text of an <code><option></code> tag as the <code>value</code> value of the same tag. In other words, when the <code>value</code> is the same as the text, omit the <code>value</code> declaration. There is absolutely no benefit in the redundancy.</p>\n</li>\n<li><p>if <code>$_GET['t']</code> is not declared (or in anyway invalid), don't even bother connecting to the database. Use an early exit so that resources are not wasted. Write something in the javascript that will inform the user of the missing/invalid data.</p>\n</li>\n<li><p>Once you have the querying file purely returning data payloads as json back to ajax, then it becomes very clear that you only need to pass the table name and the identifying value to the php script. The php script then uses a whitelist/lookup array to validate that the table name supplied is available and provides the correct (hardcoded) column name that should be used in the query of said table. In doing all of this, your php file will only need to write a single, dynamic prepared statement and pass back the encoded result set. The javascript/ajax will already be aware of what select had triggered the event, so it therefore knows what kind of markup should be generated and where it should go.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T23:59:03.110",
"Id": "496528",
"Score": "0",
"body": "You might also want to suggest the OP use jQuery for AJX and DOM selection or else ditch jQuery"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:14:50.607",
"Id": "251980",
"ParentId": "251973",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T21:48:18.793",
"Id": "251973",
"Score": "2",
"Tags": [
"php",
"jquery",
"ajax",
"mysqli"
],
"Title": "Is there a way to consolidate Ajax dropdowns that filters data from MYSQLi database"
}
|
251973
|
<p>I made this little tool for something I was trying to accomplish at work. It works as intended but a personal goal of mine is to improve my code design so it's more simple, readable, and contributable.</p>
<p><a href="https://github.com/samhld/lp_generate" rel="nofollow noreferrer">Here is the repo</a> but a snippet of relevant code is at bottom of the question.</p>
<p>The main thing I'm seeking help on is the passing of arguments through the whole stack. In the below code abstraction (or the repo, if you checked that out), you'll notice that function definitions and calling the functions involve passing a ton of arguments repeatedly. I'd prefer to make that cleaner if possible. I've looked into *args and **kwargs but not sure that's necessarily a best practice here. I'm also thinking about using Dataclasses or NamedTuples, perhaps. BTW, I'm leaning toward NamedTuples because they can be iterated on. I guess Dataclasses can't so that might be too inflexible for me? I.e., if I created a NamedTuple called args out of the args from parse_args(), I would want to pass it to functions as *args, right? Only doable with a NamedTuple?</p>
<p>Update: Added full code below:</p>
<pre><code>
import time
import argparse
import random
import string
import datetime
letters = string.ascii_lowercase
def _gen_string(num):
result_str = ''.join(random.choice(letters) for i in range(num))
return(result_str)
def _gen_int(num):
lower_bound = 10 ** (num - 1)
upper_bound = 10 ** num - 1
return(random.randint(lower_bound,upper_bound))
def gen_tag(tag_key_size, tag_value_size, key=''):
# return string Tag key-value pair
if key:
held_key = 'tag_' + key
held_key = held_key[:-4]
val = _gen_string(tag_value_size)
pair = f",{held_key}={val}"
else:
key = 'tag_' + _gen_string((tag_key_size-4))
val = _gen_string(tag_value_size)
pair = f",{key}={val}"
return(pair)
def gen_str_field(field_key_size, field_value_size, key=''):
# return string Tag key-value pair
if key:
held_key = 'str_' + key
held_key = held_key[:-4]
val = _gen_string(field_key_size)
pair = f',{held_key}="{val}"'
else:
key = 'str_' + _gen_string(field_key_size-4)
val = _gen_string(field_value_size)
pair = f',{key}="{val}"'
return(pair)
def gen_int_field(field_key_size, int_value_size, key=''):
# return int Field key-value pair
if key:
held_key = 'int_' + key
held_key = held_key[:-4]
val = _gen_int(int_value_size)
pair = f",{held_key}={val}"
else:
key = 'int_' + _gen_string(field_key_size-4)
val = _gen_int(int_value_size)
pair = f",{key}={val}i"
return(pair)
def gen_float_field(field_key_size, float_value_size, key=''):
# return float Field key-value pair
if key:
held_key = 'fl_' + key
held_key = held_key[:-3]
val = _gen_int(float_value_size)
pair = f",{held_key}={val}"
else:
key = 'fl_' + _gen_string(field_key_size-3)
val = round(random.uniform(10,99), float_value_size-2)
pair = f",{key}={val}"
return(pair)
def gen_ts(precision = 's'):
now = datetime.datetime.now()
ts = now.timestamp()
if precision == ('s' or 'S'):
ts = round(ts)
return(ts*1000000000)
elif precision == ('ms' or 'MS'):
ts = round(ts*1000)
return(ts*1000000)
elif precision == ('us' or 'US'):
ts = round(ts*1000000)
return(ts*1000)
elif precision == ('ns' or 'NS'):
ts = round(ts*1000000000)
return(ts)
else:
print("Warn: gen_ts() only takes `s`, `ms`, `us`, or `ns` as inputs")
return ts
# Return set of Tag key-value pairs with trailing space
def gen_tagset(num_tags, tag_key_size, tag_value_size, tag_keys):
if tag_keys:
tagset = ''.join(gen_tag(tag_key_size,tag_value_size, key=i) for i in tag_keys) + ' '
else:
tagset = ''.join(gen_tag(tag_key_size,tag_value_size) for i in range(num_tags)) + ' '
return(tagset[1:]) # remove leading comma
# Following 3 functions are helper functions for `gen_fieldset()`
def _gen_int_fieldset(int_fields, field_key_size, int_value_size, int_field_keys):
if int_field_keys:
int_fieldset = ''.join(gen_int_field(field_key_size,int_value_size, key=i) for i in int_field_keys)
else:
int_fieldset = ''.join(gen_int_field(field_key_size,int_value_size) for i in range(int_fields))
return(int_fieldset[1:])
def _gen_float_fieldset(float_fields, field_key_size, float_value_size, float_field_keys):
if float_field_keys:
float_fieldset = ''.join(gen_float_field(field_key_size,float_value_size, key=i) for i in float_field_keys)
else:
float_fieldset = ''.join(gen_float_field(field_key_size,float_value_size) for i in range(float_fields))
return(float_fieldset[1:])
def _gen_str_fieldset(str_fields, field_key_size, str_value_size, str_field_keys):
if str_field_keys:
str_fieldset = ''.join(gen_str_field(field_key_size,str_value_size, key=i) for i in str_field_keys)
else:
str_fieldset = ''.join(gen_str_field(field_key_size,str_value_size) for i in range(str_fields))
return(str_fieldset[1:])
# Use fieldset helper functions to generate a full fieldset
def gen_fieldset(int_fields,
float_fields,
str_fields,
field_key_size,
int_value_size,
float_value_size,
str_value_size,
int_field_keys,
float_field_keys,
str_field_keys):
int_fieldset = _gen_int_fieldset(int_fields, field_key_size, int_value_size, int_field_keys)
float_fieldset = _gen_float_fieldset(float_fields, field_key_size, float_value_size, float_field_keys)
str_fieldset = _gen_str_fieldset(str_fields, field_key_size, str_value_size, str_field_keys)
fieldset = ''
if int_fieldset:
fieldset += f"{int_fieldset},"
if float_fieldset:
fieldset += f"{float_fieldset},"
if str_fieldset:
fieldset += f"{str_fieldset},"
return(fieldset[:-1]+' ') # remove leading and trailing comma
def gen_line(measurement,
num_tags,
int_fields,
float_fields,
str_fields,
tag_key_size,
tag_value_size,
field_key_size,
int_value_size,
float_value_size,
str_value_size,
precision,
tag_keys,
int_field_keys,
float_field_keys,
str_field_keys):
tagset = gen_tagset(num_tags, tag_key_size, tag_value_size, tag_keys)
fieldset = gen_fieldset(int_fields, float_fields, str_fields, field_key_size, int_value_size, float_value_size, str_value_size, int_field_keys, float_field_keys, str_field_keys)
timestamp = gen_ts(precision)
line = f"{measurement},{tagset}{fieldset}{timestamp}"
return(line)
def gen_batch(measurement,
batch_size,
num_tags,
int_fields,
float_fields,
str_fields,
tag_key_size,
tag_value_size,
field_key_size,
int_value_size,
float_value_size,
str_value_size,
precision,
keep_keys_batch,
keep_keys_session,
tag_keys,
int_field_keys,
float_field_keys,
str_field_keys):
# Generate keys at batch level if `hold_keys` is True.
# This will keep Tag keys constant per line, reducing Series creation at database level.
if keep_keys_session:
tag_keys = tag_keys
int_field_keys = int_field_keys
float_field_keys = float_field_keys
str_field_keys = str_field_keys
elif keep_keys_batch:
tag_keys = [_gen_string(tag_key_size) for i in range(num_tags)]
int_field_keys = [_gen_string(tag_key_size) for i in range(int_fields)]
float_field_keys = [_gen_string(tag_key_size) for i in range(float_fields)]
str_field_keys = [_gen_string(tag_key_size) for i in range(str_fields)]
else:
tag_keys = []
int_field_keys = []
float_field_keys = []
str_field_keys = []
batch = []
for i in range(batch_size):
line = gen_line(measurement,
num_tags,
int_fields,
float_fields,
str_fields,
tag_key_size,
tag_value_size,
field_key_size,
int_value_size,
float_value_size,
str_value_size,
precision,
tag_keys,
int_field_keys,
float_field_keys,
str_field_keys)
batch.append(line)
return(batch)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate a batch of Line Protocol points of a specified shape")
parser.add_argument('measurement', type=str, default='cpu')
parser.add_argument('--batch_size', type=int, default=10)
parser.add_argument('--num_tags', type=int, default=3)
parser.add_argument('--int_fields', type=int, default=2)
parser.add_argument('--float_fields', type=int, default=1)
parser.add_argument('--str_fields', type=int, default=1)
parser.add_argument('--tag_key_size', type=int, default=8)
parser.add_argument('--tag_value_size', type=int, default=10)
parser.add_argument('--field_key_size', type=int, default=8)
parser.add_argument('--int_value_size', type=int, default=4)
parser.add_argument('--float_value_size', type=int, default=4)
parser.add_argument('--str_value_size', type=int, default=8)
parser.add_argument('--precision', type=str, choices = ['s','S','ms','MS','us','US','ns','NS'], default='s')
parser.add_argument('--keep_keys_batch', action='store_true')
parser.add_argument('--keep_keys_session', action='store_true', help="")
args = parser.parse_args()
if args.keep_keys_session:
tag_keys = [_gen_string(args.tag_key_size) for i in range(args.num_tags)]
int_field_keys = [_gen_string(args.tag_key_size) for i in range(args.int_fields)]
float_field_keys = [_gen_string(args.tag_key_size) for i in range(args.float_fields)]
str_field_keys = [_gen_string(args.tag_key_size) for i in range(args.str_fields)]
args.keep_keys_batch = True
else:
tag_keys = []
int_field_keys = []
float_field_keys = []
str_field_keys = []
batch = gen_batch(args.measurement,
args.batch_size,
args.num_tags,
args.int_fields,
args.float_fields,
args.str_fields,
args.tag_key_size,
args.tag_value_size,
args.field_key_size,
args.int_value_size,
args.float_value_size,
args.str_value_size,
args.precision,
args.keep_keys_batch,
args.keep_keys_session,
tag_keys,
int_field_keys,
float_field_keys,
str_field_keys)
for line in batch:
print(line)
</code></pre>
<p>The entire set of arguments is generated from flags at the command line so I generate a Namespace of these args. I imagine there's a much cleaner way to pass all these arguments through the stack of this application?</p>
<p>Thanks in advance to anyone willing to help out here!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:00:04.813",
"Id": "496235",
"Score": "0",
"body": "@Reinderien Ok -- I added the full code. It's laid out differently than this in the repo but I moved all the code into a single place for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:03:30.787",
"Id": "496237",
"Score": "0",
"body": "Yep will fix. Was deleting calls the module that I flattened out of this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:12:43.357",
"Id": "496240",
"Score": "1",
"body": "@Reinderien errors should be fixed. Sorry about that. turning that into one file led to some hiccups."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:20:14.783",
"Id": "496245",
"Score": "0",
"body": "No worries; it's basically a good question now "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:54:00.743",
"Id": "496249",
"Score": "1",
"body": "https://refactoring.guru/smells/long-parameter-list"
}
] |
[
{
"body": "<p>I'm not sure why you think that kwargs isn't a good idea. It would simplify the code quite a bit, and it is a pretty common way of doing this. You could do a data class, but it's trivial to copy the argparse args into a dictionary using the vars() function.</p>\n<p>I didn't redo all of your code, but you can get the idea from this snippet:</p>\n<pre><code>import argparse\n\ndef gen_batch(**kwargs):\n\n # Generate keys at batch level if `hold_keys` is True. \n # This will keep Tag keys constant per line, reducing Series creation at database level.\n\n # Simplified...\n # if keep_keys_session:\n # tag_keys = tag_keys\n # int_field_keys = int_field_keys\n # float_field_keys = float_field_keys\n # str_field_keys = str_field_keys\n if not keep_keys_session and keep_keys_batch:\n tag_key_size = kwargs.get('tag_key_size')\n kwargs['tag_keys'] = [_gen_string(tag_key_size) for i in range(kwargs.get('num_tags'))]\n kwargs['int_field_keys'] = [_gen_string(tag_key_size) for i in range(kwargs.get('int_fields'))]\n kwargs['float_field_keys'] = [_gen_string(tag_key_size) for i in range(kwargs.get('float_fields'))]\n kwargs['str_field_keys'] = [_gen_string(tag_key_size) for i in range(kwargs.get('str_fields'))]\n elif not keep_keys_session:\n kwargs['tag_keys'] = []\n kwargs['int_field_keys'] = []\n kwargs['float_field_keys'] = []\n kwargs['str_field_keys'] = []\n \n batch = []\n for i in range(batch_size):\n line = gen_line(**kwargs)\n batch.append(line)\n\n return(batch) \n\nif __name__ == "__main__":\n parser = argparse.ArgumentParser(description="Generate a batch of Line Protocol points of a specified shape")\n parser.add_argument('measurement', type=str, default='cpu')\n parser.add_argument('--batch_size', type=int, default=10)\n parser.add_argument('--num_tags', type=int, default=3)\n parser.add_argument('--int_fields', type=int, default=2)\n parser.add_argument('--float_fields', type=int, default=1)\n parser.add_argument('--str_fields', type=int, default=1)\n parser.add_argument('--tag_key_size', type=int, default=8)\n parser.add_argument('--tag_value_size', type=int, default=10) \n parser.add_argument('--field_key_size', type=int, default=8)\n parser.add_argument('--int_value_size', type=int, default=4)\n parser.add_argument('--float_value_size', type=int, default=4)\n parser.add_argument('--str_value_size', type=int, default=8)\n parser.add_argument('--precision', type=str, choices = ['s','S','ms','MS','us','US','ns','NS'], default='s')\n parser.add_argument('--keep_keys_batch', action='store_true')\n parser.add_argument('--keep_keys_session', action='store_true', help="")\n\n args = parser.parse_args()\n \n # make a dictionary out of the parser args\n batch_args = vars(args)\n\n # add the other items to the dictionary\n if args.keep_keys_session:\n batch_args['tag_keys'] = [_gen_string(args.tag_key_size) for i in range(args.num_tags)]\n batch_args['int_field_keys'] = [_gen_string(args.tag_key_size) for i in range(args.int_fields)]\n batch_args['float_field_keys'] = [_gen_string(args.tag_key_size) for i in range(args.float_fields)]\n batch_args['str_field_keys'] = [_gen_string(args.tag_key_size) for i in range(args.str_fields)]\n batch_args['keep_keys_batch'] = True\n else:\n batch_args['tag_keys'] = []\n batch_args['int_field_keys'] = []\n batch_args['float_field_keys'] = []\n batch_args['str_field_keys'] = []\n\n batch = gen_batch(**batch_args)\n\n for line in batch:\n print(line)\n</code></pre>\n<p>You can do the same type of transformation to get_line() and get_fieldset(). Beyond that, it might be cleaner to just extract the couple of args and pass them directly to the rest of the gen_xxx() functions rather than propagating kwargs everywhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T23:12:33.740",
"Id": "496524",
"Score": "0",
"body": "I ended up doing just this!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T01:29:06.580",
"Id": "252029",
"ParentId": "251976",
"Score": "5"
}
},
{
"body": "<p><strong>Updated</strong> to include Tomerikoo's suggestion to just use the args object instead of creating another object.</p>\n<p>In thinking about this some more, it's nearly identical to use a class rather than a dictionary to store the arguments, but it makes the code a little easier to read IMHO. For example, <code>args.str_fields</code> is more intuitive than <code>kwargs.get('str_fields')</code>. And the easiest class to use (thanks @Tomerikoo ) is the object returned from <code>parse_args()</code>. So if it's not too late, here is an updated version using an object to store the arguments rather than a dictionary. Also, I used the <code>a = x if b else y</code> syntax to condense some of the assignment statements.</p>\n<pre><code>import argparse\n\ndef gen_batch(bargs):\n\n # Generate keys at batch level if `hold_keys` is True. \n # This will keep Tag keys constant per line, reducing Series creation at database level.\n\n # Simplified...\n if not keep_keys_session:\n # these local variables are just to shorten the assignment lines\n tag_key_size = _gen_string(bargs.tag_key_size)\n keep = bargs.keep_keys_batch\n\n bargs.tag_keys = [tag_key_size for i in range(bargs.num_tags)] if keep else []\n bargs.int_field_keys = [tag_key_size for i in range(bargs.int_fields)] if keep else []\n bargs.float_field_keys = [tag_key_size for i in range(bargs.float_fields)] if keep else []\n bargs.str_field_keys = [tag_key_size for i in range(bargs.str_fields)] if keep else []\n \n batch = []\n for i in range(batch_size):\n line = gen_line(bargs)\n batch.append(line)\n\n return(batch) \n\nif __name__ == "__main__":\n parser = argparse.ArgumentParser(description="Generate a batch of Line Protocol points of a specified shape")\n parser.add_argument('measurement', type=str, default='cpu')\n parser.add_argument('--batch_size', type=int, default=10)\n parser.add_argument('--num_tags', type=int, default=3)\n parser.add_argument('--int_fields', type=int, default=2)\n parser.add_argument('--float_fields', type=int, default=1)\n parser.add_argument('--str_fields', type=int, default=1)\n parser.add_argument('--tag_key_size', type=int, default=8)\n parser.add_argument('--tag_value_size', type=int, default=10) \n parser.add_argument('--field_key_size', type=int, default=8)\n parser.add_argument('--int_value_size', type=int, default=4)\n parser.add_argument('--float_value_size', type=int, default=4)\n parser.add_argument('--str_value_size', type=int, default=8)\n parser.add_argument('--precision', type=str, choices = ['s','S','ms','MS','us','US','ns','NS'], default='s')\n parser.add_argument('--keep_keys_batch', action='store_true')\n parser.add_argument('--keep_keys_session', action='store_true', help="")\n\n args = parser.parse_args()\n \n # add the other items\n tks = _gen_string(args.tag_key_size)\n args.tag_keys = [tks for i in range(args.num_tags)] if args.keep_keys_session else []\n args.int_field_keys = [tks for i in range(args.int_fields)] if args.keep_keys_session else []\n args.float_field_keys = [tks for i in range(args.float_fields)] if args.keep_keys_session else []\n args.str_field_keys = [tks for i in range(args.str_fields)] if args.keep_keys_session else []\n args.keep_keys_batch = True if args.keep_keys_session else False\n\n batch = gen_batch(args)\n\n for line in batch:\n print(line)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:45:31.227",
"Id": "496596",
"Score": "2",
"body": "Why not just use `args`? It is already a simple container object holding some attributes, and all you do is copy its attributes to a new object... Just use `args` instead of `bargs`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T21:15:17.700",
"Id": "496609",
"Score": "2",
"body": "You are correct, there's no reason unless you need to add more customization to the container object, which was not a requirement from the OP. I guess that I was staring at it too long to see the obvious. I'll edit my answer to implement your suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:51:09.200",
"Id": "496613",
"Score": "2",
"body": "I see you already edited what I was going to reply on your previous comment that you can add any attributes you want to the existing `args` object :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T23:42:49.590",
"Id": "496617",
"Score": "1",
"body": "I did :-). Mentally, I always isolate the args object from the rest of my code, usually pushing them into local variables, but I'll keep this model in mind moving forward where it makes sense."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:41:59.777",
"Id": "252115",
"ParentId": "251976",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252029",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T22:30:55.503",
"Id": "251976",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Line protocol point generator"
}
|
251976
|
<p>Simple Machine Translator(SML) is a simulator that executes code written in hexadecimal. It supports features such as read, write, add, subtract and many more. My previous question concerning this minimal exercise link can be found <a href="https://codereview.stackexchange.com/questions/251436/simple-machine-language-simulator">here</a> for those who wants to follow up.
I made a lot of changes, restructured and move things around and would appreciate a review.</p>
<h1><code>SML.h</code></h1>
<pre><code>#ifndef SML_SML_H_
#define SML_SML_H_
#include "evaluator.h"
#include <string>
constexpr size_word register_max_size = 6;
enum REGISTERS
{
ACCUMULATOR = 0,
INSTRUCTION_COUNTER = 1,
TEMPORARY_COUNTER = 2,
INSTRUCTION_REGISTER = 3,
OPERATION_CODE = 4,
OPERAND = 5
};
class SML
{
friend void swap( SML &lhs, SML &rhs );
friend class Evaluator;
public:
SML() = default;
SML( const int memory_size, const int word_lower_lim, const int word_upper_lim );
SML( const SML &s );
const SML& operator=( const SML s );
SML( SML &&s );
~SML();
void display_welcome_message() const;
void load_program();
void execute();
private:
size_word registers[ register_max_size ];
std::string temp_str; // holds the string before it is written into the memory
bool debug;
static const size_word read_ = 0xA; // Read a word(int) from the keyboard into a specific location in memory
static const size_word write_ = 0xB; // Write a word(int) from a specific location in memory to the screen
static const size_word read_str_ = 0xC; // Read a word(string) from the keyboard into a specific location in memory
static const size_word write_str_ = 0xD; // Write a word(string) from a specific location in memory to the screen
static const size_word load_ = 0x14; // Load a word from a specific location in memory to the accumulator
static const size_word store_ = 0x15; // Store a word from the accumulator into a specific location in memory
static const size_word add_ = 0x1E; /* Add a word from a specific location in memory to the word in the accumulator; store the
result in the accumulator */
static const size_word subtract_ = 0x1F;
static const size_word multiply_ = 0x20;
static const size_word divide_ = 0x21;
static const size_word modulo_ = 0x22;
static const size_word branch_ = 0x28; // Branch to a specific location in the memory
static const size_word branchneg_ = 0x29; // Branch if accumulator is negative
static const size_word branchzero_ = 0x2A; // Branch if accumulator is zero
static const size_word halt_ = 0x2B; // Halt the program when a task is completed
static const size_word newline_ = 0x32; // Insert a new line
static const size_word end_ = -0x1869F; // End the program execution
static const size_word sml_debug_ = 0x2C; // SML debug ( 1 to turn on, 0 to turn off )
size_word word_lower_limit; /* A word should not exceed */
size_word word_upper_limit; /* this limits */
size_word memory_size;
size_word *memory = nullptr;
void set_registers();
void memory_dump() const;
};
#endif
</code></pre>
<h1><code>SML.cpp</code></h1>
<pre><code>#include "sml.h"
#include "evaluator.h"
#include <iostream>
#include <iomanip>
#include <algorithm>
SML::SML( const int mem_size, const int word_lower_lim, const int word_upper_lim )
: debug( false ), word_lower_limit( word_lower_lim ),
word_upper_limit( word_upper_lim ), memory_size( mem_size )
{
set_registers();
memory = new size_word[ memory_size ];
}
void SML::set_registers()
{
registers[ static_cast<unsigned>( ACCUMULATOR ) ] = 0;
registers[ static_cast<unsigned>( INSTRUCTION_COUNTER ) ] = 0;
registers[ static_cast<unsigned>( TEMPORARY_COUNTER ) ] = 0;
registers[ static_cast<unsigned>( INSTRUCTION_REGISTER ) ] = 0;
registers[ static_cast<unsigned>( OPERATION_CODE ) ] = 0;
registers[ static_cast<unsigned>( OPERAND ) ] = 0;
}
SML::SML( const SML &s )
{
temp_str = s.temp_str;
debug = s.debug;
word_lower_limit = s.word_lower_limit;
word_upper_limit = s.word_upper_limit;
std::copy( std::cbegin( s.registers ), std::cend( s.registers ), registers );
memory_size = s.memory_size;
memory = new size_word[ memory_size ];
std::copy( s.memory, s.memory + s.memory_size, memory );
}
SML::SML( SML &&s )
{
swap( *this, s );
memory = new size_word[ memory_size ];
std::move( s.memory, s.memory + s.memory_size, memory );
}
const SML& SML::operator=( SML s )
{
swap( *this, s );
memory = new size_word[ memory_size ];
std::move( s.memory, s.memory + s.memory_size, memory );
return *this;
}
void swap( SML &lhs, SML &rhs )
{
using std::swap;
swap( lhs.temp_str, rhs.temp_str );
swap( lhs.debug, rhs.debug );
swap( lhs.word_lower_limit, rhs.word_lower_limit );
swap( lhs.word_upper_limit, rhs.word_upper_limit );
swap( lhs.memory_size, rhs.memory_size );
swap( lhs.registers, rhs.registers );
}
void SML::display_welcome_message() const
{
std::cout << "***" << " WELCOME TO SIMPLETRON! " << "***\n\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "Please enter your program one instruction"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "(or data word) at a time. I will type the"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "location number and a question mark (?)."
<< std::setw( 6 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "You then type the word for that location"
<< std::setw( 6 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "Type the sentinel -0x1869F to stop entering"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "your program"
<< std::setw( 5 ) << std::right << "***";
std::cout << "\n\n" << std::flush;
}
void SML::load_program()
{
size_word &ins_cnt = registers[ static_cast<unsigned>( INSTRUCTION_COUNTER ) ];
size_word temp;
while( ins_cnt != memory_size )
{
std::cout << std::setw( 2 ) << std::setfill( '0' )
<< ins_cnt << " ? ";
std::cin >> std::hex >> temp;
if( temp == end_ ) {
break;
}
if( temp >= word_lower_limit && temp < word_upper_limit )
memory[ ins_cnt++ ] = temp;
else
continue;
}
ins_cnt = 0;
std::cout << std::setfill( ' ' );
std::cout << std::setw( 5 ) << std::left << "***"
<< "Program loaded into memory"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "Program execution starts..."
<< std::setw( 5 ) << std::right << "***\n";
execute();
std::cout << std::endl;
}
void SML::execute()
{
int divisor;
size_word &ins_cnt = registers[ static_cast<unsigned>( INSTRUCTION_COUNTER ) ];
size_word &ins_reg = registers[ static_cast<unsigned>( INSTRUCTION_REGISTER ) ];
while( memory[ ins_cnt ] != 0 )
{
ins_reg = memory[ ins_cnt++ ];
if( ins_reg < 1000 ) divisor = 0x10;
else if( ins_reg >= 1000 && ins_reg < 10000 ) divisor = 0x100;
else if( ins_reg >= 10000 && ins_reg < 100000 ) divisor = 0x1000;
Evaluator eval( *this ); // create an instance of evaluator
try
{
if( eval.evaluate( *this, ins_reg, divisor ) == 0 )
break;
}
catch ( std::invalid_argument &e )
{
std::cout << e.what() << "\n";
}
if( debug )
memory_dump();
}
}
void SML::memory_dump() const
{
std::cout << "\nREGISTERS:\n";
std::cout << std::setw( 25 ) << std::left << std::setfill( ' ' ) << "accumulator" << std::showpos
<< std::setw( 5 ) << std::setfill( '0' ) << std::internal << registers[ 0 ] << '\n';
std::cout << std::setw( 28 ) << std::left << std::setfill( ' ' )
<< "instruction counter" << std::noshowpos << std::setfill( '0' )
<< std::right << std::setw( 2 ) << registers[ 1 ] << '\n';
std::cout << std::setw( 25 ) << std::left << std::setfill( ' ' )
<< "instruction register" << std::showpos << std::setw( 5 ) << std::setfill( '0' )
<< std::internal << registers[ 3 ] << '\n';
std::cout << std::setw( 28 ) << std::left << std::setfill( ' ' )
<< "operation code" << std::noshowpos << std::setfill( '0' )
<< std::right << std::setw( 2 ) << registers[ 4 ] << '\n';
std::cout << std::setw( 28 ) << std::left << std::setfill( ' ' )
<< "operand" << std::noshowpos << std::setfill( '0' )
<< std::right << std::setw( 2 ) << registers[ 5 ] << '\n';
std::cout << "\n\nMEMORY:\n";
std::cout << " ";
for( int i = 0; i != 10; ++i )
std::cout << std::setw( 6 ) << std::setfill( ' ') << std::right << i;
for( size_word i = 0; i != memory_size; ++i )
{
if( i % 10 == 0 )
std::cout << "\n" << std::setw( 3 ) << std::setfill( ' ' ) << i << " ";
std::cout << std::setw( 5 ) << std::setfill( '0' ) << std::showpos << std::internal << memory[ i ] << " ";
}
std::cout << std::endl;
}
SML::~SML()
{
// resets all the registers
set_registers();
// free the memory
delete [] memory;
}
</code></pre>
<h1><code>Evaluator.h</code></h1>
<pre><code>#ifndef SML_EVALUATOR_H_
#define SML_EVALUATOR_H_
#include <iostream>
#include <stdint.h>
typedef int32_t size_word;
constexpr size_word instruction_max_sixe = 70;
class SML;
class Evaluator
{
public:
Evaluator() = default;
Evaluator( const SML & );
int evaluate( SML &s, const int ins_reg, const int divisor );
private:
void read( SML &s, const int opr );
void write( SML &s, const int opr );
void read_str( SML &s, const int opr );
void write_str( SML &s, const int opr );
void load( SML &s, const int opr );
void store( SML &s, const int opr );
void add( SML &s, const int opr );
void subtract( SML &s, const int opr );
void multiply( SML &s, const int opr );
void divide( SML &s, const int opr );
void modulo( SML &s, const int opr );
void branch( SML &s, const int opr );
void branchneg( SML &s, const int opr );
void branchzero( SML &s, const int opr );
void newline( SML &s, const int opr );
void smldebug( SML &s, const int opr );
bool division_by_zero( SML &s, const int opr );
void (Evaluator::*instruction_set[ instruction_max_sixe ])( SML &, int );
};
#endif
</code></pre>
<h1><code>Evaluator.cpp</code></h1>
<pre><code>#include "evaluator.h"
#include "sml.h"
Evaluator::Evaluator( const SML &s )
{
instruction_set[ s.read_ ] = &Evaluator::read;
instruction_set[ s.write_ ] = &Evaluator::write;
instruction_set[ s.read_str_ ] = &Evaluator::read_str;
instruction_set[ s.write_str_ ] = &Evaluator::write_str;
instruction_set[ s.load_ ] = &Evaluator::load;
instruction_set[ s.store_ ] = &Evaluator::store;
instruction_set[ s.add_ ] = &Evaluator::add;
instruction_set[ s.subtract_ ] = &Evaluator::subtract;
instruction_set[ s.multiply_ ] = &Evaluator::multiply;
instruction_set[ s.divide_ ] = &Evaluator::divide;
instruction_set[ s.modulo_ ] = &Evaluator::modulo;
instruction_set[ s.branch_ ] = &Evaluator::branch;
instruction_set[ s.branchneg_ ] = &Evaluator::branchneg;
instruction_set[ s.branchzero_ ] = &Evaluator::branchzero;
instruction_set[ s.newline_ ] = &Evaluator::newline;
instruction_set[ s.sml_debug_ ] = &Evaluator::smldebug;
}
int Evaluator::evaluate( SML &s, const int ins_reg, const int divisor)
{
size_word &opr_code = s.registers[ static_cast<unsigned>( OPERATION_CODE ) ];
size_word &opr = s.registers[ static_cast<unsigned>( OPERAND ) ];
opr_code = ins_reg / divisor;
opr = ins_reg % divisor;
if( opr_code == s.halt_ )
return 0;
else
(this->*(instruction_set[ opr_code ]))( s, opr );
return 1;
}
void Evaluator::read( SML &s, const int opr )
{
std::cin >> s.memory[ opr ];
}
void Evaluator::write( SML &s, const int opr )
{
std::cout << s.memory[ opr ];
}
void Evaluator::read_str( SML &s, const int opr )
{
std::cin >> s.temp_str;
s.memory[ opr ] = s.temp_str.size();
for( std::string::size_type i = 1; i != s.temp_str.size() + 1; ++i )
s.memory[ opr + i ] = int( s.temp_str[ i - 1 ] );
}
void Evaluator::write_str( SML &s, const int opr )
{
for( int i = 0; i != s.memory[ opr ] + 1; ++i )
std::cout << char( s.memory[ opr + i ]);
}
void Evaluator::load( SML &s, const int opr )
{
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
accumulator = s.memory[ opr ];
}
void Evaluator::store( SML &s, const int opr )
{
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
s.memory[ opr ] = accumulator;
}
void Evaluator::add( SML &s, const int opr )
{
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
accumulator += s.memory[ opr ];
}
void Evaluator::subtract( SML &s, const int opr )
{
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
accumulator -= s.memory[ opr ];
}
void Evaluator::multiply( SML &s, const int opr )
{
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
accumulator *= s.memory[ opr ];
}
void Evaluator::divide( SML &s, const int opr )
{
if( division_by_zero( s, opr ) )
throw std::invalid_argument( "Division by zero: Program terminated abnormally." );
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
accumulator /= s.memory[ opr ];
}
void Evaluator::modulo( SML &s, const int opr )
{
if( division_by_zero( s, opr ) )
throw std::invalid_argument( "Division by zero: Program terminated abnormally." );
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
accumulator /= s.memory[ opr ];
}
bool Evaluator::division_by_zero( SML &s, const int opr )
{
return ( s.memory[ opr ] == 0 );
}
void Evaluator::branchneg( SML &s, const int opr )
{
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
if( accumulator < 0 )
branch( s, opr );
}
void Evaluator::branchzero( SML &s, const int opr )
{
size_word &accumulator = s.registers[ static_cast<unsigned>( ACCUMULATOR ) ];
if( accumulator == 0 )
branch( s, opr );
}
void Evaluator::branch( SML &s, const int opr )
{
size_word &ins_cnt = s.registers[ static_cast<unsigned>( INSTRUCTION_COUNTER ) ];
s.registers[ static_cast<unsigned>( TEMPORARY_COUNTER ) ] = ins_cnt;
ins_cnt = opr;
s.execute();
ins_cnt = s.registers[ static_cast<unsigned>( TEMPORARY_COUNTER ) ];
}
void Evaluator::newline( SML &s, const int opr )
{
std::cout << '\n' << std::flush;
}
void Evaluator::smldebug( SML &s, const int opr )
{
if ( opr == 1 ) s.debug = true;
else if ( opr == 0 ) s.debug = false;
}
</code></pre>
<h1><code>main.cpp</code></h1>
<pre><code>#include "sml.h"
int main()
{
SML sml(1000, -999999, 999999 );
sml.display_welcome_message();
sml.load_program();
}
</code></pre>
<p>Below are instructions written to test the machine</p>
<h1><code>Tests</code></h1>
<pre><code>0xA60 // read a value and store in address 60( written to index 96(decimal) in the array,
0xA61 // read another value and store in address 61
0x1460 // write the value stored in address 60 to the accumulator
0x1e61 // add the value stored in address 61 to the accumulator
0x320 // print a newline
0x1562 // store the value in the accumulatore to address 62
0xb62 // write the value in address 62 to the screen
0x320 // print a newline
0xc67 // read a string and store it size at address 67, the characters would be stored from 68 to end of character
0xd67 // write the characters to screen
0x2c1 // turn on debug
-0x1869f // start execution
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T04:17:44.010",
"Id": "496270",
"Score": "1",
"body": "Can you give an example set of instructions for testing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T04:33:48.233",
"Id": "496272",
"Score": "1",
"body": "@Aryan Parekh Should I add it to the question or comment it here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T04:34:44.670",
"Id": "496273",
"Score": "1",
"body": "Anywhere you'd like, Adding it to the question would be better I think"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T05:53:31.377",
"Id": "496277",
"Score": "3",
"body": "@AryanParekh. I editted the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T06:37:40.663",
"Id": "496279",
"Score": "1",
"body": "If I enter 1) `0xA61`, 2)`0xB61` It should directly print out what I entered right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T07:21:08.547",
"Id": "496280",
"Score": "1",
"body": "@Aryan Parekh Yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T07:23:49.667",
"Id": "496281",
"Score": "2",
"body": "The program crashes, outputs something else. When I tried to debug your program, I see that you have an unhandled exception thrown in your `evaluate()` function. `0xC0000005`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T07:27:47.107",
"Id": "496282",
"Score": "1",
"body": "@Aryan Parekh Did you type \"O\" instead 0?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T07:38:10.190",
"Id": "496285",
"Score": "1",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/116135/discussion-between-theprogrammer-and-aryan-parekh)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:33:12.077",
"Id": "496307",
"Score": "1",
"body": "I too had an unhanded exception, I only typed in 1 line -0x1869f."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T06:57:34.613",
"Id": "496433",
"Score": "0",
"body": "What is the definition of `size_word`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:05:36.490",
"Id": "496434",
"Score": "1",
"body": "@Nayuki `int32_t`"
}
] |
[
{
"body": "<p>Just a few things</p>\n<h1>Use <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"noreferrer\">Raw string literals</a></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout << "***" << " WELCOME TO SIMPLETRON! " << "***\\n\\n";\n std::cout << std::setw(5) << std::left << "***"\n << "Please enter your program one instruction"\n << std::setw(5) << std::right << "***\\n";\n\n std::cout << std::setw(5) << std::left << "***"\n << "(or data word) at a time. I will type the"\n << std::setw(5) << std::right << "***\\n";\n\n std::cout << std::setw(5) << std::left << "***"\n << "location number and a question mark (?)."\n << std::setw(6) << std::right << "***\\n";\n\n std::cout << std::setw(5) << std::left << "***"\n << "You then type the word for that location"\n << std::setw(6) << std::right << "***\\n";\n\n std::cout << std::setw(5) << std::left << "***"\n << "Type the sentinel -0x1869F to stop entering"\n << std::setw(5) << std::right << "***\\n";\n\n std::cout << std::setw(5) << std::left << "***"\n << "your program"\n << std::setw(5) << std::right << "***";\n\n std::cout << "\\n\\n" << std::flush;\n</code></pre>\n<p>This can get extremely difficult to maintain. You can simply use <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"noreferrer\">string literals</a> to make your life easy</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>const char* welcome_msg = R"""(\n\n*** WELCOME TO SIMPLETRON! ***\n\n*** Please enter your program one instruction ***\n*** (or data word) at a time. I will type the ***\n*** location number and a question mark (?). ***\n*** You then type the word for that location ***\n*** Type the sentinel -0x1869F to stop entering ***\n*** your program ***\n\n)"""\n</code></pre>\n<pre><code>std::cout << welcome_msg;\n</code></pre>\n<hr />\n<h1>Simplify</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> registers[static_cast<unsigned>(ACCUMULATOR)] = 0;\n registers[static_cast<unsigned>(INSTRUCTION_COUNTER)] = 0;\n registers[static_cast<unsigned>(TEMPORARY_COUNTER)] = 0;\n registers[static_cast<unsigned>(INSTRUCTION_REGISTER)] = 0;\n registers[static_cast<unsigned>(OPERATION_CODE)] = 0;\n registers[static_cast<unsigned>(OPERAND)] = 0;\n</code></pre>\n<p>Instead of casting it to unsigned every time you use something from the <code>enum</code>, why not declare it <code>unsigned</code> first?</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum REGISTERS : unsigned\n{\n ACCUMULATOR = 0,\n INSTRUCTION_COUNTER = 1,\n TEMPORARY_COUNTER = 2,\n INSTRUCTION_REGISTER = 3,\n OPERATION_CODE = 4,\n OPERAND = 5\n};\n</code></pre>\n<p>Also, you don't have to specify the values here since they are continuous. That means this is the same as</p>\n<pre><code>enum REGISTERS : unsigned\n{\n ACCUMULATOR,\n INSTRUCTION_COUNTER ,\n TEMPORARY_COUNTER,\n INSTRUCTION_REGISTER,\n OPERATION_CODE,\n OPERAND\n};\n</code></pre>\n<hr />\n<h2>Use a loop</h2>\n<pre class=\"lang-cpp prettyprint-override\"><code> registers[ACCUMULATOR] = 0;\n registers[INSTRUCTION_COUNTER] = 0;\n registers[TEMPORARY_COUNTER] = 0;\n registers[INSTRUCTION_REGISTER] = 0;\n registers[OPERATION_CODE] = 0;\n registers[OPERAND] = 0;\n</code></pre>\n<p>Take advantage of the fact that these are all numbered from 1 to 5.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> for (int i = ACCUMULATOR; i <= OPERAND; i++)\n registers[i] = 0;\n</code></pre>\n<hr />\n<h1>Comparing <code>size_t</code> and <code>int32_t</code></h1>\n<p><code>int32_t</code> has a fixed width of 32. <br>\n<code>size_t</code> is either 32 / 64 bits, depending on the platform.<br>\nComparing both of them freely can <em><strong>sometimes</strong></em> <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"noreferrer\">be dangerous</a>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>s.memory[opr] = s.temp_str.size();\n in32_t = size_t\n</code></pre>\n<p>If <code>size_t</code> (although highly unlikely, possible ) exceeds the max size of <code>int32_t</code>, overflow! What I like to do is to keep a custom macro like <code>_DEBUG_</code>, and then use <code>#ifdef</code> to check for this.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifdef _DEBUG_\nif ( s.temp_str.size() > INT32_MAX ) // handle it here\n\n#endif // _DEBUG_\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T08:10:27.577",
"Id": "496289",
"Score": "4",
"body": "You may have swapped one bug for another with the `size_t` debug code at the end of this answer - unless you can somehow prove that `SIZE_MAX >= INT32_MAX`. 16-bit machines may be rare in your world, but they do still exist..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T08:41:16.627",
"Id": "496294",
"Score": "1",
"body": "@TobySpeight Can you explain further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T10:14:48.863",
"Id": "496301",
"Score": "3",
"body": "If `int32` is wider than `size@t` then `s.temp_str.size() > INT32_MAX` can never be true. Actually, that's not really a problem is it? Just a compiler warning, that can be suppressed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T10:22:05.390",
"Id": "496303",
"Score": "1",
"body": "@TobySpeight Could this be solved by using another `#ifdef`? To check for the platform"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:34:05.633",
"Id": "496308",
"Score": "2",
"body": "Instead of writing `#ifdef _DEBUG_ if (fault_condition) ... #endif`, write [`assert(!fault_condition)`](https://en.cppreference.com/w/cpp/error/assert). It is meant exactly for this kind of debug build testing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:41:57.500",
"Id": "496311",
"Score": "1",
"body": "@G.Sliepen That's true, but you might not always terminate the program right? Maybe print a custom warning, throw an exception etc..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:10:56.023",
"Id": "496320",
"Score": "3",
"body": "@AryanParekh You are right, but I would avoid making the behaviour of the program change depending on whether it is a debug or release build. And if you are debugging the program, having it abort due to an assertion failure is a nice way of getting a coredump and allowing actual debugging to take place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:02:08.570",
"Id": "496400",
"Score": "2",
"body": "On that enum, I'd add a value called \"LAST_VALUE\" at the end, and then in the loop, just loop on `i < LAST_VALUE` (note *not* `<=`). That way if you add more enum values you don't have to find every place where you loop through them and change them all."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T07:55:43.480",
"Id": "251989",
"ParentId": "251978",
"Score": "11"
}
},
{
"body": "<h2>Overall Observations</h2>\n<p>I do see some serious improvement here over the first question. Did you find it any easier to write this second version?</p>\n<p>The program isn't exactly user friendly, when it is executing the SML program it doesn't prompt the user for input on <code>read</code> statements.</p>\n<p>You're working on your object oriented programming in C++ and this is a good thing!</p>\n<p>There seems to be rather strong dependencies between the 2 classes this is known as <a href=\"https://stackoverflow.com/questions/2832017/what-is-the-difference-between-loose-coupling-and-tight-coupling-in-the-object-o\">tight coupling</a> and generally indicates there is a problem with the design of the objects. I haven't used <code>friend</code> in at least 27 years except for defining the <code><<</code> operator in classes that need specialized output. The responsibilities of the classes need to be segmented better.</p>\n<p>I this point I think it would be helpful if you learned the 5 SOLID programming principles. <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"noreferrer\">SOLID</a> is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better.</p>\n<ol>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class. This particular principle can be applied to functional programming as well.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"noreferrer\">Open–closed Principle</a> - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"noreferrer\">Liskov Substitution Principle</a> - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"noreferrer\">Interface segregation principle</a> - states that no client should be forced to depend on methods it does not use.</li>\n<li>The <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"noreferrer\">Dependency Inversion Principle</a> - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.</li>\n</ol>\n<p>Possible there could be a third class that represents the processor. You could also create an enum that is shared by both SML and Evaluator for the indexes into <code>instruction_set</code>.</p>\n<h2>Complexity of <code>void SML::memory_dump() const</code></h2>\n<p>Looking at <code>void SML::memory_dump() const</code> I actually see 2 separate functions if the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> is applied</p>\n<ol>\n<li>dump_registers()</li>\n<li>dump_memory()</li>\n</ol>\n<p>The outer function that contains both function could be <code>dump_current_program_state()</code>.</p>\n<pre><code>void SML::dump_current_program_state() const\n{\n dump_registers();\n memory_dump();\n}\n\nvoid SML::dump_registers() const\n{\n std::cout << "\\nREGISTERS:\\n";\n\n std::cout << std::setw(25) << std::left << std::setfill(' ') << "accumulator" << std::showpos\n << std::setw(5) << std::setfill('0') << std::internal << registers[0] << '\\n';\n\n std::cout << std::setw(28) << std::left << std::setfill(' ')\n << "instruction counter" << std::noshowpos << std::setfill('0')\n << std::right << std::setw(2) << registers[1] << '\\n';\n\n std::cout << std::setw(25) << std::left << std::setfill(' ')\n << "instruction register" << std::showpos << std::setw(5) << std::setfill('0')\n << std::internal << registers[3] << '\\n';\n\n std::cout << std::setw(28) << std::left << std::setfill(' ')\n << "operation code" << std::noshowpos << std::setfill('0')\n << std::right << std::setw(2) << registers[4] << '\\n';\n\n std::cout << std::setw(28) << std::left << std::setfill(' ')\n << "operand" << std::noshowpos << std::setfill('0')\n << std::right << std::setw(2) << registers[5] << '\\n';\n}\n\nvoid SML::memory_dump() const\n{\n std::cout << "\\n\\nMEMORY:\\n";\n std::cout << " ";\n\n for (int i = 0; i != 10; ++i)\n std::cout << std::setw(6) << std::setfill(' ') << std::right << i;\n for (size_word i = 0; i != memory_size; ++i)\n {\n if (i % 10 == 0)\n std::cout << "\\n" << std::setw(3) << std::setfill(' ') << i << " ";\n std::cout << std::setw(5) << std::setfill('0') << std::showpos << std::internal << memory[i] << " ";\n }\n std::cout << std::endl;\n}\n</code></pre>\n<h2>Magic Numbers</h2>\n<p>You have done a good job of preventing magic numbers in sml.h, however, there are Magic Numbers in the <code>main()</code> function (1000, -999999, 999999) as well as in <code>SML::memory_dump()</code> (25, 5, 28, 10), it might be better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>In <code>main()</code> you can create <code>constexpr memory_size = 1000;</code> for the first value, I'm not sure what the -999999 and 9999999 values should be called.</p>\n<h2>Registers Uninitialized</h2>\n<p>In the following constructor I don't see where the registers get initialized:</p>\n<pre><code>SML::SML(SML&& s)\n{\n swap(*this, s);\n memory = new size_word[memory_size];\n std::move(s.memory, s.memory + s.memory_size, memory);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T16:35:37.907",
"Id": "496373",
"Score": "1",
"body": "`In the following constructor I don't see where the registers get initialized:` check `swap` method, I initialized it there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T20:09:34.260",
"Id": "496387",
"Score": "2",
"body": "Are you suggesting that a `read` instruction should print a prompt on its own? The simulated machine has a `write` instruction. If a program wants to prompt the user, it should do so itself, using the available instructions, just like asm for mainstream OSes. For similar reasons why ISO C `scanf` just reads. (Although to be fair, this is clearly a toy machine, and over-simplified syscall interfaces are the norm, like in MARS, the MIPS simulator: http://courses.missouristate.edu/KenVollmar/Mars/Help/SyscallHelp.html - no facilities for controlling the terminal (no echo), or cursor movement)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:23:36.333",
"Id": "496403",
"Score": "1",
"body": "@PeterCordes I was suggesting that. The first time I ran the program with the example input it took me a while to figure out why I wasn't getting any output after the the SML started processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:57:21.983",
"Id": "496715",
"Score": "1",
"body": "@pacmaninbw: Ah, I hadn't looked at the example code from the question. That's the fault of a non-user-friendly example, *not* of the ISA / system-call interface design. (Unless the intended use-case is even more toy-like, with `read` forcing printing a prompt, so you don't get to choose to e.g. input 3 numbers without separate prompts. That would be a valid option; not the one MARS made, but worth considering.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:21:47.307",
"Id": "252008",
"ParentId": "251978",
"Score": "7"
}
},
{
"body": "<h3>Use <code>enum class</code> instead of enum</h3>\n<p>It's a good habit to make the enum a <code>enum class</code>. I can't tell you how many times I've needed to untangle two or more state-machines that used similarly or identically named states that conflicted in value. This will prevent you from passing unchecked values as registers.</p>\n<h3>Use standard containers</h3>\n<p>Your <code>memory</code> variable could be a <code>std::vector</code> - reserve the size during the ctor, and then when the sml object is destroyed, it's automatically cleaned up.</p>\n<p>Likewise, you could use <code>std::array</code> or one of the maps for the <code>registers</code>. <code>std::array</code> can be made constexpr, so if you compile with <code>c++2a</code>/<code>c++20</code>, you could potentially verify your entire program at compilation instead of at run time.</p>\n<p>Both of these should make the copy and move operators a bit easier to tame. As well</p>\n<h3>Use Standard Algorithms</h3>\n<p>Particularly in the <code>Evaluator</code> you could get practiced with standard algorithms. This isn't necessarily a speedup, but it's good practice.</p>\n<pre><code>void Evaluator::write_str( SML &s, const int opr )\n{\n for( int i = 0; i != s.memory[ opr ] + 1; ++i )\n std::cout << char( s.memory[ opr + i ]);\n}\n\nvoid Evaluator::write_str(SML &s, const Operand o){\n auto out_itr = std::ostream_iterator<char>(std::cout, "");\n std::copy(s.memory.cbegin(), std::next(s.memory.cbegin() to_underlying(O)), out_itr);\n}\n\n</code></pre>\n<p>An extra benefit of continued use of the algorithms is consistency, and conveying intent. If you're <code>finding</code> something, use <code>find</code> or <code>find_if</code> if you doing something <code>for each</code> item, like printing out, you could use <code>for_each</code>. You can also rebuild the standard algorithms, they're pretty entry level template functions, that are pretty easy to dip your toes.</p>\n<p><a href=\"https://stackoverflow.com/a/33083231/8881651\">Defined elsewhere - to convert <code>enum class</code> to int</a></p>\n<pre><code>#include <type_traits>\n\ntemplate <typename E>\nconstexpr auto to_underlying(E e) noexcept\n{\n return static_cast<std::underlying_type_t<E>>(e);\n}\n</code></pre>\n<h3>Add a <code>std::ostream</code> member, and pipe through that instead of <code>std::cout</code></h3>\n<p>This is a little nicety which goes a long way. By adding <code>std::ostream</code> member to your classes, and then constructing to default to <code>std::cout</code>, you can then output to whatever you want! Got a file you want to pipe to? Great. How about a stream that can be unit tested? Sure. Once you do this, then you can add auto-building and testing, saving you time from needing to manually check if that little change you made actually broke everything.</p>\n<h3>Use unique_ptr</h3>\n<p>Bonus edit: since I remembered about this - if you don't want to use the standard containers, then you should really manage your data (registers and memory) with unique_ptrs. <code>new</code> and <code>delete</code> are often treated as code smells, and with good reason. It's really easy to try to <code>double-free</code> or forget to <code>delete</code> and <strong>leak memory</strong>, both of these are very bad.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T17:29:14.057",
"Id": "496376",
"Score": "2",
"body": "You could [`std::cout.write()`](//en.cppreference.com/w/cpp/io/basic_ostream/write)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T17:31:46.220",
"Id": "496377",
"Score": "1",
"body": "Great review. I would add that, I want to make minimal use of the Standard algorithm as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T20:13:03.620",
"Id": "496388",
"Score": "1",
"body": "Why would you want a hash table or tree for the register file? How is that better than a `std::array` or `std::vector` with enum indices? The current design (with `static_cast<unsigned>` on every enum) is bad, but there's no need to over-complicate it with fancy data structures when you know register-numbers have a small contiguous range starting at 0. Just simple containers like vector or array for registers should be good, like you wisely suggests for memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T20:59:41.777",
"Id": "496399",
"Score": "0",
"body": "@Peter Cordes. `The current design (with static_cast<unsigned> on every enum) is bad` can you throw more light."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:08:05.677",
"Id": "496401",
"Score": "3",
"body": "@theProgrammer: [@Aryan's answer](https://codereview.stackexchange.com/a/251989/50567) already showed how to simplify the enum to avoid casting every time you use it. The values are signed-positive anyway so casting seems pointless. The overall design isn't actually bad, just the detail of cluttering up your source code with casts. An array is actually good for the register file IMO, although a standard container like `std::array` could be useful as this answer points out (along with the bad IMO suggestion of `std::unordered_map`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T22:16:19.970",
"Id": "496408",
"Score": "2",
"body": "@PeterCordes `std::array` is probably the ideal container."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T06:42:31.087",
"Id": "496432",
"Score": "0",
"body": "Although I agree with the name clashing point, I feel enum classes would be very difficult here since you'd have to continuously cast everytime you want to use it has an as an integral value ( which is a lot over here ). Wrapping it up in a namespace sounds like a good idea otherwise"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T09:31:40.683",
"Id": "496446",
"Score": "0",
"body": "@AryanParekh I just pulled in the original source files, using `enum class` and the `to_underlying` into Godbolt; and it takes no more effort than the current `static_casts` which are already in place. If that seems like too much developer overhead, then creating an accessor function which wraps the register access is still an option. (alternatively, `std::(unordered_)map` would prevent out of bounds access)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T22:17:51.740",
"Id": "496717",
"Score": "0",
"body": "Just like you wouldn't use a [CAM](https://en.wikipedia.org/wiki/Content-addressable_memory) for your register file in a hardware design, a hash table would be insane for software. If you just want bounds checking, overload `std::operator[]` of `std::array` to do that always (not just in debug builds on some implementations). e.g. [How to implement bound checking for std::array?](https://stackoverflow.com/q/49419089). Throwing `std::unordered_map` at it just for that reason seems like poor engineering, especially since register fetch is involved in decoding nearly every instruction."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T17:21:32.127",
"Id": "252011",
"ParentId": "251978",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "251989",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T22:57:41.780",
"Id": "251978",
"Score": "9",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Machine Language Simulator"
}
|
251978
|
<p>Hello I have the following code, where I need to do many checks of calls from the database,</p>
<p><strong>My TypeEnum:</strong></p>
<pre><code>export enum ProductTypes {
equipament = 'equipament',
component = 'component',
}
</code></pre>
<p><strong>this is my use case class:</strong></p>
<pre><code>export class AssignProductUseCase
implements
IUseCase<AssignProductDTO, Promise<Either<AppError, ProductInstance>>> {
constructor(
@inject(EmployeeRepository)
private employeeRepository: IEmployeeRepository,
@inject(ProductRepository)
private productRepository: IProductRepository,
@inject(ProductInstanceRepository)
private instanceRepository: IProductInstanceRepository,
@inject(ProductStocksRepository)
private stockRepository: IProductStocksRepository,
) {}
public execute = async ({
contract_id,
matricula,
parent_id,
patrimony_code,
product_id,
serial_number,
type,
}: AssignProductDTO): Promise<Either<AppError, ProductInstance>> => {
//verify type
if (!(type in ProductTypes)) throw new Error(`${type}, is invalid`);
//instance checks
const hasInstance = await this.instanceRepository.bySN(serial_number);
if (hasInstance) {
throw new Error(
`This ${serial_number} product has already been assigned `,
);
}
const parentInstance = parent_id
? await this.instanceRepository.byId(parent_id)
: null;
if (parentInstance === undefined) {
throw new Error(`Parent Instance dont exist.`);
}
//products checks
const hasProduct = await this.productRepository.byId(product_id);
if (!hasProduct) throw new Error(`This product dont exist.`);
//employee checks
const hasEmployee = await this.employeeRepository.byMatricula(matricula);
if (!hasEmployee) throw new Error(`This Employee dont exist.`);
const employeeHasProduct = await this.instanceRepository.hasInstance(
product_id,
hasEmployee.id,
);
if (employeeHasProduct) {
throw new Error(
`The enrollment employee: ${matricula} already has an instance of the product.`,
);
}
//stock checks
const stock = await this.stockRepository.byContractAndProduct(
contract_id,
product_id,
);
if (!stock) {
throw new Error(
`The product has no stock, or the contract has no supply.`,
);
}
if (stock.quantity <= 1) {
throw new Error(`The stock of this product is less than or equal to 1`);
}
//create instance
const instance = await this.instanceRepository.create(ProductInstance.build(request))
return right(instance)
};
}
</code></pre>
<p>and with respect to repository calls are small methods using mikro orm:
Here is a repository as an example:</p>
<pre><code>export class ProductInstanceRepository implements IProductInstanceRepository {
private em: EntityManager;
constructor(@inject('bootstrap') bootstrap: IBootstrap) {
this.em = bootstrap.getDatabaseORM().getConnection().em.fork();
}
public byArray = async (ids: string[]): Promise<ProductInstance[]> => {
return await this.em.find(ProductInstance, { serial_number: ids }, [
'stock',
]);
};
public create = async (
instance: ProductInstance,
): Promise<ProductInstance> => {
if (!(instance instanceof ProductInstance))
throw new Error(`Invalid Data Type`);
await this.em.persist(instance).flush();
return instance;
};
public update = async (
serial_number: string,
data: any,
): Promise<ProductInstance> => {
const instance = await this.em.findOne(ProductInstance, { serial_number });
if (!instance) throw new Error(`${data.matricula} dont exists`);
wrap(instance).assign(data);
await this.em.persist(data).flush();
return instance;
};
public all = async (pagination: Pagination): Promise<ProductInstance[]> => {
return await this.em.find(ProductInstance, {});
};
public byId = async (
serial_number: string,
): Promise<ProductInstance | undefined> => {
const instance = await this.em.findOne(ProductInstance, { serial_number });
if (!instance) return;
return instance;
};
public bySN = async (
serial_number: string,
): Promise<ProductInstance | undefined> => {
const instance = await this.em.findOne(ProductInstance, { serial_number });
if (!instance) return;
return instance;
};
public hasInstance = async (
product_id: string,
employee_id: string,
): Promise<boolean> => {
const parent = await this.em.findOne(ProductInstance, {
product: { id: product_id },
employee: { id: employee_id },
});
if (!parent) return false;
return true;
};
}
</code></pre>
<p>But this became a very ugly code, but I'm not getting a solution on how to refactor so much if, because they are essential checks for the logic. I would be very grateful if someone could give me tips on how I can refactor this in a cleaner way.</p>
<p>My logic:</p>
<p>I need to make sure that my type parameter is contained in my enum,</p>
<p>I need to check that there is already an instance of the product in the db,</p>
<p>I need to check if my instance has a parent_id parameter and if that product instance exists, if it is null there is no need for verification,</p>
<p>need to check the existence of the product and stock</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:14:41.287",
"Id": "496241",
"Score": "0",
"body": "@CertainPerformance I edited using the complete code, the codes of my repositories are very similar"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:19:05.427",
"Id": "496244",
"Score": "0",
"body": "Ah yes I understand, this part of the code I haven't finished yet, but it's basically a call to my repository\n\nlike this:\n\nconst productInstance = await this.instanceRepository.create (ProductInstance.build (request))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:22:49.493",
"Id": "496246",
"Score": "0",
"body": "I edited with the end of the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T00:21:23.297",
"Id": "496254",
"Score": "0",
"body": "@CertainPerformance can u help me bro ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T00:24:03.973",
"Id": "496255",
"Score": "0",
"body": "Yep, I'm working on it, it's a bit complicated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T00:30:19.687",
"Id": "496256",
"Score": "0",
"body": "omg thanks a lot <3, I didn’t know what to do, I just thought of isolating with functions, but I’d still continue with countless ifs"
}
] |
[
{
"body": "<p>While your code is somewhat verbose, it's not <em>that</em> bad. If you were to keep going with your current approach I think it'd be OK.</p>\n<p>That said, the main improvement that can be observed here is that for every check, you're carrying out an asynchronous request, then throwing if the result fails a test. You can make an array of objects, with each object containing:</p>\n<ul>\n<li>A function which, when called, returns the Promise</li>\n<li>A function that checks if the result passes or fails the test</li>\n<li>An error message to throw if the test was failed</li>\n</ul>\n<p>Then iterate over the array of objects:</p>\n<pre><code>const validators = [\n {\n fn: () => this.instanceRepository.bySN(serial_number),\n errorIf: (hasInstance: boolean) => hasInstance,\n errorMessage: `This ${serial_number} product has already been assigned `\n },\n {\n fn: () => parent_id ? this.instanceRepository.byId(parent_id) : Promise.resolve(null),\n errorIf: (parentInstance: unknown) => parentInstance === undefined),\n errorMessage: 'Parent Instance dont exist.',\n },\n // ...\n];\nfor (const { fn, errorIf, errorMessage } of validators) {\n const result = await fn();\n if (errorIf(result)) {\n throw new Error(errorMessage);\n }\n}\n</code></pre>\n<p>There's some boilerplate, but it looks a <em>lot</em> cleaner, and the validations being performed are easier to understand at a glance.</p>\n<p>One complication is that there is one variable which needs <em>two</em> checks: <code>stock</code>, with separate error messages, and you don't want to make two duplicate requests for the same thing. There are a couple tricky things you could do (like assign to an outside variable in the <code>fn</code>), or make a <code>getErrorMessage</code> property on a validator as well:</p>\n<pre><code>const validateStock = (stock) => {\n if (!stock) {\n return `The product has no stock, or the contract has no supply.`;\n }\n return stock.quantity <= 1\n ? 'The stock of this product is less than or equal to 1'\n : ''\n};\nconst validators = [\n {\n fn: () => this.stockRepository.byContractAndProduct(contract_id, product_id),\n errorIf: () => true,\n getErrorMessage: validateStock,\n },\n // ...\n];\nfor (const { fn, errorIf, getErrorMessage } of validators) {\n const result = await fn();\n if (errorIf(result)) {\n const errorMessage = getErrorMessage(result);\n if (errorMessage) {\n throw new Error(errorMessage);\n }\n }\n}\n</code></pre>\n<p>But I think that's over-engineered - I think I'd prefer the original <code>validators</code> array, with everything in it that's possible given its structure, and then have two separate checks outside for validating the <code>stock</code> variable.</p>\n<hr />\n<p>Other potential improvements:</p>\n<p><strong><code>Promise.all</code>?</strong> Your current code waits for each request to finish before making the next one. Unless you <em>have</em> to wait in serial like this, consider making the requests in parallel instead - parallel requests will finish more quickly.</p>\n<p><strong>Require certain parameter types instead of checking and throwing</strong> One of the main selling points of TypeScript is turning hard runtime errors into easy compile-time errors. Instead of:</p>\n<pre><code>if (!(type in ProductTypes)) throw new Error(`${type}, is invalid`);\n</code></pre>\n<p>If the <code>type</code> isn't completely dynamic, consider instead requiring an argument whose type is ProductTypes. Change:</p>\n<pre><code>} :AssignProductDTO\n</code></pre>\n<p>to</p>\n<pre><code>} :AssignProductDTO & { type: ProductTypes }\n</code></pre>\n<p>This will mean that calling the function with <code>{ type: 'NotARealType' }</code> will fail TypeScript's type-checking, but will permit <code>{ type: 'equipament' }</code>. Which leads to the next point:</p>\n<p><strong>Spelling and grammar</strong> Spelling words properly prevents bugs, makes code look more professional, and improves the user's experience. Change:</p>\n<ul>\n<li><code>equipament</code> to <code>equipment</code></li>\n<li><code>Parent Instance dont exist</code> to <code>Parent Instance doesn't exist.</code></li>\n<li><code>This product dont exist</code> to <code>This product doesn't exist.</code></li>\n</ul>\n<p><strong>Unused variable</strong> You never use the destructured <code>patrimony_code</code> variable, so feel free to remove it from the parameter list.</p>\n<p><strong>Allow TS to infer types automatically</strong> when possible - it cuts down on boilerplate, typos, and other mistakes. If <code>right(instance)</code> is typed properly, the whole <code>execute</code> method should not need to note a return type; TypeScript will automatically infer it; you should be able to remove <code>Promise<Either<AppError, ProductInstance>></code>.</p>\n<p>Remember that TypeScript doesn't track rejected Promise types - if <code>AppError</code> is a type you're using to indicate <code>Error</code>s that may be thrown by your checks inside, it shouldn't be part of the type definition.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T10:13:33.117",
"Id": "496300",
"Score": "0",
"body": "is there a possibility of using the validator as a global form?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:48:57.373",
"Id": "496357",
"Score": "0",
"body": "Sure, but the values it uses would need to be in scope for that to work. If you wanted it to be available outside this function, you could make a function that, given a`AssignProductDTO` parameter, returns the array of validators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T18:07:34.357",
"Id": "496379",
"Score": "0",
"body": "could you show me how it would look?\n\nI didn't really understand that part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T18:11:09.133",
"Id": "496380",
"Score": "0",
"body": "I was going to say something like `const getValidators = ({ contract_id, matricula, }: AssignProductDTO) => [{ fn:` but I just realized that you reference instance methods inside, so you don't really have access to an instance that the validators can be called on. I guess you can pass an instance as another parameter: `const getValidators = ({ contract_id, matricula, }: AssignProductDTO, instance: AssignProductUseCase) => [{ fn: () => instance.instanceRepository.bySN(serial_number),` etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:09:39.160",
"Id": "496418",
"Score": "0",
"body": "do you believe that applying the command pattern would not be a good option?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:33:37.290",
"Id": "496425",
"Score": "0",
"body": "You could if you like that sort of thing, but I personally don't like it so much, I think it'd require too much boilerplate and would be too dynamic."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T01:08:09.773",
"Id": "251982",
"ParentId": "251979",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251982",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:00:05.733",
"Id": "251979",
"Score": "2",
"Tags": [
"typescript"
],
"Title": "typescript : clean code remove or decrease alot if's"
}
|
251979
|
<h1>Introduction</h1>
<p>I'm working with Java 1.8. There is a lot of repetition in the <code>MessageHandler</code> class that I would like to remove but I'm having trouble implementing a fix.</p>
<h3>External Code</h3>
<p>I'm working with a message library that I should avoid changing. This library consists of these files:</p>
<p><code>BaseMessage.java</code></p>
<pre><code>package external;
public abstract class BaseMessage {
public void accept(MessageVisitor visitor) {
visitor.visit(this);
}
}
</code></pre>
<p><code>AMessage.java</code></p>
<pre><code>package external;
public class AMessage extends BaseMessage {
}
</code></pre>
<p><code>BMessage.java</code></p>
<pre><code>package external;
public class BMessage extends BaseMessage {
}
</code></pre>
<p><code>MessageVisitor.java</code></p>
<pre><code>package external;
public interface MessageVisitor extends SendVisitor {
default void visit(BaseMessage msg) {
this.defaultAction(msg);
}
}
</code></pre>
<p><code>SendVisitor.java</code></p>
<pre><code>package external;
public interface SendVisitor {
void defaultAction(BaseMessage var1);
default void visit(AMessage msg) {
this.defaultAction(msg);
}
default void visit(BMessage msg) {
this.defaultAction(msg);
}
}
</code></pre>
<h3>Internal Code</h3>
<p><code>Entrypoint.java</code></p>
<pre><code>package example;
import external.AMessage;
import external.BMessage;
import external.BaseMessage;
class Entrypoint {
MessageHandler handler;
Entrypoint(MessageHandler handler) {
this.handler = handler;
}
void handleMessage(BaseMessage message) {
if(handler != null && handler.supports(message.getClass())) {
if (handler.hasSeenBefore(message)) {
// Log that we are skipping handling
return;
} else {
handler.receive(message);
}
}
// and do more unrelated things...
}
public static void main(String[] args) {
Entrypoint entrypoint = new Entrypoint(new MessageHandler());
entrypoint.handleMessage(new AMessage());
entrypoint.handleMessage(new BMessage());
}
}
</code></pre>
<p><code>MessageHandler.java</code></p>
<pre><code>package example;
import external.AMessage;
import external.BMessage;
import external.BaseMessage;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MessageHandler {
private static Set<Class<? extends BaseMessage>> SUPPORTED_MESSAGE_TYPES = new HashSet<>(
Arrays.asList(AMessage.class, BMessage.class));
public boolean supports(Class<? extends BaseMessage> messageType) {
// this sucks
return SUPPORTED_MESSAGE_TYPES.contains(messageType);
}
private boolean hasSeenBefore(AMessage message) {
System.out.println("Checking if I've seen an AMessage");
// more complicated in the actual code
return true;
}
private boolean hasSeenBefore(BMessage message) {
System.out.println("Checking if I've seen a BMessage");
// more complicated in the actual code
return false;
}
public boolean hasSeenBefore(BaseMessage message) {
// TODO: make better
if (message instanceof AMessage) {
return hasSeenBefore((AMessage) message);
} else if (message instanceof BMessage) {
return hasSeenBefore((BMessage) message);
} else {
throw new UnsupportedOperationException("Tried to handle a message that is currently not supported: "
+ message.toString());
}
}
private void receive(AMessage message) {
// do AMessage things
System.out.println("Received an AMessage");
}
private void receive(BMessage message) {
// do BMessage things
System.out.println("Received a BMessage");
}
public void receive(BaseMessage message) {
// TODO: make better
if (message instanceof AMessage) {
receive((AMessage) message);
} else if (message instanceof BMessage) {
receive((BMessage) message);
} else {
throw new UnsupportedOperationException("Tried to handle a message that is currently not supported: "
+ message.toString());
}
}
}
</code></pre>
<h3>Question</h3>
<p>As you can see, it's a pain to maintain the <code>MessageHandler</code>; specifically, the <code>hasSeenBefore</code> method has an <code>instanceof</code> that must be added to when another message is added, and a similar thing happens in the <code>receive</code> method. It is also really bad that the <code>supports</code> function keeps a separate list of those message types that must be updated when a new message type is added.</p>
<p>My hunch says that the Visitor pattern should be applied here more, but I'm having trouble implementing that.</p>
<ul>
<li>How can I remove all this duplicated logic so that I could add new message types to the MessageHandler cleanly?</li>
<li>And how can <code>supports</code> check whether the message type is handled without maintaining a separate list?</li>
<li>Is there anything else in the internal code which is not following best practices?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T00:43:39.017",
"Id": "496258",
"Score": "0",
"body": "Can you post the complete code of MessageHandler and messages? It's not clear why you are casting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T01:25:18.803",
"Id": "496261",
"Score": "0",
"body": "Messages are casted into their subtypes so that they can be sent off to the subtype-specific handler methods. The messages contain some different fields which are checked in those subtype-specific handler methods. I think that posting the message contents would bloat this question up with details unrelated to my question, they are extremely big actually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T01:33:17.847",
"Id": "496262",
"Score": "0",
"body": "I should also mention that I am not authorized to release the full source code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T04:39:30.803",
"Id": "496274",
"Score": "2",
"body": "@karobar Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T09:48:58.953",
"Id": "496298",
"Score": "3",
"body": "This is a bit borderline. I understand how this code is used and what the problem in question is and know a suitable answer. I don't think removing unrelated bits turns it into stub, obfuscated or hypothetical code. Making the requirements excessively limiting devalues this site as it will then become only a source for reviewing homework and interview question as practically no production code can be posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:46:56.707",
"Id": "496312",
"Score": "0",
"body": "@AryanParekh There are times when the complete code can't be posted for legal reasons. In this case there was enough code for a good answer. Keep in mind the rules are that the OP can only post code they have written."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:02:47.957",
"Id": "496317",
"Score": "0",
"body": "@pacmaninbw Alright!, I felt that this question lacked the necessary details for a review."
}
] |
[
{
"body": "<p>The main problem I see is that <code>MessageHandler</code> is solely responsible for knowing all the different message types and how they should be handled. If I was implemeting this I would create a separate MessageHandler subtype for each different message type and each subtype would only know about the existence of the specific message it handles. This reduces the dependencies each message handler has and thus makes testing and maintenance much easier. The main guide line here is the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a></p>\n<p>To handle the selection of a correct MessageHandler in the <code>EntryPoint</code> class I would implement a <code>MessageHandlerRegistry</code> from which the EntryPoint can retrieve the correct handler for a message type by class. Essentially it is a simple facade for <code>Map<Class<? extends BaseMessage>, MessageHandler></code>. To handle the case of unknown message type I would make the registry return a default handler which simply logs the error and throws an exception. That way the registry never has to return null values.</p>\n<p>Populate the MessageHandlerRegistry in your bootstrap code and pass the reference to the EntryPoint class. The EntryPoint contains unnecessary null-checks. It seems obvious that the class can not function properly if it does not have a MessageHandler (or MessageHandlerRegistry in my version) so you should put the null check in the constructor and simply prevent the initialization of the EntryPoint if it's state is invalid. Make the field final so you know it will not be changed to null accidentally.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:26:42.730",
"Id": "496366",
"Score": "0",
"body": "Hey thanks, this is very helpful! After retrieving a correct MessageHandler, would you send a BaseMessage to it and then cast inside of that MessageHandler, or is there some way to get a correctly-subtyped message to that handler. In other words, `registry.get(message.getClass()).receive(???)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T20:47:41.340",
"Id": "496396",
"Score": "1",
"body": "For some of the trickier bits I was able to get an implementation which satisfied me with the aid of Joshua Bloch's example of typesafe heterogeneous containers from Effective Java, modified with assistance from this answer: https://stackoverflow.com/questions/6541656/type-safe-heterogeneous-container-pattern-to-store-lists-of-items"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T10:00:22.787",
"Id": "251994",
"ParentId": "251981",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251994",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T23:54:04.937",
"Id": "251981",
"Score": "5",
"Tags": [
"java",
"design-patterns"
],
"Title": "MessageHandler handles different message subtypes differently (can visitor pattern be applied?)"
}
|
251981
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a> and <a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Besides the summation result, I am trying to get the element count in arbitrary nested iterable things. For example, there are three elements in <code>std::vector<int> test_vector = { 1, 2, 3 };</code>, so the element count of <code>test_vector</code> is <code>3</code>. The experimental implementation of <code>recursive_count</code> is as below.</p>
<pre><code>size_t recursive_count()
{
return 0;
}
template<class T> requires (!is_elements_iterable<T> && !is_iterable<T>)
size_t recursive_count(const T& input)
{
return 1;
}
template<class T> requires (!is_elements_iterable<T> && is_iterable<T>)
size_t recursive_count(const T& input)
{
return input.size();
}
template<class T> requires (is_elements_iterable<T> && is_iterable<T>)
size_t recursive_count(const T& input)
{
size_t output{};
for (auto &element : input)
{
output += recursive_count(element);
}
return output;
}
</code></pre>
<p>Some test cases of this <code>recursive_count</code> template function.</p>
<pre><code>// std::vector<int> case
std::vector<int> test_vector = {
1, 2, 3
};
auto recursive_count_result1 = recursive_count(test_vector);
std::cout << recursive_count_result1 << std::endl;
// std::vector<std::vector<int>> case
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
auto recursive_count_result2 = recursive_count(test_vector2);
std::cout << recursive_count_result2 << std::endl;
// std::deque<int> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_count_result3 = recursive_count(test_deque);
std::cout << recursive_count_result3 << std::endl;
// std::deque<std::deque<int>> case
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_count_result4 = recursive_count(test_deque2);
std::cout << recursive_count_result4 << std::endl;
</code></pre>
<p><a href="https://godbolt.org/z/bWPer6" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous questions are focused on summation operation, and I am trying to implement a <code>recursive_count</code> template function here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>In my opinion, I am not sure the name of this function is good or not. I know there is a function <code>std::count</code> in STL which purpose is to count the elements that are equal to given specific value. If there is any better naming suggestion, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>No need for an overload that takes no parameters</h1>\n<p>Nothing calls <code>recursive_count()</code> without parameters, so that overload is unnecessary.</p>\n<h1>Unnecessary requirements</h1>\n<p>You don't need to require both <code>is_elements_iterable<T></code> and <code>is_iterable<T></code>, the former will already cover the requirements of the latter, and if you negate them then the latter covers the former. So the overloads should be:</p>\n<pre><code>template<class T> requires !is_iterable<T>\nsize_t recursive_count(const T& input)\n{\n return 1;\n}\n\ntemplate<class T> requires (!is_elements_iterable<T> && is_iterable<T>)\nsize_t recursive_count(const T& input)\n{\n return input.size();\n}\n\ntemplate<class T> requires is_elements_iterable<T>\nsize_t recursive_count(const T& input)\n{\n size_t output{};\n for (auto &element : input)\n {\n output += recursive_count(element);\n }\n return output;\n}\n</code></pre>\n<h1>Naming</h1>\n<p>Indeed you already noticed that STL has a <code>std::count</code> that does something different. However there is a function that does what you want for non-nested containers: <code>std::size</code>. So consider naming your function <code>std::recursive_size</code>.</p>\n<h1>Consider making more use of STL algorithms</h1>\n<p>You are implementing your own algorithms but you are not making use of STL's algorithms. This can reduce the amount of code you write. For example, the last overload can be rewritten as:</p>\n<pre><code>template<class T> requires is_elements_iterable<T>\nsize_t recursive_count(const T& input)\n{\n return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto &element){\n return recursive_count(element);\n });\n}\n</code></pre>\n<p>Although I'm not sure this is more readable than your version.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T11:40:28.913",
"Id": "251997",
"ParentId": "251983",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251997",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T01:10:28.747",
"Id": "251983",
"Score": "4",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
251983
|
<p>I have a json string <code>ProcessValue</code> in which I need to extract a particular key (<code>client_id</code>) value and then I need to encode that value using <code>HttpUtility.HtmlEncode</code> and put it back in the same JSON string. <code>ProcessValue</code> is one of the header name which has a json value in it.</p>
<p>Below is my code which does that but I am deserializing twice looks like. Is there any way to improve below code?</p>
<pre><code>ProcessValue = GetHeader(headers, PROCESS_DATA); // LINE A
if (!string.IsNullOrWhiteSpace(ProcessValue))
{
dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(ProcessValue);
if (jsonObject.client_id != null)
{
var value = jsonObject.client_id;
jsonObject.client_id = HttpUtility.HtmlEncode(value);
var modifiedJsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObject);
ProcessValue = modifiedJsonString;
}
ProcCustomer = DeserializeJson<ProcCustomer>(ProcessValue);
}
private T DeserializeJson<T>(string str) where T : new()
{
try
{
return JsonSerializer.Deserialize<T>(str);
}
catch (Exception e)
{
return new T();
}
}
</code></pre>
<p>Here <code>ProcessValue</code> at <code>LINE A</code> is:</p>
<pre><code>{"key1":"value1","key2":"value2","key3":"value3","key4":"value4","key5":"value6","client_id":"Hänzendes"}
</code></pre>
<p>I am extracting <code>client_id</code> value and then encoding it and after that putting it back to same json. And then I am deserializing this modified json value to <code>ProcCustomer</code> POCO. <code>ProcCustomer</code> is the POCO class which holds all the fields value. So I am deserializing and serializing to get my updated json string <code>ProcessValue</code> and then I deserialize this json to <code>ProcCustomer</code> POCO class.</p>
<p>There are places where we use <code>ProcessValue</code> json string directly as it is one of the header value and using <code>ProcCustomer</code> POCO fields as well so that is why I was doing above things. I wanted to see if there is anything I can do to optimize my above code where I don't have to deserialize and then serialize and then again deserialize to put it in POCO?</p>
<p>Also I am mixing <code>Utf8Json</code> library with <code>Newton json</code> library. I prefer to use <code>Utf8 json</code> library for both serialization and deserialization in my above code.</p>
|
[] |
[
{
"body": "<p>Even if <code>ProcessValue</code> is used as string in other objects, why you don't just deserialize it once across the class, then use the POCO object directly. Then, serialize it whenever needed.</p>\n<p>So, in your question this would be valid :</p>\n<pre><code>ProcessValue = GetHeader(headers, PROCESS_DATA); // LINE A\n\nif (!string.IsNullOrWhiteSpace(ProcessValue))\n{\n ProcCustomer = DeserializeJson<ProcCustomer>(ProcessValue);\n\n if (ProcCustomer != null && !string.IsNullOrWhiteSpace(ProcCustomer.ClientId))\n {\n ProcCustomer.ClientId = HttpUtility.HtmlEncode(ProcCustomer.ClientId);\n }\n}\n</code></pre>\n<p>This way you only deserialized it once in this scope. Also, if the <code>client_id</code> is always needs to be encoded using <code>HttpUtility.HtmlEncode</code> you could modify the POCO and do this for instance :</p>\n<pre><code>public class ProcCustomer\n{\n //.. other properties \n \n [JsonProperty("client_id")]\n public string ClientId \n { \n get => ClientId;\n set\n {\n if(!string.IsNullOrEmpty(value))\n {\n ClientId = HttpUtility.HtmlEncode(value);\n }\n else \n {\n ClientId = value;\n }\n } \n } \n}\n</code></pre>\n<p>With this, your code will be shorter as you only need to deserialize, the rest will be updated according to the POCO logic!</p>\n<p><strong>Answering the comments :</strong></p>\n<p>working with <code>ProcessValue</code> as string, will make things difficult to handle. What I suggested is to use the deserialized object (which is the POCO in your case), then work with it like any object. When you want to pass it to the <code>HttpClient</code> header, just serialize it, to pass it as sting.</p>\n<p>The main idea is to work with objects, and not with the strings! use the strings only when required. This way you'll have a better coding experience.</p>\n<p>For example, we can modify the POCO and override the <code>ToString</code> method like this :</p>\n<pre><code>public class ProcCustomer\n{\n public override string ToString() {\n return Newtonsoft.Json.JsonConvert.SerializeObject(this);\n }\n}\n</code></pre>\n<p>Now, when we want to add it to the header we can do this (example) :</p>\n<pre><code>// assuming we've already updated the POCO values\n// and we need to add it to the HttpClient header \nusing (var client = new HttpClient{ BaseAddress = baseAddress })\n{\n client.DefaultRequestHeaders.Add("", ProcCustomer.ToString());\n \n using (var response = await client.GetAsync(Url))\n {\n var responseData = await response.Content.ReadAsStringAsync();\n }\n}\n</code></pre>\n<p>If you can't modify the POCO, then you can add extensions like this :</p>\n<pre><code>// implement the extensions \npublic class JsonExtensions\n{\n public T JsonDeserialize<T>(this string str) where T : class\n {\n try\n {\n return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);\n }\n catch (Exception e)\n {\n return default;\n }\n }\n \n public string JsonSerialize<T>(this T obj) where T : class\n {\n try\n {\n return Newtonsoft.Json.JsonConvert.SerializeObject<T>(obj);\n }\n catch (Exception e)\n {\n return null;\n }\n }\n}\n</code></pre>\n<p>You can use the extensions instead of <code>ToString</code> approach</p>\n<pre><code>// EXAMPLE : \n\nProcessValue = GetHeader(headers, PROCESS_DATA); // LINE A\n\nif (!string.IsNullOrWhiteSpace(ProcessValue))\n{\n ProcCustomer = ProcessValue.DeserializeJson<ProcCustomer>();\n\n if (ProcCustomer != null && !string.IsNullOrWhiteSpace(ProcCustomer.ClientId))\n {\n ProcCustomer.ClientId = HttpUtility.HtmlEncode(ProcCustomer.ClientId);\n \n ProcessValue = ProcCustomer.JsonSerialize(); \n // or do it directly in the httpClient instead of ProcCustomer.ToString()\n \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:28:04.220",
"Id": "496347",
"Score": "0",
"body": "Thanks for your suggestion when I say `ProcessValue` string is used directly meaning they are used as a json string directly as a whole which I modified in my question. Since it's an header so we pass that whole json as an header over the network through http client. I don't extract client_id later on from that `ProcessValue` json string. So with that in mind how can I make this work? In your first example how can I have modified `ProcessValue` json string which can be used later on?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:42:26.647",
"Id": "496351",
"Score": "0",
"body": "You mean to say I can get a string from POCO object directly `Then, serialize it whenever needed.`? Can you also add an example on how can I get a JSON string from POCO back as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:43:51.937",
"Id": "496354",
"Score": "0",
"body": "@Yes, I'll put a simple example with the POCO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:08:13.697",
"Id": "496358",
"Score": "0",
"body": "Cool make sense now. Also my POCO field is like this `[DataMember(Name = \"client_id\")]\n public string ClientId { get; set; }` so should I add `[JsonProperty(\"client_id\")]` as well on top of that and rest of your code as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:11:28.117",
"Id": "496361",
"Score": "0",
"body": "@AndyP the `DataMember` would be enough for this situation, so don't add the `JsonProperty` as both are similar and Json.NET reads both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:28:47.980",
"Id": "496367",
"Score": "0",
"body": "Somehow I get `Stack overflow.` once I modified `ClientId` field in my POCO class as you mentioned above. As soon as it goes to this line `ProcCustomer = DeserializeJson<ProcCustomer>(ProcessValue);` it throws that error. Not sure why"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T16:27:05.580",
"Id": "496372",
"Score": "0",
"body": "@AndyP check if you can deserialize without using the extension like this`ProcCustomer =Newtonsoft.Json.JsonConvert.DeserializeObject<ProcCustomer>(ProcessValue);`"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T10:29:34.183",
"Id": "251996",
"ParentId": "251984",
"Score": "1"
}
},
{
"body": "<p>If you want to replace a single element in a json then you can take advantage of <code>JObject</code>.</p>\n<p>You just need to <code>Parse</code> the json but don't need to <code>Deserialize</code> it.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>//Declarations\nconst string clientIdKey = "client_id";\nvar ProcessValue = "{\\"key1\\":\\"value1\\",\\"key2\\":\\"value2\\",\\"key3\\":\\"value3\\",\\"key4\\":\\"value4\\",\\"key5\\":\\"value6\\",\\"client_id\\":\\"Hänzendes\\"}";\n\n//Parsing\nvar jObject = JObject.Parse(ProcessValue);\nvar clientId = jObject[clientIdKey];\n\n//Replacement\nif (clientId != null)\n jObject[clientIdKey] = HttpUtility.HtmlEncode(clientId);\n\n//Saving changes\nProcessValue = jObject.ToString();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:13:48.540",
"Id": "252001",
"ParentId": "251984",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251996",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T01:50:01.710",
"Id": "251984",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Update existing key value if present and then deserialize json to POCO efficiently"
}
|
251984
|
<h1>Story</h1>
<p><a href="https://programmers.co.kr/learn/courses/30/lessons/67260" rel="nofollow noreferrer">Original Link written in korean</a></p>
<p>Frodo, a backcountry explorer, came to explore an underground cave with n rooms during his expedition. All rooms are numbered 0 through n-1. There are many, the only entrances are connected with 0 rooms.</p>
<p>Each room is connected to each other by passages that allow passage in both directions, but there is only one passage directly connecting the two different rooms. There is only one shortest path between any two different rooms, and there is no case where it is impossible to move between any two rooms.</p>
<p>Having obtained a map of this underground cave prior to his expedition, Frodo planned his expedition as follows:</p>
<ol>
<li><p>You must visit every room at least once.</p>
</li>
<li><p>Certain rooms must be visited first before visiting. <br>
2.1. This means that you must visit Room B before visiting Room A. <br>
2.2. There is no or only one room that must be visited first in order to visit a room. <br>
2.3. For two or more different rooms, there is never the same room that must be visited first. <br>
2.4 A room is not a room that must be visited first and a room that must be visited later.</p>
</li>
</ol>
<p><br>Among the above plans, 2.2, 2.3 and 2.4 mean that the pair of two rooms that must be visited in order is unique in the form of A → B (visit A first and then B). In other words, Frodo made a visit plan so that the order of visit would not be arranged as follows.</p>
<ul>
<li>A → B, A → C (visit order order = [...,[A,B],...,[A,C],...]) The room to visit after visiting A is B Two or more with and C</li>
<li>The room to visit before visiting A in the form X → A, Z → A (visit order order = [...,[X,A],...,[Z,A],...]) Two or more with X and Z</li>
<li>A → B → C (visit order arrangement order = [...,[A,B],...,[B,C],...), like B, after visit A and before visit C at the same time</li>
</ul>
<p>Also, you do not have to visit the room you need to visit first and the room you will visit later, so you can visit room A and then visit another room and then visit room B.</p>
<p>When the number of rooms n, a two-dimensional array path containing the number of two rooms connected by each of the corridors in the cave, and a two-dimensional array order containing the visit order set by Frodo are given as parameters, Frodo can explore all rooms according to the rules. Complete the solution function to return whether it exists.</p>
<p><strong>It's source is kakao intern coding test.</strong></p>
<h1>I/O example:</h1>
<p><a href="https://i.stack.imgur.com/xfHyR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xfHyR.png" alt="so the light colored rooms should be visited first to visit dark colored rooms" /></a></p>
<p><strong>so the light colored rooms should be visited first to visit dark colored rooms</strong></p>
<p><strong>n path order ---> result</strong></p>
<p><strong>9,[[0,1],[0,3],[0,7],[8,1],[3,6],[1,2],[4,7],[7,5]],[[8,5],[6,7],[4,1]] --->true</strong></p>
<h1>question</h1>
<p>**this is my code. I used stack. And when frodo arrived at room A, room needed to visit first, to visit Room B, then I added rooms on dictionary that can only be accessed after arriving Room B.
so to explain my code briefly, in dictionary value B does not exist. value B is added after arriving room A</p>
<p>It could have some errors, but I/O case correct rate was about 0.95/1**</p>
<pre><code>#adding key B in dictionary
def check(a,route,res,path):
if a in res:
p=res[a]
del[res[a]]
if a not in res:
for c in path:
if p in c:
for j in c:
if j!=p :
if j in route:
if p not in route[j]:
route[j].append(p)
else:
route[j]=[p]
return None
def solution(n, path, order):
res=dict(order)
#making order library
warn=[]
for i in order:
if i[1] not in warn:
warn.append(i[1])
route={}
#making connected library except B values. so if value does not exist in library. frodo can not reach room B
for i in range(n):
for j in path:
if i in j:
for k in j:
if k in warn or i==k:
pass
else:
if i in route:
route[i].append(k)
else:
route[i]=[k]
for j in range(len(order)):
#repeated because there are len(order) B rooms.
stack=[]
visited=set()
stack.append(0)
visited.add(0)
while len(stack)!=0:
a=stack.pop()
visited.add(a)
check(a,route,res,path)
if a in route:
for i in route[a]:
if i not in visited:
stack.append(i)
#so visited room number should be same with n. it means that all rooms are visited
if len(visited)==n:
return True
return False
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T02:24:53.583",
"Id": "251987",
"Score": "1",
"Tags": [
"python-3.x",
"programming-challenge"
],
"Title": "Cave explorer: using stack"
}
|
251987
|
<p>This code is a improved version of implementation which asked for a review: <a href="https://codereview.stackexchange.com/questions/251929/product-of-all-but-one-number-in-a-sequence-follow-up">Product of all but one number in a sequence</a>.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
//without division, with O(n) time, but extra space complexity as suggested
//return new array on the heap
int *derive_products(const int *nums, int count)
{
int *retval = malloc(count * sizeof *retval);
if (!retval && count)
return 0;
int mult=1; //product of prefix or suffix elements
//swipe up
for(int i=0; i<count; i++) {
retval[i] = mult;
mult *= nums[i];
}
//swipe down
for(int j=count-1, mult=1; j>=0; j--) {
retval[j] *= mult;
mult *= nums[j];
}
return retval;
}
int main()
{
/*Given an array of integers, return a new array such that each element at index i of the
new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be
[120, 60, 40, 30, 24] */
int nums[] = {1, 2, 2, 4, 6};
int size = sizeof(nums)/sizeof(nums[0]);
int *products = derive_products(nums, size); //get a new array
for (int i = 0; i < size; i++)
printf("%d ", products[i] );
free(products); //release heap memory
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T03:48:00.923",
"Id": "496540",
"Score": "0",
"body": "Rather than \"/return new array on the heap \", get right to the point as C does not define \"heap\". Instead. \"// Returns allocated array\"/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T03:51:15.813",
"Id": "496541",
"Score": "0",
"body": "Why does code describe the output of a commented test case and then code uses a test with another set of data? I'd expect the true test case to have a commented expectation - or a run-time check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T05:58:21.850",
"Id": "496546",
"Score": "0",
"body": "@chux-ReinstateMonica I declared random int array since I only focus on product generator function. But I got the point thanks."
}
] |
[
{
"body": "<h3>Proper scoping</h3>\n<pre><code>int mult=1; //product of prefix or suffix elements\n</code></pre>\n<ol>\n<li><code>mult</code> above is only used in the first loop. The one used in the second loop is defined there, and limited to that loop. This one should be the same.</li>\n</ol>\n<h3>Proper naming</h3>\n<ol start=\"2\">\n<li><code>j</code> in the second loop is an unexpected name. As it is an outer loop, you should use <code>i</code> (again).</li>\n</ol>\n<pre><code>int size = sizeof(nums)/sizeof(nums[0]);\n</code></pre>\n<ol start=\"3\">\n<li>While <code>size</code> isn't really wrong, I would expect a different unit of measurement (namely bytes, as for <code>sizeof</code>, instead of elements) considering the name. I suggest going for <code>count</code>.</li>\n</ol>\n<h3>Check for failure</h3>\n<pre><code>int *products = derive_products(nums, size); //get a new array\n</code></pre>\n<ol start=\"4\">\n<li>The above can fail, in which case it returns null. Don't just assume success.</li>\n</ol>\n<h3>Comments</h3>\n<pre><code>//without division, with O(n) time, but extra space complexity as suggested\n//return new array on the heap \n</code></pre>\n<ol start=\"5\">\n<li><p>Comments should be to the point, omit the obvious, and describe the motivation.</p>\n<p>The above could be:</p>\n<pre><code>// without division in O(n) time\n// free(result)\n</code></pre>\n</li>\n<li><p>Yes, writing down the task as a comment is a good idea. But if you have test-data, just write a test.</p>\n</li>\n<li><p>Your comment after a line of code are pretty superfluous. Are you forced to sprinkle more comments?<br />\nSee <a href=\"https://codereview.stackexchange.com/questions/90111/guessing-a-number-but-comments-concerning\">Guessing a number, but comments concerning</a></p>\n</li>\n</ol>\n<h3>Whitespace</h3>\n<ol start=\"8\">\n<li>Your use of whitespace is inconsistent. Do you surround binary operators with single whitespace?<br />\nSometimes you do, sometimes you don't. Imho, doing so looks better, so standardise on that. There are plenty automatic code formatters, so you don't even have to do the hard work yourself.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T03:44:26.403",
"Id": "496538",
"Score": "0",
"body": "Good point about scoping. It took a while to see that `mult` declaration in `int j=count-1, mult=1;`. `for` body certainty looks like it is using the prior code's `mult`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:44:46.237",
"Id": "252005",
"ParentId": "251991",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T08:36:35.203",
"Id": "251991",
"Score": "4",
"Tags": [
"algorithm",
"c"
],
"Title": "Product of all but one number in a sequence - Follow Up (2)"
}
|
251991
|
<p>This class is being used to build some complex strings JSON and MySql.</p>
<p>Note: I'm not using the JSon converter because is difficult to create the structures the at that I want them and MySQL require extra escape characters.</p>
<p>At a later date, I may consider upgrading the class using Regular Expressions or CreateObject("System.Collections.StringBuilder"). ANy advice on either of these methods would be appreciated.</p>
<h2>EscapeString:Class</h2>
<pre><code>Attribute VB_Name = "EscapeString"
Attribute VB_PredeclaredId = True
Attribute VB_Ext_KEY = "Rubberduck" ,"Predeclared Class Module"
Option Explicit
'@PredeclaredId
Private Type TMembers
Content As String
End Type
Private this As TMembers
Public Property Get Create(ByVal Content As String) As EscapeString
With New EscapeString
.Content = Content
Set Create = .Self
End With
End Property
Public Property Get Self() As EscapeString
Set Self = Me
End Property
Public Property Get EscapeMySQL() As EscapeString
Rem https://dev.mysql.com/doc/refman/8.0/en/string-literals.html
Rem \\ A backslash (\) character
Rem \" A double quote (") character
Rem \b A backspace character
Rem \n A newline (linefeed) character
Rem \r A carriage return character
Rem \t A tab character
Rem EscapeJSON escapes all the referenced characters to this point
IIf False, Me.EscapeJSON, ""
Rem \0 An ASCII NUL (X'00') character
If InStr(Content, Chr(0)) > 0 Then Content = Replace(Content, Chr(0), "\0 ")
Rem \' A single quote (') character
If InStr(Content, "'") > 0 Then Content = Replace(Content, "'", "\'")
Rem \Z ASCII 26 (Control+Z); see note following the table
If InStr(Content, Chr(26)) > 0 Then Content = Replace(Content, Chr(26), "\Z ")
Rem \% A % character; see note following the table
If InStr(Content, "%") > 0 Then Content = Replace(Content, "%", "\%")
Rem \_ A _ character; see note following the table
If InStr(Content, "_") > 0 Then Content = Replace(Content, "_", "\_")
Set EscapeMySQL = Self
End Property
Public Property Get EscapeJSON() As EscapeString
Rem https://bettersolutions.com/vba/strings-characters/ascii-characters.htm
Rem Backslash to be replaced with \\
If InStr(Content, "\") > 0 Then Content = Replace(Content, "\", "\\")
Rem Backspace to be replaced with \b
If InStr(Content, Chr(8)) > 0 Then Content = Replace(Content, Chr(8), "\b")
Rem Newline to be replaced with \n
If InStr(Content, vbNewLine) > 0 Then Content = Replace(Content, vbNewLine, "\n")
Rem Form feed to be replaced with \f
If InStr(Content, vbLf) > 0 Then Content = Replace(Content, vbLf, "\f")
Rem Tab to be replaced with \t
If InStr(Content, vbTab) > 0 Then Content = Replace(Content, vbTab, "\t")
Rem Double quote to be replaced with \"
If InStr(Content, Chr(34)) > 0 Then Content = Replace(Content, Chr(34), "\" & Chr(34))
Set EscapeJSON = Self
End Property
Public Function ToString(Optional ContentWrapper As String = "") As String
ToString = ContentWrapper & this.Content & ContentWrapper
End Function
Public Property Get Content() As String
Content = this.Content
End Property
Public Property Let Content(ByVal Value As String)
this.Content = Value
End Property
</code></pre>
<h2>Examples</h2>
<p><img src="https://i.stack.imgur.com/YZmFd.png" alt="Examples" /></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T11:12:19.283",
"Id": "496305",
"Score": "1",
"body": "N.b. I opened an [issue](https://github.com/highlightjs/highlight.js/issues/2851) on highlight.js about the `REM` syntax highlighting issue"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:34:47.817",
"Id": "496309",
"Score": "0",
"body": "@Greedo I never noticed. I switched to using `Rem` because I think that an overabundance of apostrophes is obnoxious."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T10:20:54.050",
"Id": "251995",
"Score": "1",
"Tags": [
"vba"
],
"Title": "EscapeString Class for MySQL and JSON Using the Builder Pattern"
}
|
251995
|
<p>I have a list of integers, e.g. <code>i=[1,7,3,1,5]</code> which I first transform to a list of the respective binary representations of length <code>L</code>, e.g. <code>b=["001","111","011","001","101"]</code> with <code>L=3</code>.</p>
<p>Now I want to compute at how many of the <code>L</code> positions in the binary representation there is a <code>1</code> as well as a zero <code>0</code>. In my example the result would be <code>return=2</code> since there is always a <code>1</code> in the third (last) position for these entries. I want to compute this inside a function with a numba decorator.
Currently my code is:</p>
<pre><code>@nb.njit
def count_mixed_bits_v2(lst):
andnumber = lst[0] & lst[1]
ornumber = lst[0] | lst[1]
for i in range(1, len(lst)-1):
andnumber = andnumber & lst[i+1]
ornumber = ornumber | lst[i+1]
xornumber = andnumber ^ ornumber
result = 0
while xornumber > 0:
result += xornumber & 1
xornumber = xornumber >> 1
return result
</code></pre>
<p>First I take the AND of all numbers, ans also the OR of all numbers, then the XOR of those two results will have a 1 where the condition is fulfilled. In the end I count the number of 1's in the binary representation. My code seems a bit lengthy and I'm wondering if it could be more efficient as well. Thanks for any comment!</p>
<p>Edit: Without the numba decorator the following function works:</p>
<pre><code>def count_mixed_bits(lst):
xor = reduce(and_, lst) ^ reduce(or_, lst)
return bin(xor).count("1")
</code></pre>
<p>(Credit to trincot)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:21:43.590",
"Id": "496344",
"Score": "1",
"body": "Please do not edit the question after you have received an answer, it is against the [rules](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:25:51.063",
"Id": "496345",
"Score": "2",
"body": "I've not changed my initial question, but was asked to compare the execution time of the solutions. Why is that a problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:43:37.787",
"Id": "496353",
"Score": "1",
"body": "@pacmaninbw Against *which* of those rules exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:24:04.037",
"Id": "496364",
"Score": "1",
"body": "@StefanPochmann The rule is that everyone that sees the question and the answer should see the same question that the person who answered did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:26:14.890",
"Id": "496365",
"Score": "0",
"body": "@pacmaninbw I'd like to read that rule for myself. Where exactly on that page do you see it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:41:04.650",
"Id": "496370",
"Score": "1",
"body": "\"**Do not change the code in the question** after receiving an answer.\" seems to apply here. Adding the timing code (and generally all the changes, including revision 2) seem to fall under that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T19:48:47.070",
"Id": "496383",
"Score": "0",
"body": "@Vogel612 Doesn't \"the code\" refer to the code to be reviewed (which didn't change at all)? And isn't it to avoid negatively affecting answers (which it didn't at all)? To me it seemed perfectly fine and useful."
}
] |
[
{
"body": "<p>I only see a few micro optimisations:</p>\n<ul>\n<li>Iterate the list instead of a range, so that you don't have to do another lookup with <code>list[i+1]</code></li>\n<li>Use more assignment operators, such as <code>&=</code>, <code>|=</code> and <code>>>=</code></li>\n<li>It is not needed to use <code>lst[1]</code> in <code>andnumber = lst[0] & lst[1]</code>. It can be just <code>andnumber = lst[0]</code></li>\n</ul>\n<p>So:</p>\n<pre><code>def count_mixed_bits_v2(lst):\n andnumber = ornumber = lst[0]\n for value in lst:\n andnumber &= value\n ornumber |= value\n xornumber = andnumber ^ ornumber\n result = 0\n while xornumber > 0:\n result += xornumber & 1\n xornumber >>= 1\n return result\n</code></pre>\n<p>This visits the first list value again (in the first iteration), even though it is not necessary. But that probably does not really hurt performance, and keeps the code simple.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:05:19.583",
"Id": "496318",
"Score": "2",
"body": "I feel like `functools.reduce` might be more suited to the operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:10:17.477",
"Id": "496319",
"Score": "1",
"body": "Yes, I had the same reaction before. The OP asked a previous question on [Stack Overflow](https://stackoverflow.com/questions/64801038/list-of-binary-numbers-how-many-positions-have-a-one-and-zero/64801528#64801528) where I answered like that, but apparently, that is not supported by numba, which only supports a subset of Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:26:15.297",
"Id": "496325",
"Score": "0",
"body": "On https://numba.pydata.org/numba-doc/dev/reference/pysupported.html it says \"The functools.reduce() function is supported but the initializer argument is required.\" But I could not get it to work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:28:27.573",
"Id": "496326",
"Score": "0",
"body": "So what did your `reduce` call look like? It should be like `reduce(and_, lst, lst[0])` then"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:53:02.087",
"Id": "496336",
"Score": "0",
"body": "@trincot Yeah, you are right."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:01:05.267",
"Id": "252000",
"ParentId": "251998",
"Score": "4"
}
},
{
"body": "<p>I don't know numba, but here's a little rewrite:</p>\n<ul>\n<li>Shorter variable names like <code>and_</code>, using the underscore as suggested <a href=\"https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles\" rel=\"nofollow noreferrer\">by PEP 8</a> (<em>"used by convention to avoid conflicts with Python keyword"</em>) and as done by <a href=\"https://docs.python.org/3/library/operator.html#operator.and_\" rel=\"nofollow noreferrer\"><code>operator.and_</code></a>.</li>\n<li>Yours crashes if the list has fewer than two elements, I start with neutral values instead.</li>\n<li>Looping over the list elements rather than the indexes.</li>\n<li>Using <a href=\"https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements\" rel=\"nofollow noreferrer\">augmented assignments</a> like <code>&=</code>.</li>\n<li>In the result loop, drop the last 1-bit so you only have as many iterations as there are 1-bits.</li>\n</ul>\n<pre><code>def count_mixed_bits(lst):\n and_, or_ = ~0, 0\n for x in lst:\n and_ &= x\n or_ |= x\n xor_ = and_ ^ or_\n result = 0\n while xor_ > 0:\n result += 1\n xor_ &= xor_ - 1\n return result\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:55:58.540",
"Id": "496337",
"Score": "0",
"body": "Good points! Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:56:37.010",
"Id": "496338",
"Score": "0",
"body": "Oh, this is indeed really fast!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:59:48.760",
"Id": "496339",
"Score": "0",
"body": "@HighwayJohn What times do you get for the various solutions, and how are you measuring? Can you share your benchmark code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:03:12.320",
"Id": "496341",
"Score": "0",
"body": "Yes, let me make another edit. I think my current benchmark was flawed, since it compiled the numba function each time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:26:15.900",
"Id": "496346",
"Score": "0",
"body": "Unfortunately my benchmark comparison was deleted but your code is the fastest. Thanks a lot"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:52:18.993",
"Id": "252003",
"ParentId": "251998",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252003",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T12:08:13.740",
"Id": "251998",
"Score": "4",
"Tags": [
"python",
"numba"
],
"Title": "List of binary numbers: How many positions have a one and zero"
}
|
251998
|
<h3>Snake</h3>
<p>Snake first appeared in the 1970s. Since then it has become a video game classic that is pre-installed on many systems.
The rules are simple:
Food (often an apple) appears randomly on the grid. When the snake "eats" the food, the snake grows a little.
The player loses if the snake hits the edge of the grid or the snake itself.</p>
<p>For more information, please have a look at the article on <a href="https://en.wikipedia.org/wiki/Snake_(video_game_genre)" rel="nofollow noreferrer">wikipedia</a>.</p>
<h3>My implementation</h3>
<p>I've used pure JavaScript and a bit of JQuery in this project. The code also works on mobile devices.</p>
<h3>The code</h3>
<pre class="lang-javascript prettyprint-override"><code>let WIDTH = 400;
let HEIGHT = 400;
let RES = 20;
let snake = [];
let direction;
let tempDirection;
let isRunning;
let interval;
let appleX;
let appleY;
let scoreCount = 0;
let highscore = 0;
let snakeLength;
let speed;
let isSet;
// Resize canvas when screen too small - needed for responsiveness
window.addEventListener('load', function() {
/*
* Normal width of canvas = 400, so resize only needed when
* screen-width < 400
*/
if (window.innerWidth < 400) {
WIDTH = document.getElementById('chooseDifficulty').clientWidth;
HEIGHT = WIDTH;
document.getElementById('canvas').height = HEIGHT;
document.getElementById('canvas').width = WIDTH;
RES = WIDTH / 20;
}
});
/*
* difficulty choice
*/
document.getElementById('easy').addEventListener('click', function() {
document.getElementById('chooseDifficulty').style.display = 'none';
snakeLength = 5;
isSet = true;
speed = 120;
initialize();
});
document.getElementById('medium').addEventListener('click', function() {
document.getElementById('chooseDifficulty').style.display = 'none';
snakeLength = 7;
isSet = true;
speed = 100;
initialize();
});
document.getElementById('hard').addEventListener('click', function() {
document.getElementById('chooseDifficulty').style.display = 'none';
snakeLength = 9;
isSet = true;
speed = 80;
initialize();
});
/*
* control via arrow keys
*/
document.addEventListener('keydown', function(e) {
/*
* case user didn't choose difficulty yet
*/
if (!isSet) {
return;
}
/*
* Needed, because otherwise the arrow-up and arrow-down key would also lead
* to a scroll up and down
*/
e.preventDefault();
/*
* Start / Stop game with space
*/
if (e.code === 'Space') {
if (!isRunning) {
start();
} else {
stop();
}
}
/*
* User shouldn't be able to change direction
* when game hasn't started yet
*/
if (!isRunning) {
return;
}
/*
* Direction change needs to be saved in a temporary variable,
* because otherwise, the user would be able to cheat.
* Let's say the current direction is UP. Then the user could
* quickly press the left-arrow and then the down-arrow
* -> direction would change from UP to DOWN
*
* That's why the direction change is saved in a temporary variable
* and the main direction variable is only updated once per 'generation',
* but only if the rules allow the direction change (up to down not possible!)
*/
if (e.key === 'ArrowUp' && direction !== 'DOWN') {
tempDirection = 'UP';
} else if (e.key === 'ArrowDown' && direction !== 'UP') {
tempDirection = 'DOWN';
} else if (e.key === 'ArrowLeft' && direction !== 'RIGHT') {
tempDirection = 'LEFT';
} else if (e.key === 'ArrowRight' && direction !== 'LEFT') {
tempDirection = 'RIGHT';
}
});
/*
* Button to start / stop the game in mobile view
*/
document.getElementById('startStop').addEventListener('click', function() {
if (!isSet) {
return;
}
if (!isRunning) {
start();
document.body.style.overflow = 'hidden';
updateElement('startStop', 'Stop');
} else {
stop();
document.body.style.overflow = 'scroll';
updateElement('startStop', 'Start');
}
});
/*
* Functionality to change the direction of the snake with swipe-movements
* added with swiped-events.js
* https://github.com/john-doherty/swiped-events
*/
document.getElementById('canvas').addEventListener('swiped-left', function() {
if (!isSet || !isRunning) {
return;
}
if (direction !== 'RIGHT') {
tempDirection = 'LEFT';
}
});
document.getElementById('canvas').addEventListener('swiped-right', function() {
if (!isSet || !isRunning) {
return;
}
if (direction !== 'LEFT') {
tempDirection = 'RIGHT';
}
});
document.getElementById('canvas').addEventListener('swiped-up', function() {
if (!isSet || !isRunning) {
return;
}
if (direction !== 'DOWN') {
tempDirection = 'UP';
}
});
document.getElementById('canvas').addEventListener('swiped-down', function() {
if (!isSet || !isRunning) {
return;
}
if (direction !== 'UP') {
tempDirection = 'DOWN';
}
});
function initialize() {
// Did user reach new highscore?
if (scoreCount > highscore) {
highscore = scoreCount;
}
// Update highscore
updateElement('highscore', highscore);
// Reset
snake = [];
direction = 'RIGHT';
tempDirection = '';
isRunning = false;
appleX = -1;
appleY = -1;
scoreCount = 0;
// display score = 0;
updateElement('score', scoreCount);
// Get center of canvas
const x = Math.floor((WIDTH / RES) / 2);
const y = Math.floor((HEIGHT / RES) / 2);
// Set head of snake to center and then go left for tail
for (let i = x; i > x - snakeLength; i--) {
snake.push({x: i, y: y});
}
draw();
// Show text to tell user to start game with pressing space
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.font = '30px open-sans';
ctx.fillStyle = '00410B';
ctx.textAlign = 'center';
if (WIDTH === 400) {
ctx.fillText('Press space to play', canvas.width / 2, 100);
} else {
ctx.fillText('Press start to play', canvas.width / 2, 100);
}
}
function start() {
// Update canvas every 'speed' milliseconds
interval = setInterval(function() {
draw();
applyRules();
}, (speed));
isRunning = true;
}
function stop() {
// Stop updating the canvas
clearInterval(interval);
isRunning = false;
}
function youLost() {
// Reset
document.body.style.overflow = 'scroll';
snakeLength = -1;
isSet = false;
speed = -1;
updateElement('chooseDifficultyText', 'Game over.\nChoose difficulty:');
updateElement('startStop', 'Start');
stop();
// Show 'choose difficulty'-menu again
document.getElementById('chooseDifficulty').style.display = 'inline-block';
}
function draw() {
const cols = WIDTH / RES;
const rows = HEIGHT / RES;
// Draw
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
const x = i * RES;
const y = j * RES;
drawCell('white', 'LightGray', 1, x, y, RES, RES);
}
}
// Draw snake
for (let i = 0; i < snake.length; i++) {
// Head of snake
if (i !== 0) {
drawCell('#2B823A', 'LightGray', 1, snake[i].x * RES,
snake[i].y * RES, RES, RES);
} else {
drawCell('#00410B', 'LightGray', 1, snake[i].x * RES,
snake[i].y * RES, RES, RES);
}
}
// Draw apple
if (appleX !== -1 && appleY !== -1) {
const img = new Image();
img.src = 'apple.svg';
const ctx = document.getElementById('canvas').getContext('2d');
ctx.drawImage(img, appleX * RES, appleY * RES, RES, RES);
}
}
function applyRules() {
// Check if head of snake is outside of canvas -> game lost
if (snake[0].x > WIDTH / RES - 1 || snake[0].x < 0 ||
snake[0].y > HEIGHT / RES - 1 || snake[0].y < 0) {
youLost();
}
// Check if head touches other part of the snake -> game lost
for (let i = 1; i < snake.length; i++) {
if (snake[0].x === snake[i].x && snake[0].y === snake[i].y) {
youLost();
}
}
// Place new apple in canvas
if (appleX === -1 && appleY === -1) {
getApple();
}
// users direction-change takes place here
if (tempDirection !== '') {
if (tempDirection === 'UP' && direction !== 'DOWN') {
direction = tempDirection;
} else if (tempDirection === 'DOWN' && direction !== 'UP') {
direction = tempDirection;
} else if (tempDirection === 'LEFT' && direction !== 'RIGHT') {
direction = tempDirection;
} else if (tempDirection === 'RIGHT' && direction !== 'LEFT') {
direction = tempDirection;
}
}
// Get position of head
const headX = snake[0].x;
const headY = snake[0].y;
// Add new 'head to snake' to let snake move
if (direction === 'UP') {
snake.unshift({x: headX, y: headY - 1});
} else if (direction === 'DOWN') {
snake.unshift({x: headX, y: headY + 1});
} else if (direction === 'LEFT') {
snake.unshift({x: headX - 1, y: headY});
} else {
snake.unshift({x: headX + 1, y: headY});
}
/*
* If snake didn't eat an apple in this iteration, the last element of
* the snake has to be removed so that snake has same length after
* moving on cell
*/
if (snake[0].x !== appleX || snake[0].y !== appleY) {
snake.pop();
} else {
/*
* Case that the snake did eat an apple in this iteration. The last
* element of the snake doesn't gets removed because that way,
* the snake grows. Position of the apple gets resetted.
*/
appleX = -1;
appleY = -1;
scoreCount++;
// Update score
updateElement('score', scoreCount);
}
}
/*
* ===================
* HELPER
* ===================
*/
function drawCell(fillStyle, strokeStyle, lineWidth, x, y, width, height) {
const ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = fillStyle;
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
ctx.beginPath();
// Draw border of color strokeStyle
ctx.rect(x, y, width, height);
// Fill cell with color fillStyle
ctx.fill();
ctx.stroke();
}
function getApple() {
let isInSnake = false;
while (!isInSnake) {
isInSnake = true;
// Get random position for apple
appleX = Math.floor(Math.random() * (WIDTH / RES - 1)) + 1;
appleY = Math.floor(Math.random() * (HEIGHT / RES - 1)) + 1;
// Iterate over every element of the snake
for (let i = 0; i < snake.length; i++) {
/*
* If the newly created position for the apple is occupied by the snake,
* another position for the apple has to be found.
*/
if (snake[i].x === appleX && snake[i].y === appleY) {
isInSnake = false;
break;
}
}
}
}
function updateElement(elemId, content) {
/*
* isNaN returns true if variable isn't a number
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
*/
if (!isNaN(content)) {
/*
* creates a string of length 3, e.g. if content = 15,
* then result will be 015
*/
content = content.toString().padStart(3, '0');
}
$(document).ready(function() {
$('#' + elemId).text(content);
});
}
</code></pre>
<h3>Question</h3>
<p>All suggestions are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:18:43.327",
"Id": "496421",
"Score": "1",
"body": "I tried your demo and it seems to work fine. The only niggle I have is that it seems somewhat slow to respond to my inputs on the keyboard. I didn't try touch. A probable cause is too much redrawing. After each interval you should only draw what changes. I like your comments, that helps to understand the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:33:03.093",
"Id": "496424",
"Score": "1",
"body": "I think that when I swap `applyRules();` and `draw();` around, in the interval loop, so that `applyRules();` comes before `draw();`, that it is slightly better. This makes sense: After each interval the code first reacts to the keyboard, or touch, and then does a complete redraw, instead of the other way around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T18:56:38.930",
"Id": "508582",
"Score": "1",
"body": "I would not do `document.getElementById` in event handlers, try to save them in variables there is no need to check it each time the event happen. Also I don't know if you know but every element with id define global variable with same name, but using those globals, would probably make the code less readable. Also I don't see the reason to call `document.getElementById('canvas')` multiple times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T18:59:58.150",
"Id": "508583",
"Score": "1",
"body": "I also have question at the end you use jQuery ready, then why you don't use jQuery for other part of the code? The code would be shorter if you use jQuery, otherwise I would remove it, using it only for document ready is overkill."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:17:36.210",
"Id": "252002",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"snake-game"
],
"Title": "Responsive snake game"
}
|
252002
|
<p>I'm writing a class that works with a list of objects of a specific type (which is defined as class attribute). The class can either append objects via the append method or receive them as an initialisation parameter. when appending, some validation code is run. In the <code>__init__</code> method i need to perform the same validation, but for a list of the aforementioned objects.</p>
<p>My question is, is there a best practice for such operations? Currently i'm using list comprehension to rebind the input argument to a validated list, but i'm unsure of its efficiency (time and space wise).</p>
<pre><code>class Part(object):
"""
Minimal interface class representing a single outgoing message.
Loosely resemblant of HTTP message, but intended
in a more general scope.
"""
allowed_methods = ['delete', 'post', 'get',
'put', 'patch', 'update']
def __init__(self, action, params=None, data=None, headers=None,
method='GET'):
"""
:param action: A path to a resource
:type action: ``str``
:param method: An HTTP method such as "GET" or "POST", defaults to 'GET'
:type method: ``str``, optional
:param data: A body of data to send with the request
:type data: ``unicode``, optional
:param params: Extra parameters to add to the action
:type params: ``dict``, optional
:param headers: Extra headers to add to the request
:type headers: ``dict``, optional
"""
if not action or not isinstance(action, str):
raise TypeError(
'action must be non empty str')
method = self._normalize_method(method)
if method not in self.allowed_methods:
raise ValueError(
f'invalid method {method},'
f'allowed: {self.allowed_methods}')
self._raw = None
self._action = action
self._method = method
self.headers = headers
self.params = params
self.data = data
def __repr__(self):
return (f'<{self.__class__.__name__}>('
f'method:{self.method}, '
f'action:{self.action})')
@property
def action(self):
if self.params:
return encode_qs(self._action, self.params)
else:
return self.action
@property
def method(self):
return self._format_method(self._method)
@property
def raw(self):
if not self._raw:
self._raw = self._get_raw()
return self._raw
def _get_raw(self):
return self
@staticmethod
def _format_method(method):
"""Format the method string when accessed"""
return method
@staticmethod
def _normalize_method(method):
"""Normalize the method string after acquisition"""
return method.lower()
class BatchRequest(object):
"""docstring for BatchRequest"""
max_len = 100
part_cls = Part
def __init__(self, parts=None):
super(BatchRequest, self).__init__()
if parts is None:
self.parts = []
if len(parts) >= self.max_len:
raise ValueError(
f'too many parts, maximum length: {self.max_len}')
# what does happen under the hood?
# is the old list immediately garbage collected
# is it better to do it in place, and if so, how?
parts = [self.validate(p) for p in parts]
self.parts = parts
def validate(self, part):
if not isinstance(part, self.part_class):
raise TypeError(f'must be {type(self.part_cls)}, not {type(part)}')
# does return True make more sense here?
return part
def attach(self, part):
if len(self.parts) >= self.max_len:
raise ValueError(
f'too many parts, maximum length: {self.max_len}')
self.append(self.validate(part))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T17:08:41.230",
"Id": "496374",
"Score": "0",
"body": "@Reinderien sorry i didn't want to post a wall of code since it didn't seem relevant to the question, anyway i fixed it. Thank you for the input"
}
] |
[
{
"body": "<p>Here is the <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">standard reference</a> on how efficient list operations are. Generally, it's fast to add and remove things at the end of the list.</p>\n<p>The short answer is, both are efficient--and I see no indication you need to worry about efficiency. For example, you seem to be worrying about garbage collection--of an empty list. It's not that big a deal, it's 10 bytes or less. The longer answer is, your maximum list size is 100, and it's efficient to do anything at all with 100 items--python only moves around references to items, not the content. You should stop worrying about efficiency for this problem. Why did you start? Did you see a problem? Learn how to measure how long different parts of the code are taking. Always measure, don't assume you know what's slow. Once you see a problem, and isolate it to one area of the code, THEN try to speed it up.</p>\n<p>You should pick how to build your API based on how readable and safe it is when you use it. If you see a compelling reason that's in conflict with readability, you should try to think hard and figure out a way to get both. For example, a common option might be to offer a version of 'attach' which takes a list of parts, rather than just one, to improve efficiency. Only as a distant third options should you change your API based on efficiency.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T06:18:00.860",
"Id": "252231",
"ParentId": "252004",
"Score": "0"
}
},
{
"body": "<p>On first glance, and not having particularly enough usage context, I think that most of this seems like unwarranted abstraction. I think this is a client rather than a server based on nomenclature, in which case: where are the <code>requests</code> calls? Why track <code>allowed_methods</code> when Requests does this for you? It seems like <code>Part</code> is just a generic wrapper for an HTTP request, which doesn't really add anything of value over what <code>requests</code> itself would offer.</p>\n<p>This doesn't lend itself well to <code>TypeError</code> only:</p>\n<pre><code> if not action or not isinstance(action, str):\n raise TypeError(\n 'action must be non empty str')\n</code></pre>\n<p>You're actually checking two things: whether <code>action</code> is a string, if not raise a <code>TypeError</code>; and whether <code>action</code> is empty, in which case raise a <code>ValueError</code>.</p>\n<p>As to your primary question around</p>\n<pre><code> # what does happen under the hood? \n # is the old list immediately garbage collected\n # is it better to do it in place, and if so, how?\n parts = [self.validate(p) for p in parts]\n self.parts = parts\n</code></pre>\n<p>That all needs to go away. Notice that <code>validate</code> (correctly) does not mutate the <code>part</code>, and its <code>return</code> (aside from being incorrectly indented) is not necessary at all. As such, you do not need a comprehension, do not need a new list, and only need to loop:</p>\n<pre><code>for part in parts:\n self.validate(part)\nself.parts = parts\n</code></pre>\n<p>You ask:</p>\n<blockquote>\n<p>does return True make more sense here?</p>\n</blockquote>\n<p>No. What you're doing already (raising on validation failure) is fine. The validation you're doing doesn't bring much value, mind you - you're only verifying type - so it's not clear that this validation method needs to exist at all.</p>\n<p>In summary, and barring some example usage that concretely demonstrates why any of this code needs to exist, I would delete the entire thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-21T05:38:47.690",
"Id": "500315",
"Score": "0",
"body": "Thank you for the very detailed answer. This code is as matter of fact an interface, by itself doesn't do much aside from providing a skeleton for the subclasses that inherits from it. The request logic is handled in a different module of the repository and the allowed methods are bound to the particular services i'm using, which only exposes a subset of the rest operations. The validation code differentiate soap and rest requests and verifies application requirements inherent to both formatting and encoding."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-18T18:35:45.747",
"Id": "253631",
"ParentId": "252004",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253631",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:17:47.530",
"Id": "252004",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Python most effective way to process list objects"
}
|
252004
|
<p>I tried using recursion for this.</p>
<p>Here is the code</p>
<pre><code> public static string ReverseWords(string str)
{
var splitArr = str.Split(" ");
if(splitArr.Length == 1)
return splitArr[0];
return splitArr[splitArr.Length - 1] + " " + ReverseWords(String.Join(" ", splitArr.Take(splitArr.Length - 1));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T16:06:40.667",
"Id": "496371",
"Score": "9",
"body": "Recursion will kill itself with a string of any size (think War and Peace). A one-liner will do it: `string.Join(' ', str.Split(' ').Reverse())`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T13:31:13.287",
"Id": "496463",
"Score": "2",
"body": "Welcome to the Code Review Community. It is generally better to provide the entire class or program rather than just a single function so that we can provide a better review because there is more context. This is barely enough code to get a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T13:55:59.843",
"Id": "496471",
"Score": "0",
"body": "[edit] your question to add more details. Also since you're new around here, take a [tour] and read [ask]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T01:03:56.507",
"Id": "496536",
"Score": "0",
"body": "@pacmaninbw Sorry, but I don't get why I would be needing to provide entire class or program?\nwhen the whole Logic is inside the function. And function takes in the string of words as I tell in my quesiton."
}
] |
[
{
"body": "<p>This is horribly inefficient both in terms of storage and runtime:</p>\n<ol>\n<li>As already mentioned in comments (though not spelled out) recursion has a memory overhead directly proportional to the number of iterations - which in you case is input size.</li>\n</ol>\n<p>Remember - every function call takes up stack space, and a recursive call is the same as regular call!</p>\n<ol start=\"2\">\n<li>You create extra temporaries by rejoining the string you just split for the recursive call and having a string concatenation on each iteration.</li>\n</ol>\n<p>That's two new strings create in every step in addition to the split array!</p>\n<ol start=\"3\">\n<li>Everything mentioned in step 2 takes processing time as well as memory.</li>\n</ol>\n<p>You will not notice this overhead with any string you might type in a console for testing, but try reading and reversing a sizable text file, and the problem will become apparent.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:17:57.700",
"Id": "252022",
"ParentId": "252007",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252022",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T14:57:07.950",
"Id": "252007",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Reversing words in a string method"
}
|
252007
|
<p>Just looking for reviews to improve my coding and my structure of C#. It feels I probably have some unnecessary code that is not needed, been following some YouTube videos to accomplish some tasks.</p>
<p>Also, I am not sure if the actual structure is okay of my program. Would like to hear some opinions.</p>
<p>I am working on a project that sends a form to MySQL database. With a an extra bit of touch - Autofill most of the Text-boxes, from a button click and a given Sales Order Number found in SQL Server database.</p>
<p>If an Order Number is given then text boxes such as <code>Customer Name</code>, <code>Telephone</code>, <code>Email</code>, <code>Products</code> and <code>Pack size</code> is able to be auto-filled.</p>
<p>The <code>Products</code> is a combo-box value, so it'll be a list of ordered products and the user is able to selected a value.</p>
<p>This is the form:</p>
<p><a href="https://i.stack.imgur.com/H3GxN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H3GxN.png" alt="enter image description here" /></a></p>
<p><strong>Code:</strong></p>
<p><strong>ComplaintModel.cs</strong></p>
<pre><code>public class ComplaintModel
{
public int Id { get; set; }
public int UserId { get; set; }
public DateTime Date { get; set; }
public string OrderNumber { get; set; }
public int IsCustomerSelected { get; set; }
public string CustomerName { get; set; }
public string CustomerContactName { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
public string CustomerReference { get; set; }
public int IsProductSelected { get; set; }
public string Product { get; set; }
public string PackSize { get; set; }
public string BatchNumber { get; set; }
public int IsBestBefore { get; set; }
public DateTime BestBeforeDate { get; set; }
public string QuantityInvolved { get; set; }
public string Details { get; set; }
public string Comments { get; set; }
}
</code></pre>
<p><strong>ComplaintForm.cs</strong></p>
<pre><code>public partial class Complaints_Form : Form
{
BindingList<string> errors = new BindingList<string>();
List<ComplaintModel> mjmOrderNumber = new List<ComplaintModel>();
List<ComplaintModel> customerNames = new List<ComplaintModel>();
List<ComplaintModel> productNames = new List<ComplaintModel>();
public Complaints_Form()
{
InitializeComponent();
loadCustomers();
loadProducts();
}
private void loadCustomers()
{
DataAccess db = new DataAccess();
customerNames = db.LoadCustomers();
customer_name.DataSource = customerNames;
customer_name.DisplayMember = "CustomerName";
customer_name.SelectedIndex = -1;
}
private void loadProducts()
{
DataAccess db = new DataAccess();
productNames = db.LoadProducts();
product.DataSource = productNames;
product.DisplayMember = "Product";
product.SelectedIndex = -1;
pack_size.DataBindings.Add("Text", productNames, "PackSize", false, DataSourceUpdateMode.OnPropertyChanged);
}
public void clearBindings()
{
customer_name.DataBindings.Clear();
email.DataBindings.Clear();
telephone.DataBindings.Clear();
product.DataBindings.Clear();
product.DataSource = null;
product.Items.Clear();
pack_size.DataBindings.Clear();
}
public void searchButton_Click(object sender, EventArgs e)
{
clearBindings();
DataAccess db = new DataAccess();
mjmOrderNumber = db.FindOrderNumber(orderNumber.Text);
// Binding values from Sales Order Number here:
customer_name.DataBindings.Add("Text", mjmOrderNumber, "CustomerName", false, DataSourceUpdateMode.OnPropertyChanged);
email.DataBindings.Add("Text", mjmOrderNumber, "Email", false, DataSourceUpdateMode.OnPropertyChanged);
telephone.DataBindings.Add("Text", mjmOrderNumber, "Telephone", false, DataSourceUpdateMode.OnPropertyChanged);
product.DataSource = mjmOrderNumber;
product.DisplayMember = "Product";
pack_size.DataBindings.Add("Text", mjmOrderNumber, "PackSize", false, DataSourceUpdateMode.OnPropertyChanged);
}
private void FormValidation()
{
errors.Clear();
ComplaintModel complaint = new ComplaintModel();
complaint.Date = date.Value;
complaint.IsCustomerSelected = customer_name.SelectedIndex;
complaint.CustomerContactName = customer_contact.Text;
complaint.Telephone = telephone.Text;
complaint.Email = email.Text;
complaint.CustomerReference = customer_ref.Text;
complaint.IsProductSelected = product.SelectedIndex;
complaint.PackSize = pack_size.Text;
complaint.BatchNumber = batch.Text;
complaint.IsBestBefore = bestBeforeQuestion.SelectedIndex;
complaint.BestBeforeDate = best_before.Value;
complaint.QuantityInvolved = quantity.Text;
complaint.Details = details.Text;
complaint.Comments = comments.Text;
ComplaintsValidator validator = new ComplaintsValidator();
ValidationResult results = validator.Validate(complaint);
if (results.IsValid == false)
{
foreach (ValidationFailure failure in results.Errors)
{
errors.Add($"- {failure.ErrorMessage}");
}
string message = string.Join(Environment.NewLine, errors);
MessageBox.Show(message, "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
insertComplaintForm();
}
}
private void insertComplaintForm()
{
var confirm = MessageBox.Show("Are you sure the details you have entered are Correct?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (confirm == DialogResult.Yes)
{
DataAccess db = new DataAccess();
db.InsertComplaint(UserDetails.userId, date.Value, orderNumber.Text, customer_name.Text, customer_contact.Text, telephone.Text, email.Text, customer_ref.Text, product.Text, pack_size.Text, batch.Text, best_before.Value, quantity.Text, details.Text, comments.Text);
clearFields();
}
}
void clearFields()
{
clearBindings();
customer_name.SelectedIndex = -1;
customer_name.ResetText();
date.Value = DateTime.Today;
customer_contact.Clear();
telephone.Clear();
email.Clear();
customer_ref.Clear();
batch.Clear();
orderNumber.Clear();
best_before.ResetText();
quantity.Clear();
details.Clear();
comments.Clear();
bestBeforeQuestion.SelectedIndex = -1;
loadProducts();
product.SelectedIndex = -1;
product.ResetText();
pack_size.Clear();
}
private void saveBtn_Click(object sender, EventArgs e)
{
FormValidation();
}
private void clearBtn_Click(object sender, EventArgs e)
{
clearFields();
}
}
</code></pre>
<p><strong>DataAccess.cs</strong></p>
<pre><code>public class DataAccess
{
public List<ComplaintModel> GetComplaint(string _OrderNumber)
{
throw new NotImplementedException();
}
// Used in "ComplaintForm" to get list of Product and Customer Name from MJM Database.
public List<ComplaintModel> FindOrderNumber(string orderNumber)
{
using(SqlConnection conn = new SqlConnection(ConnectionString.MJMconnString))
{
var output = conn.Query<ComplaintModel>($@"
SELECT
TRIM(p.description) as Product,
p.searchRef1 as PackSize,
c.name AS CustomerName,
c.email as Email,
c.phone as Telephone
FROM SalesOrder so JOIN SalesOrderLine sol ON
so.id = sol.salesOrderID JOIN Customer c ON
so.customerID = c.id JOIN Product p ON
sol.productID = p.id WHERE so.number = '{orderNumber}'").ToList();
return output;
}
}
public List<ComplaintModel> LoadCustomers()
{
using(SqlConnection conn = new SqlConnection(ConnectionString.MJMconnString))
{
var output = conn.Query<ComplaintModel>($@"SELECT name AS CustomerName FROM Customer WHERE dormant = 0;").ToList();
return output;
}
}
public List<ComplaintModel> LoadProducts()
{
using (SqlConnection conn = new SqlConnection(ConnectionString.MJMconnString))
{
var output = conn.Query<ComplaintModel>($@"SELECT CONCAT(description, ' - ', searchRef1) AS Product, searchRef1 AS PackSize FROM product WHERE dormant = 0").ToList();
return output;
}
}
// This is used to send Complaint details into MySQL database for table "CustomerComplaints"
public void InsertComplaint(
int userId,
DateTime date,
string orderNumber,
string customerName,
string customerContactName,
string telephone,
string email,
string customerReference,
string product,
string packSize,
string batchNumber,
DateTime bestBeforeDate,
string quantityInvolved,
string details,
string comments)
{
using(MySqlConnection conn = new MySqlConnection(ConnectionString.ConnString))
{
List<ComplaintModel> complaint = new List<ComplaintModel>();
complaint.Add(new ComplaintModel {
UserId = userId,
Date = date,
OrderNumber = orderNumber,
CustomerName = customerName,
CustomerContactName = customerContactName,
Telephone = telephone,
Email = email,
CustomerReference = customerReference,
Product = product,
PackSize = packSize,
BatchNumber = batchNumber,
BestBeforeDate = bestBeforeDate,
QuantityInvolved = quantityInvolved,
Details = details,
Comments = comments});
conn.Execute(
@"INSERT INTO CustomerComplaints
(UserId, Date, OrderNumber, CustomerName, CustomerContactName, Telephone, Email, CustomerReference, Product, PackSize, BatchNumber,
BestBeforeDate, QuantityInvolved, Details, Comments)
VALUES
(@UserId, @Date, @OrderNumber, @CustomerName, @CustomerContactName, @Telephone, @Email, @CustomerReference, @Product, @PackSize, @BatchNumber,
@BestBeforeDate, @QuantityInvolved, @Details, @Comments)", complaint);
}
}
}
</code></pre>
<p><strong>ComplaintsValidator.cs</strong></p>
<pre><code>public class ComplaintsValidator : AbstractValidator<ComplaintModel>
{
public ComplaintsValidator()
{
RuleFor(p => p.IsCustomerSelected)
.Must(DropDownSelected).WithMessage("'Customer Name' must be valid");
RuleFor(p => p.CustomerContactName)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Length(1, 100);
RuleFor(p => p.Telephone)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Length(1, 40)
.When(p => string.IsNullOrEmpty(p.Email));
RuleFor(p => p.Email)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Length(1, 40)
.When(p => string.IsNullOrEmpty(p.Telephone));
RuleFor(p => p.CustomerReference)
.Cascade(CascadeMode.Stop)
.Length(0, 255);
RuleFor(p => p.IsProductSelected)
.Must(DropDownSelected).WithMessage("'Product Name' must be valid");
RuleFor(p => p.PackSize)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Length(1, 40);
RuleFor(p => p.BatchNumber)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Length(1, 40);
RuleFor(p => p.IsBestBefore).Must(DropDownSelected).WithMessage("Does this product have a Best Before Date?");
RuleFor(p => p.QuantityInvolved)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Length(1, 50);
RuleFor(p => p.Details)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.Length(10, 700);
RuleFor(p => p.Comments)
.Cascade(CascadeMode.Stop)
.Length(0, 700);
}
protected bool DropDownSelected(int item)
{
if (item == -1)
{
return false;
}
else
{
return true;
}
}
}
</code></pre>
<p><strong>Resource</strong></p>
<p>This is the Youtube video I have used to make the queries etc..</p>
<p><a href="https://www.youtube.com/watch?v=Et2khGnrIqc&t=2901s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=Et2khGnrIqc&t=2901s</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T08:42:07.637",
"Id": "496996",
"Score": "0",
"body": "Can you try putting this in your ORD number text box and doing the search? `' UNION ALL SELECT 'Google' as Product, 'SQL' as PackSize, 'Injection' AS CustomerName, 'Attacks,' as Email, 'Please' as Telephone -- ` and see what happens"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T09:13:08.483",
"Id": "496997",
"Score": "0",
"body": "including the `'` before `UNION`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T09:20:45.697",
"Id": "496998",
"Score": "0",
"body": "Yeah, all of it. I'm not that up to date on Dapper but I think you've got a problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T09:21:43.320",
"Id": "496999",
"Score": "0",
"body": "@RobH This is the output: `An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll\nAdditional information: All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T09:32:25.360",
"Id": "497000",
"Score": "0",
"body": "Your app has an SQL Injection vulnerability and I apparently can't count how many columns there are in a select statement. https://www.troyhunt.com/owasp-top-10-for-net-developers-part-1/ - take a look at the \"Anatomy of a SQL injection attack\" section"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T09:33:35.960",
"Id": "497001",
"Score": "1",
"body": "@RobH Thank you - I'll have to add a parameter in my dapper function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T21:01:17.920",
"Id": "497952",
"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>Here is my take on your solution. Please note that some of the things I mention are my personal prefference.</p>\n<p>ComplaintModel</p>\n<ul>\n<li>I preffer to name my <code>Id</code> field like <code>TableNameId</code>, so in your case I would change <code>Id</code> to <code>CustomerComplaintId</code> (please note that this is my personal prefference).</li>\n<li><code>IsCustomerSelected</code> (and <code>IsProductSelected</code>) sounds like a <code>bool</code> flag to me, I see you put <code>SelectedIndex</code> in there. I would rename it to <code>CustomerId</code> and if you need the flag "is selected" then make a new property, make it a bool and change it's value accordingly.</li>\n<li>Regarding DB design are <code>BachNumber</code>, <code>QuantityInvolved</code> numerics? If so consider making them a proper type (int, decimal etc.), both in DB and model.</li>\n</ul>\n<p>ComplaintForm</p>\n<ul>\n<li>Use PascalCase for class, method name and public properties. I would change <code>Complaints_Form</code> to <code>ComplaintsForm</code>, every method where you use camelCase, like <code>loadCustomers</code> -> <code>LoadCustomers</code>.</li>\n<li>I strictly specify modifier for private fields and prefix them with an underscore, in your case the top private fields would become <code>private List<ComplaintModel> _mjmOrderNumber = new List<ComplaintModel>();</code> (please note that this is my personal prefference).</li>\n<li>I'm not sure I understand how you reuse the <code>ComplaintModel</code> for Customers and Products, it seems they should be their own model (entity) which comes from Database.</li>\n<li><code>clearBindings</code> method should be private, no need to expose it outside.</li>\n<li>You construct a new <code>ComplaintModel</code> inside FormValidation and indirectly in insertComplaintform. I would make a helper function which would populate and return your ComplaintModel which you can reuse in two locations mentioned above. You would need to change the DataAccess InsertComplaint method to accept a ComplaintModel instead of multitude of parameters.</li>\n<li>In the end of FormValidation method you execute the insertComplaintForm method, I would change the FormValidation method to return a bool <code>isFormValid</code> and execute the insertComplaintForm in saveBtn_Click event after checking if form is valid. Try and keep methods responsible for a single task.</li>\n<li>This one is food-for-thought and I'd actually like some feedback from others about this - after making numerous "ClearForm", "ClearFields" "EmptyInput" methods I later started reusing a function which would traverse all controls on the form and clear them - if TextBox then <code>Clear()</code> if ComboBox then <code>SelectedIndex = -1</code>. This way I never forgot to clear a field I added long time after I implemented the original functionality.</li>\n</ul>\n<p>DataAccess</p>\n<ul>\n<li>I see now what you did with the <code>ComplaintModel</code>, you packed it with all database properties you need later on and simply fill the properties you need for lets say a ComboBox datasource. While this works it makes the <code>ComplaintModel</code> unneccesary complicated. I would return Customer(s) object from LoadCustomers, Product(s) object from LoadProducts and use those for control binding.</li>\n<li>As mentioned above I would change InsertComplaint to accept <code>ComplaintModel</code> object which would be constructed from a helper method in the Form itself.</li>\n</ul>\n<p>ComplaintsValidator</p>\n<ul>\n<li>You can set CascadeMode globally or per Validator, no need to specify it for every Rule. Like this <code>CascadeMode = CascadeMode.Stop</code>;</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T20:29:06.083",
"Id": "252211",
"ParentId": "252009",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T15:58:19.970",
"Id": "252009",
"Score": "4",
"Tags": [
"c#",
"sql",
"mysql",
"winforms",
"dapper"
],
"Title": "Is my structure of program readable?"
}
|
252009
|
<p><strong>Task</strong></p>
<p>This code accomplishes the Time Difference of Arrival (TDoA) multilateration problem (see) using <em>gradient descent</em> (known otherwise as <em>steepest descent</em>).</p>
<p><strong>Goal</strong></p>
<p>I'm looking to:</p>
<p><em>a) Improve speed:</em>
In practice, the algorithm will need to accomplish localizations 'on the fly'. Currently, it takes about a minute or so to perform one, whereas I'd like to perform thousands to hundreds of thousands in a reasonable time frame (unfortunately, I cannot put a number on that right now).</p>
<p><em>b) Improve readability:</em> The code will need to be read many times over, and every ounce counts. The code should be as brief as possible (without sacrificing readability, of course) and easy to follow.</p>
<p>And, of course, if I've overlooked some edge case, etc, that's important as well.</p>
<pre><code>import random
import math
from dataclasses import dataclass
@dataclass
class Vector:
"""Simple vector class to avoid dependencies, could
easily be replaced with Numpy array, e.g."""
x: float
y: float
z: float
def __add__(self, operand):
return Vector(self.x + operand.x,
self.y + operand.y, self.z + operand.z)
def __sub__(self, operand):
return Vector(self.x - operand.x, self.y - operand.y, self.z - operand.z)
def __rmul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar,
self.z * scalar)
def __truediv__(self, scalar):
return Vector(self.x / scalar, self.y / scalar,
self.z / scalar)
def __abs__(self):
return math.sqrt(pow(self.x, 2) + pow(self.y, 2) + pow(self.z, 2))
@dataclass
class Localize:
"""Newton-Raphson localization class."""
a: Vector
b: Vector
c: Vector
d: Vector
@staticmethod
def tend(y, q, dxq):
dyq = abs(y - q)
return (dxq - dyq) * (y - q) / dyq
def find(self, dxa, dxb, dxc, dxd, gamma=1e-3, precision=1e-10, max=int(1e+10)):
y = Vector(0, 0, 0)
for i in range(max):
f = self.tend(y, self.a, dxa) + self.tend(y, self.b, dxb) + self.tend(y, self.c, dxc) + self.tend(y, self.d,
dxd)
y += gamma * f
if abs(f) <= precision:
return y
raise Exception('Max. iterations insufficient.')
def random_point():
return Vector(random.random(), random.random(), random.random())
def test_error():
a = random_point()
b = random_point()
c = random_point()
d = random_point()
x = random_point()
localize = Localize(a, b, c, d)
y = localize.find(abs(x - a), abs(x - b), abs(x - c), abs(x - d))
return abs(x - y)
print(test_error())
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T20:26:20.093",
"Id": "496392",
"Score": "1",
"body": "It sounds like you already know what you need to do - use Numpy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:05:03.297",
"Id": "496474",
"Score": "0",
"body": "if performance is the primary factor, using a c++/c module for python might be better"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T18:54:49.527",
"Id": "252012",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"mathematics"
],
"Title": "Gradient descent algorithm for solving localization problem in 3-dimensional space"
}
|
252012
|
<p>Here is my beginner code for dealing with a linked list. I appreciate any comments on structure, logic, formatting, and anything small or large. I have run the code using gcc and tested the small <code>main</code> function using Valgrind with no errors.</p>
<p><strong>ll.h</strong></p>
<pre><code>#ifndef LL_H
#define LL_H
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct ll_LinkedList ll_LinkedList;
typedef struct ll_LinkedListNode ll_LinkedListNode;
struct ll_LinkedList {
ll_LinkedListNode* head;
};
struct ll_LinkedListNode {
void* data;
ll_LinkedListNode* next;
};
ll_LinkedList* ll_create ();
void ll_destroy (ll_LinkedList* ll);
void ll_append (ll_LinkedList* ll, void* data);
void* ll_at (ll_LinkedList* ll, size_t pos);
void ll_clear (ll_LinkedList* ll);
void ll_insert (ll_LinkedList* ll, size_t pos, void* data);
void* ll_remove (ll_LinkedList* ll, size_t pos);
bool ll_is_empty (ll_LinkedList* ll);
size_t ll_length (ll_LinkedList* ll);
void ll_prepend (ll_LinkedList* ll, void* data);
#endif
</code></pre>
<p><strong>ll.c</strong></p>
<pre><code>#include "ll.h"
void ll_append(ll_LinkedList* ll, void* data) {
ll_insert(ll, ll_length(ll), data);
}
void* ll_at(ll_LinkedList* ll, size_t pos) {
ll_LinkedListNode* node = ll->head;
while (pos > 0) {
node = node->next;
pos--;
}
return node->data;
}
void ll_clear(ll_LinkedList* ll) {
ll_LinkedListNode* node = ll->head;
while (node != NULL) {
ll_LinkedListNode* next = node->next;
free(node);
node = next;
}
ll->head = NULL;
}
ll_LinkedList* ll_create() {
ll_LinkedList* ll = malloc(sizeof(*ll));
ll->head = NULL;
return ll;
}
void ll_destroy(ll_LinkedList* ll) {
ll_LinkedListNode* node = ll->head;
while (node != NULL) {
ll_LinkedListNode* next = node->next;
free(node);
node = next;
}
free(ll);
}
void ll_insert(ll_LinkedList* ll, size_t pos, void* data) {
assert(pos <= ll_length(ll));
ll_LinkedListNode* new_node = malloc(sizeof(*new_node));
new_node->data = data;
if (ll->head == NULL) {
new_node->next = NULL;
ll->head = new_node;
}
else if (pos == 0) {
new_node->next = ll->head;
ll->head = new_node;
}
else {
ll_LinkedListNode* node = ll->head;
while (pos > 1) {
node = node->next;
pos--;
}
new_node->next = node->next;
node->next = new_node;
}
}
bool ll_is_empty(ll_LinkedList* ll) {
return ll_length(ll) == 0;
}
size_t ll_length(ll_LinkedList* ll) {
size_t length = 0;
ll_LinkedListNode* node = ll->head;
while (node != NULL) {
node = node->next;
length++;
}
return length;
}
void ll_prepend(ll_LinkedList* ll, void* data) {
ll_insert(ll, 0, data);
}
void* ll_remove(ll_LinkedList* ll, size_t pos) {
assert(pos <= ll_length(ll));
if (pos == 0) {
ll_LinkedListNode* rm = ll->head;
ll->head = rm->next;
void* data = rm->data;
free(rm);
return data;
}
else {
ll_LinkedListNode* h = ll->head;
ll_LinkedListNode* t = h->next;
while (pos > 1) {
h = h->next;
t = t->next;
pos--;
}
h->next = t->next;
void* data = t->data;
free(t);
return data;
}
}
int main() {
int a = 1;
int b = 2;
int c = 3;
int d = 4;
ll_LinkedList* ll = ll_create();
ll_insert(ll, 0, &c);
ll_insert(ll, 0, &b);
ll_insert(ll, 0, &a);
ll_insert(ll, 2, &d);
ll_insert(ll, 4, &d);
ll_clear(ll);
ll_insert(ll, 0, &c);
ll_insert(ll, 0, &b);
ll_insert(ll, 0, &a);
printf("Removed: %d\n", *((int*) ll_remove(ll, 0)));
printf("Removed: %d\n", *((int*) ll_remove(ll, 0)));
printf("Removed: %d\n", *((int*) ll_remove(ll, 0)));
ll_insert(ll, 0, &c);
ll_insert(ll, 0, &b);
ll_insert(ll, 0, &a);
printf("Removed: %d\n", *((int*) ll_remove(ll, 1)));
if (!ll_is_empty(ll)) {
printf("It is not empty.\n");
}
ll_clear(ll);
if (ll_is_empty(ll)) {
printf("It is empty.\n");
}
ll_append(ll, &a);
ll_append(ll, &b);
ll_append(ll, &c);
ll_prepend(ll, &c);
ll_prepend(ll, &c);
printf("Length: %ld\n", ll_length(ll));
for (size_t i = 0; i < ll_length(ll); ++i) {
printf("%d, ", *((int*) ll_at(ll, i)));
}
printf("null\n");
ll_destroy(ll);
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>I recommend some additional compiler warning options:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -std=c17 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion 252015.c -o 252015\n252015.c:22:1: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n ll_LinkedList* ll_create ();\n ^~~~~~~~~~~~~\n252015.c:60:16: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n ll_LinkedList* ll_create() {\n ^~~~~~~~~\n252015.c:144:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]\n int main() {\n ^~~~\n</code></pre>\n<hr />\n<p>Most of the <code>#include</code> lines are not needed for the header file, only by the implementation. In particular, these three can be moved to <code>ll.c</code>:</p>\n<pre><code>#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n</code></pre>\n<hr />\n<p><code>while (node != NULL)</code> is a little long-winded; it's idiomatic to simply write <code>while (node)</code>. Some coding standards disallow that, in which case you may be required to use the long form.</p>\n<hr />\n<pre><code> ll_LinkedList* ll = malloc(sizeof(*ll));\n ll->head = NULL;\n</code></pre>\n\n<pre><code> ll_LinkedListNode* new_node = malloc(sizeof(*new_node));\n new_node->data = data;\n</code></pre>\n<p>These are problems waiting to happen - <code>ll</code> or <code>new_node</code> might be a null pointer, and we failed to check.</p>\n<hr />\n<pre><code>void* ll_remove(ll_LinkedList* ll, size_t pos) {\n assert(pos <= ll_length(ll));\n</code></pre>\n<p><code>ll_remove()</code> is a public function, so we're in no position to vouch for the condition we're asserting. That should be a real check rather than an <code>assert()</code>:</p>\n<pre><code> if (pos <= ll_length(ll) {\n return NULL;\n }\n</code></pre>\n<p>I don't like the way this function walks the list twice (once in <code>ll_length()</code> and then again to actually do the insert. It would be more efficient to just check for going off the end of the list as we traverse it, just once. <code>ll_append()</code> traverses the list <em>three</em> times!</p>\n<hr />\n<p><code>ll_destroy()</code> could simply delegate most of its work to <code>ll_clear()</code>.</p>\n<hr />\n<p>The special-casing for element 0 in many functions could be removed by using an empty element as list head.</p>\n<hr />\n<p>A final style point that might be contentious - I would write <code>sizeof *p</code> rather than <code>sizeof(*p)</code>, only using parens around the argument in the rare cases you actually need to use a type name as argument to the <code>sizeof</code> operator (and I do prefer a space after the keyword, unlike the non-alphabetic unary operators such as <code>-</code> and <code>++</code>). So <code>sizeof (struct tm)</code>, for example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:09:56.420",
"Id": "496419",
"Score": "0",
"body": "Thanks very much for the detailed pass! I've made a number of changes thanks to this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T09:22:36.247",
"Id": "496444",
"Score": "1",
"body": "Regarding \"while (node != NULL)\", that's debatable. The MISRA C guidelines actually say that this should *not* be done. More specifically, they say \"if (node)\" should be reserved for Boolean values, because using it to test for zero/non-zero or null/non-null is a common cause of people misunderstanding the code when maintaining it. The OP should be aware of the idiom, but they shouldn't necessarily adopt it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T00:41:17.280",
"Id": "496534",
"Score": "0",
"body": "I'd recommend keeping the ```include```s and using header guards. See https://stackoverflow.com/questions/1804486/should-i-use-include-in-headers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:20:57.020",
"Id": "496640",
"Score": "0",
"body": "@thzoid: The point is that those includes are not needed by *users* of the library, only by the implementation. So users shouldn't have to pay the price, and they don't belong in our header. If you read [the top-voted answer](https://stackoverflow.com/a/1804719/4850040) to the question you linked, that's exactly what it recommends, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:22:14.370",
"Id": "496641",
"Score": "0",
"body": "Direct quote: \"*if the implementation file needs some other headers, so be it, and it is entirely normal for some extra headers to be necessary. But the implementation file (`magicsort.c`) should include them itself, and not rely on its header to include them. The header should only include what users of the software need; not what the implementers need.*\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T18:29:52.257",
"Id": "496692",
"Score": "0",
"body": "@toby-spleight My bad, I misread your answer and didn't realize OP wrote the includes into the header."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:55:00.470",
"Id": "252018",
"ParentId": "252015",
"Score": "16"
}
},
{
"body": "<p>For a beginner the code is neat. Most is already given by the previous, much more elaborate answer.</p>\n<p><em>One thing though w.r.t. coding:</em>\nC is unique in that it can use <em>aliases</em>, pointers to a variable/field.</p>\n<p>For instance below <code>current</code> first is an alias of <code>head</code> and after that of a node's <code>next</code>. With <code>*current = ...</code> you can fill the original variable.</p>\n<pre><code>void ll_insert(ll_LinkedList* ll, size_t pos, void* data) {\n assert(ll != NULL);\n // Not needed: assert(pos <= ll_length(ll));\n \n ll_LinkedListNode** current = &ll->head;\n //while (*current != NULL && pos > 0) {\n while (*current && pos > 0) {\n current = &(*current)->next;\n --pos;\n }\n // Maybe check here that pos reached 0.\n ll_LinkedListNode* new_node = malloc(sizeof(*new_node));\n new_node->data = data;\n new_node->next = *current;\n *current = new_node;\n}\n</code></pre>\n<p>As you see this gives very compact code.</p>\n<p>ll_LinkedListNode's struct declaration could move to the .c implementation with a bit of trickery.</p>\n<p>In an other language it is customary to hold in ll_LinkedList redundantly the <em>list size</em> for faster operations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T22:21:55.817",
"Id": "496409",
"Score": "3",
"body": "We don't call that an alias though, it's a pointer to a pointer. I'm sure there are other languages besides C and C++ which can do this! Note that if you use pointers to pointers, you can call yourself a two-star programmer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T22:33:43.773",
"Id": "496413",
"Score": "2",
"body": "@G.Sliepen yes _alias_ (_aliasing_) is a term I interned studying programming language design and compiler construction in Computer Science. Being a pointer to a pointer, to an existing variable or field, such pee2pees should be used locally in a smaller scope than the pointed to pointer. Yes there are some other languages, but mainstream Java cannot do this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:13:37.480",
"Id": "496420",
"Score": "0",
"body": "Thank you @JoopEggen, I have been trying to understand the double pointers in most linked lists I find and this is helpful. I will also migrate the length to be a struct member. Could you elaborate on how to move the struct declaration into the .c file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:21:50.863",
"Id": "496423",
"Score": "2",
"body": "I am not active in C since sufficient years. Then I did #ifndef's so one would have a typedef void* LinkNodePtr for all API users, and in the C typedef struct {...} *LinkNodePtr. Check whether this trick is still done, maybe nicer today."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:31:31.800",
"Id": "496438",
"Score": "3",
"body": "The `typedef` trick is still done, but considered bad style by many here since it hides C's own way of writing a pointer."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T22:10:16.030",
"Id": "252020",
"ParentId": "252015",
"Score": "6"
}
},
{
"body": "<h2>Design</h2>\n<p>Your list includes the head of the list.</p>\n<pre><code>struct ll_LinkedList {\n ll_LinkedListNode* head;\n};\n</code></pre>\n<p>You could make a lot of your code a lot simpler by including two other values (the tail and the length).</p>\n<pre><code>struct ll_LinkedList {\n ll_LinkedListNode* head;\n ll_LinkedListNode* tail;\n size_t size;\n};\n</code></pre>\n<p>This would make sure you don't have to keep calculating the size and would make appending really easy.</p>\n<h2>Code Review:</h2>\n<pre><code>#include "ll.h"\n\nvoid ll_append(ll_LinkedList* ll, void* data) {\n ll_insert(ll, ll_length(ll), data); // doubles the cost of the insert\n // you have to traverse the list\n // twice.\n}\n</code></pre>\n<hr />\n<p>What happens if <code>pos</code> is beyond the end?</p>\n<pre><code>void* ll_at(ll_LinkedList* ll, size_t pos) {\n ll_LinkedListNode* node = ll->head;\n while (pos > 0) {\n node = node->next;\n pos--;\n }\n return node->data;\n}\n</code></pre>\n<hr />\n<p>You should validate that ll is not <code>NULL</code> before assigning.</p>\n<pre><code>ll_LinkedList* ll_create() {\n ll_LinkedList* ll = malloc(sizeof(*ll));\n ll->head = NULL;\n return ll;\n}\n</code></pre>\n<hr />\n<p>Simplify the destroy:</p>\n<pre><code>void ll_destroy(ll_LinkedList* ll) {\n ll_clear(ll);\n free(ll);\n}\n</code></pre>\n<hr />\n<pre><code>void ll_insert(ll_LinkedList* ll, size_t pos, void* data) {\n\n // assuming pos is in range. \n while (pos > 1) {\n node = node->next;\n pos--;\n }\n</code></pre>\n<hr />\n<p>Some repeated code you could remove from the if statement.</p>\n<pre><code>void* ll_remove(ll_LinkedList* ll, size_t pos) {\n if (pos == 0) {\n\n // STUFF\n void* data = rm->data;\n free(rm);\n return data;\n }\n else {\n // STUFF\n void* data = t->data;\n free(t);\n return data;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:21:49.637",
"Id": "496422",
"Score": "0",
"body": "Thanks! This included a number of suggestions -- I accepted the current answer because it came first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T00:17:05.217",
"Id": "496426",
"Score": "1",
"body": "@sdasdadas Do not worry, just upvote any answer you feel tackles your problem. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T04:09:16.407",
"Id": "496542",
"Score": "0",
"body": "Disagree with tripling the size of the head node. When linked list are used a lot in user code, _many_ of them are empty. The size of an empty LL is good to keep small. As far a having ready access to the head and tail, the \"head\" node can save the tail instead and have the tail.next point to the head."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T22:34:59.063",
"Id": "252021",
"ParentId": "252015",
"Score": "11"
}
},
{
"body": "<p><strong>Use <code>const</code> when able</strong></p>\n<p>Functions like <code>ll_at()</code> and <code>ll_length()</code> could code with <code>const</code> to better convey code's usage and allow some select usages and optimizations.</p>\n<pre><code>// void* ll_at(ll_LinkedList* ll, size_t pos);\nvoid* ll_at(const ll_LinkedList* ll, size_t pos);\n\n// size_t ll_length(ll_LinkedList* ll);\nsize_t ll_length(const ll_LinkedList* ll);\n</code></pre>\n<p><strong>Code looks nice, but ...</strong></p>\n<p>Pretty layout is work. IMO, not worth the effort/time to code and <em>maintain</em> versus simply using an auto-formatter. (Consider work incorporating the <code>const</code> idea above.)</p>\n<pre><code>ll_LinkedList* ll_create ( void);\nvoid ll_destroy ( ll_LinkedList* ll);\n\nvoid ll_append ( ll_LinkedList* ll, void* data);\nvoid* ll_at (const ll_LinkedList* ll, size_t pos);\nvoid ll_clear ( ll_LinkedList* ll);\n</code></pre>\n<p>vs.</p>\n<pre><code>ll_LinkedList * ll_create(void);\nvoid ll_destroy(ll_LinkedList *ll);\nvoid ll_append(ll_LinkedList *ll, void *data);\nvoid* ll_at(const ll_LinkedList *ll, size_t pos);\nvoid ll_clear(ll_LinkedList *ll);\n</code></pre>\n<p>I'd have comments per function, so there common manual format layout is not important.</p>\n<p><strong>Apply</strong></p>\n<p>Consider an <em>apply</em> function, something that applies the function to every link's data. Very useful.</p>\n<pre><code>int ll_apply(ll_LinkedList* ll, int f(void *state, void *data), void *state) {\n ll_LinkedListNode* node = ll->head;\n while (node != NULL) {\n int retval = f(state, node->data);\n\n // maybe break on non-zero?\n if (retval) return retval;\n \n node = node->next;\n }\n return 0;\n}\n</code></pre>\n<p><strong>Use correct specifier with <code>size_t</code></strong></p>\n<pre><code>// printf("Length: %ld\\n", ll_length(ll));\nprintf("Length: %zu\\n", ll_length(ll));\n</code></pre>\n<p><strong>Could collapse code</strong></p>\n<pre><code>if (ll->head == NULL) {\n new_node->next = NULL;\n ll->head = new_node;\n}\nelse if (pos == 0) {\n new_node->next = ll->head;\n ll->head = new_node;\n}\n</code></pre>\n<p>vs</p>\n<pre><code>if (ll->head == NULL || pos == 0) {\n new_node->next = ll->head;\n ll->head = new_node;\n}\n</code></pre>\n<p><strong>Include trick</strong></p>\n<p>When the unnecessary <code>#include</code>s move from <code>ll.h</code> to <code>ll.c</code>, include <code>ll.h</code> there first:</p>\n<pre><code>// ll.c\n#include "ll.h"\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n</code></pre>\n<p>This helps verify <code>ll.h</code> does indeed compile on its own.</p>\n<p><strong>Lack of comments</strong></p>\n<p>IMO, the .h file deserves a fair amount of comment to let users know what the set does. Assume the user does <strong>not</strong> have access to the .c file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T04:23:44.873",
"Id": "252093",
"ParentId": "252015",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "252018",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:23:45.550",
"Id": "252015",
"Score": "10",
"Tags": [
"c",
"linked-list"
],
"Title": "C Linked List Code Style"
}
|
252015
|
<p>I'm doing a planning tool for users around the world. A feature is that something has to be ready at a user-specified time of day. I imagine this being a TimeSpan. For argument sake let's say 8 AM.</p>
<p>The answer seems easy at first <code>DateTimeOffset.Now.Today.AddDays(1).Add(TimeSpan.FromHours(8))</code> but that will not generate the right answer.</p>
<p>First thing is that 8 AM could be today and not tomorrow. Let's say the time is now 3 AM. 8 AM is just 5 hours away and not 29 hours away. Easily solved, but it gets harder from here...</p>
<p>2nd thing that provides a challenge is the user's timezone. Let's say the user is located at 55.692756, 12.599010 (The Little Mermaid in Copenhagen, Denmark). How is the position translated into timezone info and applied correctly?</p>
<p>3rd thing is daylight savings time. We might have to add or subtract 1 hour.</p>
<p>I'm asking because I haven't found an elegant way to express this in C#.</p>
<p>Here is what I've come up with so far. I'm using the following nuget packages:</p>
<ul>
<li>GeoTimeZone</li>
<li>TimeZoneConverter</li>
</ul>
<pre><code>var readyBy = TimeSpan.FromHours(8);
// Convert user position into time zone
var userIanaTimeZone = TimeZoneLookup.GetTimeZone(55.692756, 12.599010).Result;
var userWindowsTimeZone = TZConvert.IanaToWindows(userIanaTimeZone);
var userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(userWindowsTimeZone);
// Get the local time for the user
var userNow = DateTimeOffset.UtcNow.ToOffset(userTimeZone.BaseUtcOffset);
// Get the local date for the user
var userNowDate = userNow - userNow.TimeOfDay;
// Get ready at 8 AM today or tomorrow - whatever comes first
var readyAt = userNow < userNowDate + readyBy
? userNowDate + readyBy
: userNowDate.AddDays(1) + readyBy;
// Possible ajustment to daylight saving time
var daylightSavingTimeAjustment = userTimeZone.GetUtcOffset(readyAt) - userTimeZone.GetUtcOffset(userNow);
readyAt = (readyAt + daylightSavingTimeAjustment).ToOffset(readyAt.Offset + daylightSavingTimeAjustment);
</code></pre>
<p>Let me know if it is or or possible improvements/bugs</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T22:15:22.480",
"Id": "496407",
"Score": "0",
"body": "Guessing that location is not a right way to get a Localtime offset because you're not always have access to obtain the coords. Other thing, I'm as user is traveling accross the Globe and want to keep OS in my home Localtime. I can set it in OS settings and it will no has effect on your application. Use OS or Browser's Localtime by default and (optional) allow user to change Time Zone in the profile settings. The target of this suggestion is the same as the most of other software behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T22:38:42.873",
"Id": "496415",
"Score": "0",
"body": "Thank you for your feedback @aepot. I have the correct coordinates of the user as it is a gps tracker in a vehicle"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T07:30:18.490",
"Id": "496437",
"Score": "0",
"body": "Doesn't https://nodatime.org/ solve this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T09:31:33.243",
"Id": "496445",
"Score": "0",
"body": "@BCdotWEB possibly could you give a link to where such an example is shown?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T19:15:22.877",
"Id": "496697",
"Score": "0",
"body": "You can acchieve the same with `var userNowDate = userNow.Date;` assuming you want only a date (at 00:00:00)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:48:11.153",
"Id": "252016",
"Score": "5",
"Tags": [
"c#"
],
"Title": "At 8:00 AM in C#"
}
|
252016
|
<p>From my experience in C# programming I think that DI is important. But it's not possible to do it same way in Rust. There are some DI frameworks but I've come with an idea on how it can be made and decided to implement it my way. My implementation uses only constructor injection, no container needed. I'm only learning Rust now so can you review my code, find possible pitfalls, suggest improvements or better approaches?</p>
<p>My goals in DI:</p>
<ol>
<li>Make stubs possible for testing.</li>
<li>Systems shouldn't know "sub-dependencies" of their dependencies. Separate construction and providing dependencies from actual usage. All dependencies are "wired" in one place.</li>
<li>No global shared state.</li>
<li>The design principle that higher level systems declare what they need and lower level systems implement it, not other way.</li>
<li>Avoid God objects.</li>
<li>All dependencies can be clearly determined by a constructor signature, no looking inside code needed. Therefore I don't use Resource Locator pattern.</li>
</ol>
<pre><code>#[cfg(not(feature = "test"))]
mod Bindings {
// real implementations binding
// I assume only one implementor per each interface
// this is not always the case but al least it's good for a simple scenario
pub type Door = crate::Autocar::DoorMod::DoorImpl;
pub type Engine = crate::Autocar::EngineMod::EngineImpl;
}
// how can I move these into actual tests files?
#[cfg(all(feature = "test", feature = "test1"))]
mod Bindings {
// stubs for test1 can be binded here
pub type Door = crate::Autocar::DoorMod::DoorImpl;
pub type Engine = crate::Autocar::EngineMod::EngineImpl;
}
#[cfg(all(feature = "test", feature = "test2"))]
mod Bindings {
// stubs for test2 can be binded here
pub type Door = crate::Autocar::DoorMod::DoorImpl;
pub type Engine = crate::Autocar::EngineMod::EngineImpl;
}
// prelude for internal use
mod Usings {
pub use crate::Bindings::*;
pub use std::cell::RefCell;
pub use std::rc::Rc;
pub type Mrc<T> = Rc<RefCell<T>>; // Mutable Reference Counter
pub fn Mrc<T>(v: T) -> Mrc<T> {
Rc::new(RefCell::new(v))
}
}
fn main() {
// this code performs constructor injection itself
// all constructors are called here
use Autocar::*;
use Usings::*;
let engine = Mrc(Engine::new());
// also we can make factory methods
let make_door = || -> Door { Door::new(engine.clone()) };
let doors = vec![make_door(), make_door()];
let mut car = Car::new(engine, doors);
// all constructed, now run something
car.doors[0].open();
}
// now application code
mod Autocar {
use crate::Usings::*;
// top-level struct so no interface
pub struct Car {
// Since same Engine is used also by a Door too, I have to use Mrc.
// This may become an issue as once a dependency becomes
// used by multiple structs I have to change it everywhere to Mrc
// and insert borrow_mut() everywhere.
// Which doesn't look like a good design. But no choice. Or?
pub engine: Mrc<Engine>,
pub doors: Vec<Door>,
}
impl Car {
pub fn new(engine: Mrc<Engine>, doors: Vec<Door>) -> Car {
Car { engine, doors }
}
}
// declare Car dependencies:
// we actually need IDoor so stubs can inherit it and reflect signature changes when refactoring
pub trait IDoor {
fn is_opened(&self) -> bool;
fn open(&mut self);
}
pub trait IEngine {
fn is_running(&self) -> bool;
fn start(&mut self);
fn stop(&mut self);
}
pub(crate) mod DoorMod {
use super::*;
use crate::Usings::*;
pub struct DoorImpl {
// I tried to design the code in a way so that DI doesn't prevent optimizations.
// So I don't use IEngine here or otherwise it becomes dyn implicitly and then
// no inlining and can't be placed on the stack.
// But one issue with this approach is that IntelliSense can see
// all EngineImpl functions even if it implements multiple traits, not just IEngine.
// But a stub will contain only interface-declared functions
// so it will be at least checked by the compiler.
engine: Mrc<Engine>,
}
impl IDoor for DoorImpl {
fn is_opened(&self) -> bool {
unimplemented!()
}
fn open(&mut self) {
if self.engine.borrow().is_running() {
self.engine.borrow_mut().stop();
}
println!("opening")
}
}
impl DoorImpl {
pub fn new(engine: Mrc<Engine>) -> Self {
DoorImpl { engine }
}
}
}
pub(crate) mod EngineMod {
use super::*;
use crate::Usings::*;
pub struct EngineImpl;
impl IEngine for EngineImpl {
fn is_running(&self) -> bool {
true
}
fn start(&mut self) {
println!("starting");
}
fn stop(&mut self) {
println!("stopping");
}
}
impl EngineImpl {
pub fn new() -> Self {
EngineImpl {}
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Don't try to follow C# DI patterns in Rust. That path will lead you to nothing but pain. Rust is very different from C#, and the sort of patterns that make sense there won't fly in Rust.</p>\n<pre><code>#[cfg(all(feature = "test", feature = "test2"))]\nmod Bindings {\n // stubs for test2 can be binded here\n pub type Door = crate::Autocar::DoorMod::DoorImpl;\n pub type Engine = crate::Autocar::EngineMod::EngineImpl;\n}\n</code></pre>\n<p>This is horrific abuse of the cfg feature. Do NOT do this. Cfg settings are project-wide bits of configuration and not suited to changing out different configurations for testing scenarios.</p>\n<p>The answer, most of the time, is that you don't need to stub things for testing. That's an antipattern you learned in other languages that you need to unlearn in Rust.</p>\n<p>In the small number of cases that you really do to stub things out, use generics:</p>\n<pre><code>struct Car<Engine: IEngine, Door: IDoor>\n</code></pre>\n<p>Then you can simply instantiate with different implementions of your traits.</p>\n<pre><code>pub use std::cell::RefCell;\npub use std::rc::Rc;\npub type Mrc<T> = Rc<RefCell<T>>; // Mutable Reference Counter\npub fn Mrc<T>(v: T) -> Mrc<T> {\n Rc::new(RefCell::new(v))\n}\n</code></pre>\n<p>If you find yourself reaching for RefCell or Rc in Rust, it means you need to rethink your design. They are sometimes neccessary, but usually it means you are still thinking in another language.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T12:58:20.837",
"Id": "496566",
"Score": "0",
"body": "\"struct Car<Engine: IEngine, Door: IDoor>\" - this breaks the #2 item in my list. Everyone who uses Car now knows dependencies of it: Engine and Door."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T13:22:55.413",
"Id": "496569",
"Score": "0",
"body": "\"The answer, most of the time, is that you don't need to stub things for testing.\" - why? Integration testing is cool but when you need to test your struct independently from its dependencies how would you do this in Rust besides inserting generics everywhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T13:26:39.923",
"Id": "496570",
"Score": "0",
"body": "\"If you find yourself reaching for RefCell or Rc in Rust, it means you need to rethink your design.\" - isn't it common to have a subsystem that is used by multiple other systems? E.g. it can be MailSender which also tracks statistics on sent mails, and multiple parts of your app would use it in a mutable way. How would you do it without Rc/RefCell?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:54:40.930",
"Id": "496614",
"Score": "0",
"body": "@Vlad, I'd be happy to answer your questions. But, what I'd suggest is that you pick a real example that we could look at. This example doesn't do anything, so I can't give anything beyond really abstract advice on these subjects. If you had an example which you thought was helped by using this DI approach (maybe one not even in Rust), I could give more helpful indication of how it could be solved without using these Di techniques."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T00:05:34.670",
"Id": "496620",
"Score": "0",
"body": "If you insist, you can avoid the necessity of users of Car knowing about its dependencies using an ICar trait. Users of Car would then only use it via the trait, thus not needing to know about its dependencies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T00:06:49.207",
"Id": "496621",
"Score": "0",
"body": "As for testing, the answers are 1) Rust code simply requires less testing because its type system catches more errors. 2) Many tests can be structured so as to avoid requiring dependencies 3) testing in isolation is overrated, most of the time its a better test if done with the real dependencies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T00:15:31.810",
"Id": "496622",
"Score": "0",
"body": "The DI technique of implement a subsystem as a struct with pointers to other subsystems that it interacts is something we simply do not do in Rust. What to do instead is really hard to answer in the abstract."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T06:03:48.517",
"Id": "252095",
"ParentId": "252017",
"Score": "0"
}
},
{
"body": "<p>I didn't want to use generics because I thought that all dependency users would be forced to specify all subdependencies too. It turned out to be false in Rust. Here is what I mean:</p>\n<pre><code>mod Usings {\n pub use std::cell::RefCell;\n pub use std::rc::Rc;\n pub type Mrc<T> = Rc<RefCell<T>>; // Mutable Reference Counter\n pub fn Mrc<T>(v: T) -> Mrc<T> {\n Rc::new(RefCell::new(v))\n }\n}\n\nfn main() {\n // this code performs constructor injection itself\n // all constructors are called here\n\n use Autocar::DoorMod::*;\n use Autocar::EngineMod::*;\n use Autocar::*;\n use Usings::*;\n\n let engine = Mrc(Engine::new());\n\n // also we can make factory methods\n let make_door = || -> Door<Engine> { Door::new(engine.clone()) };\n\n let doors = vec![make_door(), make_door()];\n let mut car = Car::new(engine, doors);\n\n // all constructed, now run something\n car.doors[0].open();\n}\n\n// now application code\nmod Autocar {\n use crate::Usings::*;\n\n // top-level struct so no interface\n pub struct Car<TEngine: IEngine, TDoor: IDoor> {\n // Since same Engine is used also by a Door too, I have to use Mrc.\n // This may become an issue as once a dependency becomes\n // used by multiple structs I have to change it everywhere to Mrc\n // and insert borrow_mut() everywhere.\n // Which doesn't look like a good design. But no choice. Or?\n pub engine: Mrc<TEngine>,\n\n pub doors: Vec<TDoor>,\n }\n\n impl<TEngine: IEngine, TDoor: IDoor> Car<TEngine, TDoor> {\n pub fn new(engine: Mrc<TEngine>, doors: Vec<TDoor>) -> Self {\n Car { engine, doors }\n }\n }\n\n // declare Car dependencies:\n\n pub trait IDoor {\n fn is_opened(&self) -> bool;\n fn open(&mut self);\n }\n\n pub trait IEngine {\n fn is_running(&self) -> bool;\n fn start(&mut self);\n fn stop(&mut self);\n }\n\n pub(crate) mod DoorMod {\n use super::*;\n use crate::Usings::*;\n\n pub struct Door<TEngine: IEngine> {\n engine: Mrc<TEngine>,\n }\n\n impl<TEngine: IEngine> IDoor for Door<TEngine> {\n fn is_opened(&self) -> bool {\n unimplemented!()\n }\n\n fn open(&mut self) {\n if self.engine.borrow().is_running() {\n self.engine.borrow_mut().stop();\n }\n println!("opening")\n }\n }\n\n impl<TEngine: IEngine> Door<TEngine> {\n pub fn new(engine: Mrc<TEngine>) -> Self {\n Door { engine }\n }\n }\n }\n\n pub(crate) mod EngineMod {\n use super::*;\n use crate::Usings::*;\n\n pub struct Engine;\n\n impl IEngine for Engine {\n fn is_running(&self) -> bool {\n true\n }\n\n fn start(&mut self) {\n println!("starting");\n }\n\n fn stop(&mut self) {\n println!("stopping");\n }\n }\n\n impl Engine {\n pub fn new() -> Self {\n Engine {}\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-03T15:03:27.297",
"Id": "252988",
"ParentId": "252017",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "252095",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T21:53:43.623",
"Id": "252017",
"Score": "3",
"Tags": [
"rust",
"dependency-injection"
],
"Title": "Simple constructor DI implementation in Rust"
}
|
252017
|
<p>I've created a navigation spacer bar that has a hue background. To separate different aspects of content it was imported to Inkscape then exported as an SVG. It uses base64 image which I’m not sure is the optimal way to achieve
including the image within SVG. The code is below.</p>
<p>This is the result:</p>
<p><a href="https://i.stack.imgur.com/YOcjE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YOcjE.jpg" alt="enter image description here" /></a></p>
<pre><code> <!-- ^^^ Remaking the below Svg -->
<svg id="svg8" viewBox="0 0 208.51721 1.5955585" version="1.1"
width="208.51721mm" height="1.5955585mm" xmlns="http://www.w3.org/2000/svg"
sodipodi:docname="hue_space_bar.svg" xmlns:svg="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)"
xmlns:cc="http://creativecommons.org/ns#">
<defs id="defs2"/>
<sodipodi:namedview id="base" pagecolor="#ffffff" bordercolor="#666666"
borderopacity="1.0" inkscape:pageopacity="0.0" inkscape:pageshadow="2"
inkscape:zoom="0.98994949" inkscape:cx="396.84993" inkscape:cy="45.208726"
inkscape:document-units="mm" inkscape:current-layer="layer1" showgrid="false"
inkscape:window-width="1288" inkscape:window-height="754" inkscape:window-x="156"
inkscape:window-y="156" inkscape:window-maximized="0"/>
<metadata id="metadata5">
<rdf:RDF>
<cc:Work rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
<dc:title/>
</cc:Work>
</rdf:RDF>
</metadata>
<g inkscape:label="Layer 1" inkscape:groupmode="layer" id="layer1" transform="translate(-0.41000891,-0.47546211)">
<image id="image3721" width="208.51721" height="1.5955585" x="0.41000891" y="0.47546211"
xlink:href="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/7QA2UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAABkcAmcAFHZX
ei1vODJ5WVJ0QjJZVmlhNHBkAP/bAEMAAwMDAwMDBAQEBAUFBQUFBwcGBgcHCwgJCAkICxELDAsL
DAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/bAEMBAwMDAwMDBAQEBAUFBQUFBwcGBgcH
CwgJCAkICxELDAsLDAsRDxIPDg8SDxsVExMVGx8aGRofJiIiJjAtMD4+VP/CABEIAAMB4AMBIgAC
EQEDEQH/xAAaAAEAAwEBAQAAAAAAAAAAAAAAAgQFAwYH/8QAGwEAAgMBAQEAAAAAAAAAAAAABAUC
AwYAAQj/2gAMAwEAAhADEAAAAfog3Pyq5Hss/GGLjH8wP9NkYBodZnBnrLN0F2FsCsV8pZ2d0X6L
rAFfc4lhUuhTFSEcogEgFfSkL4ypCX2IS3w6Cvr3UXg2tUUr9beM/nuoBCu+hAVN2QrU2RVTSoB6
OEQhXKBGP//EAB0QAAIDAQADAQAAAAAAAAAAAAACAQMQIAQwMkL/2gAIAQEAAQUC4cYsLBx9UUjF
xDx/mO59E91ilYu1lZHE6x+D/8QAGhEAAgMBAQAAAAAAAAAAAAAAAAQCAxAFIP/aAAgBAwEBPwEi
KiAkc4UxYUKdp8U7IZG8d18qLj//xAAaEQADAAMBAAAAAAAAAAAAAAAABBABAgMy/9oACAECAQE/
ATAuKCs2rZrOgzGPUfjEbGYzeN//xAAUEAEAAAAAAAAAAAAAAAAAAABQ/9oACAEBAAY/AnP/xAAa
EAADAQEBAQAAAAAAAAAAAAAAATEQIEFR/9oACAEBAAE/IeI3p5s+nuILFdXoeOCzwvlY+SFD3gzt
EcrxkCx//9oADAMBAAIAAwAAABAMGJ0PzwIByB6GD7z4EP15yEPz/wAceA//xAAZEQACAwEAAAAA
AAAAAAAAAAAgQQABEDH/2gAIAQMBAT8QDIEsSKW9XO8dDbT/xAAbEQACAgMBAAAAAAAAAAAAAAAQ
QQAgATAxgf/aAAgBAgEBPxAOInk5D2Hq20RkKf/EABYQAAMAAAAAAAAAAAAAAAAAAAEQUP/aAAgB
AQABPxBmzbMFT8cxDYf/2Q== "
style="image-rendering:optimizeQuality" preserveAspectRatio="none" decoding="async"/>
</g>
</svg>
</code></pre>
<p><a href="https://i.stack.imgur.com/MPfEb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MPfEb.jpg" alt="enter image description here" /></a></p>
<p>I’m sure a lot of these tags and meta data are useless, especially <code>pagecolor="#ffffff" bordercolor="#666666"</code>. I’m wondering which parts can safely be removed without breaking the image. Is there a better way to achieve this? How could this be streamlined as much as possible, so the end result is as little code as possible?</p>
<p>Would I be better off using the eyedropper tool, selecting the main colors, then creating a basic SVG with defs and a gradient?</p>
|
[] |
[
{
"body": "<p>For a simpler svg code, you can if you want to study this example that I created for you! It takes up your example of a bar with a straightforward linear gradient. As you can see you can change the colors as you like, the size of your bar (rect)! You can also choose to make your bar responsive in width or not by placing a fixed size in px or percentage! In short, this example gives you a lot of possibilities.</p>\n<pre><code><svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 256 256"\n enable-background="new 0 0 256 256" xml:space="preserve">\n<linearGradient id="grd_0d" x1="0%" y1="0%" x2="100%" y2="0%">\n <stop offset="0" style="stop-color:#FF0000"/>\n <stop offset="0.1" style="stop-color:#FFC000"/>\n <stop offset="0.2" style="stop-color:#FFFB00"/>\n <stop offset="0.3" style="stop-color:#15FF00"/>\n <stop offset="0.5" style="stop-color:#0000FF"/>\n <stop offset="0.6" style="stop-color:#0015FF"/>\n <stop offset="0.8" style="stop-color:#E600Ff"/>\n <stop offset="1" style="stop-color:#FF0000"/>\n</linearGradient>\n<rect width="100%" height="20" fill="url(#grd_0d)"></rect>\n</svg>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T15:20:15.207",
"Id": "499752",
"Score": "0",
"body": "Thanks, this is alot more streamline than my example..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T15:20:59.437",
"Id": "499753",
"Score": "1",
"body": "base64 takes up to much space & inkscape exports loads of junk code with it.."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-11T13:06:49.193",
"Id": "253337",
"ParentId": "252023",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "253337",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:33:20.610",
"Id": "252023",
"Score": "2",
"Tags": [
"image",
"html5",
"svg",
"base64"
],
"Title": "SVG hue navigation bar"
}
|
252023
|
<p>I decided to create a rock, paper, scissors game in C#.</p>
<p>I realised early on that standard if-else evaluation in rock-paper-scissors would take up a lot of code. So I decided to use more efficient choice comparison in my game as you will see below.</p>
<p>Is this an efficient choice comparison? Or should I stick to 'if else'. How could I improve this code? Maybe I am not doing something right?</p>
<p>I am looking for any sort of feedback.</p>
<pre><code>namespace RockPaperScissors
{
public class Weapon
{
public string Name { get; set; }
public string WeakTo { get; set; }
public string StrongTo { get; set; }
}
public static class AvailableOptions
{
public static Weapon[] Options => new Weapon[]
{
new Weapon()
{
Name = "Rock",
WeakTo = "Paper",
StrongTo = "Scissors"
},
new Weapon()
{
Name = "Paper",
WeakTo = "Scissors",
StrongTo = "Rock"
},
new Weapon()
{
Name = "Scissors",
WeakTo = "Rock",
StrongTo = "Paper"
},
};
}
public class RockPaperScissors
{
public string[] PossibleValues = new string[] { "Rock", "Paper", "Scissors" };
public int Rounds { get; set; }
public void StartGame()
{
int roundsCompleted = 0;
while (Rounds > roundsCompleted)
{
Console.WriteLine("Rock");
System.Threading.Thread.Sleep(500);
Console.WriteLine("Paper");
System.Threading.Thread.Sleep(500);
Console.WriteLine("Scissors");
System.Threading.Thread.Sleep(500);
Console.WriteLine("Shoot!");
Ask();
roundsCompleted++;
}
}
private void Ask()
{
Console.WriteLine("----------------------------------");
string input = Console.ReadLine();
Random rnd = new Random();
string consoleInput = PossibleValues[rnd.Next(0, PossibleValues.Length)];
Console.WriteLine(consoleInput);
Console.WriteLine("----------------------------------");
Evaluate(consoleInput, input);
}
private void Evaluate(string ConsoleInput, string UserInput)
{
foreach (Weapon w in AvailableOptions.Options)
{
switch (UserInput)
{
case var _ when UserInput.Trim().ToLower() == w.Name.Trim().ToLower():
switch (w)
{
case var _ when (w.StrongTo == ConsoleInput):
Console.WriteLine("You won");
break;
case var _ when (w.WeakTo == ConsoleInput):
Console.WriteLine("You lost");
break;
default:
Console.WriteLine("Tie");
break;
}
break;
}
}
Thread.Sleep(2000);
Console.Clear();
}
class Program
{
static void Main(string[] args)
{
RockPaperScissors rockPaperScissors = new RockPaperScissors()
{
Rounds = 5,
};
rockPaperScissors.StartGame();
Console.ReadLine();
}
}
}
}
</code></pre>
<p>Thank you CodeReview StackExchange,</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:33:13.700",
"Id": "496492",
"Score": "0",
"body": "`Console.WriteLine(\"----------------------------------\");` can be changed to `Console.WriteLine(new string('-', 30));`. Also `switch-case` of one `case` statement can be changed to simple `if`. Two more things: you may use `enum` instead of `string` for weapon type, and don't create `new Random()` each round, create it once."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:35:34.207",
"Id": "252024",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"classes"
],
"Title": "Rock paper scissors in C# using more efficient choice comparison"
}
|
252024
|
<p>I have this piece of code in my program, where I assign 10000 as the size of the buffer. Now How can I check if the file that I am copying is less than 10000, for example 5000, than how to free the remaining 5000 back?</p>
<p>Thank You.</p>
<pre><code>private void copyFile(File in, File out) {
var buffer = new byte[10000];
try {
FileInputStream dis = new FileInputStream(in);
FileOutputStream dos = new FileOutputStream(out);
int count;
do {
count = dis.read(buffer);
if (count != -1)
dos.write(buffer, 0, count);
} while (count != -1);
dis.close();
dos.close();
} catch (IOException e) {
program.print("Error copying file: " + e.toString() + "\n", null);
}
}
</code></pre>
<p>EDIT: Is there anyway, I can optimize this more?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T04:32:04.530",
"Id": "496429",
"Score": "2",
"body": "You don't free memory. The garbage collector, which runs occasionally, frees memory. Your array will be collected at some point after it goes out of scope. There is a way to ask the GC politely to run. Don't. It knows what it's doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T06:27:58.317",
"Id": "496431",
"Score": "1",
"body": "PLEASE learn your APIs. Copying files by hand is not even yesterday anymore. See `java.nio.file.Files.copy()`"
}
] |
[
{
"body": "<p>Streams should always be closed. You will have resource leaks if your method throws an exception. Either close the streams in a <code>finally</code> block, or use <code>try-with-resources</code> to make sure they get closed.</p>\n<p>Optional curly braces aren't. Skipping them will often lead to bugs when code gets modified later.</p>\n<p>The typical loop structure used for working with streams looks more like</p>\n<pre><code>int charsRead;\nwhile ((charsRead = dis.read(buffer) > 0) {\n // do stuff\n}\n</code></pre>\n<p>10,000 is pretty big for a buffer. That may not be the best choice.</p>\n<p>Please don't swallow the stack trace. That's critical information when this code needs to be debugged later.</p>\n<p>Opinion: <code>var</code> is icky.</p>\n<p>If you apply all these changes, your code might look more like:</p>\n<pre><code>private void copyFile(File in, File out) {\n byte[] buffer = new byte[1024];\n try (FileInputStream dis = new FileInputStream(in);\n FileOutputStream dos = new FileOutputStream(out)) {\n int charsRead;\n while ((buffer = dis.read(buffer) > 0) {\n dos.write(buffer, 0, charsRead);\n }\n } catch (IOException e) {\n //I don't know how to use your logging library to display exception stack trace, so..\n e.printStackTrace(System.err);\n }\n}\n</code></pre>\n<p>Of course, this is assuming that you can't use the rather intuitively named <code>Files.copy()</code> instead. That would be much better.</p>\n<pre><code>private void copyFile(File in, File out) {\n try {\n Files.copy(in.toPath(), out.toPath());\n } catch (IOException e) {\n e.printStackTrace(System.err);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T04:55:11.453",
"Id": "252033",
"ParentId": "252025",
"Score": "5"
}
},
{
"body": "<p>A remark on exception handling.</p>\n<p>Exceptions are meant to communicate to a method's caller that the method did not complete its job.</p>\n<p>In your case, the job is to copy a file. And if, during that process, an exception happens, then most probably, the <code>out</code> file hasn't become a valid copy of the <code>in</code> file. You have to inform your caller of that failure. Informing the user instead is wrong for two reasons:</p>\n<ul>\n<li>If not receiving an exception, your caller method assumes everything was done, will maybe later read that file copy, and get an error or incomplete data, being hard to debug.</li>\n<li>As your method's job has nothing to do with user interface, it's strange to talk to the user. Some top-level activity has to receive exceptions and should know how to inform the user.</li>\n</ul>\n<p>So, it's better to just declare the exceptions that can happen, and let some instance up the call stack decide how to deal with that. Your method should just report its failure to its caller and let him deal with it:</p>\n<pre><code>private void copyFile(File in, File out) throws IOException {\n var buffer = new byte[10000];\n \n FileInputStream dis = new FileInputStream(in);\n FileOutputStream dos = new FileOutputStream(out);\n int count;\n do {\n count = dis.read(buffer);\n if (count != -1)\n dos.write(buffer, 0, count);\n } while (count != -1);\n dis.close();\n dos.close();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T14:45:03.237",
"Id": "252060",
"ParentId": "252025",
"Score": "2"
}
},
{
"body": "<p>Few things to be looked into</p>\n<ol>\n<li>There should be a finally block where all the stream open should be closed, this will make sure that there will not be any open stream even in case of exception from loop.</li>\n</ol>\n<p><a href=\"https://www.javatpoint.com/finally-block-in-exception-handling\" rel=\"nofollow noreferrer\">https://www.javatpoint.com/finally-block-in-exception-handling</a></p>\n<ol start=\"2\">\n<li>Function used for printing exception needs to be changed to System.err or e.printstacktrace().</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T14:08:39.737",
"Id": "252933",
"ParentId": "252025",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "252033",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:45:24.803",
"Id": "252025",
"Score": "2",
"Tags": [
"java",
"performance",
"memory-management"
],
"Title": "Copy file using read and write streams"
}
|
252025
|
<pre><code>std::array < char, 27 > new_alphabet() {
std::array < int, 26 > a;
static std::random_device rd;
static std::mt19937 mte(rd());
std::uniform_int_distribution < int > dist(0, 25);
std::generate(a.begin(), a.end(), [ & ]() {
return dist(mte);
});
std::array < char, 27 > alpha = {
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
};
for (int x = 0; x < 26; x++) {
std::swap(alpha[x], alpha[a[x]]);
}
return alpha;
}
int main() {
for (int i = 0; i < 10000000; i++) {
new_alphabet();
}
return 0;
}
</code></pre>
<p>The above code works fine and creates randomised alphabets, each loop would generate for example:</p>
<pre><code>Y G T X R P D U L H I M V O B E F Z Q W J K A C S N
G Q I J F O P L A K M B D T R C H V Y X S U Z E N W
B O N U C Y K T H Q J F V W L M E S X A P R D Z I G
Q B D C V Z R E W O P L M S N X T H A I K U J Y G F
R J B G M E Z P V Q D Y C H I S O F X L N K T U A W
A M E S D H Q J R K Y P N X G T F B L O U W I Z V C
H E L G M F Q K J A X R S I V N W P T D O Y Z U B C
V S O B F R K A J D H Q T P N E I M X U Y Z C L W G
D E M R P Y S K G O C B A Q I H L J T U F N V X Z W
...
</code></pre>
<p>Generating 10,000,000 alphabets takes ~5 seconds on my 2.6 GHz i7. Compiling with <code>g++ -std=c++11 -O3</code>.</p>
<p>Is this the most efficient approach to this, and if there any optimisations, how can I improve or speed up this code?</p>
<p>The above uses the Mersenne Twister engine for generating 26 random values used to swap the array indexes.</p>
<p>Would it be possible to use an xorshift generator here?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T08:47:16.317",
"Id": "496442",
"Score": "1",
"body": "Why not use `std::shuffle`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T10:26:19.053",
"Id": "496454",
"Score": "0",
"body": "I did initially use std::shuffle however it was twice as slow as the above method."
}
] |
[
{
"body": "<p>This method is biased. Use <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher-Yates shuffle</a>.</p>\n<p><strong>TL;DR</strong>: There are <span class=\"math-container\">\\$26^{26}\\$</span> possible outcomes of <code>a</code>. There are <span class=\"math-container\">\\$26!\\$</span> possible permutations of the alphabet. Since <span class=\"math-container\">\\$26!\\$</span> doesn't evenly divide <span class=\"math-container\">\\$26^{26}\\$</span>, permutations are not equiprobable.</p>\n<hr />\n<p>Regarding speed, I don't think that generating <code>a</code> beforehand is beneficial. It results in 3 memory fetches down the line: <code>alpha[x], tmp = a[x], alpha[tmp]</code>. Generating a random number inside the loop makes only two fetches. It is likely to not be measurable with an alphabet as short as 26 characters, but when shuffling a billion-strong alphabet you'd see the difference.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T01:23:50.420",
"Id": "252028",
"ParentId": "252026",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T23:56:21.620",
"Id": "252026",
"Score": "1",
"Tags": [
"c++",
"performance"
],
"Title": "Fastest method of randomly swapping array indexes / generating random alphabets in C++"
}
|
252026
|
<p>Solving <a href="http://www.usaco.org/index.php?page=viewproblem2&cpid=892" rel="nofollow noreferrer">this</a> problem.</p>
<p>Right now, my solution entails finding the largest sorted sublist, starting from the beginning, all the way to the end. However, I feel like the way I wrote the <code>sorted_sublist</code> function can definitely be improved. Besides that, I'm looking for any way to improve the way I write my code.</p>
<p>My code:</p>
<pre><code>with open("sleepy.in", "r") as fin:
n = int(next(fin))
nums = [int(i) for i in fin.readline().split()]
def sorted_sublist(n, nums):
for i in range(n):
sublist = nums[i:n]
if sublist == sorted(sublist):
return sublist
def main(n, nums):
x = sorted_sublist(n, nums)
return n - len(x)
with open("sleepy.out", "w+") as fout:
print(main(n, nums), file=fout)
</code></pre>
<p><strong>Problem synopsis:</strong>
Given a list of numbers, find the number of steps it would take to sort this list by repeatedly placing the first element of this list into another slot, provided that you do this in an optimal fashion.</p>
<p><strong>Example:</strong></p>
<p>Input:</p>
<pre><code>4
4 3 2 1
</code></pre>
<p>Step 1. Place the 4 to the back of the list: 3, 2, 1, 4</p>
<p>Step 2. Place the 3 to the third index of the list: 2, 1, 3, 4</p>
<p>Step 3. Place the 2 to the second index of the list: 1, 2, 3, 4</p>
<p>Output: 3, as it took three optimal steps to reach a sorted list</p>
|
[] |
[
{
"body": "<p>Nice solution and implementation. Few suggestions:</p>\n<ul>\n<li><strong>Naming</strong>: the name <code>main</code> is generally used for the entry point of the program. In this case, a better name could be <code>steps_to_sort_cows</code>.</li>\n<li><strong>Sublist bounds</strong>: since <code>n</code> is fixed, instead of <code>sublist = nums[i:n]</code> you can write <code>sublist = nums[i:]</code></li>\n</ul>\n<h2>Complexity</h2>\n<p>The time complexity is <span class=\"math-container\">\\$O(n*n*log(n))\\$</span>. Basically, for each cow sort all the remaining cows. Typically, it's considered not optimal for large inputs.</p>\n<p>The space complexity is also not optimal. For each cow two lists are created, one for the new sublist and one for the sorted sublist.</p>\n<h2>Improved</h2>\n<p>To reduce space and time complexity, find the size of the sorted sublist in this way:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def steps_to_sort_cows(n, cows):\n first_sorted_cow = cows[-1]\n sorted_cows = 0\n for c in reversed(cows):\n if c > first_sorted_cow:\n return n - sorted_cows\n first_sorted_cow = c\n sorted_cows += 1\n return 0\n</code></pre>\n<p>Starting from the end, count the number of sorted cows and then return <code>n - sorted_cows</code>.</p>\n<p>This approach takes <span class=\"math-container\">\\$O(n)\\$</span> time and <span class=\"math-container\">\\$O(1)\\$</span> space complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:11:52.370",
"Id": "496477",
"Score": "0",
"body": "I wish they tried the suffixes not from longest to shortest but from shortest to longest, then the complexity analysis would be a bit more interesting :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T06:56:49.323",
"Id": "252036",
"ParentId": "252027",
"Score": "3"
}
},
{
"body": "<p>Some suggestions:</p>\n<ul>\n<li>Use better indentation. Always the same, and especially not just <em>one</em> space. Four spaces are the standard.</li>\n<li>You're inconsistent, I'd replace <code>fin.readline()</code> with another <code>next(fin)</code>.</li>\n<li><code>open</code> has mode <code>'r'</code> by default, no need to specify. And you don't really want <code>+</code> when writing.</li>\n<li>For the file variable, personally I prefer just <code>f</code>, and use <code>fin</code> and <code>fout</code> only when I have both open in parallel (like when the input file has multiple test cases).</li>\n<li>Your solution is to identify the longest sorted suffix and then discount it. A faster and shorter way to do that is to simply pop off from the end as long as it's sorted. And we can use N as sentinel to simplify and speed up a bit further.</li>\n</ul>\n<p>So my rewrite is:</p>\n<pre><code>with open('sleepy.in') as f:\n cows = list(map(int, f.read().split()))\n\nwhile cows.pop() > cows[-1]:\n pass\n\nwith open('sleepy.out', 'w') as f:\n print(len(cows) - 1, file=f)\n</code></pre>\n<p>Alternatively, find the last index where the number didn't go up:</p>\n<pre><code>with open('sleepy.in') as f:\n n = int(next(f))\n cows = list(map(int, next(f).split()))\n\nresult = max(i for i in range(n) if cows[i] <= cows[i-1])\n\nwith open('sleepy.out', 'w') as f:\n print(result, file=f)\n</code></pre>\n<p>(Should better use <code>next</code> and <code>range(n)[::-1]</code>, but meh, I like brevity and we're spending Θ(n) on reading the input anyway.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:02:16.417",
"Id": "496473",
"Score": "0",
"body": "Sorry, I was using the repl tool to write my code, it auto-indents it as such. Your solution is really clever, I had never even thought of that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:05:09.967",
"Id": "496475",
"Score": "0",
"body": "Doesn't it at least always indent by the same amount? Which repl tool is it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:40:38.980",
"Id": "496493",
"Score": "0",
"body": "It defaults to 2 spaces per indent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T01:35:16.533",
"Id": "496537",
"Score": "0",
"body": "by the way, why it is bad practice to include the \"+\" when writing to a file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T10:43:52.847",
"Id": "496555",
"Score": "1",
"body": "@12rhombiingridwnocorners Why did you include the \"+\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T12:28:11.077",
"Id": "496562",
"Score": "0",
"body": "oops, i thought the w+ mode was for when the file didn't exist yet. thanks for the help!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T14:40:18.037",
"Id": "252059",
"ParentId": "252027",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252036",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T00:15:37.563",
"Id": "252027",
"Score": "4",
"Tags": [
"python",
"sorting"
],
"Title": "Best way to find the largest sorted suffix in a list - USACO Sleepy Cow Sorting Python"
}
|
252027
|
<p><a href="https://leetcode.com/problems/string-to-integer-atoi/" rel="nofollow noreferrer">link here</a></p>
<p>I'll include a solution in Python and C++ and you can review one. I'm mostly interested in reviewing the C++ code which is a thing I recently started learning; those who don't know C++ can review the Python code.</p>
<hr />
<h2>Problem statement</h2>
<blockquote>
<p>Implement <code>atoi</code> which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned.</p>
</blockquote>
<h3>Note:</h3>
<blockquote>
<p>Only the space character <code>' '</code> is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−2³¹, 2³¹ − 1]. If the numerical value is out of the range of representable values, 2³¹ − 1 or −2³¹ is returned.</p>
</blockquote>
<h3>Example 1:</h3>
<pre><code>Input: str = "42"
Output: 42
</code></pre>
<h3>Example 2:</h3>
<pre><code>Input: str = " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.
</code></pre>
<h3>Example 3:</h3>
<pre><code>Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
</code></pre>
<h3>Example 4:</h3>
<pre><code>Input: str = "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
</code></pre>
<h3>Example 5:</h3>
<pre><code>Input: str = "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.
</code></pre>
<hr />
<h2><code>str_int.py</code></h2>
<pre><code>def convert(s):
chars = (c for c in s)
ss = []
while True:
try:
current = next(chars)
if (space := current.isspace()) and ss:
break
if (pm := current in '+-') and ss:
break
if not current.isnumeric() and not pm and not space:
break
if not space:
ss.append(current)
except StopIteration:
break
try:
number = int(''.join(ss).strip())
if number < 0:
return max(-2 ** 31, number)
return min(2 ** 31 - 1, number)
except ValueError:
return 0
if __name__ == '__main__':
print(convert(" 48-"))
</code></pre>
<h2><code>str_int.h</code></h2>
<pre><code>#ifndef LEETCODE_STR_TO_INT_H
#define LEETCODE_STR_TO_INT_H
#include <string>
int atoi_impl(const std::string& s, size_t start_idx, size_t end_idx);
int convert_str(const std::string &s);
#endif //LEETCODE_STR_TO_INT_H
</code></pre>
<h2><code>str_int.cpp</code></h2>
<pre><code>#include <string>
#include <iostream>
int atoi_impl(const std::string& s, size_t start_idx, size_t end_idx) {
try {
return std::stoi(s.substr(start_idx, end_idx));
}
catch (const std::out_of_range &e) {
return (s[start_idx] == '-') ? INT32_MIN : INT32_MAX;
}
catch (const std::invalid_argument &e) {
return 0;
}
}
int convert_str(const std::string &s) {
size_t start_idx = 0;
size_t end_idx = s.size();
for (size_t i = 0; i < s.size(); ++i) {
bool digit = std::isdigit(s[i]);
bool pm = s[i] == '+' || s[i] == '-';
bool space = std::isspace(s[i]);
if (i == start_idx && !space && !digit && !pm)
return 0;
if ((space || !digit) && i != start_idx) {
end_idx = i;
break;
}
if (space)
start_idx++;
}
if (start_idx != end_idx)
return atoi_impl(s, start_idx, end_idx);
return 0;
}
int main() {
std::cout << "result1: " << convert_str(" -912332") << "\n";
}
</code></pre>
|
[] |
[
{
"body": "<p>It would be a good idea to add <strong>unit tests</strong> to both implementations, both to demonstrate that the code works as intended, and to allow refactorings with confidence. Include enough tests to excercise <em>all</em> the requirements in the specification (out of range, invalid characters, <code>+</code>/<code>-</code>/nothing, etc).</p>\n<p>I'll review the C++ code in more detail.</p>\n<p>We're missing <code>#include <cctype></code>, needed for <code>std::isspace()</code> and <code>std::isdigit()</code>, and <code>#include <stdexcept></code>.</p>\n<p>The requirement says that "<em>Only the space character ' ' is considered a whitespace character</em>", so we should not be using <code>std::isspace()</code> which will match a wider set of characters, including newline and tab.</p>\n<p>The algorithm is inefficient - there's no reason to traverse the string more than once. We can consider a single character at a time, starting conversion when we see the first non-space character, and finishing at the end of the digits.</p>\n<p>Using <code>std::stoi()</code> is probably outside the spirit of an exercise such as this - you're expected to demonstrate the ability to code the core algorithm!</p>\n<p>We need to be extremely careful to avoid integer overflow. We can't check for it after it's happened, as we're into the world of Undefined Behaviour, making the <em>whole program</em> unspecified! One possibility is to accumulate the result in an unsigned type which has larger range than the corresponding signed type. But be careful when dealing with the most-negative value in the range, which doesn't have a corresponding positive value!</p>\n<hr />\n<h1>Alternative implementation</h1>\n<p>Here's how I would address the problems above. Start with some tests:</p>\n<pre><code>#include <iostream>\n#include <cstdlib>\n\n#define COMPARE(expected, actual) \\\n do { \\\n if (expected != actual) { \\\n ret = EXIT_FAILURE; \\\n std::cerr << "Expected " << (expected) \\\n << " but got " << (actual) \\\n << " from " << #actual << '\\n'; \\\n } \\\n } while (0)\n\nint main()\n{\n int ret = EXIT_SUCCESS;\n COMPARE(0, convert_str(""));\n COMPARE(0, convert_str("0"));\n COMPARE(0, convert_str("-0"));\n COMPARE(1, convert_str("1"));\n COMPARE(1, convert_str(" 1"));\n COMPARE(1, convert_str("1e2"));\n COMPARE(0, convert_str("\\t1"));\n COMPARE(-1, convert_str(" -1"));\n COMPARE(-1, convert_str(" -001"));\n COMPARE(2147483647, convert_str("2147483647"));\n COMPARE(2147483647, convert_str("2147483648"));\n COMPARE(-2147483648, convert_str("-2147483648"));\n COMPARE(-2147483648, convert_str("-2147483649"));\n return ret;\n}\n</code></pre>\n<p>Now let's implement the function. I'll use an iterator through a <em>string view</em> for this:</p>\n<pre><code>#include <cctype>\n#include <cstdint>\n#include <string_view>\n#include <type_traits>\n\nint_fast32_t convert_str(std::string_view s)\n{\n uint_fast32_t value = 0;\n bool negative = false;\n auto i = s.begin();\n auto const end = s.end();\n\n // skip whitespace\n while (i != end && *i == ' ') {\n ++i;\n }\n if (i == end) {\n return 0;\n }\n\n // handle optional sign indicator\n if (*i == '-') {\n negative = true;\n ++i;\n } else if (*i == '+') {\n ++i;\n }\n\n // process the digits\n while (i != end && std::isdigit(unsigned(*i))) {\n if (value > 214748364\n || value == 214748364 && *i > '7' + negative) {\n // would overflow\n return negative ? -2147483648 : 2147483647;\n }\n\n // usual case\n value = value * 10 + (*i - '0');\n ++i;\n }\n\n // convert to result type\n int_fast32_t signed_value = value;\n return negative ? -signed_value : signed_value;\n}\n</code></pre>\n<p>There are still some issues (I don't like the hard-coded magic numbers), but this is both safer and clearer than the original.</p>\n<h2>Exercise</h2>\n<p>Now change the interface to accept any kind of character type, and return a desired integer type (with appropriate saturation values):</p>\n<pre><code>template<typename Integer, typename Char, typename Traits>\nInteger convert_str(std::basic_string_view<Char,Traits> s);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T09:33:28.523",
"Id": "496447",
"Score": "0",
"body": "There is a problem with leetcode's platform that causes a runtime error that indicates there is an overflow which does not happen elsewhere and cannot be caught using `try` and `catch` I'm mentioning this because I know that `stoi()` is probably illegal and that's why I overloaded the `atoi_impl()` function. And regarding the traversal of the string more than once, can you point to where that happens for a second time? Do you mean in `atoi_impl()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T12:58:49.883",
"Id": "496459",
"Score": "0",
"body": "Actually I was mistaken - it's just harder to follow when split into two functions (`convert_str()` and `atoi_impl()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T13:00:27.647",
"Id": "496460",
"Score": "0",
"body": "No, I wasn't mistaken - `convert_str()` goes looking for `end_idx`, then `atoi_impl()` starts again at the beginning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T13:14:41.010",
"Id": "496461",
"Score": "0",
"body": "you're right, I overlooked it while trying several approaches"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T13:41:51.593",
"Id": "496465",
"Score": "0",
"body": "I just noticed that the first `atoi_impl()` returns wrong results which might invalidate the question, so I omitted it from my answer and kept only the working one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:13:50.653",
"Id": "496478",
"Score": "0",
"body": "Okay, thanks a lot for the excellent answer, and I have several questions: 1) how does my code run without including `<cctype>` and `<stdexcept>`? And how to ensure these things don't happen? 2) I removed the part that included overflow checking because the end result was false, however is it acceptable to match the digits pre / post modifications for avoiding overflow? If no, then why? 3) What does `#define` do differently than a function? 4) `if (*i == '-')` Is `i` a pointer? 5) I have not learned using templates yet, so i'll get to the final part later when I do, thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:56:26.897",
"Id": "496484",
"Score": "0",
"body": "also what are some use cases for templates do you recommend (generally)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:54:40.247",
"Id": "496495",
"Score": "2",
"body": "(5) Don't worry about templates yet if that's beyond your current learning. (4) `i` is an _iterator_ into the string view; it isn't a pointer, but is designed to be used similarly. (3) I used `#define` here because it can reproduce its argument as a string (`#actual`), but that's something of a distraction and you don't need to understand that yet. (2) I don't understand your question. (1) Just luck that your platform happens to define those functions with the includes you have. In general, you need to read each function's documentation to see which include is required."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T09:14:39.063",
"Id": "252042",
"ParentId": "252030",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252042",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T01:50:22.317",
"Id": "252030",
"Score": "3",
"Tags": [
"python",
"c++",
"programming-challenge"
],
"Title": "Leetcode atoi (string to integer)"
}
|
252030
|
<p>I'm posting a solution for LeetCode's "String to Integer (atoi)". If you'd like to review, please do. Thank you!</p>
<h3><a href="https://leetcode.com/problems/string-to-integer-atoi/" rel="nofollow noreferrer">Problem</a></h3>
<blockquote>
<p>Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned.</p>
</blockquote>
<p><strong>Note:</strong></p>
<blockquote>
<p>Only the space character ' ' is considered a whitespace character.
Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, 231 − 1 or −231 is returned.</p>
</blockquote>
<p><strong>Example 1:</strong></p>
<pre><code>Input: str = "42"
Output: 42
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: str = " -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42.
</code></pre>
<p><strong>Example 3:</strong></p>
<pre><code>Input: str = "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
</code></pre>
<p><strong>Example 4:</strong></p>
<pre><code>Input: str = "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed.
</code></pre>
<p><strong>Example 5:</strong></p>
<pre><code>Input: str = "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−231) is returned.
</code></pre>
<h3>Code</h3>
<pre><code>from typing import List
import collections
import itertools
import functools
import math
import string
import random
import bisect
import re
import operator
import heapq
import queue
from queue import PriorityQueue
from itertools import combinations, permutations
from functools import lru_cache
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from collections import Counter
class Solution:
def myAtoi(self, s):
s = re.findall(r'^\s*[+-]?\d+', s)
try:
MAX, MIN = 2147483647, -2147483648
res = int(''.join(s))
if res > MAX:
return MAX
if res < MIN:
return MIN
return res
except:
return 0
if __name__ == "__main__":
print(Solution().myAtoi(" -42"))
</code></pre>
<h3>References:</h3>
<ul>
<li><p><a href="https://leetcode.com/problems/string-to-integer-atoi/" rel="nofollow noreferrer">LeetCode 8. String to Integer (atoi)</a></p>
</li>
<li><p><a href="https://codereview.stackexchange.com/questions/252030/leetcode-atoi-string-to-integer">Leetcode atoi (string to integer)</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Nice solution, it's compact and simple to understand. There is little to improve, few suggestions:</p>\n<ul>\n<li><strong>Imports</strong>: there are a lot of imports, maybe leftovers of previous attempts.</li>\n<li><strong>Try Except block</strong>: should be around the code that can cause the exception.</li>\n</ul>\n<p>Applying the suggestions:</p>\n<pre><code>import re\n\nclass Solution:\n def myAtoi(self, s: str) -> int:\n MAX, MIN = 2147483647, -2147483648\n s = re.findall(r'^\\s*[+-]?\\d+', s)\n try:\n res = int(''.join(s))\n except:\n return 0\n if res > MAX:\n return MAX\n if res < MIN:\n return MIN\n return res\n</code></pre>\n<h2>Performance</h2>\n<pre><code>Runtime: 36 ms, faster than 51.56% of Python3 online submissions\nMemory Usage: 14.1 MB, less than 32.27% of Python3 online submissions\n</code></pre>\n<p>Regex makes the code compact but is not the fastest approach. Faster solutions iterate through the string character by character.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T03:21:23.647",
"Id": "252032",
"ParentId": "252031",
"Score": "2"
}
},
{
"body": "<h2>Magic numbers</h2>\n<pre><code>2147483647, -2147483648\n</code></pre>\n<p>are actually</p>\n<pre><code>1<<31 - 1, -(1<<31)\n</code></pre>\n<p>which better conveys your intent: the limits of a signed 32-bit integer.</p>\n<h2>Pre-compile your regex</h2>\n<p>Consider putting a</p>\n<pre><code>DIGIT_PATTERN = re.compile(r'^\\s*[+-]?\\d+')\n</code></pre>\n<p>in global scope, so that multiple calls to <code>myAtoi</code> are faster.</p>\n<h2>Never bare <code>except</code></h2>\n<p>You should likely instead <code>except ValueError</code>, which is more narrow and well-defined.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:22:35.470",
"Id": "252064",
"ParentId": "252031",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252032",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T02:23:03.070",
"Id": "252031",
"Score": "3",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "LeetCode 8: String to Integer (atoi)"
}
|
252031
|
<p>Here's my attempt. I iterate through each vertex in the graph and do a DFS to see if I reach back on a vertex I already visited in this vertex's iteration. It seems to work but I am not satisfied with how I short-circuit my code when it found a cycle using if clauses, could not think of a better way to do that.</p>
<pre><code>public boolean isCyclic(Map<T, List<T>> adjacencyList) {
for (T node: adjacencyList.keySet()) {
Set<T> visited = new HashSet<>();
visited.add(node);
if (isCyclic(visited, node) == true)
return true;
}
return false;
}
private boolean isCyclic(Set<T> visited, T node) {
boolean retval;
for (T connectedNode: map.get(node)) {
if (visited.contains(connectedNode)) {
// We've reached back to a vertex, i.e. a back-edge
return true;
} else {
visited.add(connectedNode);
if (isCyclic(visited, connectedNode) == true)
return true;
}
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>I didn't find another way to do it, but I will give you some tips on the current implementation.</p>\n<h2>Always add curly braces to <code>loop</code> & <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<h2>Simplify the boolean conditions.</h2>\n<p>In both of the method, you can simplify the boolean validations.</p>\n<h3>Equivalence</h3>\n<p><code>isCyclic(visited, node) == true</code> can be <code>isCyclic(visited, node)</code></p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (isCyclic(visited, node) == true) {\n return true;\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (isCyclic(visited, node)) {\n return true;\n}\n</code></pre>\n<h3>Code reduction</h3>\n<p>In the second method, instead of using the <code>java.util.Set#contains</code> method, you can check the returned boolean of the <code>java.util.Set#add</code> directly; this will allow you to remove an instruction.</p>\n<p><a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Set.html#add(E)\" rel=\"nofollow noreferrer\">Documentation</a>:</p>\n<pre><code>Returns:\ntrue if this set did not already contain the specified element\n</code></pre>\n<p><strong>Basic example</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Set<Character> set = new java.util.HashSet<>(Set.of('A', 'B', 'C'));\nSystem.out.println(set.add('A')); // false\nSystem.out.println(set.add('D')); // true\n</code></pre>\n<p>This will add the element, if not already present and return <code>true</code> if it was not present.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (visited.contains(connectedNode)) {\n // We've reached back to a vertex, i.e. a back-edge\n return true;\n} else {\n visited.add(connectedNode);\n if (isCyclic(visited, connectedNode)) {\n return true;\n }\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (!visited.add(connectedNode)) {\n // We've reached back to a vertex, i.e. a back-edge\n return true;\n} else {\n if (isCyclic(visited, connectedNode)) {\n return true;\n }\n}\n</code></pre>\n<hr />\n<p>In the second method, you can remove the <code>retval</code> variable, since it does nothing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T20:39:10.147",
"Id": "496513",
"Score": "1",
"body": "Upvoted just for the brackets with for/if part. i introduced so many errors when adding a second statement and forgetting to add the brackets and I swore never to write an if without brackets again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T20:49:31.147",
"Id": "496515",
"Score": "0",
"body": "Thank you for the handy advice, yes I got lazy about the curlies around the if condition :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:34:45.370",
"Id": "252069",
"ParentId": "252034",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252069",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T05:50:46.307",
"Id": "252034",
"Score": "3",
"Tags": [
"java",
"graph",
"depth-first-search"
],
"Title": "Detecting a cycle in a directed graph via an adjacency list implementation and a recursive DFS"
}
|
252034
|
<p>I'm looking to simplify the below code for validating an onChange event. The <code>allowedInput</code> is a regex that is passed (optional) from all the form components.</p>
<pre><code> const validatedOnChange = (event: ChangeEvent<HTMLInputElement>): void => {
if (isDisabled) {
return;
}
if (allowedInput) {
if (allowedInput.test(event.target.value)) {
onChange({ name, value: event.target.value });
}
return;
}
onChange({ name, value: event.target.value });
};
</code></pre>
<p>This is a common utility method used for all my React form components. Hence looking to write a readable and consistent code.</p>
|
[] |
[
{
"body": "<p>Obviously the code does have some redundancy, which violates the <a href=\"http://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</a> principle.</p>\n<p>This could be simplified by calling <code>onChange()</code> if <code>allowedInput</code> is <code>false</code>y or if that is not the case then only when the call to the test method on it returns a <code>true</code>thy value:</p>\n<pre><code>const validatedOnChange = (event: ChangeEvent<HTMLInputElement>): void => {\n if (isDisabled) {\n return;\n }\n if (!allowedInput || allowedInput.test(event.target.value)) {\n onChange({ name, value: event.target.value });\n }\n};\n</code></pre>\n<p>One could opt to take the <code>return</code> early approach, which might be more readable and decrease the indentation on the call to <code>onChange()</code> but would have an extra line:</p>\n<pre><code> if (allowedInput && !allowedInput.test(event.target.value)) {\n return;\n }\n onChange({ name, value: event.target.value });\n \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:52:23.417",
"Id": "252070",
"ParentId": "252035",
"Score": "2"
}
},
{
"body": "<h1>Simplify.</h1>\n<p>You have 3 conditions checks, <code>isDisabled</code>, "allowedInput", and <code>allowedInput.test</code>, and two effective paths, do nothing, or call <code>onChange</code>. Yet you have 2 returns statements, calls to <code>onChange</code>.</p>\n<p>All functions will return you should try to avoid needing to add returns.</p>\n<p>You should always avoid repeating the same code. The 2 expressions calling <code>onChange</code> need only be expressed once.</p>\n<p>All these things will negatively impact maintenance, and readability.</p>\n<h2>Destructure</h2>\n<p>You can also simplify the code using destructure assignment to unpack <code>value</code> from the argument <code>event</code> in the functions arguments negating the need to have the path <code>event.target.value</code> expressed 3 times.</p>\n<h2>Short circuit</h2>\n<p>Lastly the if token is just noise and not needed as the call to <code>onChange</code> can be via a short circuit around <code>&&</code> The right side is only executed if the left side evaluates to <code>true</code></p>\n<p>This gives you following</p>\n<pre><code>const validatedOnChange = ({target: {value}}) => {\n !isDisabled && (!allowedInput || allowedInput.test(value)) && onChange({name, value});\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T20:09:36.443",
"Id": "252080",
"ParentId": "252035",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252070",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T06:51:45.783",
"Id": "252035",
"Score": "4",
"Tags": [
"javascript",
"react.js"
],
"Title": "Validating javascript onChange event"
}
|
252035
|
<p>I am trying to resolve below problem to improve my skill. I would appreciate it if someone improve my code in a better way.</p>
<p>Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable. For example, '001' is not allowed.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define MIN_ALPH 1
#define MAX_ALPH 26
//return number of possible encode methods
int encode(unsigned int num)
{
int count=0;
unsigned int ddigit;
//encode by 2 digits
for(int i=10; i<=num; i*=10)
{
ddigit = (num % (i*10)) / (i/10);
if (ddigit >= MIN_ALPH && ddigit <= MAX_ALPH)
count++;
}
//extra count for the single digit encoding since all digits are non-zero
return ++count;
}
int main(void)
{
/*Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
count the number of ways it can be decoded.
For example, the message '111' would give 3,
since it could be decoded as 'aaa', 'ka', and 'ak'.
You can assume that the messages are decodable.
For example, '001' is not allowed.*/
printf( "result: %d\n", encode(512));
printf( "result: %d\n", encode(542));
printf( "result: %d\n", encode(112));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T06:17:42.970",
"Id": "496851",
"Score": "0",
"body": "thanks folks for review, follow up question is posted here: https://codereview.stackexchange.com/questions/252230/encode-message-by-alphabets-follow-up"
}
] |
[
{
"body": "<p>The terminology is a bit sloppy - I would call the operation of going from digits back to alphabetic characters <em>decoding</em> rather than encoding - and our function isn't really either of those: it's <em>counting</em>. (I'm guessing that you're not a native English speaker, so don't take this criticism too harshly!).</p>\n<hr />\n<p>The interface is surprising: accepting an integer type greatly limits the maximum length of input, and we could return an unsigned type as result:</p>\n<pre><code>unsigned int count_decodings(const char *input);\n</code></pre>\n<p>As a hint, it is safe to convert a character to digit by subtracting <code>'0'</code> (C guarantees that the digits 0..9 have consecutive encodings, regardless of the host environment's character coding).</p>\n<hr />\n<p>The algorithm produces <strong>incorrect results</strong>:</p>\n<p>This comment is not justified:</p>\n<pre><code>//extra count for the single digit encoding since all digits are non-zero\nreturn ++count;\n</code></pre>\n<p>Some digits may indeed be zero - for example, <code>10</code> and <code>201</code> can each be decoded exactly one way. That should suggest some extra testing you could (and should) do.</p>\n<hr />\n<p>It's good that we have some tests in <code>main()</code>; I would go further and make the tests <em>self-checking</em>. Instead of merely printing the results, we should compare against the expected values, and return <code>EXIT_SUCCESS</code> only if all the tests pass. There are several libraries available to help with unit testing like this, or you could could do it quite simply:</p>\n<pre><code>int failures = 0;\nfailures += count_decodings("10") != 1;\nfailures += count_decodings("11") != 2;\n// more tests here\n</code></pre>\n<p>We don't have any indication of which tests have failed, and what their expected and actual results were. We could create macros to help here (which is exactly what the unit-testing frameworks provide for us).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T06:16:38.093",
"Id": "496548",
"Score": "0",
"body": "does 10 mean 010? 010 cannot be decoded since first digit is zero?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T08:18:09.617",
"Id": "496551",
"Score": "0",
"body": "Please see latest answer in this thread. Can you review algorithm part. I will add method with digit to char conversion later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:24:27.930",
"Id": "496642",
"Score": "1",
"body": "`010` isn't a valid input, so we don't need to consider it, according to the problem statement. Though it would be nice if we returned `0` in that case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T08:54:10.677",
"Id": "252041",
"ParentId": "252039",
"Score": "5"
}
},
{
"body": "<p>For the message <code>111111</code> I get 13 combinations:</p>\n<pre><code>......aaaaaa\n\n_.... kaaaa\n._... akaaa\n.._.. aakaa\n..._. aaaka\n...._ aaaak\n\n\n__.. kkaa\n_._. kaka\n_.._ kaak\n.__. akka\n._._ akak\n..__ aakk\n\n___ kkk\n</code></pre>\n<p>With a "3" in first place you lose kkk, kaak, kaka, kkaa and kaaaa. I think you have to start from the combinatorial maximum and then check how many you can rule out. But this must be very non-trivial. Where's that from?</p>\n<p>This:</p>\n<pre><code>99991999919999199991999919\n</code></pre>\n<p>can still be read in many ways depending on how you combine the five choices for "ai" or "s".</p>\n<hr />\n<p>The program only prints "6" for "111111". It only counts from "aaaaaa" to "aaaak" (above).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T11:21:01.603",
"Id": "252050",
"ParentId": "252039",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252041",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T08:37:30.587",
"Id": "252039",
"Score": "6",
"Tags": [
"c",
"encoding"
],
"Title": "Encode message by alphabets"
}
|
252039
|
<p>I want to make my calculator code shorter.</p>
<p>Here is my code:</p>
<pre><code>extern "C"
{
int printf(const char *format, ...);
extern int scanf(const char *format, ...);
double pow(double x, double y);
}
int main()
{
do
{
double num1;
double a, b = 1;
char ch1;
float r;
scanf("%lf", &num1);
printf("\ta - Factorial\n\tb - Continue\n");
scanf(" %c", &ch1);
switch (ch1)
{
case 'a':
r = b;
for (a = 1; a <= num1; a++)
{
b = b * a;
}
if (b < 500000001 & num1 > 0)
{
printf("%f\n", b);
}
else
{
if (b > 500000000)
{
printf("Number is Big\n");
}
if (num1 < 1)
{
printf("Number is Small\n");
}
}
break;
case 'b':
double num2;
char ch2;
scanf("%lf", &num2);
printf("\ta - Add\n\tb - Substract\n\tc - Multiply\n\td - Divide\n\te - Power\n\tf - Radical\n");
scanf(" %c", &ch2);
switch (ch2)
{
case 'a':
r = num1 + num2;
if (num1 + num2 < 500000001 & num1 + num2 > -500000001 & num1 - num2 < 500000001 & num2 - num1 < 500000001)
{
printf("%lf + %lf = %f\n", num1, num2, r);
}
else if (num1 + num2 > 500000000)
{
printf("Number is Big\n");
}
break;
case 'b':
r = num1 - num2;
if (num1 + num2 < 500000001 & num1 + num2 > -500000001 & num1 - num2 < 500000001 & num2 - num1 < 500000001)
{
printf("%lf - %lf = %f\n", num1, num2, r);
}
else if (num1 + num2 > 500000000)
{
printf("Number is Big\n");
}
break;
case 'c':
r = num1 * num2;
if (num1 * num2 < 500000001 & num1 * num2 > -500000001)
{
printf("%lf * %lf = %f\n", num1, num2, r);
}
else
{
if (num1 * num2 > 500000000)
{
printf("Number is Big\n");
}
if (num1 * num2 < -500000000)
{
printf("Number is Small\n");
}
}
break;
case 'd':
r = num1 / num2;
if (num1 * num2 < 500000001 & num1 * num2 > -500000001 && num2 > 0 | num1 == 0 & num2 != 0)
{
printf("%lf / %lf = %f\n", num1, num2, r);
}
else
{
if (num1 * num2 > 500000000)
{
printf("Number is Big\n");
}
if (num1 * num2 < -500000000)
{
printf("Number is Small\n");
}
if (num1 > 0 & num2 == 0 | num1 == 0 & num2 == 0)
{
printf("Undefined\n");
}
}
break;
case 'e':
r = pow(num1, num2);
if (pow(num1, num2) < 500000001 & pow(num1, num2) > -500000001)
{
printf("%lf ^ %lf = %f\n", num1, num2, r);
}
else
{
if (pow(num1, num2) > 500000000)
{
printf("Number is Big\n");
}
if (pow(num1, num2) > -500000000)
{
printf("Number is Small\n");
}
}
case 'f':
r = pow(num1, 1 / num2);
if (pow(num1, num2) < 500000001 & pow(num1, num2) > -500000001)
{
printf("%lf √ %lf = %f\n", num1, num2, r);
}
else
{
if (pow(num1, num2) > 500000000)
{
printf("Number is Big\n");
}
if (pow(num1, num2) > -500000000)
{
printf("Number is Small\n");
}
}
break;
default:
printf("Invalid\n");
}
break;
}
}
while (1);
}
</code></pre>
<p>Can I make this code shorter? Is it possible to do? If it is, how?</p>
<p>(This code may be updated in my <a href="https://github.com/ArianKG" rel="nofollow noreferrer">GitHub</a> account.)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T08:57:40.883",
"Id": "496443",
"Score": "7",
"body": "We can only review the code that's here, so your requirement (2) is off-topic for Code Review. What do you have against `#include`, anyway? That's the standard means of accessing library functions, and much safer than declaring standard functions as you have done here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:26:00.237",
"Id": "496490",
"Score": "1",
"body": "This is not C++, it is C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:53:54.937",
"Id": "496494",
"Score": "1",
"body": "It is C++. You can test it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T19:15:55.380",
"Id": "496510",
"Score": "2",
"body": "While it appears that the edits don't really incorporate advice from the answer, please be aware: after receiving an answer you should not make changes to your code anymore. This is to ensure that answers do not get invalidated. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T22:03:19.223",
"Id": "496519",
"Score": "1",
"body": "@Arian: It compiles like a C program. What about it makes it C++?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T00:19:16.497",
"Id": "496532",
"Score": "1",
"body": "Although a C++ compiler would compile this program, nothing about it is C++,."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T05:51:11.190",
"Id": "496545",
"Score": "0",
"body": "@MartinYork My file name is Program.cpp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T06:01:02.137",
"Id": "496547",
"Score": "1",
"body": "@Arian Read my answer below. Lots of C code can be compiled by the C++ compiler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T09:45:56.340",
"Id": "496552",
"Score": "1",
"body": "@Arian This code is quite bad and poorly written. IMO, I think the you should focus more on writing cleaner code than trying to make the code short."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T18:07:48.567",
"Id": "497783",
"Score": "0",
"body": "I have rolled back Rev 8 → 7. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>This is not a full review, but try using functions actually used in modern C++. There is no point in using <code>printf()</code> and <code>scanf()</code>, as they are just in the language for C-portability. <code>std::cout</code> and <code>std::cin</code> would be the C++ equivalents (you have to <code>#include <iostream></code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T20:15:22.213",
"Id": "497813",
"Score": "0",
"body": "*Just* for C portability? Not that that isn't important enough by itself, but iostream has some distinct advantages (and not only disadvantages) over pre-C++20 iostream."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:51:23.537",
"Id": "252066",
"ParentId": "252040",
"Score": "4"
}
},
{
"body": "<p>There is no better way to say this, but your code is shockingly bad. I will just provide a short summary of the things that can be improved:</p>\n<ul>\n<li><code>#include</code> headers like everyone else does, don't forward declare standard library functions.</li>\n<li>Since you tagged the post C++, use C++'s <code>iostream</code> functionality; it gives you type safety.</li>\n<li>Split your program into several functions, and just have a small loop in <code>main()</code> that reads input and calls another function to do the processing.</li>\n<li>Use either <code>double</code> or <code>float</code>, don't mix them. Why is <code>r</code> a <code>float</code>?</li>\n<li>Don't use arbitrary numbers to check if something is "big". Just don't check the result at all, print it and let the user decide whether they think it is useful or not.</li>\n<li>Use <code>&&</code> instead of <code>&</code>, the latter is a bitwise AND which does not do what you want.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T20:13:21.800",
"Id": "497812",
"Score": "0",
"body": "Pre-C++20 iostream has some often critical shortcomings compared to stdio. Still, [`<format>`](https://en.cppreference.com/w/cpp/utility/format/format) mostly solved that, and they are not really important here, imho."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T21:31:09.170",
"Id": "252083",
"ParentId": "252040",
"Score": "7"
}
},
{
"body": "<h2>Questions:</h2>\n<blockquote>\n<p>Can I make this code shorter?</p>\n</blockquote>\n<p>Yes</p>\n<blockquote>\n<p>Is it possible to do?</p>\n</blockquote>\n<p>Yes</p>\n<blockquote>\n<p>If it is, how?</p>\n</blockquote>\n<p>By using functions. You can move common code to a named function.</p>\n<h2>Notes</h2>\n<p>This is C code not C++.</p>\n<p>Sure it compiles with a C++ compiler (so does a lot of C). C++ is a style of programming, you are not using the C++ style you are using the C style of programming.</p>\n<p>Additionally, you are using a lot of C library functions that have C++ equivalents.</p>\n<h2>Review</h2>\n<ol>\n<li>Split your code into functions</li>\n<li>Use C++ libraries (not C)</li>\n<li>Improve your user interface (ask the question then expect answers).</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T20:16:57.480",
"Id": "497814",
"Score": "0",
"body": "It is bad C++ code, avoiding all the good points of writing C++, in a bad C-like style. But it is most certainly C++ despite that. And it is indubitably not C."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T22:13:29.190",
"Id": "252084",
"ParentId": "252040",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "252084",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T08:51:52.447",
"Id": "252040",
"Score": "0",
"Tags": [
"c++",
"console",
"io"
],
"Title": "A calculator in C++"
}
|
252040
|
<p>My aim is to merge all workbooks having multiple sheets from any specified folder to one workbook of multiple sheets. The problem is I don’t want external links to be maintained, If I use "breaklink" it will break all links(external links) b/w sheets of all workbooks. what I exactly I need is, After merging all sheets of workbooks in one workbook, I need links b/w these merged sheets.</p>
<p><em><strong>CODE FOR MERGE ALL WORKBOOKS INTO ONE WORKBOOK :</strong></em></p>
<pre><code>Sub merge()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = "C:\Users\Samiya jabbar\Desktop\test"
Filename = Dir(FolderPath)
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T12:03:15.193",
"Id": "496456",
"Score": "3",
"body": "\"I need links b/w these merged sheets\" - what does \"b/w\" mean? To me, that means \"black and white\", as in photography or TV. It's unclear - does this code actually do what you want it to do, or do you need help resolving a bug? If it's functional, what kind of review are you looking for? At a minimum, I'd _strongly_ recommend some indention to make the nesting levels more obvious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:53:05.417",
"Id": "496815",
"Score": "0",
"body": "The links between sheets within a single workbook are formatted as `<sheetname>!<range>`. When you merge/move/copy those sheets into a different workbook, the original workbook name is added `[<workbook>]<sheetname>!<range>`. So my recommendation is after you merge a set of sheets from a workbook, perform a find and replace on any formulas to remove the string between (and including) the square brackets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T08:11:51.743",
"Id": "496990",
"Score": "0",
"body": "Thanks, @FreeMan for your recommendation, b/w means between. I have got the answer now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T08:16:01.970",
"Id": "496991",
"Score": "0",
"body": "Thanks, @Peter T for your response. yes, hope this strategy will be worked fine. But I have got a simple solution, I am sharing here to help others."
}
] |
[
{
"body": "<p>First you have to open all files that are involved before you start moving.\nNow move sheets (don't copy them), instead of <code>.copy</code>, use <code>.move </code>.\nSave your merged workbook.</p>\n<p><em><strong>REVISED CODE FOR MERGE ALL WORKBOOKS INTO ONE WORKBOOK :</strong></em></p>\n<pre><code>Sub merge()\n\nDim FolderPath As String\n\nDim Filename As String\n\nDim Sheet As Worksheet\n\nApplication.ScreenUpdating = False\n\nFolderPath = "C:\\Users\\Samiya jabbar\\Desktop\\test"\n\nFilename = Dir(FolderPath)\n\nDo While Filename <> ""\n\nWorkbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True\n\nFor Each Sheet In ActiveWorkbook.Sheets\n\nSheet.move After:=ThisWorkbook.Sheets(1)\n\nNext Sheet\n\nFilename = Dir()\n\nLoop\n\nApplication.ScreenUpdating = True\n\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T08:23:29.753",
"Id": "252295",
"ParentId": "252044",
"Score": "0"
}
},
{
"body": "<p>Here are a couple of pointers:</p>\n<ul>\n<li>FolderPath should be a constant because it's value will never change</li>\n<li>Using a wildcard Filter with the path will ensure that you open the correct files</li>\n<li>Although ActiveWorkbook does the job, it is best to get in the habit of using qualified references</li>\n<li><code>Workbook.Worksheets</code> returns a Worksheets Collection (not to be confused with a normal VBA Collection)</li>\n<li>Worksheets can be used to perform group operations on all of it's Worksheets at one time</li>\n<li>Download <a href=\"https://rubberduckvba.com/\" rel=\"nofollow noreferrer\">RubberDuck</a>. Among its many great features is Code Indentation. It will save you a ton of time reformatting and show you unclosed code blocks</li>\n</ul>\n<hr />\n<pre><code>Sub merge()\n Const FolderPath As String = "C:\\Users\\Samiya jabbar\\Desktop\\test"\n Const Pattern As String = "*.xl*"\n \n Dim Filename As String\n\n Dim Sheet As Worksheet\n\n Application.ScreenUpdating = False\n\n Filename = Dir(FolderPath & Pattern)\n\n Do While Filename <> ""\n\n Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True).Worksheets.Move After:=ThisWorkbook.Sheets(1)\n\n Filename = Dir()\n\n Loop\n\n Application.ScreenUpdating = True\n\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-20T00:08:37.607",
"Id": "252393",
"ParentId": "252044",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252295",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T09:47:20.583",
"Id": "252044",
"Score": "3",
"Tags": [
"vba",
"excel",
"macros"
],
"Title": "internal links b/w sheets of merged workbooks, using VBA (EXCEL MACROS)"
}
|
252044
|
<p>I am looking to alter one combobox between two DataSources depending on the button clicked.</p>
<p>Here are the 2 lists:</p>
<pre><code>List<ComplaintModel> productNames = new List<ComplaintModel>();
List<ComplaintModel> specificProductNames = new List<ComplaintModel>();
</code></pre>
<p>This is the functions for both of the Data Sources:</p>
<pre><code>public Complaints_Form()
{
InitializeComponent();
// When Form is loaded - load with this Data Source First
loadProducts();
}
private void loadProducts()
{
DataAccess db = new DataAccess();
productNames = db.LoadProducts();
product.DataSource = productNames;
product.DisplayMember = "Product";
product.SelectedIndex = 0;
}
// On button click - alter the Data Source
public void searchButton_Click(object sender, EventArgs e)
{
// New datasource
DataAccess db = new DataAccess();
specificProductNames = db.FindOrderNumber(orderNumber.Text);
product.DataSource = specificProductNames;
product.DisplayMember = "Product";
product.SelectedIndex = 0;
}
</code></pre>
<p><strong>Question</strong></p>
<ul>
<li>Is this the correct way of altering between data-sources?</li>
</ul>
<p>The reason I have this question - the form is actually fairly slow. Especially when I load or clear the textboxes and also clear the data-bindings.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T10:19:20.233",
"Id": "252045",
"Score": "2",
"Tags": [
"c#",
"winforms"
],
"Title": "What is the correct way to alter ComboBox between two DataSources?"
}
|
252045
|
<p>Problem space: I have the concept of a <code>Job</code> that needs to be processed. Jobs need to be processed sequentially, as one may depend on another. It's possible for a Job to be paused, in which case the next Job should <em>not</em> be started - the Job should either be explicitly continued, or cancelled, in order to get the next one to start.</p>
<p>If the background service doing these Jobs finishes, it should wait for an update to a RESTful resource before trying to start processing again. I don't want the service to busy-wait.</p>
<pre><code>public class ExecutionBackgroundService : BackgroundService
{
private readonly IJob _job;
private readonly AutoResetEvent _isRunning = new AutoResetEvent(true);
public ExecutionBackgroundService(IJob job)
{
_job = job;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Required for the method to be executed asynchronously, allowing startup to continue.
await Task.Yield();
while (!stoppingToken.IsCancellationRequested)
{
_isRunning.WaitOne(); // blocks the thread, waiting for the event to be set by something else calling the Resume method
await _job.Process();
}
}
/// <summary>
/// Notifies the background service to resume processing.
/// </summary>
public void Resume()
{
_isRunning.Set();
}
}
</code></pre>
<p>Jobs are represented by a DB entity. The <code>IJob</code> implementation looks something like this:</p>
<pre><code> public async Task Process()
{
using var scope = _serviceScopeFactory.CreateScope();
var database = scope.ServiceProvider.GetService<MyDbContext>();
var iterator = new DatabaseJobIterator(database);
var worker = scope.ServiceProvider.GetService<IWorker>();
while (iterator.HasNext())
{
await worker.DoLongRunningWork(iterator.Next);
}
}
</code></pre>
<p>Where the implementing class is singleton-scoped, and the DB and <code>IWorker</code> are both request-scoped (hence why I'm getting them using the scope factory).</p>
<p><code>DatabaseJobIterator</code> is basically a simplified <code>IEnumerator</code> that just exposes two methods <code>HasNext</code> and <code>Next</code>, where <code>HasNext</code> will query the database for the oldest job, and assign it to <code>Next</code>. If the job is ready to be processed, it returns true. If the job is paused, it returns false.</p>
<p>An API controller that handles POSTs and PUTs to Jobs will then just call <code>Resume</code> on the background service, indicating that it might have new items to process if it isn't already running.</p>
<p>My question is whether I've used the <code>AutoResetEvent</code> correctly. Is there a more standard way to get the background service to wait without e.g. busy-waiting in a <code>while (true)</code> loop?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T12:08:31.307",
"Id": "496869",
"Score": "0",
"body": "Are your API and your BackgroundService running in a same or in a separate process? In other words are we talking about cross-process synchronization or in-process?"
}
] |
[
{
"body": "<p>I suggest <code>SemaphoreSlim</code> instead of <code>AutoResetEvent</code> here because it has asynchronous API and will not block the current thread, and it accepts <code>CancellationToken</code>. <code>Task.Yield</code> is good hack but it can be useless because <code>await</code> in case of not <code>null</code> <code>SynchronizationContext</code> will restore the context and <code>WaitOne()</code> can anyway block the current thread.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class ExecutionBackgroundService : BackgroundService\n{\n private readonly IJob _job;\n private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); // 1 is concurrency degree\n\n public ExecutionBackgroundService(IJob job)\n {\n _job = job;\n }\n\n protected override async Task ExecuteAsync(CancellationToken stoppingToken)\n {\n try\n {\n while (true)\n {\n await _semaphore.WaitAsync(stoppingToken);\n await _job.Process();\n }\n }\n catch (OperationCanceledException ex)\n { } // occurs when WaitAsync receives canceling callback from the Token, you may log it if needed.\n }\n\n /// <summary>\n /// Notifies the background service to resume processing.\n /// </summary>\n public void Resume()\n {\n lock (_semaphore)\n {\n if (_semaphore.CurrentCount == 0) // is it waiting now?\n _semaphore.Release();\n }\n }\n}\n</code></pre>\n<p>This way is better because now you may cancel the Token without calling the <code>Resume()</code>.</p>\n<p>Btw it's a programming pattern - <strong>Producer/Consumer</strong>. The best way for moving forward is using the specially designed for this purpose almost brand-new classes - <code>System.Threading.Channels</code>. Refer to this <a href=\"https://devblogs.microsoft.com/dotnet/an-introduction-to-system-threading-channels/\" rel=\"nofollow noreferrer\">link</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-20T11:58:38.623",
"Id": "497293",
"Score": "1",
"body": "The implementation of `Resume` is not thread-safe, two or more threads can enter the if-statement concurrently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-20T13:21:24.733",
"Id": "497304",
"Score": "0",
"body": "@Johnbot good catch, thanks! Fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T17:47:17.487",
"Id": "252380",
"ParentId": "252047",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T11:02:25.497",
"Id": "252047",
"Score": "4",
"Tags": [
"c#",
"asp.net-core"
],
"Title": "A background service that will wait for items to process without busy-waiting"
}
|
252047
|
<p>I've seen in Java a class vector implemented, it's very useful because you can declare vectors without say the size of the vector explicitly, and it has a lot of functions operating with its elements. But it hasn't implemented mathematical operations: sum, subtract, inner and outer products and so on. So I've made and extended class with these math operators and functions. Here's the code:</p>
<pre><code>package vectors.com;
import java.util.Collection;
import java.util.Vector;
public class Vectors extends Vector<Double> {
private static final long serialVersionUID = 1L;
public Vectors() {super();}
public Vectors(Collection<? extends Double> c) {super(c);}
public Vectors(int initialCapacity, int capacityIncrement) {super(initialCapacity, capacityIncrement);}
public Vectors(int initialCapacity) {super(initialCapacity);}
public static long getSerialversionuid() {return serialVersionUID;}
public Vectors opposite() {
for(int i = 0; i < this.size(); ++i) this.set(i, -this.get(i));
return this;
}
public Vectors sum(Vectors w) {
if(this.size() != w.size()) throw new IllegalArgumentException("The dimmensions must be equals.");
Vector<Double> v = new Vector<Double>();
Vectors z = new Vectors(v);
Double f = 0.;
for(int i = 0; i < this.size(); ++i) {
f = this.get(i) + w.get(i);
z.add(i, f);
}
return z;
}
public Vectors subtract(Vectors w) {
if(this.size() != w.size()) throw new IllegalArgumentException("The dimmensions must be equals.");
return this.sum(w.opposite());
}
public Vectors externProduct(Double lambda) {
for(int i = 0; i < this.size(); ++i) {
this.set(i, lambda * this.get(i));
}
return this;
}
public Double scalarProduct(Vectors w) {
if(this.size() != w.size()) throw new IllegalArgumentException("The dimmensions must be equals.");
Double s = 0.;
for(int i = 0; i < this.size(); ++i) {
s += this.get(i) * w.get(i);
}
return s;
}
public Double absolute() {
Double radicand = 0.;
for(int i = 0; i < this.size(); ++i) radicand += Math.pow(this.get(i), 2);
return Math.sqrt(radicand);
}
public Double angle(Vectors w) {
return Math.acos(this.scalarProduct(w) / (this.absolute() * w.absolute()));
}
public Vectors makeVector(Vectors w) {
return w.subtract(this);
}
private Double determinant(Double[][] A) {
int rows = A.length;
int columns = A[0].length;
if(rows != columns) throw new IllegalArgumentException("Rows and Columns must be equals.");
if(rows == 1) return A[0][0];
if(rows == 2) return A[0][0] * A[1][1] - A[1][0] * A[0][1];
return A[0][0] * A[1][1] * A[2][2] + A[1][0] * A[2][1] * A[0][2] + A[0][1] * A[1][2] * A[2][0] -
( A[0][2] * A[1][1] * A[2][0] + A[0][1] * A[1][0] * A[2][2] + A[1][2] * A[2][1] * A[0][0] );
}
public Vectors vectorialProduct(Vectors w) {
if(this.size() != w.size()) throw new IllegalArgumentException("Number of components must be equals.");
if(this.size() != 3) throw new IllegalArgumentException("Sorry, only for 3D vectors.");
Double[][] A = {{this.get(1), this.get(2)}, {w.get(1), w.get(2)}};
Double[][] B = {{this.get(0), this.get(2)}, {w.get(0), w.get(2)}};
Double[][] C = {{this.get(0), this.get(1)}, {w.get(0), w.get(1)}};
Vector<Double> z = new Vector<Double>();
Vectors z1 = new Vectors(z);
z1.set(0, determinant(A));
z1.set(1, determinant(B));
z1.set(2, determinant(C));
return z1;
}
public Double mixProduct(Vectors v, Vectors w) {
if(this.size() != v.size() || this.size() != w.size() || v.size() != w.size())
throw new IllegalArgumentException("Number of components must be equals.");
if(this.size() != 3 || v.size() != 3 || this.size() != 3)
throw new IllegalArgumentException("Sorry, only for 3D vectors.");
Double[][] A = new Double[3][3];
for(int i = 0; i < this.size(); ++i) {
A[0][i] = this.get(i);
A[1][i] = v.get(i);
A[2][i] = w.get(i);
}
return determinant(A);
}
@Override
public int hashCode() {return super.hashCode();}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!super.equals(obj)) return false;
if (getClass() != obj.getClass()) return false;
return true;
}
}
</code></pre>
<p>Thanks</p>
|
[] |
[
{
"body": "<h2>Always add curly braces to <code>loop</code> & <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<h2>Extract the expression to variables when used multiple times.</h2>\n<p>In your code, you can extract the similar expressions into variables; this will make the code shorter and easier to read.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (this.size() != v.size() || this.size() != w.size() || v.size() != w.size())\n throw new IllegalArgumentException("Number of components must be equals.");\nif (this.size() != 3 || v.size() != 3 || this.size() != 3)\n throw new IllegalArgumentException("Sorry, only for 3D vectors.");\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>int currentSize = this.size();\nint firstSize = first.size();\nint secondSize = second.size();\n\nif (currentSize != firstSize || currentSize != secondSize || firstSize != secondSize) {\n throw new IllegalArgumentException("Number of components must be equals.");\n}\n\nif (currentSize != 3 || firstSize != 3 || currentSize != 3) {\n throw new IllegalArgumentException("Sorry, only for 3D vectors.");\n}\n</code></pre>\n<h2>Replace the <code>for</code> loop with an enhanced 'for' loop</h2>\n<p>In your code, you don’t actually need the index provided by the loop, you can the enhanced version.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i < this.size(); ++i) {\n radicand += Math.pow(this.get(i), 2);\n}\n</code></pre>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (Double currentDouble : this) {\n radicand += Math.pow(currentDouble, 2);\n}\n</code></pre>\n<h2>Always use the primitives when possible</h2>\n<p>When you know that it's impossible to get a null value with the number, try to use the primitives; this can prevent the unboxing of the value in some case.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>Double f = 0.;\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>double f = 0.;\n</code></pre>\n<h2>Parameter names</h2>\n<p>I suggest that you name your parameters with a meaningful name.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> public Vectors sum(Vectors w) {}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> public Vectors sum(Vectors other) {}\n</code></pre>\n<p>Single letter variable tends to make the code harder to read in must case.</p>\n<h2>Java naming convention</h2>\n<ul>\n<li>Variable and parameter name should be in camelCase style</li>\n</ul>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> private Double determinant(Double[][] A) {}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> private Double determinant(Double[][] a) {}\n</code></pre>\n<h2>Use the multiplication operator instead of <code>Math.Pow</code></h2>\n<p>The <code>Math.Pow</code> tend to be slower in some case when compared with the multiplication operator.</p>\n<p>In my opinion, it's best to use the multiplication operator when the <code>exponent < 5</code>.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i < this.size(); ++i) {\n radicand += Math.pow(this.get(i), 2);\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (Double currentDouble : this) {\n radicand += (currentDouble * currentDouble);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T13:06:53.263",
"Id": "252054",
"ParentId": "252051",
"Score": "5"
}
},
{
"body": "<p>In addition to Doi9t's valuable answer, I'd like to comment on overall design.</p>\n<p>Your <code>Vectors</code> class defines methods for mathematical vector operations. I question wether it's a good idea to extend <code>java.util.Vector</code>.</p>\n<p>How many of the methods you inherit from <code>Vector</code> are meaningful to your interpretation as a mathematical vector? Some examples:</p>\n<ul>\n<li>How often have you extended a 5-dimensional vector to become 6-dimensional, by adding some number at the last position (<code>add()</code> method)?</li>\n<li>How often have you searched a vector to contain some given value, regardless of the position (<code>contains()</code> method)?</li>\n</ul>\n<p>In my opinion, methods like these don't make sense for mathematical vectors.</p>\n<p>Extending <code>Vector</code> means that all the methods from that class also become part of your visible public API, and will only confuse potential users of your class, giving them a hard time sorting out what is useful and what not.</p>\n<p>For this reason, I'd recommend not to extend <code>Vector</code>, but to keep your class independent from the Java Collections framework. If it makes implementation easier for you, you can introduce a <code>Vector</code>-typed field to store the elements.</p>\n<p>What I like about your code:</p>\n<ul>\n<li>You throw IllegalArgumentExceptions in all the right places.</li>\n<li>When you do some math, you return a new vector, and don't modify an existing one, effectively treating <code>Vectors</code> as an immutable class. But this only applies to your own methods, the <code>Vector</code> methods like <code>set()</code>, <code>add()</code> and <code>remove()</code> are still publicly available, breaking that property - another reason not to extend <code>Vector</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:14:45.480",
"Id": "496479",
"Score": "1",
"body": "Unfortunalty your last point is not true. For example, `opposite()` mutates the object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T11:26:07.747",
"Id": "496559",
"Score": "1",
"body": "I 100% agree. `java.util.Vector` has nothing at all to do with the vectors we are talking about here. It's simply the Java designers struggling to find a synonym for \"dynamically resizable array\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T09:28:19.420",
"Id": "496753",
"Score": "0",
"body": "@RoToRa You're right, I didn't recognize that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T14:25:14.143",
"Id": "252057",
"ParentId": "252051",
"Score": "10"
}
},
{
"body": "<h1>To mutate or not to mutate?</h1>\n<p>One problematic thing you are doing, is being inconsistent in whether you mutate (modify, change) the underlying list of numbers or not, and not telling the user about it.</p>\n<p>For example, <code>opposite()</code> modifies the list, but <code>sum()</code> does not. This can be quite confusing for the user of the class and a source of bugs. At the very least you need to clearly document (using JavaDoc) when you modify something and possibly choose methods names that also reflect it (more about the method names later). Better would be, if you were consistent and either allways modify in all methods or never modify in any method. Preferable you should choose to never modify the list (read up on immutable objects and their advantages).</p>\n<p>Even worse in some cases such as <code>subtract()</code> you modify the vector passed in as a parameter. Having a class modify it's method parameters is even more unexpected to the user, and should never be done.</p>\n<h1>Extending <code>Vector</code></h1>\n<p>Java's <code>Vector</code> is for one an out of date, legacy class, which long as been replaced by <code>ArrayList</code>. There is no reason to use it anymore.</p>\n<p>More importantly it is questionable if you should extend from any class at all. The problem is, aside from <code>Vector</code> and <code>ArrayList</code> there are other list-like objects in Java (and many of its libraries), ad by extending one such class you are limiting the user, so that they may need to copy all the data into your <code>Vectors</code> class and when finished copy them back out.</p>\n<p>Instead if would make sense to not extend any class, but just let the user pass in a <code>List</code> object into your constructor (<code>List</code> is an interface that is implemented by many list-like classes) and work with that as the data source.</p>\n<h1>Better names</h1>\n<p>Your object and most of your methods are badly named. The object name <code>Vectors</code> suggests it contains multiple vectors, although it contains one.</p>\n<p>Also the method names either don't use or incorrectly use mathematical terms. For example, <code>opposite</code> is a relativly uncommon word. What it does is usually refered to as <code>negate</code> or <code>invert</code>. And <code>sum</code> sounds like it sums up all numbers in the list. Something like <code>addToEach</code> would be clearer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:09:00.230",
"Id": "252062",
"ParentId": "252051",
"Score": "6"
}
},
{
"body": "<p>I would like to add that this is really pointless:</p>\n<pre><code>public static long getSerialversionuid() {return serialVersionUID;}\n</code></pre>\n<p>No one should ever need to call that. This is only for the serialization process.</p>\n<p>See <a href=\"https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it\">https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T08:42:10.893",
"Id": "252296",
"ParentId": "252051",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T11:38:08.160",
"Id": "252051",
"Score": "6",
"Tags": [
"java"
],
"Title": "Extending class vector in java"
}
|
252051
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/251997/231235">G. Sliepen's answer</a>. Based on the mentioned suggestion, the naming of the function for getting the element count in arbitrary nested iterables is updated into <code>recursive_size</code>. Here, I am trying to implement the functions (<code>recursive_count</code> and <code>recursive_count_if</code>) which purpose are similar to <code>std::count</code> and <code>std::count_if</code> and can be used in various type arbitrary nested iterable things. In the template function <code>recursive_count</code>, the first parameter is an input nested iterable object and the second parameter is the target value to search for.</p>
<pre><code>// recursive_count implementation
template<class T1, class T2> requires (!is_elements_iterable<T1> && is_iterable<T1>)
auto recursive_count(const T1& input, const T2 target)
{
return std::count(input.begin(), input.end(), target);
}
// for loop version
template<class T1, class T2> requires (is_elements_iterable<T1>)
auto recursive_count(const T1& input, const T2 target)
{
size_t output{};
for (auto &element : input)
{
output += recursive_count(element, target);
}
return output;
}
</code></pre>
<p>In the template function <code>recursive_count_if</code>, the first parameter is also an input nested iterable object and the second parameter is a unary predicate which returns <code>true</code> for the required elements.</p>
<pre><code>// recursive_count_if implementation
template<class T1, class T2> requires (!is_elements_iterable<T1> && is_iterable<T1>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
return std::count_if(input.begin(), input.end(), predicate);
}
// for loop version
template<class T1, class T2> requires (is_elements_iterable<T1>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
size_t output{};
for (auto &element : input)
{
output += recursive_count_if(element, predicate);
}
return output;
}
</code></pre>
<p>Some test cases for <code>recursive_count</code> template function:</p>
<pre><code>// std::vector<std::vector<int>> case
std::vector<int> test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };
std::vector<decltype(test_vector)> test_vector2;
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
// determine how many integers in a std::vector<std::vector<int>> match a target value.
int target1 = 3;
int target2 = 5;
int num_items1 = recursive_count(test_vector2, target1);
int num_items2 = recursive_count(test_vector2, target2);
std::cout << "number: " << target1 << " count: " << num_items1 << '\n';
std::cout << "number: " << target2 << " count: " << num_items2 << '\n';
// std::deque<std::deque<int>> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
// determine how many integers in a std::deque<std::deque<int>> match a target value.
int num_items3 = recursive_count(test_deque2, target1);
int num_items4 = recursive_count(test_deque2, target2);
std::cout << "number: " << target1 << " count: " << num_items3 << '\n';
std::cout << "number: " << target2 << " count: " << num_items4 << '\n';
</code></pre>
<p>Some test cases for <code>recursive_count_if</code> template function:</p>
<pre><code>// std::vector<std::vector<int>> case
std::vector<int> test_vector{ 1, 2, 3, 4, 4, 3, 7, 8, 9, 10 };
std::vector<decltype(test_vector)> test_vector2;
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
test_vector2.push_back(test_vector);
// use a lambda expression to count elements divisible by 3.
int num_items1 = recursive_count_if(test_vector2, [](int i) {return i % 3 == 0; });
std::cout << "#number divisible by three: " << num_items1 << '\n';
// std::deque<std::deque<int>> case
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
// use a lambda expression to count elements divisible by 3.
int num_items2 = recursive_count_if(test_deque2, [](int i) {return i % 3 == 0; });
std::cout << "#number divisible by three: " << num_items2 << '\n';
</code></pre>
<p><a href="https://godbolt.org/z/WErYWe" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<ul>
<li><p>The function for getting the element count in arbitrary nested iterables is renamed into <code>recursive_size</code>.</p>
</li>
<li><p>Besides the total element count, I am trying to implement the functions (<code>recursive_count</code> and <code>recursive_count_if</code>) which purpose are similar to <code>std::count</code> and <code>std::count_if</code> and can be used in various type arbitrary nested iterable things here.</p>
</li>
</ul>
</li>
<li><p>Why a new review is being asked for?</p>
<p>As similar as <a href="https://codereview.stackexchange.com/a/251997/231235">G. Sliepen's answer</a> mentioned, there is another version of the last overload <code>recursive_count</code> template function implementation with <code>std::transform_reduce</code>:</p>
<pre><code>// transform_reduce version
template<class T1, class T2> requires (is_elements_iterable<T1>)
auto recursive_count(const T1& input, const T2 target)
{
return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [target](auto& element) {
return recursive_count(element, target);
});
}
</code></pre>
<p>Also, there is another version of the last overload <code>recursive_count_if</code> template function implementation with <code>std::transform_reduce</code>:</p>
<pre><code>// transform_reduce version
template<class T1, class T2> requires (is_elements_iterable<T1>)
auto recursive_count_if(const T1& input, const T2 predicate)
{
return std::transform_reduce(std::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto& element) {
return recursive_count_if(element, predicate);
});
}
</code></pre>
<p>I am wondering which version is more readable.</p>
<p><a href="https://godbolt.org/z/a5scY8" rel="nofollow noreferrer">A Godbolt link for this (using <code>std::transform_reduce</code>) version is here.</a></p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:07:05.380",
"Id": "496486",
"Score": "2",
"body": "Instead of asking for a review of one algorithm at a time, maybe it makes sense to write a library with recursive versions of all the STL algorithms, and submit that as one review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:13:06.480",
"Id": "496487",
"Score": "2",
"body": "@G.Sliepen Thank you for the comment. If building a library about these recursive functions then submitting as one review is better than asking one by one. I am going to do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T19:41:53.877",
"Id": "496702",
"Score": "2",
"body": "FWIW, I think \"please review my library\" might fall too easily foul of the site rules like \"provide the code, not [merely] a link to the code\" and \"keep the amount of code manageable.\" On the other hand, it would definitely reduce the amount of repetition happening in these questions. Jimmy has to keep explaining what `concept is_iterable` does, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T00:19:03.287",
"Id": "496722",
"Score": "0",
"body": "@Quuxplusone Based on your comment, it seems not a good idea to propose \"a library\" to review, does it?"
}
] |
[
{
"body": "<p>I think <code>recursive_count_if</code> is a bad API to begin with, because by design it can't work on a lot of types. Consider:</p>\n<pre><code>std::vector<std::vector<std::string>> v = {{"hello"}, {"world"}};\nauto size5 = [](std::string s) { return s.size() == 5; };\nauto n = recursive_count_if(v, size5);\n</code></pre>\n<p>With your current implementation, this doesn't work, right?</p>\n<p>Worse, if the STL's <code>std::string</code> were non-explicitly constructible from <code>char</code>, like this—</p>\n<pre><code>std::string example = 'x'; // fortunately does not compile today\n</code></pre>\n<p>—then the above snippet <em>would</em> compile, and set <code>n</code> to zero. Because it would call <code>size5('h')</code>, <code>size5('e')</code>, <code>size5('l')</code>, and so on, each of which would evaluate to <code>false</code>. This is certainly not what the programmer intended!</p>\n<p>I think the user of this API should have to tell the function explicitly how many "levels" to unwrap downward: <code>recursive_count_if<0>(r, p)</code> should be <code>std::ranges::count_if(r, p)</code>, and then <code>recursive_count_if<1>(r, p)</code> should be what the user intends in the above snippet, and so on.</p>\n<p>In fact, maybe you should just implement a <code>flatten</code> filter that takes a "range of ranges of <code>E</code>" and returns a "range of <code>E</code>." Then <code>recursive_count_if<1>(r, p)</code> would simply be <code>std::ranges::count_if(flatten(r), p)</code>, and <code>recursive_count_if<2>(r, p)</code> would be <code>std::ranges::count_if(flatten(flatten(r)), p)</code>, and so on. I like that API a lot better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:18:20.913",
"Id": "496719",
"Score": "2",
"body": "Good point about `std::string`. But maybe it can be made to work if recursion stops automatically if, for `recursive_count()`, the container's `value_type` matches `T2` (or rather, that `T2{}==(*T1{}.begin())` is a valid expression), and in the case of `recursive_count_if`, if `T2::operator()(*T1{}.begin())` is a valid expression?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T01:16:09.340",
"Id": "496723",
"Score": "0",
"body": "@G.Sliepen I also think so. The point is to make recursion stops properly in the right time based on the type matching process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T07:31:44.063",
"Id": "496739",
"Score": "0",
"body": "@Quuxplusone I am trying to implement the function which could be used like `recursive_count_if<N>(r, p)`. However, the function template can't be designed with the syntax similar to `template<std::size_t N, class T1, class T2>` because function template partial specialization is not allowed. If there is any hint to deal with this problem, please let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T14:55:46.760",
"Id": "496786",
"Score": "1",
"body": "@JimmyHu: You're trying to specialize `foo<0, T1, T2>` differently from `foo<N, T1, T2>`, right? Think about how you could use `if constexpr` here; or, pre-C++17, think about what you could do with overload resolution if `foo<I, T1, T2>` consists of the single statement `return fooImpl<T1, T2>(std::index_constant<I>(), r, p);`. </hint>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:07:35.620",
"Id": "496788",
"Score": "1",
"body": "@G.Sliepen: Think about when `p` is a generic lambda. In general, \"figuring out the argument type of a callable\" is a fool's errand. See https://quuxplusone.github.io/blog/2018/06/12/perennial-impossibilities/#detect-the-first-argument-type-of-a-function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:03:16.770",
"Id": "496805",
"Score": "0",
"body": "@Quuxplusone: That's a very informative blog post. Although I'm not suggesting to determine the type of parameter `T2` takes, but just to check whether applying `T2` to a `T1` works. That should be more well-defined, but of course might be surprising if you use a generic lambda and it matches the `value_type` of the outer container when you expect it to go down to the inner-most container."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:40:38.277",
"Id": "496810",
"Score": "1",
"body": "@G.Sliepen: Right, \"check whether applying `p` to a `T1` is well-formed\" is easy and unambiguous; but then it requires the user to define their predicate `p` so that it is SFINAE-friendly, which generic lambdas aren't, in general. E.g. try your idea with `recursive_count_if(vec_of_vec_of_string, [](const auto& s) { return s.starts_with(\"foo\"); })`. It blows up because `p(vec_of_vec_of_string[0])` seems well-formed yet when we go to instantiate `p`'s body we find that `vector<string>` has no member function `starts_with` (and by then it's too late to backtrack)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:45:11.227",
"Id": "496811",
"Score": "2",
"body": "Vice versa, if `p` were, like, `[](auto x) { return x.size()==5; }`, then the question arises whether we might want to apply it at _multiple_ levels! Is this like that [\"How many squares do you see?\"](https://duckduckgo.com/?q=how+many+squares&iax=images&ia=images) brainteaser? :) Really, I just think it's a bad API. Using a library API as simple as `count_if` shouldn't require the user to solve a puzzle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T03:50:17.270",
"Id": "496848",
"Score": "0",
"body": "@Quuxplusone I am trying to implement another version of `recursive_count_if` with specified value_type based on G. Sliepen's comments, please check https://codereview.stackexchange.com/q/252225/231235"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:00:21.510",
"Id": "252154",
"ParentId": "252053",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252154",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T12:49:15.117",
"Id": "252053",
"Score": "2",
"Tags": [
"c++",
"recursion",
"c++20"
],
"Title": "A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
252053
|
<p>I was wondering if you'd be able to review my basic Tax Calculator that incorporates OOP techniques. I'd greatly appreciate it if you didn't mention about my variable naming convention i.e. Hungarian notation, it is a requirement for my university course. Also, please ignore the fact it says about "Windows Forms Application", this is purely a console app in C++. Furthermore, please just treat my program as it is supposed to be inputted I haven't done error-checking. The main point of this is just to get feedback on how I've used OOP techniques. Thanks very much in advance.</p>
<p><a href="https://i.stack.imgur.com/f7VfJ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/f7VfJ.jpg" alt="enter image description here" /></a></p>
<pre><code>// Tax Calculator.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
class Person {
private:
string m_sName;
string m_sBandIncomeTaxName;
bool m_bPayIncomeTax;
bool m_bPayStudentLoan;
double m_dAnnualSalary;
double m_dTaxRate;
double m_dMonthlyIncomeTax;
double m_dWeeklySalary;
double m_dNationalInsurancePay;
double m_dNationalInsuranceRate;
double m_dStudentLoanPay;
double m_dTakeHomePay;
public:
//Constructor
Person() :
m_sName("No name specified"),
m_sBandIncomeTaxName("No name specified"),
m_bPayStudentLoan(0.0),
m_bPayIncomeTax(0.0), m_dAnnualSalary(0.0),
m_dTaxRate(0.0),
m_dMonthlyIncomeTax(0.0),
m_dWeeklySalary(0.0),
m_dNationalInsurancePay(0.0),
m_dNationalInsuranceRate(0.0),
m_dStudentLoanPay(0.0),
m_dTakeHomePay(0.0){}
string GetName() const { return m_sName; }
double GetNationalInsuranceRate() { return m_dNationalInsuranceRate; }
double GetNationalInsurancePay() { return m_dNationalInsurancePay; }
double GetWeeklySalary() { return m_dWeeklySalary; }
double GetAnnualSalary() const { return m_dAnnualSalary; }
double GetMonthlyIncomeTax() { return m_dMonthlyIncomeTax; }
double GetStudentLoanPay() { return m_dStudentLoanPay; }
double GetMonthlyTakeHomePay() { return m_dTakeHomePay; }
bool GetStudentLoanBool() { return m_bPayStudentLoan; }
bool GetIncomeTaxBool() { return m_bPayIncomeTax; }
void SetNationalInsuranceRate(double dNationalInsuranceRate) { m_dNationalInsuranceRate = dNationalInsuranceRate; };
void SetName(string sName) { m_sName = sName; }
void SetAnnualSalary(double dAnnualSalary) { m_dAnnualSalary = dAnnualSalary; }
void SetPayIncomeTax(bool bPayIncomeTax) { m_bPayIncomeTax = bPayIncomeTax; }
void SetPayStudentLoan(bool bPayStudentLoan) { m_bPayIncomeTax = bPayStudentLoan; }
void SetBandIncomeTaxName(string sBandIncomeTaxName) { m_sBandIncomeTaxName = sBandIncomeTaxName; }
void SetTaxRate(double dTaxRate) { m_dTaxRate = dTaxRate; }
void CalculateMonthlyIncomeTax();
void CalculateWeeklyIncome();
void CalculateNationalInsurance();
void CalculateAnnualStudentLoan();
void CalculateMonthlyTakeHomePay();
};
void Person::CalculateMonthlyIncomeTax() {
m_dMonthlyIncomeTax = (m_dAnnualSalary * m_dTaxRate) / 12;
}
void Person::CalculateWeeklyIncome() {
m_dWeeklySalary = (m_dAnnualSalary / 12) / 4;
}
void Person::CalculateNationalInsurance() {
double dRemainderOver = 0;
if (GetWeeklySalary() > 162 && GetWeeklySalary() < 892) {
dRemainderOver = GetWeeklySalary() - 162;
SetNationalInsuranceRate(0.12);
m_dNationalInsurancePay = dRemainderOver * GetNationalInsuranceRate();
}
else
{
dRemainderOver = GetWeeklySalary() - 892;
SetNationalInsuranceRate(0.2);
m_dNationalInsurancePay = dRemainderOver * GetNationalInsuranceRate();
}
}
void Person::CalculateAnnualStudentLoan() {
if (m_dAnnualSalary > 25000) {
m_dStudentLoanPay = m_dAnnualSalary * 0.9;
}
else {
m_dStudentLoanPay = 0;
}
}
void Person::CalculateMonthlyTakeHomePay() {
m_dTakeHomePay = (m_dAnnualSalary / 12) - (m_dNationalInsurancePay * 4) - (m_dStudentLoanPay / 12) - m_dMonthlyIncomeTax;
}
void AddPerson(Person& objPerson)
{
std::string sName = "";
double dAnnualSalary = 0;
std::cout << "Enter the name of the person: " ;
cin >> sName;
objPerson.SetName(sName);
std::cout << "How much do you get annually?: " << char(156);
cin >> dAnnualSalary;
objPerson.SetAnnualSalary(dAnnualSalary);
}
void DoYouPayAnnualIncomeTax(Person& objPerson)
{
unsigned char cChoice;
bool bPayAnnualIncomeTax = false;
bool bPayStudentLoan = false;
std::cout << "Do you pay annual income tax?: (y/n) ";
cin >> cChoice;
cChoice = tolower(cChoice);
if (cChoice == 'y')
{
objPerson.SetPayIncomeTax(true);
}
else if ('n') {
objPerson.SetPayIncomeTax(false);
}
else
{
std::cout << "You've entered an invalid choice!\n";
}
}
void DoYouPayStudentLoan(Person& objPerson)
{
unsigned char cChoice;
bool bPayAnnualIncomeTax = false;
bool bPayStudentLoan = false;
std::cout << "Do you pay a student loan (y/n): ";
cin >> cChoice;
cChoice = tolower(cChoice);
if (cChoice == 'y')
{
objPerson.SetPayStudentLoan(true);
}
else if ('n') {
objPerson.SetPayStudentLoan(false);
}
else
{
std::cout << "You've entered an invalid choice!\n";
}
}
void CalcBandIncomeTaxPayer(Person& objPerson) {
if (objPerson.GetAnnualSalary() < 11850)
{
objPerson.SetBandIncomeTaxName("Personal Allowance");
objPerson.SetTaxRate(0.0);
}
else if (objPerson.GetAnnualSalary() < 46350)
{
objPerson.SetBandIncomeTaxName("Basic Rate");
objPerson.SetTaxRate(0.2);
}
else if (objPerson.GetAnnualSalary() < 150000)
{
objPerson.SetBandIncomeTaxName("Higher Rate");
objPerson.SetTaxRate(0.4);
}
else
{
objPerson.SetBandIncomeTaxName("Additional Rate");
objPerson.SetTaxRate(0.45);
}
}
void DisplayResults(Person &objPerson) {
std::cout << "*********************" << std::endl;
if (objPerson.GetIncomeTaxBool() == true) {
objPerson.CalculateMonthlyIncomeTax();
std::cout << "You pay in monthly income tax: " << char(156) << objPerson.GetMonthlyIncomeTax() << std::endl;
}
if (objPerson.GetStudentLoanBool())
{
objPerson.CalculateAnnualStudentLoan();
std::cout << "Annual Student loan: " << char(156) << objPerson.GetStudentLoanPay() << std::endl;
}
//Make the calculations
std::cout << "Monthly National Insurance: " << char(156) << objPerson.GetNationalInsurancePay() << std::endl;
std::cout << "Monthly Student Loan: " << char(156) << objPerson.GetStudentLoanPay() << std::endl;
std::cout << "Take home pay: " << char(156) << objPerson.GetMonthlyTakeHomePay();
std::cout << "*********************" << std::endl;
}
int main()
{
std::cout << std::setprecision(2) << std::fixed;
Person objPerson;
//Get input from user
AddPerson(objPerson);
DoYouPayAnnualIncomeTax(objPerson);
DoYouPayStudentLoan(objPerson);
CalcBandIncomeTaxPayer(objPerson);
objPerson.CalculateWeeklyIncome();
objPerson.CalculateNationalInsurance();
objPerson.CalculateMonthlyTakeHomePay();
DisplayResults(objPerson);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:33:18.627",
"Id": "496481",
"Score": "0",
"body": "_my variable naming convention is a requirement for my university course._ Great. That said, you won't spend the rest of your career in this university course - you'll spend it in industry, whose standards are somewhat different from company to company. All constructive feedback is on topic, and it's important that you get a feeling for what the rest of the universe understands to be standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:34:16.203",
"Id": "496482",
"Score": "0",
"body": "For C++ there aren't very strong naming standards, mind you, so Hungarian notation is fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:13:29.393",
"Id": "496488",
"Score": "0",
"body": "@Reinderien That's right, the win32 API also uses the Hungarian notation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T20:52:13.047",
"Id": "496516",
"Score": "4",
"body": "It's good to include the problem statement, but please not as an image! Also, ensure you have the legal right to reproduce that if you didn't write it yourself. It's normally better to summarise the problem *in your own words*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T05:02:24.057",
"Id": "496543",
"Score": "1",
"body": "I'm a big fan of Hungarian notation. However, **you are doing Hungarian notation wrong!** Simonyi didn't mean to repeat the actual type in the prefix; he meant the *semantic* type. So, `d` is useless as a prefix because the variable is *already a `double`*. You and the compiler both know that already. Correct Hungarian notation would be something like `c` to indicate that the `double` is semantically a *currency* value. This is something neither you or the compiler know. Other examples include things like `u` to mean \"unsafe\"/\"unsanitized\"/\"user input\", and `sz` to mean NUL-terminated string."
}
] |
[
{
"body": "<h2>Overall Observations</h2>\n<p>The program would be simpler if the following functions were members of the Person Class:</p>\n<ol>\n<li>void AddPerson(Person& objPerson)</li>\n<li>void DoYouPayAnnualIncomeTax(Person& objPerson)</li>\n<li>void DoYouPayStudentLoan(Person& objPerson)</li>\n<li>void CalcBandIncomeTaxPayer(Person& objPerson)</li>\n<li>void DisplayResults(Person& objPerson)</li>\n</ol>\n<p>In that case the class <code>Person</code> would not need most of the getter and setter functions, and all or most of the attributes / member variables could be private. As members of <code>Person</code> those functions would have direct access to private variables and could skip some intermediate steps.</p>\n<p>Example:</p>\n<pre><code>void Person::CalcBandIncomeTaxPayer() {\n\n if (m_dAnnualSalary < 11850)\n {\n m_sBandIncomeTaxName = "Personal Allowance";\n m_dTaxRate = 0.0;\n\n }\n else if (m_dAnnualSalary < 46350)\n {\n m_sBandIncomeTaxName = "Basic Rate";\n m_dTaxRate = 0.2;\n }\n else if (m_dAnnualSalary < 150000)\n {\n m_sBandIncomeTaxName = "Higher Rate";\n m_dTaxRate = 0.4;\n }\n else\n {\n m_sBandIncomeTaxName = "Additional Rate";\n m_dTaxRate = 0.45;\n }\n\n}\n</code></pre>\n<p><code>Addperson</code> should call <code>void DoYouPayAnnualIncomeTax(Person& objPerson)</code> and <code>void DoYouPayStudentLoan(Person& objPerson)</code>.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>The code is inconsistently using <code>std::</code> there are functions where <code>std::cout</code> is used and then the next line uses <code>cin</code>. Whatever you do, be consistent.</p>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Magic Numbers</h2>\n<p>There are Magic Numbers throughout the program, in the <code>CalcBandIncomeTaxPayer()</code> function examples would be: <code>11850</code>, <code>0.0</code>, <code>46350</code> and <code>0.2</code>; it would better to create symbolic constants for them to make the code more readable and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:16:23.047",
"Id": "252063",
"ParentId": "252055",
"Score": "5"
}
},
{
"body": "<h1><strike><code>using namespace std</code></strike></h1>\n<p>It is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">bad practice</a> to have this in your program. Sometimes it is OK if you are writing a small program for something like a programming challenge. Otherwise, I highly discourage the use of this in your programs. The <code>std</code> namespace is HUGE and writing this statement means that now you have no idea what is a part of the standard library and what isn't, you have just erased that line.</p>\n<hr />\n<h1>Default member initialization</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> string m_sName;\n string m_sBandIncomeTaxName;\n\n bool m_bPayIncomeTax;\n bool m_bPayStudentLoan;\n\n double m_dAnnualSalary;\n double m_dTaxRate;\n double m_dMonthlyIncomeTax;\n double m_dWeeklySalary;\n double m_dNationalInsurancePay;\n double m_dNationalInsuranceRate;\n double m_dStudentLoanPay;\n double m_dTakeHomePay;\n\npublic:\n\n //Constructor\n Person() :\n m_sName("No name specified"),\n m_sBandIncomeTaxName("No name specified"),\n m_bPayStudentLoan(0.0),\n m_bPayIncomeTax(0.0), m_dAnnualSalary(0.0),\n m_dTaxRate(0.0),\n m_dMonthlyIncomeTax(0.0),\n m_dWeeklySalary(0.0),\n m_dNationalInsurancePay(0.0),\n m_dNationalInsuranceRate(0.0),\n m_dStudentLoanPay(0.0),\n m_dTakeHomePay(0.0) {}\n</code></pre>\n<p><strong>I feel</strong> you can use default member initialization here since it will do the same job but look a little cleaner since you will avoid repeating the name. <a href=\"https://stackoverflow.com/questions/36600187/whats-the-differences-between-member-initializer-list-and-default-member-initia#:%7E:text=Code%201%3A%20Default%20member%20initializer&text=count%20has%20a%20default%20member,members%20for%20initialization%20is%20determined.\">This thread on Satck Overflow talks about it in detail</a></p>\n<pre class=\"lang-cpp prettyprint-override\"><code> private:\n string m_sName{ "No name specified" };\n string m_sBandIncomeTaxName{ "No name specified" };\n\n bool m_bPayIncomeTax = false;\n bool m_bPayStudentLoan = false;\n\n double m_dAnnualSalary = 0;\n double m_dTaxRate = 0;\n double m_dMonthlyIncomeTax = 0;\n double m_dWeeklySalary = 0;\n double m_dNationalInsurancePay = 0;\n double m_dNationalInsuranceRate = 0;\n double m_dStudentLoanPay = 0;\n double m_dTakeHomePay = 0;\n</code></pre>\n<hr />\n<h1>Avoid using getters and setters</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> string GetName() const { return m_sName; }\n double GetNationalInsuranceRate() { return m_dNationalInsuranceRate; }\n double GetNationalInsurancePay() { return m_dNationalInsurancePay; }\n double GetWeeklySalary() { return m_dWeeklySalary; }\n double GetAnnualSalary() const { return m_dAnnualSalary; }\n double GetMonthlyIncomeTax() { return m_dMonthlyIncomeTax; }\n double GetStudentLoanPay() { return m_dStudentLoanPay; }\n double GetMonthlyTakeHomePay() { return m_dTakeHomePay; }\n bool GetStudentLoanBool() { return m_bPayStudentLoan; }\n bool GetIncomeTaxBool() { return m_bPayIncomeTax; }\n\n void SetNationalInsuranceRate(double dNationalInsuranceRate) { m_dNationalInsuranceRate = dNationalInsuranceRate; };\n void SetName(string sName) { m_sName = sName; }\n void SetAnnualSalary(double dAnnualSalary) { m_dAnnualSalary = dAnnualSalary; }\n void SetPayIncomeTax(bool bPayIncomeTax) { m_bPayIncomeTax = bPayIncomeTax; }\n void SetPayStudentLoan(bool bPayStudentLoan) { m_bPayIncomeTax = bPayStudentLoan; }\n void SetBandIncomeTaxName(string sBandIncomeTaxName) { m_sBandIncomeTaxName = sBandIncomeTaxName; }\n void SetTaxRate(double dTaxRate) { m_dTaxRate = dTaxRate; }\n</code></pre>\n<p>If you simply make the necessary variables <code>public</code>, you will remove the need to have so many extra functions, which would make your code magically look cleaner, even though you did nothing.</p>\n<hr />\n<h1>Taking input that has whitespaces</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code> std::string sName = "";\n double dAnnualSalary = 0;\n std::cout << "Enter the name of the person: " ;\n cin >> sName;\n</code></pre>\n<p>There is a problem here, to check it lets test it with some input</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Enter the name of the person: Aryan Parekh\nHow much do you get annually?: £Do you pay annual income tax?: (y/n) Do you pay a student loan (y/n): *********************\nMonthly National Insurance: £-178.40\nMonthly Student Loan: £0.00\nTake home pay: £713.60*********************\n</code></pre>\n<p>As you can see, immediately after I entered my name the program starts doing weird things. The reason is <code>std::cin</code> will stop reading when it finds a whitespace.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Aryan Parekh \n ^\n It stops here\n</code></pre>\n<p>But <code>Parekh</code> is still there, so for the next prompt which is <code>How much do you get annually?</code>, it takes <code>Parekh</code> when it's expecting a <code>double</code>. After that it goes all downhill. <br>\nUnless the users are only going to have one word in their name, you will have to use <code>std::getline</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::getline( std::cin, sName );\n</code></pre>\n<p>Now when we test with the same input</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Enter the name of the person: Aryan Parekh\nHow much do you get annually?: £\n</code></pre>\n<p>That works.</p>\n<hr />\n<h1><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#:%7E:text=In%20computer%20programming%2C%20the%20term,be%20replaced%20with%20named%20constants\" rel=\"noreferrer\">Magic numbers</a></h1>\n<p>There are <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#:%7E:text=In%20computer%20programming%2C%20the%20term,be%20replaced%20with%20named%20constants\" rel=\"noreferrer\">magic numbers</a> throughout your program, unnamed numbers. You <strong>should</strong> name them. Because it is impossible for others who are reading your code to find out what they mean unless you already know what a line does are you explicitly mention it.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> if (GetWeeklySalary() > 162 && GetWeeklySalary() < 892) {\n\n dRemainderOver = GetWeeklySalary() - 162;\n SetNationalInsuranceRate(0.12);\n m_dNationalInsurancePay = dRemainderOver * GetNationalInsuranceRate();\n }\n</code></pre>\n<hr />\n<h1>Always validate your input</h1>\n<p>There are many instances in your program where you haven't checked whether the user had entered what was asked for. For example</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout << "Do you pay a student loan (y/n): ";\ncin >> cChoice;\n</code></pre>\n<p>The user can always accidentally enter something else or even nothing at all. You always should validate your input. Otherwise, you're counting on the user to enter everything perfectly because if he doesn't your program will go bonkers.<br></p>\n<p>The question also states that your programme should not accept negative/0 as salary input, but you haven't handled that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:25:46.540",
"Id": "496501",
"Score": "0",
"body": "The original poster clearly states at the beginning of the question that they are not checking input, that puts a little restriction on what we can review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:29:11.160",
"Id": "496502",
"Score": "0",
"body": "Also limit your answers on homework questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:30:04.747",
"Id": "496503",
"Score": "0",
"body": "@pacmaninbw I did read that, but I wasn't sure as to what he meant by \" Furthermore, please just treat my program as it is supposed to be inputted I haven't done error-checking \""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:30:14.487",
"Id": "496504",
"Score": "0",
"body": "@pacmaninbw What do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T18:45:02.563",
"Id": "496506",
"Score": "0",
"body": "This wasn’t homework so why was that tag added?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T18:45:56.917",
"Id": "496507",
"Score": "0",
"body": "And thanks for reviewing my program. I’ll definitely improve the points you’ve raised."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T18:46:23.453",
"Id": "496508",
"Score": "0",
"body": "@GeorgeAustinBradley I haven't added that tag, but isn't this an assignment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T22:16:04.497",
"Id": "496520",
"Score": "2",
"body": "I remember being taught, \"don't treat your user like an input file\"."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:53:38.317",
"Id": "252071",
"ParentId": "252055",
"Score": "8"
}
},
{
"body": "<p>Others have mentioned the scattering of magic numbers through the code, and suggested that you give names to them. I'd consider going further than that, and make the tax rules as much as possible be data-driven. In the Real World, governments tweak the thresholds pretty frequently, and you wouldn't want to have to re-compile versions of your program with different constants embedded in it every tax year.</p>\n<p>As a starter, you could define</p>\n<pre><code>std::map<int,int> tax_rates = {\n // upper limit (GBP) => rate (percent)\n {11850, 0},\n {46350, 20},\n</code></pre>\n<p>And then when government adds a new 50% band, or some of your people are on the Scottish scale, you can apply those changes without changing the logic.</p>\n<p>Going further, it would be better to be able to load the rates from data files.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T12:32:17.553",
"Id": "496564",
"Score": "1",
"body": "The one problem I see with this is that the string for tax band name doesn't get assigned, but I don't know if that is important or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:27:35.810",
"Id": "496644",
"Score": "1",
"body": "If that's important, then it would be worth defining a `struct tax_band` with everything that's needed. Left as an exercise for the interested reader..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T20:50:51.590",
"Id": "252081",
"ParentId": "252055",
"Score": "4"
}
},
{
"body": "<p>Personally, I would suggest that you should have two classes, not just one and some static functions.</p>\n<p>Consider the extensibility of this for the future.</p>\n<p>If you have class <em>person</em> and another class <em>taxregime</em> then you have the makings of useful program. As someone else has said, all the constants that you use should be configurable. By having the <em>taxregime</em> class these values could get injected in the constructor for that class. As such, you could now create <em>tax2020</em>, <em>tax2019</em>, <em>tax2018</em>, etc as instances of that class.</p>\n<p>If that <em>taxregime</em> class then has the fundamental calculations in, then you pass it the instance of the <em>person</em> so</p>\n<pre><code> thisYear.getAnnualTax(thisPerson)\n</code></pre>\n<p>Moreover, when the actual tax regime in the country changes, to include extra tax bands etc, or withdrawing personal allowances once you exceed an income threshold, the calculation logic will need to change.</p>\n<p>Your program would become extensible by deriving a new class <em>taxRegime2022</em> from <em>taxRegime</em> and the specific logic that you need to override, for NI, or for tax, can be overridden in there.</p>\n<p>Now you have something where you can make projections or reports based on both the person and the year of income. (If you earned X in 2018 you'd pay this, but if you earned it in 2022 you'd pay this other amount)</p>\n<p>That goes beyond what the question specifically asks for, but solves the real world problem, rather than just the simple requirements.</p>\n<p>Only you can work out whether there is value in doing that for this assignment, or in a job.</p>\n<p>EDIT: pacmaninbow's useful answer suggested a Person::CalcBandIncomeTaxPayer() method. It's a great idea BUT...</p>\n<p>From a <strong>data</strong> point of view, the magic numbers and the calculation have nothing to do with a person, which is why they shouldn't be there. They have to do with the tax regime, and that's why I think you need that second class. Object orientation is primarily about encapsulating and isolating data correctly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T18:03:40.637",
"Id": "252116",
"ParentId": "252055",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252063",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T13:41:10.153",
"Id": "252055",
"Score": "4",
"Tags": [
"c++",
"c++11",
"homework"
],
"Title": "Tax Calculator (using OOP techniques)"
}
|
252055
|
<p>I've started working on a data annotation tool to do segmentation on images or from a video file.</p>
<p>I decided to use Electron because I kind of like designing GUI with HTML/CSS and that it's very easy to set up.</p>
<p>Basically, the application as a limited set of functionality for now :</p>
<ul>
<li>Select an input folder, video file or a single image;</li>
<li>Select an output folder, that isn't used yet;</li>
<li>Save the initial configuration so I don't have to redo it every time I reload the app;</li>
<li>Load images from a folder and load them in a canvas, where we can navigate between each images with previous/next buttons</li>
<li>Call a python script that parses a video and returns a path to an image file representing the current video, where we can also navigate between frames with previous/next (This might be a tad sketchy, but I don't mind as it works very well. I also don't want this reviewed, you may consider it as an external library).</li>
</ul>
<p>This is the first part of the application, where I only deal with loading images and saving configuration, as you may see.</p>
<p><strong>HTML</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline' 'unsafe-eval';" />
<style>
label {
display:block;
padding:5px 0px;
}
.hidden {
display:none;
}
.closed-pane {
display:none;
}
</style>
</head>
<body>
<div>
<h2>Configuration</h2>
<button class="toggle-pane configuration-pane-toggle">Toggle</button>
<div class="configuration-pane">
<ol>
<li>Select which folder or file you want to load. You may load either a folder with images, a single image or a video file that will be parsed;</li>
<li>Specify where you want the annotations to be saved. Note that if there already are annotations in this folder, they will be loaded;</li>
<li>If loading a video, specify if you want to skip some frames as the annotation may get really long;</li>
<li>If you don't want to redo this everytime you open the app, click "Save Config", a json file will be saved beside index.html</li>
<li>Click Start and get started!</li>
</ol>
<label> Input : <input type="text" class="configuration-input"/> <button class="configuration-select-input">Select</button> </label>
<label> Output : <input type="text" class="configuration-output"/> <button class="configuration-select-output">Select</button> </label>
<label> Skip n frames : <input type="number" class="configuraiton-video-skip"/> </label>
<button class="configuration-start">Start</button>
<button class="configuration-save-config">Save config</button>
</div>
</div>
<div>
<h2>Annotation</h2>
<div>
Explanations :
<ol>
<li>Press 1 to use the line annotator. You only need to click the beginning and the end of the line to create a segment. Then, use to scroll up/down to make the line bigger or smaller</li>
</ol>
</div>
<div>
<div class="navigation-pane">
<button class="navigation-save-progress">Save</button>
<button class="navigation-previous">Previous</button>
<button class="navigation-next">Next</button>
</div>
<img id="current-image" class="hidden" width="1280" height="720" src=""/>
<div class="canvas-container" style="position: relative;">
<canvas id="image-canvas" width="1280" height="720" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="writer-canvas" width="1280" height="720" style="position: absolute; left: 0; top: 0; z-index: 999;"></canvas>
</div>
</div>
</div>
</body>
<script src="config-io.js"></script>
</html>
</code></pre>
<p><strong>JavaScript</strong></p>
<p><em>main.js (Electron's entry point)</em></p>
<pre><code>const { app, BrowserWindow } = require('electron');
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
enableRemoteModule: true
}
});
win.setFullScreen(true);
win.loadFile('src/index.html')
win.webContents.openDevTools()
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
</code></pre>
<p><em>config-io.js</em></p>
<pre><code>const fs = require('fs');
const {dialog} = require('electron').remote;
const path = require("path");
const spawn = require("child_process").spawn;
const readline = require('readline');
const constants = Object.freeze({
imageExtensions : ["png", "jpg", "jpeg"],
videoExtensions : ["mp4"]
});
function isImage(f) {
const ext = f.substring(f.lastIndexOf(".")+1);
return constants.imageExtensions.includes(ext);
}
const html = Object.freeze({
txtInput : document.getElementsByClassName("configuration-input")[0],
btnChooseInput : document.getElementsByClassName("configuration-select-input")[0],
btnChooseOutput : document.getElementsByClassName("configuration-select-output")[0],
txtOutput : document.getElementsByClassName("configuration-output")[0],
numSkipFrame : document.getElementsByClassName("configuraiton-video-skip")[0],
btnSaveConfig : document.getElementsByClassName("configuration-save-config")[0],
btnStart : document.getElementsByClassName("configuration-start")[0],
btnPrevious : document.getElementsByClassName("navigation-previous")[0],
btnNext : document.getElementsByClassName("navigation-next")[0],
imgCurrent : document.getElementById("current-image"),
cvsCurrentImg : document.getElementById("image-canvas")
});
const currentImageControler = function() {
function init() {
const file = html.txtInput.value;
const fileName = file.substring(file.lastIndexOf(path.sep)+1);
const isFile = fileName.lastIndexOf(".") != -1;
if (isFile) {
const extension = file.substring(file.lastIndexOf(".")+1);
if (constants.videoExtensions.includes(extension)) {
return fromVideo();
} else if (constants.imageExtensions.includes(extension)) {
return fromFile();
} else {
console.log("File not recognized");
return;
}
}
console.log("folder");
return fromFolder();
}
const fromVideo = function() {
const PythonFilePath = "Path to a script";
let pythonProcess;
let currentValue;
const initialize = function() {
pythonProcess = spawn('python3',[PythonFilePath, html.txtInput.value, html.txtOutput.value, html.numSkipFrame.value ?? 1]);
pythonProcess.stderr.pipe(process.stderr);
readline.createInterface({
input: pythonProcess.stdout,
terminal: false
}).on('line', function(line) {
currentValue = line;
html.imgCurrent.src = currentValue;
});
html.btnNext.onclick = next;
html.btnPrevious.onclick = previous;
document.onclose = (_) => stop().bind(this);
}
function stop() {
pythonProcess.kill();
}
function previous(e) {
pythonProcess.stdin.write("back\n");
}
function next(e) {
pythonProcess.stdin.write("next\n");
}
initialize();
};
const fromFolder = function() {
let currentIndex;
let files;
const initialize = function() {
fs.readdir(html.txtInput.value, {encoding : "utf8"}, function(err, res) {
files = res.filter(isImage).map(x => html.txtInput.value + path.sep + x);
console.log(files);
currentIndex = 0;
html.imgCurrent.src = files[currentIndex];
html.btnNext.onclick = next.bind(this);
html.btnPrevious.onclick = previous.bind(this);
});
}
function next() {
if (currentIndex >= files.length - 1) return;
currentIndex++;
update();
}
function previous() {
if (currentIndex == 0) return;
currentIndex--;
update();
}
const update = function() {
html.imgCurrent.src = files[currentIndex];
}
initialize();
};
const fromFile = function() {
let currentValue;
const initialize = function() {
currentValue = html.txtInput.value;
html.imgCurrent.src = currentValue;
}
function current() {
return currentValue;
}
initialize();
}
init();
}
window.onload = function() {
if (!fs.existsSync("config.json")) return;
const result = fs.readFileSync("config.json", {encoding: "utf-8"});
const config = JSON.parse(result);
html.txtInput.value = config.input;
html.txtOutput.value = config.output;
html.numSkipFrame.value = config.skip_n;
}
html.imgCurrent.onload = function() {
var ctx = html.cvsCurrentImg.getContext("2d");
ctx.drawImage(html.imgCurrent, 10, 10);
};
html.btnChooseInput.onclick = function() {
dialog.showOpenDialog({properties: ['openDirectory', 'openFile']}).then(function (response) {
if (response.canceled) return;
html.txtInput.value = response.filePaths[0];
});
};
html.btnChooseOutput.onclick = function() {
dialog.showOpenDialog({properties: ['openDirectory', 'createDirectory'] }).then(function (response) {
if (response.canceled) return;
html.txtOutput.value = response.filePaths[0];
});
};
html.btnStart.onclick = function() {
currentImageControler();
document.getElementsByClassName("configuration-pane")[0].classList.toggle("closed-pane");
};
html.btnSaveConfig.onclick = function() {
const config = {
input : html.txtInput.value,
output : html.txtOutput.value,
skip_n : html.numSkipFrame.value
};
const jsonConfig = JSON.stringify(config);
fs.writeFile("config.json", jsonConfig, ["utf-8"], () => alert("saved"));
};
Array.from(document.getElementsByClassName("toggle-pane")).forEach(function(element) {
element.addEventListener('click', function(e) { e.target.nextElementSibling.classList.toggle("closed-pane"); });
});
</code></pre>
<p>The whole thing works, but I'm pretty bad when it comes to structuring Javascript code. I come from an object oriented background, but I've been told countless times that while Javascript supports objects, it's not exactly the best paradigm to deal with what Javascript is.</p>
<p>So, I would like some feedback on the way my code is structured, I don't like how everything is laid out, I feel like it's messy.</p>
|
[] |
[
{
"body": "<p><strong>Style rules</strong> You have a few rules in a <code><style></code> tag, but you also have some in inline attributes. To be consistent, better to put it all in the <code><style></code> tag. For example, change</p>\n<pre><code><div class="canvas-container" style="position: relative;">\n</code></pre>\n<p>to</p>\n<pre><code><div class="canvas-container">\n</code></pre>\n<pre><code>.canvas-container {\n position: relative;\n}\n</code></pre>\n<p><strong>Destructure</strong> when you can, it's nice and concise (and can reduce the likelihood of typo-based problems). You're doing it in some places, but not others. <code>const spawn = require("child_process").spawn;</code> can be <code>const { spawn } = require("child_process");</code>.</p>\n<p><strong><code>Object.freeze</code> is shallow</strong> You have:</p>\n<pre><code>const constants = Object.freeze({\n imageExtensions : ["png", "jpg", "jpeg"],\n videoExtensions : ["mp4"]\n});\n</code></pre>\n<p>This will prevent the parent <code>constants</code> from having properties added or removed, but will not prevent the values from being <em>mutated</em> (which is different from reassignment). For example, someone could do <code>constants.imageExtensions.push('BUG')</code>.</p>\n<p>I'm not sure what the <code>Object.freeze</code> here is intended to do. If it's meant to show that the object shouldn't be changed at all, consider using the naming convention for absolute constants instead, with all caps:</p>\n<pre><code>const IMAGE_EXTENSIONS = ["png", "jpg", "jpeg"];\nconst VIDEO_EXTENSIONS = ["mp4"];\n</code></pre>\n<p>or use regular expressions (whose patterns are immutable).</p>\n<p><strong>Use <code>querySelector</code> to retrieve a single element</strong> If you only want the first element of a collection, then rather than use a method that returns a collection and selecting the <code>[0]</code>th element of the collection, better to use <code>querySelector</code> which will return the first matching element.</p>\n<pre><code>txtInput : document.getElementsByClassName("configuration-input")[0],\n</code></pre>\n<p>can be</p>\n<pre><code>txtInput : document.querySelector(".configuration-input"),\n</code></pre>\n<p>Another benefit of using <code>querySelector</code> by default is that it accepts a selector string, and selector strings are incredibly flexible, much more so than any other selection method. (They also match up exactly with CSS rules.)</p>\n<p>To select an element with an ID, prefix it with <code>#</code>, eg <code>document.querySelector('#current-image')</code>.</p>\n<p><strong>Precise variable names</strong> help prevent bugs.</p>\n<ul>\n<li><p>Not a variable, but <code>configuraiton</code> is misspelled - easy source of bugs. Could fix the spelling, or shorten it (and all similar elements) to <code>config</code>.</p>\n</li>\n<li><p>I'd expect a variable named <code>file</code> to be a <a href=\"https://developer.mozilla.org/en/docs/Web/API/File\" rel=\"nofollow noreferrer\">File object</a>. If you just have a string, use something like <code>fileName</code> or <code>pathToFile</code>.</p>\n</li>\n</ul>\n<p>Or, even better, to get the file or folder name and extension, use <code>path</code> methods instead of manipulating the string manually. Use the <a href=\"https://nodejs.org/api/path.html#path_path_basename_path_ext\" rel=\"nofollow noreferrer\"><code>.basename</code></a> method:</p>\n<pre><code>const filePath = html.txtInput.value;\nconst baseName = path.basename(filePath);\nconst extension = path.extname(filePath);\n</code></pre>\n<p><strong>Logs are for debugging</strong>, not for an ordinary user to read - if the file isn't recognized as an image or video, better to display that as an error message by putting it into an element on the screen, eg</p>\n<pre><code><div class='error-file-not-recognized hidden'>\n File extension not recognized (Allowed extensions are: ...)\n</div>\n</code></pre>\n<pre><code>document.querySelector('.error-file-not-recognized').classList.remove('hidden');\n</code></pre>\n<p><strong>Unnecessary variables and parameters</strong> In <code>fromVideo</code>, you have a persistent outer scoped variable <code>currentValue</code>, but it's only used in the <code>line</code> callback. I'd remove the variable entirely and change to:</p>\n<pre><code>}).on('line', function(line) {\n html.imgCurrent.src = line;\n});\n</code></pre>\n<p>You aren't using the <code>current</code> function in <code>fromFile</code> either, nor its associated <code>currentValue</code>.</p>\n<p>You also don't need to declare a parameter that isn't going to be used. Eg</p>\n<p><code>function previous(e) {</code> can be <code>function previous() {</code>, and <code>document.onclose = (_) =></code> can be <code>document.onclose = () =></code>.</p>\n<p>Using <code>_</code> as a parameter name is a common convention when you need a <em>later</em> parameter but don't need the initial parameter(s), eg:</p>\n<pre><code>const arr = Array.from(\n { length: 5 },\n (_, i) => i\n);\n</code></pre>\n<p>But since you aren't using later parameters, you can empty the argument list entirely.</p>\n<p><strong>bind</strong> <code>fn.bind(this)</code> is only useful when <code>fn</code> references <code>this</code> inside, and you need to make sure the calling context is preserved. But the <code>stop</code> function doesn't reference <code>this</code>, so it's not needed. You can use <code>document.onclose = stop;</code>. Same thing applies to the <code>fromFolder</code> function, which has the same issue in a couple places.</p>\n<p><strong>Assign immediately with <code>const</code></strong> Rather than declaring a variable with <code>let</code> and then reassigning it inside a function, consider declaring the variable with <code>const</code> and assigning it a value immediately:</p>\n<pre><code>const pythonProcess = spawn('python3', // ...\n</code></pre>\n<p><strong>Don't ignore errors</strong> Some of the callback-based functions you're calling return an error as the first parameter. Don't ignore this - the whole reason the error is the first parameter rather than a later one is to prompt the programmer to check for errors before going on to parse the result. When an error occurs, inform the user by changing an element in the DOM (not by just <code>console.log</code>ging) so they can try again or send a bug report or something, rather than the script failing silently.</p>\n<p>The same thing applies to the uses of <code>dialog</code>, though they're Promise-based, not callback-based, so to catch errors, add a <code>.catch</code> onto the end of them.</p>\n<p>On a somewhat similar note, to make it clearer to the user what the script is currently doing, when <code>fromVideo</code> or <code>fromFolder</code> is called, consider setting the <code>imgCurrent.src</code> <em>immediately</em> (maybe to a placeholder like "Please wait for the image to load..."), and then set it again when the <code>line</code> or <code>readdir</code> callback runs.</p>\n<p><strong>Use <code>const</code></strong> whenever you can. You're already doing this in most places, but you also have a spare <code>var</code>: <code>var ctx = html.cvsCurrentImg.getContext("2d");</code>. Consider using ESLint and <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\"><code>no-var</code></a>.</p>\n<p><strong>Concise iteration</strong> Instead of:</p>\n<pre><code>Array.from(document.getElementsByClassName("toggle-pane")).forEach(function(element) {\n</code></pre>\n<p>consider using <code>querySelectorAll</code>, whose NodeLists have <code>forEach</code>:</p>\n<pre><code>document.querySelectorAll('.toggle-pane').forEach((element) => {\n</code></pre>\n<p>Or invoke the iterator:</p>\n<pre><code>for (const element of document.querySelectorAll('.toggle-pane')) {\n</code></pre>\n<p><strong>Overall</strong> This general structure of lots of somewhat-related event handlers being placed in the JS willy-nilly is pretty common with vanilla DOM manipulation. It's not <em>bad</em> per se, but it does look somewhat messy, and gets much worse the larger the page gets. If it were me, I'd strongly prefer to use a framework like React instead, removing the need to select elements from the DOM, allowing listeners to be tied directly with their associated DOM elements, and with better state management and more functional logic.</p>\n<p>If you have time to learn (if you already know how JS works, it's pretty easy), IMO it makes larger projects <em>much</em> easier to manage, and is a lot nicer than vanilla DOM manipulation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-20T14:46:45.857",
"Id": "497318",
"Score": "0",
"body": "Thank you for your answers and suggestions, I appreciate it :) I'll look into React.JS"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T18:27:28.393",
"Id": "252073",
"ParentId": "252056",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252073",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T14:07:17.320",
"Id": "252056",
"Score": "6",
"Tags": [
"javascript",
"electron"
],
"Title": "Data annotation tool 1 : Managing inputs and configuration"
}
|
252056
|
<p>Taken the following Exercise from Cracking the coding interview:</p>
<pre><code>Given a linked list which might contain a loop, implement an algorithm that
returns the node at the beginning of the loop (if one exists).
EXAMPLE
Input: A -> B -> C -> D -> E -> C [the same C as earlier]
Output: C
</code></pre>
<p>My Solution here was to store each node in a unordered_set. If we insert a node and it already exists it must be the begin of the loop.</p>
<p>Here my code:</p>
<p>LinkedList.h - Impelments a very primitive LinkedList with some operations. I know it has flaws (like not cleaning the memory. But not the concern of this question).</p>
<p>MySolution.cpp - Function <code>findBeginning</code> is the solution. Rest is some helper code to test with a looped list and a non looped list.</p>
<p><strong>LinkedList.h</strong></p>
<pre><code>#include <vector>
#include <iostream>
#include <string>
template<typename T>
struct Node{
T val;
Node *next;
~Node() {
std::cout << "destroyed: " << val << '\n';
}
};
template<typename T>
Node<T>* makeNode(T value)
{
return new Node<T>{value, nullptr};
}
Node<char>* makeLinkedList(const std::string& values)
{
Node<char>* head = nullptr;
Node<char>* curr = nullptr;
for(const auto& value : values) {
auto newNode = makeNode(value);
if(head == nullptr) {
head = newNode;
curr = head;
}
else {
curr->next = newNode;
curr = curr->next;
}
}
return head;
}
template<typename T>
void printLinkedList(Node<T> * head)
{
auto curr = head;
while(curr != nullptr) {
std::cout << curr->val << " -> ";
curr = curr->next;
}
std::cout<< "nullptr" << "\n";
}
</code></pre>
<p><strong>MySolution.cpp</strong></p>
<pre><code>#include "LinkedList.h"
#include <cassert>
#include <unordered_set>
/*
Store each node in a unordered_set. If Item already exsists in unordered set
it must be the beginning of the loop
*/
template<typename T>
Node<T>* findBeginning(Node<T>* head)
{
if(head == nullptr) {
return nullptr;
}
std::unordered_set<Node<T>*> table;
auto curr = head;
while(curr != nullptr) {
auto resultPair = table.insert(curr);
if(!resultPair.second) { // found duplicate
return curr;
}
curr = curr->next;
}
return nullptr;
}
template<typename T>
Node<T>* getLastNode(Node<T>* head)
{
auto curr = head;
while(curr->next != nullptr) {
curr = curr->next;
}
return curr;
}
int main()
{
auto nonLooped = makeLinkedList("ABCDE");
auto looped = makeLinkedList("ABCDE");
auto last = getLastNode(looped);
auto cNode = looped->next->next;
last->next = cNode;
assert(findBeginning(nonLooped) == nullptr);
assert(findBeginning(looped)->val == 'C');
}
</code></pre>
<p>Now I wonder if findBeginning is a good Solution for the problem? I think it is very easy to understand. The reason I ask this is because the book only presents an other solution which does not need an additional data structure but uses to pointers to race each other.</p>
<p><strong>BookSolution (Translated by me from Java to C++):</strong></p>
<pre><code>template<typename T>
Node<T>* findBeginning(Node<T>* head)
{
auto slow = head;
auto fast = heas;
// Find meeting point. This will be LOOP_SIZE -k steps into the linked list
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow = fast) { // Collision
break;
}
}
// Error Check - no meeting point, and therefore no loop
if (fast == nullptr || fast->next == nullptr) {
return nullptr;
}
// Move slow to Head. Keep fast at Meeting Point. Each are k steps from the
// Loop Start. If they move at the same pace, they must meet at Loop start
slow = head;
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
// Both now point to the start of the loop
return fast;
}
</code></pre>
<p>Let me know what you think about both solutions. Is there another Solution you would solve the problem?</p>
|
[] |
[
{
"body": "<p>This is a very common interview question.</p>\n<p>There are two common solutions.</p>\n<ol>\n<li>Walk the list and see if you find a common node.</li>\n<li>Walk the list with two pointers. One pointer goes at speed 1 the second pointer moves at speed 2. If there is a loop they will eventually match or you will reach the end of the list.</li>\n</ol>\n<p>The problem with technique 1 is that it can use up a large amount of memory storing all the nodes you have found. The problem with the second technique is that it does not find the node where the loop happens (it just detects the loop) but does not use up any extra space.</p>\n<p>So you have picked a good solution to the problem (as stated) as you need to find the node where loop is formed.</p>\n<p>The only comment of the test is that this is not required.</p>\n<pre><code>if(head == nullptr) {\n return nullptr;\n}\n</code></pre>\n<p>Since you don't give much to review I will also look at the code creating the list. Again not much to review here:</p>\n<p>But we can simplify the makeLinkedList().</p>\n<pre><code>Node<char>* makeLinkedList(const std::string& values)\n{\n Node<char> sentinal('?', nullptr);\n Node<char>* curr = &sentinal;\n\n for(const auto& val: values) {\n curr->next = new Node<char>{val, nullptr};\n curr = curr->next;\n }\n return sentinal->next;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:16:09.883",
"Id": "252067",
"ParentId": "252058",
"Score": "5"
}
},
{
"body": "<p>If you want to optimize for ease of understanding, then your solution is indeed better than the book solution. However, in general the best algorithms are those that are fast and use little memory. The book solution is hard to beat.</p>\n<p>If this is a programming challenge, and you don't care what happens with the linked list afterwards, then another possible solution is to modify nodes in some way to record whether you have visited them or not. For example, you can assume that pointers are aligned to at least 4 bytes, and thus store data in the lowest two bits without destroying any information. Thus you could solve the problem like so:</p>\n<pre><code>template<typename T>\nNode<T>* findBeginning(Node<T>* head)\n{\n while (head) {\n if ((uintptr_t)head->next & 1) {\n break;\n }\n\n auto next = head->next;\n head->next = (Node<T> *)((uintptr_t)head->next | 1);\n head = next;\n }\n\n return head;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:18:25.433",
"Id": "496498",
"Score": "1",
"body": "At least de-mangle the pointers you have messed with before returning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:23:30.243",
"Id": "496500",
"Score": "1",
"body": "@MartinYork I did mention this solution is only for programming challenges where you don't care about the linked list afterwards. Otherwise, I would just go for Floyd's cycle finding algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T23:24:45.700",
"Id": "496525",
"Score": "1",
"body": "@MartinYork Considering that OP's code (and both answers to date) assume leaking is fine, what does a little more breakage matter."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:20:02.623",
"Id": "252068",
"ParentId": "252058",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T14:30:38.717",
"Id": "252058",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Linked List Loop detection"
}
|
252058
|
<p>I'm using Symfony 4, I have a class named <strong>Fiche</strong>, it contains the attributes and by default the getters and setters functions of course.</p>
<p>Inside this Class, I have created over than <strong>107</strong> others functions to make calculations and then create the lines <strong>(over 40)</strong> of the <strong>pay slip</strong> of an employee and get gross salary and net salary.</p>
<p>The Fiche class becomes very big and it's no more organized, so how can I put each collection of functions in others classes and when I render the Fiche object inside twig I can access to those function ?</p>
<p>This is part of my class :</p>
<pre><code>class Fiche
{
// attributes
// ............
public function calculTotalSalaireBrut()
final public function netAPayer()
public function calculPrimesDiverses()
public function statutSalarie()
final public function calculTauxSalaireMensuel()
final public function calculTauxSalHeuresSupp()
final public function calculMontantSalHeuresSupp()
// over than 100 others functions
}
</code></pre>
<p>In the controller:</p>
<pre><code>/**
* @Route("/voir/{token}", name="front_fiche_voir")
* @Security("has_role('ROLE_ENTREPRISE')")
*/
public function show(Fiche $fiche)
{
$this->denyAccessUnlessGranted('VIEW', $fiche);
return $this->render('front/fiche/show.html.twig', array(
'fiche' => $fiche,
));
}
</code></pre>
<p>a part of code inside twig template :</p>
<pre><code> <td class="td-right">{{ fiche.totalHeuresMaj }}</td>
<td class="td-right">{{ fiche.calculTauxSalHeuresSuppN|number_format(2, '.', '') }}</td>
<td class="td-right">{{ fiche.calculMontantSalHeuresSuppN|number_format(2, '.', '') }}</td>
</code></pre>
<p>How can I organize my class ? How can I put each collection of functions in others classes and <strong>have the possibility to access</strong> to them <strong>via the Object</strong>, either in PHP or in twig</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:37:30.890",
"Id": "496505",
"Score": "2",
"body": "Please add the full code, or at least \" enough \" for a proper review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T21:15:19.447",
"Id": "496517",
"Score": "2",
"body": "If you plan to communicate with other programmers about bigger parts of your code, it would help if it was easy for them to read it. Personally I can work with French, but a lot of people here can't. They won't be able to read your code without having a dictionary handy. Basically my suggestion is to write your code in English. Output should, of course, remain French. As for your question: Is there a logical way that **Fiche** can be split into multiple classes? We cannot judge that based on the code in your question."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:03:19.100",
"Id": "252061",
"Score": "1",
"Tags": [
"php",
"design-patterns"
],
"Title": "How to put my functions outside a class to get organized, Design pattern"
}
|
252061
|
<p>I have built a small tkinter program that I want to have a few different themes it can change between. In order to dynamically change the colours/font for each widget I have subclassed tkinter, and I am just wondering if there is any smarter way of doing this? I am aware that ttk can do something similar, but then as I understand it you are forced to use one of the ttk themes, rather than the standard tkinter widget design, which I prefer to avoid</p>
<p>Example for the button widget:</p>
<pre><code>class Button(tk.Button):
objects = []
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.__class__.objects.append(self)
@classmethod
def set_config(cls, **val):
for obj in cls.objects:
obj.config(val)
def destroy(self):
cur_obj = next(idx for idx, x in enumerate(self.objects) if x.bindtags() == self.bindtags())
del self.__class__.objects[cur_obj]
super().destroy()
</code></pre>
<p>A full example of the running code has been included below.<br />
This is not my current implementation, but just a minimal example to show how the color changer works in practice. NB: The <code>tk_dynamic</code> module contains the subclasses for each widget in the same spirit as the one for <code>Button</code>, shown above.</p>
<pre><code>from utils import tk_dynamic as tkd
from tkinter import ttk
import tkinter as tk
themes = ['light', 'dark']
theme_map = {
'light': {
tkd.Tk: dict(bg='#f0f0ed'),
tkd.Label: dict(bg='#f0f0ed', fg='black'),
tkd.Button: dict(bg='gray85', fg='black'),
tkd.LabelFrame: dict(bg='#f0f0ed'),
tkd.Radiobutton: dict(bg='gray85', selectcolor='white')
},
'dark': {
tkd.Tk: dict(bg='black'),
tkd.Label: dict(bg='black', fg='#ffffff'),
tkd.Button: dict(bg='gray47', fg='#ffffff'),
tkd.LabelFrame: dict(bg='black'),
tkd.Radiobutton: dict(bg='gray47', selectcolor='gray78')
}
}
class ThemedTkinter:
def __init__(self, theme=themes[0]):
self.root = tkd.Tk()
self.active_theme = theme
self.theme_var = tk.StringVar(value=theme)
self.make_widgets()
self._change_theme()
self.root.mainloop()
def make_widgets(self):
tkd.Label(self.root, text='This is a test application').pack()
# Create a test row
lf1 = tkd.LabelFrame(self.root)
lf1.pack(expand=True, fill=tk.X)
svar = tk.IntVar()
tkd.Label(lf1, text='Option 1').pack(side=tk.LEFT)
tkd.Radiobutton(lf1, text='Off', indicatoron=False, value=0, variable=svar).pack(side=tk.RIGHT)
tkd.Radiobutton(lf1, text='On', indicatoron=False, value=1, variable=svar).pack(side=tk.RIGHT)
# Create choice to change theme
lf2 = tkd.LabelFrame(self.root)
lf2.pack(expand=True, fill=tk.X)
tkd.Label(lf2, text='Active theme').pack(side=tk.LEFT)
theme_choices = ttk.Combobox(lf2, textvariable=self.theme_var, state='readonly', values=themes)
theme_choices.bind("<FocusOut>", lambda e: theme_choices.selection_clear())
theme_choices.bind("<<ComboboxSelected>>", lambda e: self._change_theme())
theme_choices.config(width=11)
theme_choices.pack(side=tk.RIGHT, fill=tk.X, padx=2)
def _change_theme(self):
if self.theme_var.get() != self.active_theme:
self.active_theme = self.theme_var.get()
chosen_theme = theme_map[self.active_theme]
for k, v in chosen_theme.items():
k.set_config(**v)
ThemedTkinter()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:05:00.077",
"Id": "496485",
"Score": "1",
"body": "Please show the entire program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T16:27:33.483",
"Id": "496491",
"Score": "0",
"body": "The entire program is several thousand lines of code, but you can see it here https://github.com/oskros/MF_run_counter"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T14:54:23.547",
"Id": "496896",
"Score": "0",
"body": "yes added an example of the entire program now"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T15:51:02.673",
"Id": "252065",
"Score": "2",
"Tags": [
"python",
"tkinter"
],
"Title": "Creating tkinter widgets that can dynamically change configs"
}
|
252065
|
<p>So, the concept of the code is simple. Take any file, read the binary character counts and construct a Huffman tree, and then output the bit code of each character (displayed as its 8-bit value).</p>
<p>This is for a class where we're learning proper modern C++ practices. So no C-style casting, no manual allocations, and unsafe pointers, etc.</p>
<p>I had to work a lot with unique_ptr and shared_ptr in this small assignment, and it's also my first time doing a const_cast which I know should be rarely if at all used.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <fstream>
#include <string>
#include <queue>
#include <vector>
#include <memory>
struct Node {
std::shared_ptr<Node> s_left;
std::shared_ptr<Node> s_right;
int16_t s_charcode;
uint64_t s_count;
Node(int16_t frequency, uint64_t c_count) {
s_left = s_right = nullptr;
s_charcode = frequency;
s_count = c_count;
}
Node(std::shared_ptr<Node> l, std::shared_ptr<Node> r) {
if (r->s_count > l->s_count) {
s_right = r;
s_left = l;
}
else {
s_right = l;
s_left = r;
}
s_count = l->s_count + r->s_count;
s_charcode = -1;
}
};
class CompareNode
{
public:
bool operator()(std::shared_ptr<Node>& left, std::shared_ptr<Node>& right) {
return left->s_count > right->s_count;
}
};
class HuffmanEncoder {
public:
HuffmanEncoder(const std::string& path) :
char_counts(256)
{
m_input.open(path, std::ios::binary);
if (!m_input.is_open()) {
std::cout << "File not accessible or doesn't exist.\n";
exit(EXIT_FAILURE);
}
if (!evaluate_input()) {
std::cout << "Error while reading file.\n";
exit(EXIT_FAILURE);
}
}
void construct_tree();
void output_codes();
private:
std::basic_ifstream<uint8_t> m_input;
std::vector<uint64_t> char_counts;
std::priority_queue<std::shared_ptr<Node>, std::vector<std::shared_ptr<Node>>, CompareNode> min_heap;
bool evaluate_input();
bool bit_search_traversal(const uint8_t& character, const std::shared_ptr<Node>& node, std::string& bits);
auto get_top_ptr();
};
bool HuffmanEncoder::evaluate_input()
{
uint8_t c;
while (m_input.get(c)) {
char_counts[c]++;
}
if (m_input.bad() || !m_input.eof())
return false;
for (uint16_t char_index = 0; char_index < 256; char_index++) {
if (char_counts[char_index] != 0)
min_heap.push(std::move(std::unique_ptr<Node>(new Node{ static_cast<int16_t>(char_index), char_counts[char_index] })));
}
return true;
}
// Has to be encapsulated cause it's a dangerous but valid operation
// Top method of pq returns const reference, but we need to move ownership of shared_ptr from pq, so const_cast
auto HuffmanEncoder::get_top_ptr()
{
std::shared_ptr<Node> temp = std::move(const_cast<std::shared_ptr<Node>&>(min_heap.top()));
min_heap.pop();
return std::move(temp);
}
void HuffmanEncoder::construct_tree() {
while (min_heap.size() > 1) {
std::shared_ptr<Node> node_one = get_top_ptr();
std::shared_ptr<Node> node_two = get_top_ptr();
min_heap.push(std::move(std::unique_ptr<Node>(new Node{ std::move(node_one), std::move(node_two) })));
}
}
// In-Order search
bool HuffmanEncoder::bit_search_traversal(const uint8_t& character, const std::shared_ptr<Node>& node, std::string& bits)
{
if (node == nullptr)
return false;
if (node->s_charcode == character)
return true;
bits += "0";
if (bit_search_traversal(character, node->s_left, bits))
return true;
else
bits.pop_back();
bits += "1";
if (bit_search_traversal(character, node->s_right, bits))
return true;
else
bits.pop_back();
return false;
}
void HuffmanEncoder::output_codes() {
for (uint16_t charcode = 0; charcode < 256; charcode++) {
if (char_counts[charcode] != 0) {
std::string bits{ "" };
bit_search_traversal(static_cast<uint8_t>(charcode), min_heap.top(), bits);
std::cout << charcode << ": " << bits << std::endl;
}
}
}
int main(int argc, char* argv[])
{
if (argc != 2)
return EXIT_FAILURE;
HuffmanEncoder encoder{ argv[1] };
encoder.construct_tree();
encoder.output_codes();
return 0;
}
</code></pre>
<p>NOTE: The exit() statements in the constructor and methods are there due to how the automatic test evaluates the code, otherwise I'd throw and exception</p>
<p>The code is as simple as it can be I'd reckon. I'm just worried whether I'm using the unique_ptr and shared_ptr along with all the moves correctly. Wouldn't want leaks and security issues, would we?..</p>
<p>I'm also wondering if it'll be able to process files of about 10GB.
As far as I know, basic_fstream with .get() is buffered so there shouldn't be an issue there, but I'm new to C++ (about two months) so I'm not entirely sure.</p>
<p>Code compiled with -W4 with no errors or warnings. Example input file worked as intended.</p>
<p><a href="https://drive.google.com/drive/folders/1kzqzr2tuHxkDQwa41XxSLtlmNZt0g8VG?usp=sharing" rel="noreferrer">Here is a link to GDrive with an example input file and its output. The example_cleartext_input is the same as example_input</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:15:05.140",
"Id": "496497",
"Score": "1",
"body": "Welcome to Code Review! Great first question, is it possible to add a small example test input with the generated output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:20:11.913",
"Id": "496499",
"Score": "0",
"body": "Example added now :)"
}
] |
[
{
"body": "<pre><code>struct Node {\n std::shared_ptr<Node> s_left;\n std::shared_ptr<Node> s_right;\n</code></pre>\n<p>I don't think we really need <code>shared_ptr</code> here, as we're not really sharing ownership of the nodes. <code>std::unique_ptr</code> should work fine.</p>\n<hr />\n<pre><code>int16_t s_charcode;\nuint64_t s_count;\n</code></pre>\n<p>Being pedantic, but we should use the integer types in the <code>std::</code> namespace for C++ (<code>std::int16_t</code>, <code>std::uint64_t</code>), instead of the C ones in the global namespace.</p>\n<hr />\n<pre><code>Node(int16_t frequency, uint64_t c_count) {\n s_left = s_right = nullptr;\n s_charcode = frequency;\n s_count = c_count;\n}\n</code></pre>\n<p>We should use a constructor initializer list to initialize member variables:</p>\n<pre><code>Node(int16_t frequency, uint64_t c_count):\n s_charcode(frequency),\n s_count(c_count) { }\n</code></pre>\n<hr />\n<pre><code>Node(std::shared_ptr<Node> l, std::shared_ptr<Node> r) {\n if (r->s_count > l->s_count) {\n s_right = r;\n s_left = l;\n }\n else {\n s_right = l;\n s_left = r;\n }\n\n s_count = l->s_count + r->s_count;\n s_charcode = -1;\n}\n</code></pre>\n<p>Again, we can use the constructor initializer list. We can also avoid extra copies of the <code>std::shared_ptr</code> by using <code>std::move</code>, e.g.:</p>\n<pre><code>Node(std::shared_ptr<Node> l, std::shared_ptr<Node> r):\n s_right(std::move(r)),\n s_left(std::move(l)),\n s_count(s_right->s_count + s_left->s_count),\n s_charcode(-1)\n{\n if (s_right->s_count <= s_left->s_count)\n s_right.swap(s_left);\n}\n</code></pre>\n<hr />\n<pre><code> bool operator()(std::shared_ptr<Node>& left, std::shared_ptr<Node>& right) {\n return left->s_count > right->s_count;\n }\n</code></pre>\n<p>This should take the <code>shared_ptr</code> arguments by <code>const &</code>. The function itself can also be declared <code>const</code>, since it doesn't change anything in the <code>CompareNode</code> class.</p>\n<hr />\n<pre><code>std::priority_queue<std::shared_ptr<Node>, std::vector<std::shared_ptr<Node>>, CompareNode> min_heap;\n</code></pre>\n<p><code>min_heap</code> is declared to use <code>std::shared_ptr<Node></code>, but is given <code>std::unique_ptr</code>s:</p>\n<pre><code>for (uint16_t char_index = 0; char_index < 256; char_index++) {\n if (char_counts[char_index] != 0)\n min_heap.push(std::move(std::unique_ptr<Node>(new Node{ static_cast<int16_t>(char_index), char_counts[char_index] })));\n}\n</code></pre>\n<p>Which is a little strange... We could create <code>shared_ptr</code>s directly, or change the data structure to store <code>unique_ptr</code>s.</p>\n<p>Note that <code>std::make_unique</code> and <code>std::make_shared</code> exist, so we don't have to use <code>new</code>.</p>\n<hr />\n<pre><code>auto HuffmanEncoder::get_top_ptr()\n{\n std::shared_ptr<Node> temp = std::move(const_cast<std::shared_ptr<Node>&>(min_heap.top()));\n min_heap.pop();\n return std::move(temp);\n}\n</code></pre>\n<p>Note that <code>return temp;</code> suffices. We don't need to explicitly call <code>std::move</code> there.</p>\n<hr />\n<pre><code> min_heap.push(std::move(std::unique_ptr<Node>(new Node{ std::move(node_one), std::move(node_two) })));\n</code></pre>\n<p>Again, we can <code>std::make_shared</code> or <code>std::make_unique</code>, and there's no need for the outermost <code>std::move</code>. The argument is already an r-value:</p>\n<pre><code> min_heap.push(std::make_unique<Node>(std::move(node_one), std::move(node_two)));\n</code></pre>\n<hr />\n<pre><code>bool HuffmanEncoder::bit_search_traversal(const uint8_t& character, const std::shared_ptr<Node>& node, std::string& bits)\n</code></pre>\n<p>Passing the <code>shared_ptr</code> by <code>const&</code> is good. But there's no need to pass a Plain Old Data type like <code>uint8_t</code> by <code>const&</code>. It's faster to just copy it.</p>\n<hr />\n<pre><code>bits += "0";\nif (bit_search_traversal(character, node->s_left, bits))\n return true;\nelse\n bits.pop_back();\n</code></pre>\n<p>Using a <code>std::string</code> to collect the bits might be quite slow. Perhaps use a <code>std::vector<bool></code> for this and convert to string when we need to.</p>\n<p>Also, I think we can avoid the pushing and popping from the string:</p>\n<pre><code>if (bit_search_traversal(character, node->s_left, bits))\n{\n bits += "0";\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T20:36:05.610",
"Id": "496512",
"Score": "1",
"body": "We don't actually know whether to use `int16_t` or `std::int16_t`, since neither `<stdint.h>` nor `<cstdint>` is included! Obviously we prefer the latter in new C++ code, but the missing include is something else to mention in review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T21:19:49.117",
"Id": "496518",
"Score": "0",
"body": "Thanks for the awesome feedback! This will be very helpful to me in the future"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T22:53:20.203",
"Id": "496523",
"Score": "1",
"body": "Just noticed. Where you suggest initializing the Node using the left and right node using an initializer list, it is not possible. Once one of the arguments was moved, it is not available anymore to be used in the next initialization step in the comparison"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T10:27:27.313",
"Id": "496553",
"Score": "1",
"body": "Good point. I've edited the post with one possible way around this."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T19:34:17.360",
"Id": "252078",
"ParentId": "252072",
"Score": "5"
}
},
{
"body": "<p>To add to user673679's answer:</p>\n<h1>Avoid using the <code>auto</code> return type for member function declarations</h1>\n<p>You used the <code>auto</code> return type for <code>get_top_ptr()</code>, but this is the only feature you used that is not in C++11. So if you avoid this, your code can be compiled with a wider range of compilers. Also, it is much nicer to see up front in the function declaration inside <code>class HuffmanEncoder</code> what return type to expect when calling this function.</p>\n<h1>Avoid non-standard <code>ifstream</code>s</h1>\n<p>Unfortunately, the C++ standard does not guarantee that <code>std::basic_ifstream<uint8_t></code> works as expected, see <a href=\"https://stackoverflow.com/a/17876141/5481471\">this answer</a>. To be compatible with as many C++ environments as possible, just use <code>std::ifstream</code>, read <code>char</code>s, and cast them as necessary, like so:</p>\n<pre><code>class HuffmanEncoder {\n ...\n std::ifstream input;\n};\n\nbool HuffmanEncoder::evaluate_input()\n{\n char c;\n while (m_input.get(c)) {\n char_counts[static_cast<uint8_t>(c)]++;\n }\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T19:45:40.480",
"Id": "252079",
"ParentId": "252072",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "252078",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T17:11:45.010",
"Id": "252072",
"Score": "7",
"Tags": [
"c++",
"console",
"c++17",
"encoding"
],
"Title": "Huffman encoding bitcodes display"
}
|
252072
|
<p>I'm trying to write a <code>TRANSACTION</code> with <code>node-postgres</code> in an Express API. [The code below works as it's supposed to, mostly looking for what should be corrected/changed]</p>
<p>This would be a <code>POST</code> request that creates a "transaction" and updates a record in a separate table. So basically a couple of queries at once. Below is the code:</p>
<p>For context, <code>db</code> is a connection pool to a postgres db.</p>
<pre class="lang-js prettyprint-override"><code>// @desc Add a Transaction
// @route DELETE /api/v1/envelopes/:id/transactions
exports.addEnvelopeTransaction = async (req, res) => {
const { id } = req.params;
const { title, amount } = req.body;
const date = new Date();
const envelopeQuery = "SELECT * FROM envelopes WHERE envelopes.id = $1";
const transactionQuery = "INSERT INTO transactions(title, amount, date, envelope_id)VALUES($1, $2, $3, $4) RETURNING *";
const updateEnvQuery = "UPDATE envelopes SET budget = budget - $1 WHERE id = $2 RETURNING *";
try {
// Use SQL TRANSACTION
await db.query('BEGIN');
const envelope = await db.query(envelopeQuery, [id])
if (envelope.rowCount < 1) {
return res.status(404).send({
message: "No envelope information found",
});
};
const newTransaction = await db.query(transactionQuery, [title, amount, date, id]);
await db.query(updateEnvQuery, [amount, id]);
await db.query('COMMIT');
res.status(201).send({
status: 'Success',
message: 'New transaction created',
data: newTransaction.rows[0],
});
} catch (err) {
await db.query('ROLLBACK');
return res.status(500).send({
error: err.message
});
}
};
</code></pre>
<p>I smell some bad code here, I can't really tell if I'm using <code>BEGIN</code>, <code>COMMIT</code>, and <code>ROLLBACK</code> in the appropriate places.</p>
<p>What should I change?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T18:40:01.180",
"Id": "252074",
"Score": "1",
"Tags": [
"node.js",
"api",
"express.js",
"postgresql"
],
"Title": "Creating a transaction with node-pg and Express"
}
|
252074
|
<p>I am looking for help for two things:</p>
<p>1.how precise this approximation is (such as Big O or percent error)
2. How efficient the algorithm for time / space usage.</p>
<p>I created an algorithm to estimate an integral. The algorithm creates squares and adds the estimate of the remain sum times the area together. Since this function is 2d, the area is multiplied by f(x, y) at a point. The function in this program is f(x, y) = x + (a * y).</p>
<p>The documented code is below.</p>
<pre><code>
def f(x:float, y:float, a:float)->float:
"""
param x:float, x within the function domain
param y:float, y within the function domain
param a:float, a paramter of the curve
Output: Number of function at the point
"""
return x + (a * y)
class Square:
def __init__(self, xi:float, yi:float, xf:float, yf:float)->None:
"""
param xi:float, smaller coordinate of x
param yi:float, smaller coordinate of y
param xf:float, larger cooordinate of x
"""
self.xi = xi
self.yi = yi
self.xf = xf
self.yf = yf
def estimate(self, a:float)->float:
"""
param a:float, a from the curve paramter
Output: a term to add to estimate the intergal
"""
xd = self.xf - self.xi
yd = self.yf - self.yi
if xd < 0:
xd = xd * -1
if yd < 0:
yd = yd * -1
area_delta = xd * yd
est = f(self.xi, self.yi, a)
return area_delta * est
def main()->None:
""""
Input: None
Output:None
Note: driver program
"""
x = [1.0, 2.0, 3.0]
y = [2.0, 3.0, 4.0]
a = 1.0
add = 0.0
square = None
for row in range(len(x)):
for col in range(len(x)):
if row <= col:
continue
square = Square(x[row], y[row], x[col], y[col])
add = add + square.estimate(a)
print(add)
if __name__ == "__main__":
main()
<span class="math-container">``</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T20:42:01.370",
"Id": "496514",
"Score": "0",
"body": "Note: a is a constant argument of the function to compute."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T18:37:16.790",
"Id": "496693",
"Score": "0",
"body": "It is suggested to wait a few days before accepting an answer to choose the best answer from a broader pool"
}
] |
[
{
"body": "<p>You are just re-implementing the <code>abs</code> built-in here. (If a number is negative make it positive):</p>\n<pre><code> xd = self.xf - self.xi \n yd = self.yf - self.yi \n if xd < 0:\n xd = xd * -1 \n if yd < 0:\n yd = yd * -1 \n</code></pre>\n<p>In general I do not understand why you have a whole class defined. I think this should be written more compactly because the actual calculations performed are very simple.</p>\n<p>To be more user friendly I would have a function having as input the domain of integration and the function to integrate like:</p>\n<pre><code>def weighted_area(xrange, yrange, function, precision):\n</code></pre>\n<p>An argument should be the precision in case the user wants to change the integration step.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:41:41.407",
"Id": "252126",
"ParentId": "252075",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252126",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T18:45:31.943",
"Id": "252075",
"Score": "5",
"Tags": [
"python"
],
"Title": "Geometry Approximation of an Integral"
}
|
252075
|
<p>I have some things (I'll call them <code>Item</code>s) that can either be passed around directly or referred to by reference. For the items that are referred to, there is a storage from which the items can be obtained.</p>
<p>My problem is that I want to keep the storage immutable, but I can't figure out how to do so elegantly. It seems that to work with the items and the storage at the same time, every method has to accept the existing storage as input and then output an updated storage alongside the item. This is how this looks in code:</p>
<pre class="lang-scala prettyprint-override"><code>sealed trait Item
case class ItemRef(id: String) extends Item
case class ItemDef(propA: String, propB: Boolean) extends Item
type ItemStore = Map[String, ItemDef]
def makeItem(rawItemData: Map[String, String], itemStore: ItemStore): (Item, ItemStore) = {
val id = generateItemId(data) // Some unique ID for this item
if(shouldItemDefBeUsed(data)) { // Ie, is the item small or simple?
(buildItemDef(data), this)
} else if(data contains id) { // Avoid building the complex def unless needed
(ItemRef(id), this)
} else {
val itemDef = buildItemDef(data)
(ItemRef(id), this.copy(items = items + (id -> itemDef)))
}
}
</code></pre>
<p>In the code above, <code>makeItem</code> is really annoying to use since it has to take the store as input and returns two outputs:</p>
<pre class="lang-scala prettyprint-override"><code>val initialStore: ItemStore = Map.empty[String, ItemDef]
val (itemA, storeWithA) = makeItem(itemAData, initialStore)
val (itemB, storeWithAAndB) = makeItem(itemAData, storeWithA)
</code></pre>
<p>Besides being annoying to use, this is also error prone:</p>
<pre class="lang-scala prettyprint-override"><code>val store: ItemStore = Map.empty[String, ItemDef]
val (itemA, storeWithA) = makeItem(itemAData, store)
val (itemB, storeWithAAndB) = makeItem(itemAData, store) // !! Forgot to use updated store
</code></pre>
<p>And it's not very readable to make a collection of items:</p>
<pre class="lang-scala prettyprint-override"><code>def makeItems(rawItemsData: List[Map[String, String]], itemStore: ItemStore): (List[Item], ItemStore) = {
rawItemsData.foldLeft(List.empty[Item], itemStore)({case ((items, store), currentItemData) =>
val (currentItem, updatedStore) = makeItem(currentItemData, store)
(items :+ currentItem, updatedStore)
})
}
</code></pre>
<p>Is there a better pattern for doing this? I feel like there must be some cleaner way that doesn't involve returning tuples and taking extra arguments, but I'm just not seeing it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T08:42:48.560",
"Id": "496750",
"Score": "2",
"body": "I don't think this is appropriate for Code Review. The code, as posted, does not compile. (Where does `data` come from? What does `this` refer to?) According to the Help Center page [What types of questions should I avoid asking?](https://codereview.stackexchange.com/help/dont-ask), this site is for \"_questions about code that already works correctly (to the best of your knowledge)_\", and also \"_questions should not contain ... hypothetical code_\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T14:24:08.893",
"Id": "496781",
"Score": "1",
"body": "To the best of your knowledge does the code work as expected? If not then @jwvh is correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T16:47:02.367",
"Id": "496802",
"Score": "0",
"body": "@jwvh I wasn't sure it it was a good fit here or not. What would be a better site for it? The example I posted doesn't compile because I left some specific implementation details out because my question doesn't need them. The code does work though, and I am just looking for alternative solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T01:36:14.683",
"Id": "496842",
"Score": "1",
"body": "Code submitted on CodeReview should be ready and prepared for just that, a full code review, where it might be evaluated for its efficiency, safety, resilience, style, etc. If there's only one aspect that you're really interested in then [StackOverflow](https://stackoverflow.com/) is probably a better platform where they're a little more tolerant of partial and stubbed out code. That being said, you still need to post _enough_ code to confidently *demonstrate* the issue you're asking about."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T19:11:01.323",
"Id": "252076",
"Score": "1",
"Tags": [
"functional-programming",
"scala",
"immutability"
],
"Title": "Managing and referencing items in an immutable store"
}
|
252076
|
<p>I've written a little bit of code to pull data out of my FitBit and store it in a GCP database for further analysis. <a href="https://github.com/kcinnick/fitnick" rel="noreferrer">The project is available here</a>, but what I'd like to ask about specifically is the Flask app & code I'm using to serve up a web interface for the project:</p>
<pre><code>from datetime import date
import os
from flask import Flask, make_response, render_template, request
from flask_wtf import FlaskForm
from wtforms import StringField
from fitnick.activity.activity import Activity
from fitnick.database.database import Database
from fitnick.heart_rate.time_series import HeartRateTimeSeries
from fitnick.heart_rate.models import heart_daily_table
app = Flask(__name__)
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY
month_options = [i for i in range(1, 13)]
day_options = [i for i in range(1, 32)]
year_options = range(2020, 2021)
class DateForm(FlaskForm):
date = StringField('date')
@app.route("/", methods=['GET'])
def index():
"""
Currently serves as the endpoint for the get_heart_rate_zone methods, even
though it's currently set to the index page
:return:
"""
heart_rate_zone = HeartRateTimeSeries(config={'database': 'fitbit'})
statement = heart_daily_table.select().where(heart_daily_table.columns.date == str(date.today()))
rows = [i for i in Database(database='fitbit', schema='heart').engine.execute(statement)]
# retrieve rows for today already in database, if there are none then get rows via fitnick
if len(rows) == 0:
rows = heart_rate_zone.get_heart_rate_zone_for_day(database='fitbit')
rows = [i for i in rows]
form = DateForm(request.form)
if request.method == 'GET':
return render_template(
template_name_or_list="index.html",
rows=rows,
form=form,
month_options=month_options,
day_options=day_options,
year_options=year_options
)
def set_search_date(request, search_date):
if request.method == 'POST':
# collect search date information from the dropdown forms if they're all supplied.
if all([request.form.get('month_options'), request.form.get('day_options'), request.form.get('year_options')]):
search_date = '-'.join(
[f"{request.form['year_options']}",
f"{request.form['month_options']}".zfill(2),
f"{request.form['day_options']}".zfill(2)])
else:
# use the search_date value we set in lines 59-62
pass
return search_date
@app.route("/get_heart_rate_zone_today", methods=['GET', 'POST'])
def get_heart_rate_zone_today():
"""
Endpoint for getting heart rate zone data from the FitBit API.
:return:
"""
heart_rate_zone = HeartRateTimeSeries(config={'database': 'fitbit'})
form = DateForm(request.form)
value = 'Updated heart rate zone data for {}.'
if form.date._value(): # set search_date, default to today if none supplied
search_date = form.date._value()
else:
search_date = str(date.today())
if request.method == 'POST':
# collect search date information from the dropdown forms if they're all supplied.
search_date = set_search_date(request, search_date)
rows = heart_rate_zone.get_heart_rate_zone_for_day(
database='fitbit',
target_date=search_date)
rows = [i for i in rows]
else: # request.method == 'GET'
# no date supplied, just return data for today.
heart_rate_zone.config = {'base_date': date.today(), 'period': '1d'}
statement = heart_daily_table.select().where(heart_daily_table.columns.date == str(date.today()))
rows = Database(database='fitbit', schema='heart').engine.execute(statement)
return render_template(
template_name_or_list="index.html",
value=value.format(search_date),
rows=rows,
form=form,
month_options=month_options,
day_options=day_options,
year_options=year_options
)
@app.route("/get_activity_today", methods=['GET', 'POST'])
def get_activity_today():
"""
Endpoint for getting activity data for a given date from the FitBit API.
:return:
"""
activity = Activity(config={'database': 'fitbit'})
form = DateForm(request.form)
search_date = form.date._value()
if request.method == 'POST':
search_date = set_search_date(request, search_date)
row = activity.get_calories_for_day(day=search_date)
value = 'Updated activity data for {}.'.format(search_date)
else:
row, value = {}, ''
return render_template(
template_name_or_list='activity.html',
form=form,
row=row,
value=value,
month_options=month_options,
day_options=day_options,
year_options=year_options
)
@app.route('/<page_name>')
def other_page(page_name):
"""
Stand-in endpoint for any undefined URL.
:param page_name:
:return:
"""
response = make_response(f'The page named {page_name} does not exist.', 404)
return response
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>Specifically, I'm trying to cut down on some code repetition. I have two pages currently, one for grabbing heart rate zone data and another for collecting activity data. When it comes to retrieving the date entered into the form on either page & then querying the database and returning the proper results, it seems like there's a lot of code repetition.</p>
<p>It feels like there should be a way to collapse the code in the <code>index</code>, <code>get_heart_rate_zone_today</code> and <code>get_activity_today</code> functions where essentially what is being checked is if the request is GET or POST and if it's POST, query the data for the given day from the FitBit API, add it to the database & return the data (when it's a GET request, we just return the data in the database). This section of the get_heart_rate_zone_today function is an example of what I mean:</p>
<pre><code>if form.date._value(): # set search_date, default to today if none supplied
search_date = form.date._value()
else:
search_date = str(date.today())
if request.method == 'POST':
# collect search date information from the dropdown forms if they're all supplied.
search_date = set_search_date(request, search_date)
rows = heart_rate_zone.get_heart_rate_zone_for_day(
database='fitbit',
target_date=search_date)
rows = [i for i in rows]
else: # request.method == 'GET'
# no date supplied, just return data for today.
heart_rate_zone.config = {'base_date': date.today(), 'period': '1d'}
statement = heart_daily_table.select().where(heart_daily_table.columns.date == str(date.today()))
rows = Database(database='fitbit', schema='heart').engine.execute(statement)
</code></pre>
<p>However, there are still enough differences from a code perspective (the different actions the code should take depending on if it's activity or heart rate zone data being retrieved) that the easiest way I've found thus far is to just write separate functions for each retrieval method.</p>
<p>I'd really appreciate it if someone could check out the Flask code I have below and get your thoughts on it, what I'd like to do and if it's the right idea for solving the 'problem' I have currently, which is the semi-duplicated code. Thank you for the time!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T00:58:50.960",
"Id": "496535",
"Score": "1",
"body": "I don't think that it's worth it to extract anything out into common functions. I don't know Flask but I am familiar with Django, and it looks similar. The biggest commonality is that those three routines (index, get_heart_rate_zone_today, and get_activity_today) is that they have POST and GET functionality, but that's typical for web apps. Within the POST and GET areas, there isn't enough commonality to reduce code IMHO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:53:24.807",
"Id": "496597",
"Score": "0",
"body": "Thanks for taking a look and for the comment, @DaveB. This is kind of the same conclusion I was coming to as well, and I was trying to figure out if I just wasn't being creative enough or if they're really just different *enough* to warrant their own functions & code."
}
] |
[
{
"body": "<p>A few general suggestions, based on the code</p>\n<p>1.- <strong>Organization</strong>. It could be a hacky project, but you should avoid doing db queries on the views, it will lead to hard to maintain code, as you are noticing now. Try to have a separate file to handle all queries, and then use if you want a function to communicate between them.stants defined above, which may suit bett</p>\n<p>2.- <strong>Keep as little logic in the views as possible.</strong> Create functions you can reuse, for example to retrieve data from db, or to populate the search data</p>\n<p>3.- <strong>Constants</strong>. If the months, years, etc.. are not going to change consider using tuples for them. Also the range you are creating only has a year on it</p>\n<p>With this, it should lead to places where you can see reusable code, specially db queries</p>\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T17:22:12.987",
"Id": "252542",
"ParentId": "252077",
"Score": "1"
}
},
{
"body": "<h2>List comprehensions</h2>\n<p>This pattern is seen throughout your code:</p>\n<pre><code>[i for i in range(1, 13)]\n</code></pre>\n<p>In the case above, there's no need to make a list comprehension; simply hold onto the range directly. In a case like this:</p>\n<pre><code>rows = [i for i in rows]\n</code></pre>\n<p>you're better off calling the list constructor, i.e.</p>\n<pre><code>rows = list(rows)\n</code></pre>\n<p>or better, if you're able, the tuple constructor for immutable variables:</p>\n<pre><code>rows = tuple(rows)\n</code></pre>\n<h2>Redundant method check</h2>\n<p>This:</p>\n<pre><code>if request.method == 'GET':\n</code></pre>\n<p>is written on an <code>index</code> method that only accepts <code>GET</code>, so the <code>if</code> is redundant and can be dropped.</p>\n<h2>set_search_date</h2>\n<p>This is a curious method. First, it doesn't set anything - it returns a date. Unless I'm missing something, rename this to be <code>get_search_date</code>. You can also combine your predicates:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if (\n request.method == 'POST'\n and all(\n f'{k}_options' in request.form\n for k in (\n 'month', 'day', 'year',\n )\n )\n):\n return '-'.join # ...\n\nreturn search_date\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T18:25:36.147",
"Id": "252548",
"ParentId": "252077",
"Score": "1"
}
},
{
"body": "<p>My advice would be to restructure the project by splitting it into several files.\nIn this file you have everything mixed up together, you are instantiating the Flask instance, you define the routes, and you have functions in between.</p>\n<p>This file can only grow over time and can become overwhelming, making code maintenance more tedious and difficult in the long run.</p>\n<p>To start Flask the idea is to have a small launcher file that looks like this:</p>\n<pre><code>from flask import Flask\n\napp = Flask(__name__)\napp.config.from_object('config.Config')\n</code></pre>\n<p>and a <strong>config file</strong> that would look like this:</p>\n<pre><code>from os import environ, path\nfrom dotenv import load_dotenv\n\nbasedir = path.abspath(path.dirname(__file__))\nload_dotenv(path.join(basedir, '.env'))\n\n\nclass Config:\n """Base config."""\n SECRET_KEY = environ.get('SECRET_KEY')\n SESSION_COOKIE_NAME = environ.get('SESSION_COOKIE_NAME')\n STATIC_FOLDER = 'static'\n TEMPLATES_FOLDER = 'templates'\n\n\nclass ProdConfig(Config):\n FLASK_ENV = 'production'\n DEBUG = False\n TESTING = False\n DATABASE_URI = environ.get('PROD_DATABASE_URI')\n\n\nclass DevConfig(Config):\n FLASK_ENV = 'development'\n DEBUG = True\n TESTING = True\n DATABASE_URI = environ.get('DEV_DATABASE_URI')\n</code></pre>\n<p>Source and recommended reading: <a href=\"https://hackersandslackers.com/configure-flask-applications/\" rel=\"nofollow noreferrer\">Configuring Your Flask App</a>. I use a similar scheme to be able to switch easily between test and production environments, without touching the code base. Instead, changes are made to a config file. Note that in your app you have hardcoded: <code>app.run(debug=True)</code></p>\n<p>I would also keep the routes in a distinct file.\nA simplistic example to import your routes:</p>\n<pre><code>from flask import Flask\n\ndef create_app():\n """Initialize the core application."""\n app = Flask(__name__, instance_relative_config=False)\n app.config.from_object('config.Config')\n\n with app.app_context():\n # Include our Routes\n from . import routes\n\n return app\n</code></pre>\n<p>Source: <a href=\"https://hackersandslackers.com/flask-application-factory/\" rel=\"nofollow noreferrer\">Demystifying Flask’s Application Factory</a></p>\n<p>If you have some helper functions they can go to another file as well. No need to clutter the codebase.</p>\n<p>In short, my suggestion is to spend more time reading up on Flask and take the time to build a sound <strong>boilerplate</strong> that you can reuse for future projects.</p>\n<p>I am not familiar with your database scheme but it is obvious there is repetition across your code eg: <code>get_heart_rate_zone_for_day(database='fitbit')</code> or: <code>Database(database='fitbit', schema='heart')</code>. The DB name is mentioned multiple times. It should be set up once and for all at the start of your application. At the very least you could have defined a constant at the top of your code.</p>\n<p>I suppose something like this at the top of your code should do:</p>\n<pre><code>FITBIT_DB = Database(database='fitbit', schema='heart')\n</code></pre>\n<p>Then use FITBIT_DB from now on to refer to the DB. Just this should make the code ligher.</p>\n<p>At the top of your code you have this:</p>\n<pre><code>month_options = [i for i in range(1, 13)]\nday_options = [i for i in range(1, 32)]\nyear_options = range(2020, 2021)\n</code></pre>\n<p>I presume you have 3 combo boxes in your Jinja template.\nTo make the code <strong>future-proof</strong> and not having to review it every year, you should make the year range dynamic:</p>\n<pre><code>from datetime import datetime\ncurrent_year = datetime.now().year\nyear_options = range(current_year, current_year + 1)\n</code></pre>\n<p>But it doesn't seem that you are using WTF for validating the dates. Dates like 30 Feb should trigger an error, even if the code does not crash and ends up returning no data.</p>\n<p>Not sure this code is correct:</p>\n<pre><code>def set_search_date(request, search_date):\n if request.method == 'POST':\n # collect search date information from the dropdown forms if they're all supplied.\n if all([request.form.get('month_options'), request.form.get('day_options'), request.form.get('year_options')]):\n</code></pre>\n<p>First of all, there is no need to make it a list.</p>\n<p>Reminder: what the all function does: <em>check if all items in a list are True</em>. So I would check that this code does what you really think it does. If in doubt you can dump the contents of the POST request and see for yourself what happens.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T05:25:03.723",
"Id": "497697",
"Score": "0",
"body": "Thank you so much for taking the time to review the code and write this, as well as the links!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-23T22:20:21.350",
"Id": "252566",
"ParentId": "252077",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252566",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T19:19:42.947",
"Id": "252077",
"Score": "12",
"Tags": [
"python",
"template",
"flask"
],
"Title": "Suggestions on cleaning up Flask app"
}
|
252077
|
<p>I am looking for help for two things.</p>
<ol>
<li>proof of correctness (the tests have passed, but I do not now how to prove it correct)</li>
<li>Improvements on the Algorithm Efficiency.</li>
</ol>
<p>The algorithm goes through 2 arrays arrays through permutations. The ordering is set up based on the array index, NOT the number inside the index. Noteably, if both parallel arrrays are set up diffrent, the algorithm should run fine.The algorithm then adds the function to the sum, which estimates computes the series.</p>
<p>Code is below.</p>
<pre><code>
def f(x:float, y:float, a:float)->float:
"""
param x:float, x coordinate
param y:flaot, y coordinate
param a:float, paramter of the curve
"""
return x + (y * a)
def main():
"""
algorithm:
Suppouse arrays are orderd by thier index and NOT the element inside
Go through an ordering which meets that (one ordering is enough)
add on the function at that point to the sequence
"""
x = [1.0, 2.0, 3.0]
y = [2.0, 3.0, 4.0]
a = 2.0
seq = [0.0] * len(x)
for row in range(0, len(x) + 1):
for col in range(0, len(x) + 1):
for at in range(row, col):
seq[at] = seq[at] + f(x[at], y[at], a)
print(seq)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T22:25:32.053",
"Id": "496522",
"Score": "2",
"body": "Where is the task description? Where is the example? Where are those tests? How are we supposed to tell whether it's correct when we don't even know what it shall do?"
}
] |
[
{
"body": "<h3>Disclaimer: Not a Code Reviewer</h3>\n<p>Just some comments:</p>\n<ul>\n<li><p>Looks not bad at all;</p>\n</li>\n<li><p>First thing first, read through <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> if you like – I should also do that myself ( ˆ_ˆ )</p>\n</li>\n<li><p>Name things just a bit more descriptive, I understand that math people code like that and use single variable naming a lot;</p>\n</li>\n<li><p>Comment concise (one perfect scenario – which does not exist – would be the understandability of the code without any comment);</p>\n</li>\n<li><p>Use <code>unittest</code> if you like;</p>\n</li>\n<li><p>Turn on your IDE's spell checking;</p>\n</li>\n<li><p>Not sure about what we are doing overall, but my guess is that we might be able to start the second loop from the <code>row + 1</code>:</p>\n</li>\n</ul>\n<pre><code>def get_linear_calc(x: float, y: float, coeff: float) -> float:\n """\n param x:float, x coordinate\n param y:flaot, y coordinate\n param coeff:float, parameter of the curve\n """\n return x + (y * coeff)\n\n\ndef get_ordered_sequence(x, y, coeff):\n """\n algorithm:\n Suppose arrays are ordered by their index and NOT the element inside\n Go through an ordering which meets that (one ordering is enough)\n add on the function curr that point to the sequence\n """\n seq = [0.0] * len(x)\n for row in range(len(x) + 1):\n for col in range(row + 1, len(x) + 1):\n for curr in range(row, col):\n seq[curr] += get_linear_calc(x[curr], y[curr], coeff)\n return seq\n\n\nif __name__ == "__main__":\n x = (1.0, 2.0, 3.0, 2.0)\n y = (2.0, 3.0, 4.0, 1.0)\n coeff = 2.0\n print(get_ordered_sequence(x, y, coeff))\n</code></pre>\n<p>PS: I don't name things well, ignore my naming.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T20:33:09.053",
"Id": "252121",
"ParentId": "252082",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "252121",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T21:27:14.847",
"Id": "252082",
"Score": "1",
"Tags": [
"python-3.x",
"combinatorics"
],
"Title": "Summing Sequence with Combinatorics"
}
|
252082
|
<p>So, here is the code:</p>
<pre><code>#pragma once
#include <vector>
#include <iostream>
#include <queue>
#include <functional>
using node = int;
using cost = int;
using arc = std::pair<node, cost>;
using AdjList = std::vector<std::vector<arc>>; // first is node, second is cost
class Graph {
private:
AdjList adjList;
std::vector<node> nodes;
public:
Graph(int n) : nodes{ n }, adjList{ n } {}
void addEdge(const node v, const node u, const cost c) {
adjList[v].push_back({ u, c });
adjList[u].push_back({ v, c });
}
std::vector<int> dijkstra(const node n) const {
std::vector<cost> dist(adjList.size(), INT_MAX);
std::vector<bool> visited(adjList.size(), false);
dist[n] = 0;
std::priority_queue<node, std::vector<node>, std::greater<int>> to_visit;
to_visit.push(n);
while (!to_visit.empty()) {
node v = to_visit.top();
to_visit.pop();
visited[v] = true;
for (const arc& a : adjList[v]) {
node u = a.first;
cost c = a.second;
if (!visited[u] and (dist[u] == INT_MAX or dist[u] > dist[v] + c)) {
dist[u] = dist[v] + c;
to_visit.push(v);
}
}
}
return dist;
}
friend std::ostream& operator<<(std::ostream& stream, const Graph& g) {
for (size_t i = 0; i < g.adjList.size(); i++) {
stream << "node " << i << "\n";
for (const arc& p : g.adjList[i]) {
stream << "connected with " << p.first << " cost: " << p.second << " ";
}
stream << "\n";
}
return stream;
}
};
</code></pre>
<p>I think I did a decent job, but I want to make sure I'm not missing anything. I'm using just a adjacent list for storing the arcs. I was unsure if I should <code>reserve</code> some memory for the <code>vectors</code> there, because maybe it's going to get a little bit slow with the <code>push_back</code> operation, but I also wanted to be able to get rid of the <code>O(n^2)</code> for storing.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T03:45:59.983",
"Id": "496539",
"Score": "0",
"body": "That is not Dijkstra algorithm you implemented."
}
] |
[
{
"body": "<p>Graph seems quite reasonable:<br />\nBut your distance implementation is not an implementation of Dijkstra.</p>\n<p>Dijkstra finds only the cheapest path between two nodes (technically).<br />\nBut I suppose you can use the technique to find the distance from a node to all others nodes. Dijkstra works by finding the cheapest distance to a node then expanding from there (it never re-expands a node, because it does not need to). To do this you need a sorted frontier list so you always expand from the node with the lowest cost to get there and keep track of nodes that were visited.</p>\n<hr />\n<p>Some notes:</p>\n<pre><code>// Node Id can only by positive.\nusing node = int;\n\n// Dijkstra assumes all costs are positive.\nusing cost = int;\n</code></pre>\n<p>Lets have a look at your search:</p>\n<pre><code> // Returning the min distances to all nodes.\n // Sure: but you can not tell what the route to get there is\n // so this does not help you traverse the graph it only\n // tells you the shortest distances.\n // Also how do you tell the difference between a\n // a distsance of INT_MAX and a node that was never reached.\n std::vector<int> dijkstra(const node n) const {\n\n // I think this is what is causing you to go wrong.\n // The distance is usually part of the to_visit.\n // You sort the list by the distance.\n std::vector<cost> dist(adjList.size(), INT_MAX);\n\n // Sure. You need this for dijkstra\n // In a classic implementation I would have used\n // std::set<Node> as we don't need (in general) to traverse\n // the whole graph to find a route from A to B.\n // Since you are finding the distance to all nodes. This seems\n // like a better choice.\n std::vector<bool> visited(adjList.size(), false);\n\n dist[n] = 0;\n\n // This is a mistake.\n // The order here based on the node-id.\n // It should be based on the cost to get to a node.\n // You always keep it sorted by the cost to get to the node\n // But you may have multiple routes to a node in the list with\n // different costs so after extraction from the list you check\n // if already visited (because if it is already visited then\n // this is not the shortest route).\n //\n // I am sure I could construct a graph that would break this.\n std::priority_queue<node, std::vector<node>, std::greater<int>> to_visit;\n to_visit.push(n);\n while (!to_visit.empty()) {\n node v = to_visit.top();\n to_visit.pop();\n visited[v] = true;\n for (const arc& a : adjList[v]) {\n node u = a.first;\n cost c = a.second;\n\n // In dijkstra the cost to a node is not known until\n // you actually visit it for the first time (as you may\n // see a node from many other nodes.\n if (!visited[u] and (dist[u] == INT_MAX or dist[u] > dist[v] + c)) {\n dist[u] = dist[v] + c;\n to_visit.push(v);\n }\n }\n }\n return dist;\n }\n</code></pre>\n<h2>This is what it normally looks like:</h2>\n<pre><code> struct DN {\n node src;\n node dst;\n cost c;\n\n friend bool operator<(DN const& lhs, DN const& rhs) {return lhs.c < rhs.c;}\n };\n\n std::vector<node> dijkstra(node begin, node end) const\n {\n std::vector<node> route(adjList.size(), INT_MAX)\n std::set<node> visited;\n std::priority_queue<DN> frontier;\n\n frontier.push({INT_MAX, begin, 0});\n\n while (!frontier.empty()) {\n node v = frontier.top();\n frontier.pop();\n\n // If we have already been here go to next value.\n if (visited.find(v.dst) != visited.end()]) {\n continue;\n }\n\n // OK. Found it and save the cost.\n visited.insert(v.dst);\n route[v.dst] = v.src;\n\n // If we reached the end exit.\n if (v.dst == end) {\n break;\n }\n\n for (const arc& a : adjList[v.dst]) {\n // Add nodes to frontier list.\n // That is sorted by the cost to the node.\n frontier.push({n, std::get<0>(a), v.c + std::get<1>(a));\n }\n }\n // You can start from the end node\n // and retrace the path the beginning node.\n return route;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T13:54:28.267",
"Id": "496576",
"Score": "0",
"body": "Thanks for the feedback. I should have mentioned that I was using dijkstra here to find the cheapest path between `u` to all of the other nodes. You also pointed out the problem with the implementation: sorting them by `id` is going to give me wrong results because the invariant of the algorithm is not followed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T15:00:02.360",
"Id": "496660",
"Score": "0",
"body": "You know `set::insert()` returns both an iterator to the relevant node, *and an indicator whether it inserted*? find+insert is thus doubled work for no gain."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T06:43:21.387",
"Id": "252097",
"ParentId": "252085",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "252097",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-13T22:57:26.663",
"Id": "252085",
"Score": "6",
"Tags": [
"c++",
"c++11",
"graph",
"dijkstra"
],
"Title": "Graph implementation with Dijkstra"
}
|
252085
|
<p>I have the following code working fine:</p>
<p><code>rowData</code> is an object and I want to display download button only if the <code>completePathName</code> is not null and hence I did the following which is working fine. I am wondering if I can improve the following code in some manner or the conditional if that I have used is fine?</p>
<pre><code>buttonTemplate = (rowData: any, column: any) => {
//if(typeof rowData !=='undefined' && typeof rowData.completePathName !=='undefined'){
if(rowData.completePathName === null){
return (
console.log("Inside first return - testing rowData:"),
console.log(rowData),
console.log(rowData.completePathName),
<div style={{textAlign: 'center', width: '6em'}}>
<span>
<Button type='button' icon="pi pi-pencil" style={{marginRight: '5px'}} onClick={(e) => this.handleClick(rowData, e)} tooltip='Edit'/>
<Button icon="pi pi-trash" style={{marginRight: '5px'}} tooltip='Delete' />
</span>
</div>
);
}
else {
return (
console.log("Inside second return - testing rowData:"),
console.log(rowData),
console.log(rowData.completePathName),
<div style={{textAlign: 'center', width: '6em'}}>
<span>
<Button type='button' icon="pi pi-pencil" style={{marginRight: '5px'}} onClick={(e) => this.handleClick(rowData, e)} tooltip='Edit'/>
<Button icon="pi pi-trash" style={{marginRight: '5px'}} tooltip='Delete' />
<Button icon="pi pi-download" tooltip='Download' />
</span>
</div>
);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The only thing that changes in the JSX is the download button, so it'd be more appropriate to use <a href=\"https://reactjs.org/docs/conditional-rendering.html\" rel=\"nofollow noreferrer\">conditional rendering</a> when the JSX comes to that line to decide whether you need to render the last button or not:</p>\n<pre><code>const ButtonTemplate = (rowData: any) => (\n <div style={{textAlign: 'center', width: '6em'}}>\n <span>\n <Button type='button' icon="pi pi-pencil" style={{marginRight: '5px'}} onClick={(e) => this.handleClick(rowData, e)} tooltip='Edit'/>\n <Button icon="pi pi-trash" style={{marginRight: '5px'}} tooltip='Delete' />\n {\n rowData.completePathName !== null &&\n <Button icon="pi pi-download" tooltip='Download' />\n }\n </span>\n </div>\n);\n</code></pre>\n<p>Other notes:</p>\n<ul>\n<li><p>Since you don't use the <code>column</code> parameter, you should remove it entirely</p>\n</li>\n<li><p>Using <code>any</code> defeats the whole point of using TypeScript, since it effectively disables type-checking for that expression - if you can give proper types to things, it'll make your life a whole lot easier. Consider figuring out how you can type <code>rowData</code>. It may look something like:</p>\n<pre><code>rowData: {\n completePathName: string | null\n}\n</code></pre>\n<p>(or something similar - just for an example)</p>\n</li>\n<li><p>If you want to be able to call this as a <em>component</em>, give it an upper-case name: <code>ButtonTemplate</code>, not <code>buttonTemplate</code>. That'll let you do</p>\n<pre><code><ButtonTemplate {...{ rowData, column }} />\n</code></pre>\n<p>to render it.</p>\n</li>\n<li><p>You have a lot of inline styles, which makes the JSX harder to read. Consider separating out the style into CSS instead. With Sass, you could give the container a class of <code>buttons-container</code>, and then do:</p>\n<pre><code>.buttons-container {\n text-align: center;\n width: 6em;\n button:not([tooltip="Download"]) {\n margin-right: 5px;\n }\n}\n</code></pre>\n<p>and remove <strong>all</strong> the inline styles from the JSX.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T01:51:45.043",
"Id": "252090",
"ParentId": "252089",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T01:36:38.523",
"Id": "252089",
"Score": "1",
"Tags": [
"react.js"
],
"Title": "Using conditional if in react"
}
|
252089
|
<p>Here's a fairly simple task from <a href="https://cses.fi/problemset/task/1070/" rel="noreferrer">CSES Problem Set - Permutations 1070</a> that reads:</p>
<blockquote>
<p>A permutation of integers 1,2, …, n is called beautiful if there are no adjacent elements whose difference is 1.</p>
<p>Given n, construct a beautiful permutation if such a permutation exist</p>
</blockquote>
<p>The constraints are pretty tight:</p>
<ul>
<li><strong>Time limit</strong>: 1.00 s</li>
<li><strong>Memory limit</strong>: 512 MB</li>
<li><em>1 ≤ n ≤ 10^6</em></li>
</ul>
<p>Here's the code:</p>
<pre><code>n = int(input())
if n == 2 or n == 3:
print("NO SOLUTION")
elif n == 1:
print(1)
elif n == 4:
print("3 1 4 2")
else:
for i in range(1, n + 1, 2):
print(str(i) + " ", end=" ")
for i in range(2, n + 1, 2):
print(str(i) + " ", end=" ")
</code></pre>
<p>It passes all tests except for n = 1000000. For that test it takes 15 sec. on my machine. The code is in Python 3.8</p>
<p>The question is, what can can be improved in terms of printing the numbers?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:20:43.277",
"Id": "496706",
"Score": "3",
"body": "Doesn't this depend on the speed of the terminal?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T03:04:55.907",
"Id": "496726",
"Score": "1",
"body": "@Matt, it does. Just to add it is executed on CPython"
}
] |
[
{
"body": "<p>Nice solution, few suggestions:</p>\n<ul>\n<li>Printing the numbers one by one might be the issue. Generate the list of numbers first and then call <code>print</code> only once.</li>\n<li>The case <code>n==1</code> is already handled, so the first <code>elif</code> can be removed.</li>\n</ul>\n<p>Applying the suggestions:</p>\n<pre class=\"lang-py prettyprint-override\"><code>n = int(input())\nif n == 2 or n == 3:\n print("NO SOLUTION")\nelif n == 4:\n print("3 1 4 2")\nelse:\n beautiful_perm = [*range(1, n + 1, 2), *range(2, n + 1, 2)]\n print(' '.join(map(str, beautiful_perm)))\n</code></pre>\n<p>By inverting the ranges we don't need to check for <code>n==4</code>:</p>\n<pre><code>n = int(input())\nif n == 2 or n == 3:\n print("NO SOLUTION")\nelse:\n beautiful_perm = [*range(2, n + 1, 2), *range(1, n + 1, 2)]\n print(' '.join(map(str, beautiful_perm)))\n</code></pre>\n<p>Runtime on CSES:</p>\n<pre><code>n = 906819 (CPython3)\nOriginal: 0.92 s\nImproved: 0.26 s\n\nn = 1000000 (CPython3)\nOriginal: timeout\nImproved: 0.28 s\n\nn = 1000000 (PyPy3)\nOriginal: 0.61 s\nImproved: 0.15 s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T11:40:43.620",
"Id": "496648",
"Score": "2",
"body": "`print(' '.join(map(str, range(2, n + 1, 2))), ' '.join(map(str, range(1, n + 1, 2))))` is slightly more efficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T09:18:34.560",
"Id": "496752",
"Score": "5",
"body": "I'd even add that the fact they tell that the memory limit is 512Mb is a hint that you shouldn't print everything one by one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T14:06:08.680",
"Id": "496779",
"Score": "1",
"body": "@Walfrat Maybe I'm missing something. How does a memory limit of 512MB prevent you from printing everything one by one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T14:51:48.383",
"Id": "496785",
"Score": "9",
"body": "Nothing, but if instead it was 52Kb, you would have problem printing everything in one go. Since you have that much of memory, it is more likely that you are expected to build the full solution before printing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T19:15:48.903",
"Id": "496824",
"Score": "1",
"body": "If the solution on your machine goes down from 0.61 to 0.15, how do you expect OP going from 15.0 to 1.0?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T06:04:30.147",
"Id": "252096",
"ParentId": "252094",
"Score": "30"
}
},
{
"body": "<p>Your code gets accepted as-is. Just need to choose PyPy3 instead of CPython3.</p>\n<p>Another version that also gets accepted with CPython3 (using <a href=\"https://codereview.stackexchange.com/a/252096/228314\">Marc's</a> logic but a simpler way to print):</p>\n<pre><code>n = int(input())\nif 2 <= n <= 3:\n print("NO SOLUTION")\nelse:\n print(*range(2, n + 1, 2), *range(1, n + 1, 2))\n</code></pre>\n<p>Printing like that moves the loop from your own Python loop with lots of <code>print</code> calls to a single call and looping in C. Even faster is Marc's way with <code>' '.join</code>, though. Times for test case #20, where n=906819, the largest where yours is fast enough to not get killed:</p>\n<pre><code> CPython3 PyPy3\nYours 0.93 s 0.56 s\nMine 0.37 s 0.32 s\nMarc's 0.25 s 0.14 s\n</code></pre>\n<p>Why is Marc's way even faster? The <a href=\"https://docs.python.org/3/library/functions.html#print\" rel=\"noreferrer\"><code>print</code> documentation</a> says <em>"The file argument must be an object with a <code>write(string)</code> method"</em>. And if we use our own such object we can see a lot fewer write calls in Marc's than in mine:</p>\n<pre><code>class Write:\n def write(self, string):\n print(f'write({string!r})')\n\nnums = range(5)\n\nprint(' '.join(map(str, nums)), file=Write())\nprint()\nprint(*nums, file=Write())\n</code></pre>\n<p>Output:</p>\n<pre><code>write('0 1 2 3 4')\nwrite('\\n')\n\nwrite('0')\nwrite(' ')\nwrite('1')\nwrite(' ')\nwrite('2')\nwrite(' ')\nwrite('3')\nwrite(' ')\nwrite('4')\nwrite('\\n')\n</code></pre>\n<p>The overhead of all those function calls is probably what makes mine slower. The overhead of <code>' '.join(...</code> just seems to be smaller.</p>\n<p>That said, I usually prefer my way if it's fast enough and thus try that first. Except maybe in a competition where I have reason to believe it might not be fast enough and there's a penalty for unsuccessful submissions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T13:00:41.510",
"Id": "496567",
"Score": "2",
"body": "+1 for the compact code. If I run it on CSES (PyPy3 n=100000), it runs in 0.34 s, two times slower than mine. Do you know why? Or is CSES not reliable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T13:17:20.127",
"Id": "496568",
"Score": "3",
"body": "@Marc I'd say it actually runs about *three* times slower. The minimum times (for small n like n=1) are 0.05 s. If we subtract that overhead, it's 0.10 s for yours and 0.29 s for mine. To me CSES does look \"reliable\", in the sense that repeatedly submitting the same code repeatedly gives me the same times and that that overhead is relatively small (unlike for example LeetCode, where times for the same code vary widely and the overhead can be over 99% of the reported time). And from experience (with CPython) I *expect* my way to be slower, I just prefer it for simplicity when it's fast enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T13:45:12.140",
"Id": "496574",
"Score": "3",
"body": "@Marc Btw with CPython3, the difference is smaller. Mine gets 0.02 s for n=1 and 0.44 s for n=1e6, so 0.42 s without overhead. For yours it's 0.02 s and 0.28 s, so 0.26 s without overhead. So yours is about factor 1.6 times faster there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T14:06:14.703",
"Id": "496578",
"Score": "2",
"body": "Thanks a lot for the explanation! It could have been a review on its own ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T14:59:12.447",
"Id": "496580",
"Score": "2",
"body": "@Marc Yeah you're right, especially since the question's title and last paragraph both explicitly make it about printing. Added stuff to my answer now."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T11:25:58.933",
"Id": "252103",
"ParentId": "252094",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": "252096",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T05:14:39.960",
"Id": "252094",
"Score": "26",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "Printing 1,000,000 numbers in 1 sec. in Python"
}
|
252094
|
<p>I have a list of <code>N</code> integers, e.g. <code>intList=[1,7,3,1,5]</code> with <code>N=5</code> and all integers have a binary representation of lenght <code>l</code>, e.g. <code>binList=["001","111","011","001","101"]</code> with <code>l=3</code>. Now I want to add random flips from <code>1->0 & 0->1</code>. Each of the <code>l</code> positions should flip with a probabiliy <code>mu</code>. (<code>mu</code> varies over many magnitudes & <code>N</code> is around 100-100000) This happens over many iterations. Currently my code is</p>
<pre><code>@nb.njit()
for x in range(iterations):
...other code...
for number in range(N):
for position in range(l):
if random.random() < mu:
intList[number] = intList[number] ^ (1 << position)
...other code...
</code></pre>
<p>The numba decorator is necessary. Since this part takes most of the execution time I just want to make sure that it is already optimal. Thanks for any comment!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T20:53:46.300",
"Id": "496607",
"Score": "1",
"body": "What is the expected magnitude of `n` and `l`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T12:39:01.463",
"Id": "496772",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T13:43:29.147",
"Id": "496775",
"Score": "0",
"body": "You may post the benchmark as an answer. Updating the question based on feedbacks is prohibited on the forum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T13:54:49.057",
"Id": "496776",
"Score": "0",
"body": "@GZ0 Where exactly does it say so? We even frequently *request* updating questions (usually for clarity)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T13:59:14.687",
"Id": "496778",
"Score": "0",
"body": "@HighwayJohn Some people with too much power apparently prefer not to read and think, so yeah, better post it as an answer. Might even gain some upvotes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:27:51.827",
"Id": "496790",
"Score": "0",
"body": "@superbrain I meant updating questions based on answers, not feedbacks in the comments like you refer to. For the forum rule, just see the link from Vogel612's comment before me. The primary concern is that a follow-up edit with updated or new code may invalidate previously posted answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:33:28.583",
"Id": "496791",
"Score": "0",
"body": "@GZ0 Where does the linked page say it? I only see \"must not edit the code in the question\" and \"should not append your revised code to the question\", neither of which they had done. Which of the answers got invalidated, and how?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T16:31:26.150",
"Id": "496801",
"Score": "0",
"body": "@superbrain Adding benchmarks is somewhat analogous to \"append your revised code to the question\" but less problematic (than the counterexamples on the linked page). To me it is a borderline acceptable scenario. However, it is a common practice on the forum for moderators to roll back any code changes after an answer is posted. Therefore I would suggest not making such edits at all. If you want to challenge the practice, you may post on the [meta forum](https://codereview.meta.stackexchange.com/)."
}
] |
[
{
"body": "<p>You could replace</p>\n<pre><code> for position in range(l):\n if random.random() < mu:\n intList[number] = intList[number] ^ (1 << position)\n</code></pre>\n<p>with</p>\n<pre><code> for bit in bits:\n if random() < mu:\n intList[number] ^= bit\n</code></pre>\n<p>after preparing <code>bits = [1 << position for position in range(l)]</code> before the show and importing the <code>random</code> <em>function</em>.</p>\n<p>Don't know whether that helps when using numba, and you didn't provide benchmark code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T11:54:03.373",
"Id": "252105",
"ParentId": "252099",
"Score": "5"
}
},
{
"body": "<p><code>l</code> is a poor variable name. It doesn't convey any information about what it is and it is easy to confuse with the number <code>1</code>. I'll use <code>nbits</code>.</p>\n<p>If <code>nbits</code> is not too large, it might make sense to precompute a table of possible bit flips and their probablities. For a probability of <em>mu</em> that a bit flips, the probability that it doesn't flip is <code>(1 - mu)</code>. The probability that no bits are flipped is <code>(1 - mu)**nbits</code>; that only 1 bit flips is <code>mu*(1 - mu)**(nbits - 1)</code>; that two are flipped is <code>(mu**2)*(1 - mu)**(nbits - 2)</code>; and so on. For each number of flipped bits, each pattern is equally likely.</p>\n<p>For the sample problem above, <code>nbits</code> is 3, and there are 8 possible bit flips: [0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111]. There is one possibility of no bits flipped which has a probability of <code>(1 - mu)**3</code>. There are 3 possibilities with 1 bit flipped; each with a probablility of <code>(mu*(1 - mu)**2)</code>. For 2 bits, there are also 3 possibilities, each with a probability of <code>(mu**2)*(1 - mu)</code>. Lastly, the probability that all bits are flipped is <code>mu**3</code>. So we get:</p>\n<pre><code>p = [(1-mu)**3, (mu*(1-mu)**2), ((mu**2)*(1-mu)), mu**3]\n\nflips = [0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111]\nweights = [p[0], p[1], p[1], p[2], p[1], p[2], p[2], p[3]]\n</code></pre>\n<p>Obviously, for larger <code>nbits</code>, you would have a function that calculates the probabilities and weights.</p>\n<p>Then use <code>random.choices()</code> to pick the bit flips based on the weights:</p>\n<pre><code>for number in range(N):\n intList[number] ^= random.choices(flips, weight=weights)[0]\n</code></pre>\n<p>According to the docs, it is a bit more efficient to use cumulative weights.</p>\n<pre><code>import itertools\n\ncum_weights = list(itertools.accumulate(weights))\n</code></pre>\n<p>Note that <code>flips</code> is the same as <code>range(8)</code>, so we can do:</p>\n<pre><code>for number in range(N):\n intList[number] ^= random.choices(range(2**nbits), cum_weights=cum_weights)[0]\n</code></pre>\n<p>Lastly, if <code>N</code> isn't too big, we can use the <code>k</code> parameter to pick all the flips for the entire list in one call.</p>\n<pre><code>for index, bits in enumerate(random.choices(range(2**nbits), weights=weights, k=N)):\n intList[index] ^= bits\n</code></pre>\n<p>It <code>nbits</code> is too large to make a table for all possible bit flips, make a smaller table. Then use bit-shifts and or-operations to get the required number of bits. For example, with a table for 8-bits, a 16-bit flip can be calculated like this:</p>\n<pre><code>hi, lo = random.choices(range(2**nbits), cum_weights=cum_weights, k=2)\n\nflip = hi << 8 | lo\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:55:02.693",
"Id": "496647",
"Score": "0",
"body": "\"*There are 3 possibilities with 1 bit flipped; each with a probablility of `(mu*(1 - mu)**2)/3`*\". This is incorrect. Each of them has a probablility of `mu*(1 - mu)**2`. Same with the 2-flipped-bit case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:11:25.283",
"Id": "496678",
"Score": "0",
"body": "@GZ0, Thanks and fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:45:50.147",
"Id": "496686",
"Score": "0",
"body": "Some minor improvements for efficiency: (1) using a list comprehension `intList = [v ^ flipped for v, flipped in zip(intList, choices(..., k=N))]`; (2) in the computation of `p`, direct multiplication for small integer powers is more efficient than `**`, which needs to deal with arbitrary floating-point powers; (3) `1-mu` does not need to be computed multiple times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T19:01:22.367",
"Id": "496695",
"Score": "0",
"body": "Suggestion for computing the weights: `weights = [1]` and then `for _ in range(nbits):\n weights = [w * p for p in (1-mu, mu) for w in weights]`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T06:23:35.790",
"Id": "252133",
"ParentId": "252099",
"Score": "2"
}
},
{
"body": "<p>It is absolutely not optimal for a small <code>mu</code>. It's generally more efficient to first generate how many bits you'd like to flip using a Binomial distribution, and then sample the indices. However, then we have to generate words with <code>k</code> set bits, which involves more expensive RNG calls. However when <code>mu</code> is <em>very</em> small <strong>and</strong> <code>l</code> is <em>very</em> large, this is the most efficient method.</p>\n<p>But for <code>l</code> that fit inside a single computer word, we can be more efficient. Note that we can first solve the problem for a small <code>w <= l</code> (like 8 or 16), and then combine multiple copies of these <code>w</code> into a single larger integer.</p>\n<p>Our main technique is to precompute an <a href=\"https://en.wikipedia.org/wiki/Alias_method\" rel=\"nofollow noreferrer\">alias method</a> table for <strong>all</strong> integers up to width <code>w</code> to sample them according to the number of bits set. This is actually feasible for small <code>w</code> (say, up to 16). So without further ado:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nfrom collections import deque\n\nclass VoseAliasMethod:\n # Vose's Alias Method as described at https://www.keithschwarz.com/darts-dice-coins/.\n def __init__(self, weights):\n pmf = weights / np.sum(weights)\n self.n = pmf.shape[0]\n self.prob = np.zeros(self.n, dtype=np.float64)\n self.alias = np.zeros(self.n, dtype=np.int64)\n\n p = pmf * self.n\n small = deque(np.nonzero(p < 1.0)[0])\n large = deque(np.nonzero(p >= 1.0)[0])\n while small and large:\n l = small.popleft()\n g = large.popleft()\n self.prob[l] = p[l]\n self.alias[l] = g\n p[g] = (p[g] + p[l]) - 1.0\n (small if p[g] < 1.0 else large).append(g)\n self.prob[small] = 1.0\n self.prob[large] = 1.0\n\n def sample(self, size):\n ri = np.random.randint(0, self.n, size=size)\n rx = np.random.uniform(size=size)\n return np.where(rx < self.prob[ri], ri, self.alias[ri])\n</code></pre>\n<p>And the sampling code itself, following the parameters <a href=\"https://stackoverflow.com/questions/64901084/why-is-this-code-in-python-so-much-faster-than-in-c\">from your question here</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>w = 10; mu = 0.0001 # Or whatever parameters you wish.\npopcount = np.array([bin(n).count("1") for n in range(2**w)])\npmf = np.exp(popcount*np.log(mu) + (w - popcount)*np.log(1 - mu))\nsampler = VoseAliasMethod(pmf)\n\nl = 10; n = 10000 # Or however many you'd want of length < 64.\nwords_needed = int(np.ceil(l / w))\n\nintlist = np.zeros(n, dtype=np.int64)\nfor _ in range(10000):\n raw_samples = sampler.sample((n, words_needed))\n if l % w != 0: raw_samples[:,-1] >>= words_needed*w - l\n raw_samples <<= w*np.arange(words_needed)\n result = np.bitwise_or.reduce(raw_samples, axis=1)\n intlist ^= result\n</code></pre>\n<p>Compared to your implementation from your other question this runs in ~2.2 seconds as opposed to ~6.1 seconds for your <code>numba</code> implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T14:05:41.127",
"Id": "497180",
"Score": "0",
"body": "Thanks! This looks really promising. I'll have a closer look later this day and then I'll try to understand what you have done."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T02:11:41.483",
"Id": "252349",
"ParentId": "252099",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252349",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T09:18:30.763",
"Id": "252099",
"Score": "6",
"Tags": [
"python",
"performance",
"numba"
],
"Title": "Random changes in a list of binary numbers"
}
|
252099
|
<p>Dijkstra's algorithm can be used to efficiently find the shortest path between two given nodes. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later.</p>
<p>References: <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="nofollow noreferrer">Wikipedia</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T10:00:17.600",
"Id": "252100",
"Score": "0",
"Tags": null,
"Title": null
}
|
252100
|
This tag should be used for questions that involve Dijkstra's algorithm.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T10:00:17.600",
"Id": "252101",
"Score": "0",
"Tags": null,
"Title": null
}
|
252101
|
<p>Hello this is one of my learning purposes projects, a little bit modified version of a popular game called Hangman. <br><br>
I am a beginner so if you guys could point out some obvious mistakes/good practices/better solutions or implementations I will be grateful.<br><br></p>
<p>Here is a <strong><a href="https://isaayy.github.io/Hangman/" rel="noreferrer">preview</a></strong> hosted on github + <strong><a href="https://github.com/Isaayy/Hangman" rel="noreferrer">repository</a></strong><br>
And my code :</p>
<p><strong>HTML :</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Hangman</title>
</head>
<body>
<main>
<div class='header'>
<h1 class='header__heading'>Hangman</h1>
<div class="header__lifes">
<svg class="header__icon icon-1">
<use xlink:href='img/sprite.svg#icon-heart'></use>
</svg>
<svg class="header__icon icon-2">
<use xlink:href='img/sprite.svg#icon-heart'></use>
</svg>
<svg class="header__icon icon-3">
<use xlink:href='img/sprite.svg#icon-heart'></use>
</svg>
<svg class="header__icon icon-4">
<use xlink:href='img/sprite.svg#icon-heart'></use>
</svg>
<svg class="header__icon icon-5">
<use xlink:href='img/sprite.svg#icon-heart'></use>
</svg>
</div>
</div>
<p class='description'>This is version of the classic letter guessing game called Hangman. You are shown a set of blank letters that match a word or phrase and you have to guess what these letters are to reveal the hidden word.</p>
<div class="keyword">
</div>
<div class="menu">
<input type="text" class='menu__input' value="" id='test'>
<p class='menu__message hidden'></p>
<button class="menu__btn">Try!</button>
</div>
<a href="#" class="cta">Start!</a>
</main>
<script src='script.js'></script>
</body>
</html>
</code></pre>
<p><strong>JS :</strong></p>
<pre><code>'use strict';
const cta = document.querySelector('.cta');
const header = document.querySelector('.header__heading');
const description = document.querySelector('.description');
const lifesBox = document.querySelector('.header__lifes');
const input = document.querySelector('.menu__input');
const guess = document.querySelector('.menu__btn')
// ###############################
// change layout
cta.addEventListener('click', () =>{
description.style.transition = 'all 1s';
description.style.opacity = "0";
header.style.transition = 'all 1s';
header.style.transform="translateX(-150%)";
lifesBox.style.opacity = "1";
input.style.opacity = "1";
guess.style.opacity = "1";
cta.style.display = 'none';
})
// ###############################
// keyword generator
let keyword;
let wordsLeft ;
const keywordBox = document.querySelector('.keyword');
const generateKeyword = () => {
// TODO in future add more keywords in a better way
const keywords = [
'ability',
'able',
'about',
'above',
'accept',
'according',
'account',
'across',
'act',
'action',
'activity',
'actually',
];
const randomNumber = Math.floor(Math.random() * keywords.length);
keyword = keywords[randomNumber];
wordsLeft = keyword.length;
for(let i = 0 ; i<keyword.length ; i++){
keywordBox.innerHTML += `<div class=keyword__letter-${i}></div>`;
}
}
generateKeyword();
// ###############################
// game starts
const inputValidation = (str) => {
const lettersOnly = /^[a-z]+$/i;
const valid = lettersOnly.test(str) ? true : false; // checking both empty and non number
return valid;
}
let lifes = 5;
let game = true;
// ###############################
// game ends
const endGame = winOrLose => {
input.classList.toggle('hidden');
input.nextElementSibling.classList.toggle('hidden');
if (winOrLose === 'win'){
input.nextElementSibling.textContent = "You win";
input.nextElementSibling.style.color = "green";
}
else {
input.nextElementSibling.textContent = "You lost";
input.nextElementSibling.style.color = "red";
}
guess.textContent = 'Play again'
game = false;
}
// ###############################
// index finder
const allIndexes = (letter) => { // for keywords with more than 1 letter ex. apple
let arr = [];
for(let i = 0 ; i < keyword.length ; i ++){
if (keyword[i] == letter){
arr.push(i);
}
}
return arr;
}
// ###############################
// game
let usedLetters = [];
guess.addEventListener('click',() =>{
if (inputValidation(input.value) && game && !usedLetters.includes(input.value)){
if (input.value.length <= 1){ // single letter input
if (keyword.includes(input.value)){
const indexArray = allIndexes(input.value);
for (let i = 0; i < indexArray.length; i++) {
document.querySelector(`.keyword__letter-${indexArray[i]}`).textContent = input.value;
}
usedLetters.push(input.value);
input.value = '';
wordsLeft-=indexArray.length;
if (wordsLeft == 0){ // Winning game
endGame('win');
}
}
else{
lifes--;
if (lifes == 0 ){ // Losing game
endGame('lose');
}
let life = document.querySelector(`.icon-${lifes+1}`);
life.style.fill = "#333333";
}
}
else { // word input
if (input.value == keyword){
for (let i = 0 ; i < keyword.length ; i++){
document.querySelector(`.keyword__letter-${i}`).textContent = keyword[i];
}
endGame('win');
}
else {
lifes--;
let life = document.querySelector(`.icon-${lifes+1}`);
life.style.fill = "#333333";
}
}
}
else if (!game) { // Play again
guess.textContent = 'Try!'
game = true;
input.value = '';
input.classList.toggle('hidden');
input.nextElementSibling.classList.toggle('hidden');
lifes = 5 ;
for (let i = 0; i < lifes; i++) {
let life = document.querySelector(`.icon-${i+1}`);
life.style.fill = "#8F0045";
}
keywordBox.textContent = '';
generateKeyword();
}
})
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:27:23.327",
"Id": "496595",
"Score": "0",
"body": "Pressing enter should check if the letter is correct, it should not be necessary to press the button with the mouse imo"
}
] |
[
{
"body": "<p>Cool game! I like the colours and simplicity.</p>\n<h1>Additional Features:</h1>\n<p>Give a list of letters already guessed that were wrong. I have poor memory.</p>\n<p>Don't punish user for making the same guess twice (E.G don't lose a heart for guessing 'a' twice, only 1 heart)</p>\n<p>Validate the guess, so 'ab' shouldn't do anything. Currently you lose a heart.</p>\n<p>Most importantly, show the answer at game over!</p>\n<h1>Glitch</h1>\n<p>During my testing, I was able to make infinite guesses and tried every single letter, but could never win the game. I made correct guesses after having 0 lives:</p>\n<p><a href=\"https://i.stack.imgur.com/00zUU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/00zUU.png\" alt=\"enter image description here\" /></a></p>\n<h1>Code suggestions</h1>\n<p>Currently if your JS loads before the document, there should be errors. I suggest wrapping your code in a load document function. On the same note, it's hard to see the flow of the program. It would be much easier if you had 1 function showing what's happening rather than throughout the whole file.</p>\n<p>Declare variables at the top of the page, or in the function they are used. You can separate parts into separate files, or check what standards are popular for this in JS. But try to avoid declaring variables outside of functions, throughout the JS file.</p>\n<pre><code>const inputValidation = (str) => {\n const lettersOnly = /^[a-z]+$/i;\n const valid = lettersOnly.test(str) ? true : false; // checking both empty and non number\n return valid;\n}\n</code></pre>\n<p>'inputValidation' is not a good name, it does not make sense. 'isInputValid' would make more sense.</p>\n<p>The function can be shortened to:</p>\n<pre><code>const inputValidation = (str) => {\n const lettersOnly = /^[a-z]+$/i;\n return lettersOnly.test(str); // checking both empty and non number\n}\n</code></pre>\n<p>I have to go, but will continue the review later</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T15:13:57.567",
"Id": "496581",
"Score": "1",
"body": "*Currently if your JS loads before the document* His code works because the `<script>` tag is located at the bottom of the `<body>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T15:44:04.397",
"Id": "496583",
"Score": "1",
"body": "thanks for your feedback and time"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T14:50:53.900",
"Id": "252109",
"ParentId": "252102",
"Score": "4"
}
},
{
"body": "<p><strong>Prefer CSS rules over JS</strong> It helps to separate concerns by putting CSS rules as much in the CSS file as possible - putting lots of rules in the JS can detract from the code's logic, which is likely what one is more worried about. Here, rather than assigning to style properties when the game starts, consider adding a class to the container <em>only</em>, and having CSS rules that only apply when that class exists. For example, change:</p>\n<pre><code>cta.addEventListener('click', () =>{\n \n description.style.transition = 'all 1s';\n description.style.opacity = "0";\n \n header.style.transition = 'all 1s';\n header.style.transform="translateX(-150%)";\n // ...\n});\n</code></pre>\n<p>to</p>\n<pre><code>cta.addEventListener('click', () =>{\n document.querySelector('main').classList.add('started');\n});\n</code></pre>\n<pre><code>.started .description {\n transition: all 1s;\n opacity: 0;\n}\n.started .header__heading {\n transition: all 1s;\n transform: translateX(-150%);\n}\n</code></pre>\n<p>This way, when you care about layout, the <em>one</em> place to look at is the CSS, rather than having to go through the JS to see what style properties were assigned when.</p>\n<p><strong>Use precise variable names</strong> The variable <code>wordsLength</code> confused me until I realized it was referring to a count of <em>letters</em>, not <em>words</em>. Also, you have a <code>keyword</code> variable that contains the word to be picked, but also a <code>keyword</code> <em>class</em> in the DOM that contains the partially filled in letters. This could be confusing - consider giving them completely distinct names.</p>\n<p><strong>Allow keyboard only</strong> The user will be entering letters on their keyboard. Consider allowing them to submit their guess by pressing the enter key.</p>\n<p><strong><code>keyword__letter</code> is weird</strong> - you're only using it to be able to select particular children indicies of the parent container. Consider removing it entirely and instead going through the parent's <code>children</code> property. Eg</p>\n<pre><code>document.querySelector(`.keyword__letter-${i}`).textContent\n</code></pre>\n<p>can be</p>\n<pre><code>keywordBox.children[i].textContent\n</code></pre>\n<p><strong>Simplify and fix <code>inputValidation</code></strong>:</p>\n<pre><code>const inputValidation = (str) => {\n const lettersOnly = /^[a-z]+$/i;\n const valid = lettersOnly.test(str) ? true : false; // checking both empty and non number\n return valid;\n}\n</code></pre>\n<ul>\n<li><p>simplifies to</p>\n<pre><code>const inputValidation = (str) => /^[a-z]+$/i.test(str);\n</code></pre>\n</li>\n<li><p>is a function, so for readability, it should contain a <em>verb</em>, perhaps <code>isInputValid</code></p>\n</li>\n<li><p>Letters should be guessed one letter at a time for proper Hangman, so consider removing the <code>+</code> from the regular expression - or, you could remove the validation here entirely and instead use a <code>pattern</code> and <code>maxlength</code> attribute in the HTML:</p>\n<pre><code><input type="text" class="menu__input" pattern="[A-Za-z]" maxlength=1>\n</code></pre>\n</li>\n</ul>\n<p><strong>Always use <code>===</code></strong>, never use <code>==</code> or <code>!=</code> - sloppy comparison with <code>==</code> has <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">weird rules</a> that a script-writer or script-reader should not have to memorize in order to understand what's going on. Consider using the ESLint rule <a href=\"https://eslint.org/docs/rules/eqeqeq\" rel=\"noreferrer\"><code>eqeqeq</code></a>.</p>\n<p><strong>Guess click function is too long</strong> - it has lots of <code>if</code>/<code>else</code> branches that make the overall logic hard to understand at a glance. Consider splitting it up. For example, maybe something like:</p>\n<pre><code>guess.addEventListener('click', () => {\n if (!game) { // Play again\n resetGame();\n return;\n }\n // Input should be validated from the HTML\n const { value } = input;\n if (usedLetters.includes(value)) {\n // maybe give the user a visual indication that the letter has already been picked here\n return;\n }\n if (value.length === 1) {\n handleSingleLetterInput(value);\n } else {\n handleWordInput(value);\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T09:38:19.233",
"Id": "496755",
"Score": "0",
"body": "thank you very much"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T17:11:44.930",
"Id": "252113",
"ParentId": "252102",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "252113",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T10:46:37.583",
"Id": "252102",
"Score": "6",
"Tags": [
"javascript",
"html"
],
"Title": "My version of hangman game"
}
|
252102
|
<p>Hello I would like to know which pattern would be better in this case, I have many ifs and validations in my useCase, I was between strategy and commadn pattern to decouple this:</p>
<pre><code>@injectable()
export class AssignProductUseCase
implements
IUseCase<AssignProductDTO, Promise<Either<AppError, ProductInstance>>> {
constructor(
@inject(EmployeeRepository)
private employeeRepository: IEmployeeRepository,
@inject(ProductRepository)
private productRepository: IProductRepository,
@inject(ProductInstanceRepository)
private instanceRepository: IProductInstanceRepository,
@inject(ProductStocksRepository)
private stockRepository: IProductStocksRepository,
) {}
public execute = async ({
contract_id,
matricula,
parent_id,
patrimony_code,
product_id,
serial_number,
type,
}: AssignProductDTO): Promise<Either<AppError, ProductInstance>> => {
//verify type
if (!(type in ProductTypes)) throw new Error(`${type}, is invalid`);
//instance checks
const hasInstance = await this.instanceRepository.bySN(serial_number);
if (hasInstance) {
throw new Error(
`This ${serial_number} product has already been assigned `,
);
}
const parentInstance = parent_id
? await this.instanceRepository.byId(parent_id)
: null;
if (parentInstance === undefined) {
throw new Error(`Parent Instance doesn't exist.`);
}
//products checks
const hasProduct = await this.productRepository.byId(product_id);
if (!hasProduct) throw new Error(`This product doesn't exist.`);
//employee checks
const hasEmployee = await this.employeeRepository.byMatricula(matricula);
if (!hasEmployee) throw new Error(`This Employee doesn't exist.`);
const employeeHasProduct = await this.instanceRepository.hasInstance(
product_id,
hasEmployee.id,
);
if (employeeHasProduct) {
throw new Error(
`The enrollment employee: ${matricula} already has an instance of the product.`,
);
}
//stock checks
const stock = await this.stockRepository.byContractAndProduct(
contract_id,
product_id,
);
if (!stock) {
throw new Error(
`The product has no stock, or the contract has no supply.`,
);
}
if (stock.quantity <= 1) {
throw new Error(`The stock of this product is less than or equal to 1`);
}
//create instance
const instance = await this.instanceRepository.create(ProductInstance.build(request))
return right(instance)
};
}
</code></pre>
<p>did i do my commad logic:</p>
<p>command interface:</p>
<pre><code>export interface Command {
getName(): string;
execute(): void;
undo(): void;
}
</code></pre>
<p>command bus:</p>
<pre><code>export type Type<T = unknown> = new (...arguments_: readonly any[]) => T;
export abstract class CommandBus {
private handlers: { [k: string]: Command } = {};
constructor(...params: Command[]) {
params.forEach(command => {
if (!command.getName()) return;
this.handlers[command.getName()] = command;
});
}
protected registerCommand = (command: Type<Command>): void => {
if (!command.name) return;
const hasCommand = this.handlers[command.name];
if (hasCommand) throw new Error(`Command ${command.name} already exists`);
this.handlers[command.name] = command.prototype;
};
protected executeCommand = async (command: Type<Command>): Promise<any> => {
const hasCommand = this.handlers[command.name];
if (!hasCommand) throw new Error(`Command ${command.name} dont exists`);
return await this.handlers[command.name].execute();
};
protected undoCommand = async <TCommand extends Command>(
command: TCommand,
): Promise<any> => {};
}
</code></pre>
<p>I have doubts about the command, as it is about data validations with calls to the database the most correct would be: create simple commands for each validation, without a receiver. create a receiver for each entity / and create the validation / query commands etc, or would it be better to use the strategy pattern? I want to improve my code, but I have these doubts</p>
<p>typescript</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T11:51:35.417",
"Id": "252104",
"Score": "1",
"Tags": [
"typescript"
],
"Title": "Typescript: command pattern with orm"
}
|
252104
|
<p><strong>Hi everyone !</strong></p>
<p>I am new to <strong>react</strong> and more of a backend developper (working with Django, Symfony, Code Igniter mostly).</p>
<p>But I want to get better at frontend and React seems to have a great community so I thought it was a good place to start :) (not litteral start, I got basics in HTML, CSS and JS !)</p>
<p>So I took the <a href="https://reactjs.org/tutorial/tutorial.html" rel="nofollow noreferrer">official tutorial</a> and I have been struggling a little for the <a href="https://reactjs.org/tutorial/tutorial.html#wrapping-up" rel="nofollow noreferrer">last part</a>.
It is adding functionnalities to the code we wrote before :</p>
<blockquote>
<p>Display the location for each move in the format (col, row) in the move history list.</p>
</blockquote>
<blockquote>
<p>Bold the currently selected item in the move list.</p>
</blockquote>
<blockquote>
<p>Rewrite Board to use two loops to make the squares instead of hardcoding them.</p>
</blockquote>
<blockquote>
<p>Add a toggle button that lets you sort the moves in either ascending or descending order.</p>
</blockquote>
<blockquote>
<p>When someone wins, highlight the three squares that caused the win.</p>
</blockquote>
<blockquote>
<p>When no one wins, display a message about the result being a draw.</p>
</blockquote>
<p>My repo is <a href="https://github.com/Damiaou/react-tutorial" rel="nofollow noreferrer">here</a> so you can test locally if you want too and I put it in <a href="https://codesandbox.io/s/mystifying-hooks-ft6g4?file=/src/App.js:0-5212" rel="nofollow noreferrer">a sandbox if you feel to give it a try</a>.</p>
<p>I paste the JS part here since it is the interesting one :</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function Square(props) {
return (
<button
className={props.className}
onClick={props.onClick}
>
{props.value}
</button>
);
}
class Board extends React.Component {
inWinnerLine(i) {
return this.props.winningLine ? this.props.winningLine.includes(i) : false;
}
renderSquare(i) {
const won = this.inWinnerLine(i) ? 'won' : 'no-luck';
return (
<Square
value={this.props.squares[i]}
onClick={() => this.props.onClick(i)}
className={`square ${won}`}
/>
);
}
render() {
// Need a three element array to loop
const looper = [0, 1, 2];
// And a counter to go to 8
let inc = 0;
return (
<div>
{looper.map((value, index) => {
return (
<div className="board-row">
{looper.map((val, id) => {
inc++;
return this.renderSquare(inc - 1);
})}
</div>
);
})}
</div>
);
}
}
class Game extends React.Component {
constructor(props) {
super(props);
this.state = {
history: [{
squares: Array(9).fill(null),
}, ],
stepNumber: 0,
xIsNext: true,
winningLine: null,
winner: null,
};
}
calculateWinner(squares) {
const lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
for (let i = 0; i < lines.length; i++) {
const [a, b, c] = lines[i];
if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
this.setState({
winner: squares[a],
winningLine: lines[i],
});
return squares[a];
}
}
this.setState({
winner: null,
winningLine: null,
});
return null;
}
handleClick(i) {
// TODO if I go back to winner step the game cannot continue
const history = this.state.history.slice(0, this.state.stepNumber + 1);
const current = history[history.length - 1];
const squares = current.squares.slice();
if (squares[i] || this.state.winner) {
return;
}
squares[i] = this.state.xIsNext ? 'X' : 'O';
this.setState({
history: history.concat([{
squares: squares,
position: getPosition(i),
}, ]),
xIsNext: !this.state.xIsNext,
stepNumber: history.length,
});
if (this.calculateWinner(squares)) {
return;
}
}
jumpTo(step) {
const history = this.state.history.slice(0, step);
const current = history[history.length - 1];
const squares = current.squares.slice();
this.calculateWinner(squares);
this.setState({
stepNumber: step,
xIsNext: (step % 2) === 0,
});
}
highlight(position) {
return position === this.state.stepNumber ? 'highlight' : '';
}
sort() {
// Add action on sort button click
this.setState({
history: this.state.history.slice(0).reverse(),
reverse: !this.state.reverse,
});
}
render() {
const history = this.state.history;
const current = history[this.state.stepNumber];
const winner = this.state.winner;
const moves = history.map((step, move) => {
let move_for_display = this.state.reverse ?
history.length - 1 - move :
move;
const desc = step.position ?
'Back to round n°' + move_for_display + ' ' + step.position :
'Back to beginning';
return (
<li key={move}>
<button className={this.highlight(move)} onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
});
let status;
if (winner) {
status = winner + ' won.';
} else {
status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
}
return (
<div className="game">
<div className="game-board">
<Board
winningLine={this.state.winningLine}
squares={current.squares}
onClick={(i) => this.handleClick(i)}
/>
</div>
<div className="game-info">
<div>{status} - <button className='sort' onClick={() => this.sort()}>Sort</button></div>
<ol>{moves}</ol>
</div>
</div>
);
}
}
// ========================================
ReactDOM.render(
<Game />,
document.getElementById('root')
);
function getPosition(i) {
let pos;
switch (i) {
case 0:
pos = '(1, 1)';
break;
case 1:
pos = '(2, 1)';
break;
case 2:
pos = '(3, 1)';
break;
case 3:
pos = '(2, 1)';
break;
case 4:
pos = '(2, 2)';
break;
case 5:
pos = '(2, 3)';
break;
case 6:
pos = '(3, 1)';
break;
case 7:
pos = '(3, 2)';
break;
case 8:
pos = '(3, 3)';
break;
default:
pos = 'Something went wrong';
}
return pos;
}</code></pre>
</div>
</div>
</p>
<p>I appreciate the time you took to read this and any feedback will be welcome, I have seen similar question but they seemed old so I did a new one, sorry if I should not have.</p>
<p>Also my english might be bad, sorry about that too - french here ;)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T15:06:52.377",
"Id": "497899",
"Score": "1",
"body": "So what is the problem you are having? What do you expect compared to what your are getting. A codesandbox would make it easier to help you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:04:25.913",
"Id": "497936",
"Score": "0",
"body": "Hi, thank you for your answer. Actually I get pretty much what I was expecting, the code works but as a React beginner I am looking for feedback on the way I did it and what could/should be improve for a real world app.\nI just put it in a sandbox -> https://ft6g4.csb.app/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T20:40:33.070",
"Id": "497941",
"Score": "1",
"body": "First glance looks fine. GetPos could be simplified to a dict instead of a function, a few `ifs` could use the ternary operator. Are you attached to a class based approach? I could add a refactored functional version if you're interested"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T08:50:04.357",
"Id": "498026",
"Score": "0",
"body": "I am not attached to a class based approch, I would be very interested in a function version :) [this](https://coderwall.com/p/s7592q/use-dictionary-lookups-instead-of-switch-statements) kind of dict ?"
}
] |
[
{
"body": "<p>First, congratulations on working code.</p>\n<p>Recommendations:</p>\n<ul>\n<li>Simplify your state</li>\n<li>Simplify your controls</li>\n<li>Simplify your functions</li>\n</ul>\n<p>Your state is overly complex, even with no user interaction it is very complex. Every action drastically changes every node in your state. I've updated your <a href=\"https://codesandbox.io/s/original-tic-tac-toe-00kz5?file=/src/index.js\" rel=\"nofollow noreferrer\">code sandbox</a> to show these state changes.</p>\n<p>You are actually building a data model, not state.\nYou are then tightly coupling your data model to your controls.<br />\nAs more features are added, updating the model becomes very difficult. Simple changes require you to touch too many things (controls, actions, state)</p>\n<p><a href=\"https://reactjs.org/docs/thinking-in-react.html\" rel=\"nofollow noreferrer\">Thinking in react</a> states "Step 3: Identify The Minimal (but complete) Representation Of UI State"</p>\n<p>I identify your minimal (but complete) state as</p>\n<ol>\n<li>Moves (holds the order and location of players clicks)</li>\n<li>Last history button clicked.</li>\n<li>Is history descending.</li>\n</ol>\n<p>For our first iteration, we will simply focus on <strong>1. Moves</strong></p>\n<p>We can accomplish 80% of the application with only this state.<br />\nAlso taking an iterative approach will show how the application can handle change.</p>\n<p>Moves will be a simple array:</p>\n<pre><code>+---------------------+--------+---------------+\n| Action | square | state.moves |\n+---------------------+--------+---------------+\n| No clicks | |[] |\n| X clicks top Left | 0 |[0] |\n| Y clicks center | 4 |[0, 4] |\n| X clicks top center | 1 |[0, 4, 1]. |\n+---------------------+--------+---------------+\n</code></pre>\n<p>Updating our state is trivial.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>\n const addMove = (boardIndex) => (oldState) => {\n const { moves } = oldState;\n return {\n moves: [...moves, boardIndex]\n };\n };\n \n handleClickSquare = (boardIndex) => {\n this.setState(addMove(boardIndex));\n };\n \n</code></pre>\n<p>Ok, trivial if you understand: <a href=\"https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback\">useState callback</a>, <a href=\"https://www.samanthaming.com/tidbits/49-2-ways-to-merge-arrays/\" rel=\"nofollow noreferrer\">spread operator</a>, and <a href=\"https://medium.com/@kbrainwave/currying-in-javascript-ce6da2d324fe\" rel=\"nofollow noreferrer\">currying</a></p>\n<p>Although our state is simple, it holds a lot of implied information.\nFrom our simple state we can derive most of the data model.</p>\n<p>We can determine:</p>\n<ol>\n<li>Who (X or O) owns each square.</li>\n<li>Status:\n<ul>\n<li>Is there a winner?</li>\n<li>Who won?</li>\n<li>Is there a tie?</li>\n<li>Who is next.</li>\n</ul>\n</li>\n<li>What squares caused the win.</li>\n<li>History of moves.</li>\n</ol>\n<p>Let's examine each one individually.</p>\n<pre><code>// selectSquareOwners \n// Builds a tic-tac-toe board of 9 squares and who (X or O) occupies \n// each square.\n// For each square, find if it is occupied and by who. \n// If the square index is in move list, it is occupied, if the move \n// index is odd it is owned by X, if it is even, it is owned by Y\nexport const selectSquareOwners = (state) => {\n const emptySquares = Array(9).fill("");\n return emptySquares.map((cur, i) => {\n const { moves = [] } = state || {};\n const move = moves.indexOf(i);\n const notFound = !~move;\n const isEven = move % 2;\n if (notFound) {\n return "";\n }\n return isEven ? "O" : "X";\n });\n}; // ["", "X", "", "O", "X" , ...]\n\n// Builds a tic-tac-toe board of 9 squares. Each square is represented by an \n// object containing: {\n// isWinner - does the square participate in the win\n// owner: who owns the square (X or O)\n// index: the id of the square \n// }\nexport const selectSquares = (state) => {\n const xoSquares = selectSquareOwners(state); // => ["X", "X", "X", "", "O", "O" , ...]\n const winningRow = getWinningRow(xoSquares); // => [0, 1, 2]\n return xoSquares.map((owner, index) => {\n const isWinner = !!~winningRow.indexOf(index);\n return { isWinner, owner, index };\n });\n}; \n</code></pre>\n<p>Here is the <a href=\"https://codesandbox.io/s/code-review-tic-tac-toe-rbvte?file=/src/Refactor/selectors.js:442-1121\" rel=\"nofollow noreferrer\">code</a> without time travel.</p>\n<p>You may be concerned about the efficiency of this code.<br />\nThere is definitely room for improvement, but with such a small data set, the end user will not notice them so I choose simple code over efficient code here. If efficiency becomes a priority, consider using <a href=\"https://github.com/reduxjs/reselect\" rel=\"nofollow noreferrer\">reselect</a>.</p>\n<blockquote>\n<p>I understand that changing all nodes when user make an input is not a good practice.</p>\n</blockquote>\n<p>Unfortunately it is not that easy. It's all about tradeoffs and understanding secondary effects. In the <a href=\"https://codepen.io/gaearon/pen/LyyXgK?editors=0010\" rel=\"nofollow noreferrer\">tutorial before time travel</a>, updating all nodes is still simple. As more features are added, simplifying the state should be considered. I choose small, composable functions and controls. This is easy to test and easy to reuse, but comprehending the final result may be more difficult like seeing the forest for the trees. Understanding tradeoffs will come with experience. Keep calm and Code on.</p>\n<p>Here is the complete <a href=\"https://codesandbox.io/s/code-review-tic-tac-toe-final-xg3th?file=/src/Refactor/selectors.js\" rel=\"nofollow noreferrer\">code</a></p>\n<p>I will address control improvements soon.</p>\n<p>Here are past code reviews for simplifying controls.</p>\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/questions/252189/a-better-solution-for-nested-maps/252610#252610\">Better solution for nested maps</a></li>\n<li><a href=\"https://codereview.stackexchange.com/questions/204110/reactjs-component-to-classify-a-list-of-books/204258#204258\">A good approach for building controls</a></li>\n<li><a href=\"https://codereview.stackexchange.com/questions/201576/react-component-wrappers-for-form-fields-with-90-similar-code/203774#203774\">DRY code</a></li>\n<li><a href=\"https://codereview.stackexchange.com/users/178181/mke-spa-guy?tab=answers&sort=activity\">...all reviews</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T07:31:56.720",
"Id": "498535",
"Score": "1",
"body": "Wow, thank you for the extensive answer. There's a lot to study and I understand that changing all nodes when user make an input is not a good practice.\nThe working code example are a great help !\nI'm going to read again `Thinking in React`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T14:38:07.730",
"Id": "498950",
"Score": "0",
"body": "I've added my response above. Reach out if I can clarify anything else."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-29T03:08:03.993",
"Id": "252805",
"ParentId": "252111",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252805",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T16:51:16.173",
"Id": "252111",
"Score": "7",
"Tags": [
"javascript",
"tic-tac-toe",
"react.js"
],
"Title": "Tic Tac Toe in React (official tutorial)"
}
|
252111
|
<p>Here's my attempt, I believe the runtime is O(V*(ElogE + log E)) since the while loop runs V times and it takes ElogE + log E to do the priority queue operations inside the loop.</p>
<pre><code>class Edge implements Comparable<Edge> {
T source;
T destination;
int weight;
public Edge(T source, T destination, int weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
}
public int compareTo(Edge other) {
return this.weight - other.weight;
}
}
public void printMSTPrims(Map<T, List<Edge> > adjacencyList) {
// Records all visited destinations.
Set<T> visited = new HashSet<>();
Queue<Edge> edges = new PriorityQueue<>();
T currentNode = adjacencyList.entrySet().iterator().next().getKey();
visited.add(currentNode);
// Run until we've visited all vertices
while (visited.size() < adjacencyList.size()) {
// Take all edges from current node and add to the PQ.
for (Edge edge: adjacencyList.get(currentNode)) {
edges.add(edge);
}
// Pick the smallest edge to a destination node not already visited.
Edge edge = edges.remove();
while (!edges.isEmpty() && visited.contains(edge.destination)) {
edge = edges.remove();
}
// Found an eligible edge, print its contents. This edge does not have to necessarily start from the currentNode.
System.out.println(edge.source + "--" + edge.weight + "--" + edge.destination);
// Go next to this destination vertex.
currentNode = edge.destination;
//Now that you've reached this edge as a destination, record it.
visited.add(currentNode);
}
}
</code></pre>
<p>PS. I assume the graph does not have self-loops and double-edges.</p>
|
[] |
[
{
"body": "<p>For who is not familiar with <a href=\"https://en.wikipedia.org/wiki/Prim%27s_algorithm\" rel=\"nofollow noreferrer\">Prim's algorithm</a>: it finds a minimum spanning tree for a weighted undirected graph.</p>\n<p><a href=\"https://i.stack.imgur.com/c491r.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c491r.gif\" alt=\"enter image description here\" /></a></p>\n<p>My suggestions:</p>\n<ul>\n<li><strong>Generics</strong>: the class <code>Edge</code> should be declared as <code>Edge<T></code> or it won't compile as is. Or is it an inner class? Also the generic is missing in <code>Comparable</code> and the method <code>compareTo</code>.</li>\n<li><strong>compareTo</strong>: typically, for primitive types is better to use <code><</code>,<code>></code>, and return -1,0 or 1. In your case, <code>compareTo</code> could overflow the integer with a negative weight. You can change it from:\n<pre><code>public int compareTo(Edge other) {\n return this.weight - other.weight;\n}\n</code></pre>\nTo:\n<pre><code>public int compareTo(Edge other) {\n return Integer.compare(this.weight,other.weight);\n}\n</code></pre>\n</li>\n<li><strong>addAll instead of for-loop</strong>: adding all edges to the queue can be done with <code>addAll</code>. From:\n<pre><code>for (Edge edge: adjacencyList.get(currentNode)) {\n edges.add(edge);\n}\n</code></pre>\nTo:\n<pre><code>edges.addAll(adjacencyList.get(currentNode));\n</code></pre>\n</li>\n<li><strong>Testing</strong>: the method <code>printMSTPrims</code> is hard to test. Would be better to have a method <code>mstPrims</code> that returns a result and then print it with another method. In that case, would be easier to test <code>mstPrims</code>.</li>\n<li><strong>Naming</strong>: the name <code>edges</code> is a bit generic, an alternative can be <code>edgeQueue</code> or just <code>queue</code>.</li>\n</ul>\n<p>Your final assumption:</p>\n<blockquote>\n<p>PS. I assume the graph does not have loops and self-edges.</p>\n</blockquote>\n<p>So a tree? A (connected) acyclic undirected graph is a <a href=\"https://en.wikipedia.org/wiki/Tree_(graph_theory)\" rel=\"nofollow noreferrer\">tree</a>. Anyway, looking at your method I don't think there should be problems even if there are cycles.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T05:10:20.300",
"Id": "496627",
"Score": "0",
"body": "Thanks Marc, yes ```Edge``` is an inner class, I only pasted the relevant part of the code. and ```I assume the graph does not have loops and self-edges.``` is worded poorly, I meant to say ```I assume the graph does not have self-loops and double-edges.```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T05:11:26.803",
"Id": "496628",
"Score": "0",
"body": "(By self-loops I mean an edge from a node to itself)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T08:52:57.397",
"Id": "496636",
"Score": "0",
"body": "@user2495123 got it, thanks. I am glad that I could help!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T03:54:38.993",
"Id": "252131",
"ParentId": "252117",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code> for (Edge edge: adjacencyList.get(currentNode)) {\n edges.add(edge);\n }\n</code></pre>\n</blockquote>\n<p>This could more simply be</p>\n<pre><code> edges.addAll(adjacencyList.get(currentNode));\n</code></pre>\n<p>A note on naming. I would find <code>queue</code> or <code>edgeQueue</code> to be just as generic as <code>edges</code>. I mean, we really don't care that it is a queue. Think about what the purpose of the queue is. In this case, it is to determine what edges to travel. So I would call it <code>untraveled</code>. I.e. I would name it like <code>visited</code>. Or possibly <code>remainingEdges</code>.</p>\n<p>I would find <code>neighbors</code> or <code>neighborsOf</code> to be more explanatory than <code>adjacencyList</code> and better match <code>visited</code>. In general, I would try to avoid mixing meanings of something like <code>List</code>. In this case, you are referring to list in its graph theory meaning. But Java also has a <code>List</code>. Does your adjacency list (graph) have to be a Java <code>List</code>? No, it doesn't. Seeing as how it isn't a <code>List</code> but a <code>Map</code>.</p>\n<blockquote>\n<pre><code> while (visited.size() < adjacencyList.size()) {\n</code></pre>\n</blockquote>\n<p>You might consider flipping this logic. Instead of building a visited list, start with a destinations list:</p>\n<pre><code> Set<T> remaining = adjacencyList.keySet();\n</code></pre>\n<p>with</p>\n<pre><code> while (!remaining.isEmpty()) {\n</code></pre>\n<p>and</p>\n<pre><code> while (!edges.isEmpty() && !remaining.contains(edge.destination)) {\n</code></pre>\n<p>Note that this also allows you to say</p>\n<pre><code> T currentNode = remaining.iterator().next();\n remaining.remove(currentNode);\n</code></pre>\n<p>which is somewhat simpler than your current form.</p>\n<p>If you are using <code>remainingEdges</code>, you could call this <code>remainingDestinations</code> or <code>remainingNodes</code> or similar.</p>\n<p>A benefit of this is that it localizes the relationship between <code>remaining</code> and <code>adjacencyList</code> to just one place. So if you later wanted to remove that relationship, you could do so easily. And in the more common case of reading the code, you would only need to look one place to see it. The current code is confusing in that there is no particular reason why the collection of things to visit should be the same size as the adjacency list. That's not a a property of the algorithm but of your implementation.</p>\n<p>Consider a case where we have a global adjacency list and a local list of places to visit. You can't easily adjust your method to cover that directly. But if we create a remaining collection, then we can. So why not create it now? It simplifies the current logic and leaves the method more expandable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:00:34.273",
"Id": "496703",
"Score": "0",
"body": "Invaluable advice, thank you! Yes, using a Set instead of a visited array is more intuitive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:02:10.380",
"Id": "496704",
"Score": "0",
"body": "```there is no particular reason why the collection of things to visit should be the same size as the adjacency list. That's not a a property of the algorithm ```\n\nHmm, I'd argue it is, because Prim's ends when the number of edges you have visited = V - 1. Or in other words (I think), when # vertices you've visited are equal to vertices in the graph/adjList"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:58:54.933",
"Id": "252142",
"ParentId": "252117",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252131",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T18:35:18.880",
"Id": "252117",
"Score": "3",
"Tags": [
"java",
"graph"
],
"Title": "Prim's algorithm via Priority Queues to print the minimum spanning tree of an undirected graph"
}
|
252117
|
<p>So this is the code to a calculator I made for a game. Essentially what the calculator does is, it calculates the cost of buying the next stat.</p>
<p>So I wrote the code just for the Human race and the strength stat. From the way I see it, I will have to do for each race the same code 3 times for each stat.</p>
<p>I was hoping there would be a shorter way around this like</p>
<p>instead of <code>human.strength</code> I would like it to be <code>race.strength</code> where <code>race = user_race</code>.</p>
<p>Thanks</p>
<pre class="lang-py prettyprint-override"><code>class race:
"""The different races in the calculator"""
def __init__(self, race, strength, agility, health, strength_cost, agility_cost, health_cost):
self.race = race
self.strength = strength
self.agility = agility
self.health = health
self.strength_cost = strength_cost
self.agility_cost = agility_cost
self.health_cost = health_cost
human = race('Human', 15, 17, 18, 5, 3, 4)
elf = race('Elf', 11, 21, 14, 4, 3, 5)
giant = race('Giant', 25, 11, 27, 4, 8, 3)
print("Human, Giant, Elf")
user_race = str(input("Enter your race:")).lower()
print("Strength, Agility, Health")
user_stat = str(input("Enter your desired stat:")).lower()
user_present_stat_value = int(input("Enter your present stat value:"))
user_desired_stat_value = int(input("Enter your desired stat value:"))
if user_race == 'human' and user_stat == 'strength':
human_strength_present_statdif = (user_present_stat_value - human.strength) # difference of present stat with respect of base stat
human_strength_desired_statdif = (user_desired_stat_value - human.strength) #difference of desired stat with respect of base stat
human_strength_present_stat_cost = (human.strength_cost + (human_strength_present_statdif - 1) * human.strength_cost) #The cost of present stat stat
human_strength_total_present_cost = ((human_strength_present_statdif / 2) * (human.strength_cost + human_strength_present_stat_cost)) # The total cost from base stat to present stat
human_strength_desired_stat_cost = (human.strength_cost + (human_strength_desired_statdif - 1) * human.strength_cost) #The cost of desired stat
human_strength_total_desired_cost = ((human_strength_desired_statdif / 2) * (human.strength_cost + human_strength_desired_stat_cost)) # The total cost base stat to desired stat
human_strength_net_cost = (human_strength_total_desired_cost - human_strength_total_present_cost) # The Net cost from the difference of Total desired stat and Total present stat
print("Net cost: " + str(human_strength_net_cost))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T19:35:38.023",
"Id": "496601",
"Score": "0",
"body": "\"From the way I see it I will have to do for each race the same code 3 times for each stat.\" Have you considered passing arguments and standardizing your functions to make the whole thing less tedious? [Example](https://codereview.stackexchange.com/q/146417/52915)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T19:38:55.433",
"Id": "496603",
"Score": "0",
"body": "Why not make use of functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T19:40:09.430",
"Id": "496604",
"Score": "0",
"body": "IMO, a constructor with more than 3 data members indicates that the class is doing too much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T20:54:57.660",
"Id": "496608",
"Score": "0",
"body": "@theProgrammer Thanks for that bit of info!!! I can get around it now :D"
}
] |
[
{
"body": "<p>If you are just trying to make an interactive calculator, the classes, etc. are not needed.</p>\n<p>First, make a simple table that lets you look up the stats based on race. Keep it easy for a human (like you) to edit it, make changes, add new races or stats, etc.</p>\n<pre><code>keys = "base_strength base_agility base_health strength_cost agility_cost health_cost".split()\n\ntraits = [\n # base base base strength agility health \n #race strength agility health cost cost cost\n "human 15 17 18 5 3 4",\n "elf 11 21 14 4 3 5",\n "giant 25 11 27 4 8 3",\n]\n</code></pre>\n<p>It's just a list of strings. Now transform it into a format that makes it easy to use in a program. We'll turn it into a dict of dicts so we can look up values using something like: <code>stat["elf"]["base_agility"]</code>. Here's the code:</p>\n<pre><code>stats = {}\n\nfor row in traits:\n row = row.strip().split()\n stats[row[0]] = dict(zip(keys, map(int, row[1:])))\n</code></pre>\n<p>Now your code that calculates the cost of changing strength for a human, can be turned into a generic function that works for any race or stat:</p>\n<pre><code>def calc_change_cost(race, stat_name, present_value, desired_value):\n base_value = stats[race][f"base_{stat_name}"]\n stat_cost = stats[race][f"{stat_name}_cost"]\n\n present_statdif = present_value - base_value\n present_stat_cost = stat_cost + (present_statdif - 1) * stat_cost\n total_present_cost = (present_statdif / 2) * (stat_cost + present_stat_cost)\n\n desired_statdif = desired_value - base_value\n desired_stat_cost = stat_cost + (desired_statdif - 1) * stat_cost\n total_desired_cost = (desired_statdif / 2) * (stat_cost + desired_stat_cost)\n\n net_cost = total_desired_cost - total_present_cost\n\n return net_cost\n</code></pre>\n<p>You'll notice the repeated code for calculating <code>total_present_cost</code> and <code>total_desired_cost</code>. Those lines could be refactored into another function (an exercise for the reader).</p>\n<p>Now, the main program just collects the user's inputs, calls the function above, and prints the results:</p>\n<pre><code>user_race = str(input("Enter your race (Human, Giant, Elf):")).lower()\nuser_stat = str(input("Enter your desired stat (Strength, Agility, Health):")).lower()\npresent_value = int(input("Enter your present stat value:"))\ndesired_value = int(input("Enter your desired stat value:"))\n\nnet_cost = calc_change_cost(user_race, user_stat, present_value, desired_value)\nprint(f"Net cost to change {user_race} {user_stat} from {present_value} to {desired_value}: {net_cost}")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T05:45:23.017",
"Id": "503726",
"Score": "0",
"body": "Holy... That's amazing what you did. I managed to write a script for this but it isn't anywhere as good as yours. I get results but the code is very basic and long since I don't know much about python.\nThanks for this :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T07:56:05.517",
"Id": "252178",
"ParentId": "252119",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T19:17:20.130",
"Id": "252119",
"Score": "5",
"Tags": [
"python-3.x"
],
"Title": "Python - Game stat calculator"
}
|
252119
|
<p>I have an interface, implemented by a service, that I inject here and there in my codebase.
I would like to give the opportunity to use either the normal method <em>or</em> its async equivalent.</p>
<pre><code>public interface IServiceDoStuff
{
void DoSomeHeavyWork();
Task DoSomeHeavyWorkAsync();
}
</code></pre>
<p>In my implementation I just do it like this</p>
<pre><code>public class Service: IServiceDoStuff
{
public void DoSomeHeavyWork(){ ... }
public Task DoSomeHeavyWorkAsync()
{
return Task.Run(() => { DoSomeHeavyWork();});
}
}
</code></pre>
<p>So my consumers just go</p>
<pre><code>await injectedService.DoSomeHeavyWorkAsync();
</code></pre>
<p>My question is simply : <strong>is that a correct way to offer those two alternatives ?</strong></p>
<p><code>Tasks</code>, <code>async</code> and <code>await</code> have been giving me headaches forever, as it has always been one of the most obscure .NET features I work with. I can never feel confident about the code I write using those features.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:49:39.063",
"Id": "496612",
"Score": "1",
"body": "[Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation](https://blog.stephencleary.com/2013/11/taskrun-etiquette-examples-dont-use.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:59:02.820",
"Id": "496764",
"Score": "0",
"body": "Please read these Stephen Toub's excellent articles about this topic: [async wrapper for sync](https://devblogs.microsoft.com/pfxteam/should-i-expose-asynchronous-wrappers-for-synchronous-methods/), [sync wrapper for async](https://devblogs.microsoft.com/pfxteam/should-i-expose-synchronous-wrappers-for-asynchronous-methods/)"
}
] |
[
{
"body": "<p>If your implementation does not create interrupts of some sort there is no point in making it async. If the consumer does not want to wait for your code to execute its better to let them control that and execute your code seperate from the main thread.</p>\n<p>Edit: if the interface and implementation are shipped seperate or if its possible someone will replace default none async implementation with a async implementation. Than it could be a good practice to make the interface Async and in your default implementation return Task.FromResult or Task.CompletedTask.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:28:08.980",
"Id": "252140",
"ParentId": "252120",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T19:20:00.480",
"Id": "252120",
"Score": "2",
"Tags": [
"c#",
".net",
"async-await"
],
"Title": "Giving an alternative Async method to a service"
}
|
252120
|
<p>LeetCode 125 requires receiving a string and checking if it is a valid palindrome. I have done this and am confident with an int and a single word, but this question requires the use a of a sentence with non-alphanumeric characters. The function must ignore non-alphanumeric characters and whitespaces.</p>
<pre><code>public bool isPalindrome(string s) {
s = System.Text.RegularExpressions.Regex.Replace(s, @"\W|_", "");
if (s == null || s == "" || s.Length == 1 || s == " ")
{
return true;
}
for (int i = 0, j = s.Length - 1; i <= s.Length / 2 && j >= s.Length /2;i--,j++)
{
if (Char.ToLower(s[i]) == Char.ToLower(s[j]))
{
continue;
}
return false;
}
return true;
}
</code></pre>
<p>It is my first time ever using Regex, maybe that gives my function a performance hit? Would it be better if I could implement this without Regex?</p>
<p>Example inputs are: <code>"a man, a plan, a canal: Panama"</code> -- returns <code>true</code>, <code>"race a car"</code> -- returns <code>false</code>, <code>"a man, a plan, a canal -- Panama"</code> -- returns <code>true</code>. The stats on this are: <code>Runtime 136 ms, faster than 11.75% of c# submissions</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:55:24.223",
"Id": "496615",
"Score": "1",
"body": "You have a typo: `i--,j++`. I'd start with `.Replace(s, @\"[\\W_]+\", \"\").ToLower();` but I've never written C#"
}
] |
[
{
"body": "<h3>Disclaimer: Not a <a href=\"https://en.wikipedia.org/wiki/Code_review\" rel=\"nofollow noreferrer\">Code Reviewer</a></h3>\n<ul>\n<li>Your solution looks fine;</li>\n<li>Overall, we would want to stay away from regular expressions in solving algorithm problems – especially easy LeetCode questions are to measure our implementation skills;</li>\n<li>C# has two simple functions that would do the job of (<code>\\W|_</code>):</li>\n</ul>\n<pre><code>public class Solution {\n public bool IsPalindrome(string s) {\n var left = 0;\n var right = s.Length - 1;\n\n while (left < right) {\n if (!char.IsLetterOrDigit(s[left])) {\n ++left;\n\n } else if (!char.IsLetterOrDigit(s[right])) {\n --right;\n\n } else {\n if (char.ToLower(s[left]) != char.ToLower(s[right])) {\n return false;\n }\n\n ++left;\n --right;\n }\n }\n\n return true;\n }\n}\n\n</code></pre>\n<ul>\n<li><p>We can just a bit improve the runtime, but not so much, using a more readable expression such as:</p>\n<ul>\n<li><p><code>(?i)[^a-z0-9]+</code>;</p>\n<ul>\n<li><code>(?i)</code> matches the remainder of the pattern based on the <strong>i</strong>nsensitive flag;</li>\n</ul>\n</li>\n<li><p><code>[^A-Za-z0-9]+</code>;</p>\n</li>\n</ul>\n</li>\n</ul>\n<pre><code>public class Solution {\n\n public bool IsPalindrome(string s) {\n\n s = System.Text.RegularExpressions.Regex.Replace(s, @"(?i)[^a-z0-9]+", "");\n\n if (s == null || s == "" || s.Length == 1 || s == " ") {\n return true;\n }\n\n for (int i = 0, j = s.Length - 1; i <= s.Length / 2 && j >= s.Length / 2; i++, j--) {\n if (Char.ToLower(s[i]) == Char.ToLower(s[j])) {\n continue;\n }\n\n return false;\n }\n\n return true;\n }\n}\n</code></pre>\n<h3>RegEx Circuit</h3>\n<p><a href=\"https://jex.im/regulex/#!flags=&re=%5E(a%7Cb)*%3F%24\" rel=\"nofollow noreferrer\">jex.im</a> visualizes regular expressions:</p>\n<p><a href=\"https://i.stack.imgur.com/3jXst.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3jXst.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<h3>Demo</h3>\n<p>If you wish to simplify/update/explore the expression, it's been explained on the top right panel of <a href=\"https://regex101.com/r/rywfJa/1/\" rel=\"nofollow noreferrer\">regex101.com</a>. You can watch the matching steps or modify them in <a href=\"https://regex101.com/r/rywfJa/1/debugger\" rel=\"nofollow noreferrer\">this debugger link</a>, if you'd be interested. The debugger demonstrates that how <a href=\"https://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines\" rel=\"nofollow noreferrer\">a RegEx engine</a> might step by step consume some sample input strings and would perform the matching process.</p>\n<hr />\n<h3>Happy Coding! ( •ˆ_ˆ• )</h3>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T01:14:04.603",
"Id": "496624",
"Score": "1",
"body": "The first solution works much better. I thought about using `Char.IsLetterOrDigit` but I couldn't remember the function so I tried regex. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:57:38.920",
"Id": "252128",
"ParentId": "252122",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252128",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:02:49.777",
"Id": "252122",
"Score": "4",
"Tags": [
"c#",
"regex",
"palindrome"
],
"Title": "Check if string is palindrome LeetCode"
}
|
252122
|
<p>What follows is a Dockerfile for my Vim settings, so I could use it anywhere.</p>
<p>While it is public, it is not intended for mass usage, and so the face that it creates the password in the build process isn't a problem.
There is no <code>COMMAND</code> at the end because it is intended to be run with mount. The command I run it with <code>docker run -itv /:/tmp/real_root uberhumus/vim-anywhere:latest vi <Filename></code>
Was I supposed to <code>COPY</code> the .vimrc later? Or use <code>ADD</code> instead? Am I too splurgy with the layers? Is there a smarter way to do the <code>RUN</code>, <code>WORKDIR</code>, <code>RUN</code> situations I ran into?</p>
<p>Thanks!</p>
<pre><code>
ENV DEBIAN_FRONTEND=noninteractive
ARG TZ=Asia/Jerusalem
RUN apt-get update; \
apt-get dist-upgrade -y && \
apt-get autoremove -y && \
apt-get autoclean -y && \
apt-get install -y vim tmux bash-completion shellcheck ssh git pylint flake8 python sudo expect curl cmake build-essential python3-dev golang npm openjdk-11-jre exuberant-ctags && \
echo vim-anywhere > /etc/hostname
ARG USERNAME=yotam
RUN PASSWORD=$(openssl rand -base64 16 | tr -d "=") && \
useradd -m -s /bin/bash $USERNAME && \
usermod -aG sudo $USERNAME && \
echo "$USERNAME:$PASSWORD" | chpasswd && \
echo $PASSWORD
WORKDIR /home/$USERNAME
COPY .vimrc .
RUN mkdir -p ./.vim/pack/plugins/start
WORKDIR /home/$USERNAME/.vim/pack/plugins/start
RUN git clone https://github.com/tpope/vim-fugitive.git/ && \
git clone --depth 1 https://github.com/dense-analysis/ale.git && \
git clone https://github.com/ycm-core/YouCompleteMe.git
WORKDIR /home/$USERNAME/.vim/pack/plugins/start/YouCompleteMe
RUN git submodule update --init --recursive && \
python3 install.py --all && \
chown -R $USERNAME:$USERNAME /home/$USERNAME
USER $USERNAME<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The best I've got is:</p>\n<pre><code>FROM ubuntu:20.04\n\nENV DEBIAN_FRONTEND=noninteractive\nARG TZ=Asia/Jerusalem\nARG USERNAME=yotam\nRUN apt-get update; \\\n apt-get dist-upgrade -y && \\\n apt-get autoremove -y && \\\n apt-get autoclean -y && \\\n apt-get install -y vim tmux bash-completion shellcheck ssh git pylint flake8 python sudo expect curl cmake build-essential python3-dev golang npm openjdk-11-jre exuberant-ctags && \\\n useradd -m -s /bin/bash $USERNAME && \\\n usermod -aG sudo $USERNAME && \\ \n echo vim-anywhere > /etc/hostname\n\nWORKDIR /home/$USERNAME\nCOPY .vimrc .\nRUN mkdir -p ./.vim/pack/plugins/start \nWORKDIR /home/$USERNAME/.vim/pack/plugins/start\nRUN git clone https://github.com/tpope/vim-fugitive.git/ && \\\n git clone --depth 1 https://github.com/dense-analysis/ale.git && \\\n git clone https://github.com/ycm-core/YouCompleteMe.git\nWORKDIR /home/$USERNAME/.vim/pack/plugins/start/YouCompleteMe\nRUN git submodule update --init --recursive && \\\n python3 install.py --all && \\\n chown -R $USERNAME:$USERNAME /home/$USERNAME && \\\n PASSWORD=$(openssl rand -base64 16 | tr -d "=") && \\\n echo "$USERNAME:$PASSWORD" | chpasswd && \\\n echo $PASSWORD\nWORKDIR /home/$USERNAME\nUSER $USERNAME\n</code></pre>\n<p>This gives me only minor advantages which are:</p>\n<ol>\n<li>The password is echoed at the end of the build and is easier to find in the output.</li>\n<li>The return to the homedir at the end is more what you'd intuitively expect.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T01:04:08.640",
"Id": "507531",
"Score": "1",
"body": "Why not pass the `PASSWORD` as a `--build-arg`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-11T07:49:16.533",
"Id": "507556",
"Score": "0",
"body": "@masseyb answer it, it's a good point."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T20:14:19.017",
"Id": "252210",
"ParentId": "252124",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "252210",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:28:34.487",
"Id": "252124",
"Score": "1",
"Tags": [
"dockerfile",
"docker"
],
"Title": "Dockerfile of Vim + Plugins and .vimrc"
}
|
252124
|
<p>I wanted to practice more object-oriented programming and decided to write a console based Quiz Application. In one of my previous question, a reviewer left some links on SOLID design pattern, I went through it and tried as much as possible to follow it to the best of my ability.</p>
<h1>MAJOR CONCERNS</h1>
<ol>
<li>I used boost library to serialize my object and I noticed my executable size increased quite a lot. I would appreciate if any one could give suggestion on how to save my objects without boost dependency, links would be preferable.</li>
<li>I really considered removing the default constructor from my classes, but eventually left them since a container must be initialized if no default constructor is given. Does this show a poor class design?</li>
<li>Some of my method functions were supposed to return a value for example <code>get()</code>, but in a scenario where an object of type <code>Quiz</code> was not found, I decided to throw an error. I recieved several warnings from g++ compiler, is it a poor design to throw, if no return value was produced in a function?</li>
</ol>
<h1>namespace QUIZMAKER.h</h1>
<pre><code>#ifndef QUIZ_QUIZMAKER_H_
#define QUIZ_QUIZMAKER_H_
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
namespace QuizMaker
{
struct Question
{
friend std::ostream& operator<<( std::ostream &os, const Question &question );
public:
Question() = default;
Question( const std::string &title, const std::string &question )
: title_{ title }, question_{ question } {}
std::string title_;
std::string question_;
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize( Archive &archive, const unsigned int version )
{
archive & title_;
archive & question_;
}
};
struct QuestionOptions{
friend std::ostream& operator<<( std::ostream &os, const QuestionOptions &options );
public:
QuestionOptions() = default;
QuestionOptions( const std::vector<std::string> &options, const std::string &correct_option )
: options_{ options }, correct_option_{ correct_option } {}
std::vector<std::string> options_;
std::string correct_option_;
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize( Archive &archive, const unsigned int version )
{
archive & options_;
archive & correct_option_;
}
};
struct TagContainer
{
friend std::ostream& operator<<( std::ostream &os, const TagContainer &tag_c );
TagContainer() = default;
explicit TagContainer( const std::vector<std::string> &tag_c ) : tag_container_{ tag_c } {}
std::vector<std::string> tag_container_;
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize( Archive &archive, const unsigned int version )
{
archive & tag_container_;
}
};
struct Quiz
{
public:
Quiz() = default;
Quiz( const Question &question, const QuestionOptions &options, const TagContainer &tag_c )
: quiz_{ question }, quiz_options_( options ), quiz_tag_{ tag_c } {}
Quiz( std::ifstream &file_handle );
Question quiz_;
QuestionOptions quiz_options_;
TagContainer quiz_tag_;
private:
friend class boost::serialization::access;
template<typename Archive>
void serialize( Archive &archive, const unsigned int version )
{
archive & quiz_;
archive & quiz_options_;
archive & quiz_tag_;
}
};
std::ostream& operator<<( std::ostream &os, const Question &question );
std::ostream& operator<<( std::ostream &os, const QuestionOptions &options );
}
#endif
</code></pre>
<h1>namespace QUIZMAKER.cpp</h1>
<pre><code>#include "Quiz_Maker.h"
#include "Exception.h"
#include <sstream>
#include <algorithm>
namespace QuizMaker
{
std::ostream& operator<<( std::ostream& os, const Question& question )
{
os << "Title: " << question.title_ << '\n';
os << question.question_;
return os;
}
std::ostream& operator<<( std::ostream& os, const QuestionOptions& opt )
{
int alphabelt = 65;
for( const auto options : opt.options_ )
os << char( alphabelt++ ) << ". " << options << '\n';
return os;
}
std::ostream& operator<<( std::ostream &os, const TagContainer &tag_c )
{
for( const auto tag : tag_c.tag_container_ )
os << "[" << tag << "] ";
return os;
}
}
</code></pre>
<h1>EXCEPTION.H</h1>
<pre><code>#ifndef QUIZ_EXCEPTION_H_
#define QUIZ_EXCEPTION_H_
#include <fstream>
struct Exception
{
bool ofile_handle_error( std::ofstream &file_handle );
bool ifile_handle_error( std::ifstream &file_handle );
void throw_get_error() { throw std::invalid_argument( "Access error: Record not found." ); }
};
#endif
</code></pre>
<h1>EXCEPTION.CPP</h1>
<pre><code>#include "Exception.h"
#include <iostream>
bool Exception::ofile_handle_error( std::ofstream &file_handle )
{
if( !file_handle ) {
std::cerr << "Write Error: File cannot be accessed.";
return true;
}
return false;
}
bool Exception::ifile_handle_error( std::ifstream &file_handle )
{
if( !file_handle ) {
std::cerr << "Read Error: File cannot be accessed.";
return true;
}
return false;
}
</code></pre>
<h1>PERSISTENCE_MGR.H</h1>
<pre><code>#ifndef QUIZ_PERSISTENCEMGR_H_
#define QUIZ_PERSISTENCEMGR_H_
#include "Quiz_Application.h"
struct PersistenceMgr
{
void output( std::ofstream& file_handle, const QuizApplication &app );
QuizApplication input( std::ifstream& file_handle );
};
#endif
</code></pre>
<h1>PERSISTENCE_MGR.CPP</h1>
<pre><code>#include "PersistenceMgr.h"
#include "Exception.h"
void PersistenceMgr::output( std::ofstream& file_handle, const QuizApplication& app )
{
Exception e;
if( e.ofile_handle_error( file_handle ) )
return;
boost::archive::text_oarchive archive{ file_handle };
archive << app;
}
QuizApplication PersistenceMgr::input( std::ifstream& file_handle )
{
Exception e;
QuizApplication app{};
if( e.ifile_handle_error( file_handle ) )
return app;
boost::archive::text_iarchive archive{ file_handle };
archive >> app;
return app;
}
</code></pre>
<h1>QUIZ_APPLICATION.H</h1>
<pre><code>#ifndef QUIZ_QUIZAPPLICATION_H_
#define QUIZ_QUIZAPPLICATION_H_
#include "Quiz_Maker.h"
#include <vector>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/vector.hpp>
using namespace QuizMaker;
using QuizContainer = std::vector<QuizMaker::Quiz>;
class QuizApplication
{
public:
QuizApplication() = default;
QuizApplication( const QuizContainer &quiz_c )
: quiz_container_( quiz_c ) {}
QuizApplication( std::ifstream &file_handle );
void display();
QuizApplication& append( const QuizMaker::Quiz &quiz );
QuizApplication& remove( const std::string &title );
QuizContainer::const_iterator get( const std::string &title ) const;
QuizContainer::iterator get( const std::string &title );
unsigned count() const { return quiz_container_.size(); }
private:
QuizContainer quiz_container_;
std::vector<std::string> tokenize( const std::string &line );
TagContainer process_tag( const std::vector<std::string> &tokens );
Question process_question( const std::vector<std::string> &tokens );
void process_question_title( Question &question, const std::vector<std::string> &tokens );
QuestionOptions process_options( const std::vector<std::string> &tokens );
void process_correct_options( QuestionOptions &question_options, const std::vector<std::string> &tokens );
friend class boost::serialization::access;
template<typename Archive>
void serialize( Archive &archive, const unsigned int version )
{
archive & quiz_container_;
}
};
#endif
</code></pre>
<h1>QUIZ_APPLICATION.CPP</h1>
<pre><code>#include "Quiz_Application.h"
#include "Exception.h"
#include <vector>
using namespace QuizMaker;
QuizApplication::QuizApplication( std::ifstream &file_handle )
{
Exception e;
if( !e.ifile_handle_error( file_handle ) ) {
std::string quiz_text;
std::string word;
while( !file_handle.eof() )
{
file_handle >> word;
if( word == "<quiz>" ) {
continue;
}
if( word == "</quiz>" )
{
QuizMaker::Quiz quiz_obj{};
std::vector<std::string> tokens = tokenize( quiz_text );
quiz_obj.quiz_tag_ = process_tag( tokens );
quiz_obj.quiz_ = process_question( tokens );
quiz_obj.quiz_options_ = process_options( tokens );
tokens.clear();
quiz_text = "";
quiz_container_.push_back( quiz_obj );
continue;
}
quiz_text += word += " ";
}
}
}
std::vector<std::string> QuizApplication::tokenize( const std::string &line )
{
std::vector<std::string> tokens;
std::stringstream stream( line );
std::string intermediate;
while( std::getline( stream, intermediate, ' ' ) )
tokens.push_back( intermediate );
return tokens;
}
TagContainer QuizApplication::process_tag( const std::vector<std::string> &tokens )
{
TagContainer tag;
auto iter = std::find( tokens.cbegin(), tokens.cend(), "<tag>" );
if( iter == tokens.cend() )
return tag;
auto iter2 = std::find( iter + 1, tokens.cend(), "</tag>" );
if( iter2 == tokens.cend() )
return tag;
for( auto it = iter + 1; it != iter2; ++it )
tag.tag_container_.push_back( *it );
return tag;
}
Question QuizApplication::process_question( const std::vector<std::string> &tokens )
{
Question question_obj;
auto iter = std::find( tokens.cbegin(), tokens.cend(), "<question>" );
if( iter == tokens.cend() )
return question_obj;
auto iter2 = std::find( iter + 1, tokens.cend(), "</question>" );
if( iter2 == tokens.cend() )
return question_obj;
for( auto it = iter + 1; it != iter2; ++it )
{
question_obj.question_ += *it;
question_obj.question_ += " ";
}
process_question_title( question_obj, tokens );
return question_obj;
}
void QuizApplication::process_question_title( Question &question_obj, const std::vector<std::string> &tokens )
{
auto iter = std::find( tokens.cbegin(), tokens.cend(), "<title>" );
if( iter == tokens.cend() )
return;
auto iter2 = std::find( iter + 1, tokens.cend(), "</title>" );
if( iter2 == tokens.cend() )
return;
for( auto it = iter + 1; it != iter2; ++it )
{
question_obj.title_ += *it;
if( it != iter2 - 1 )
question_obj.title_ += " ";
}
}
QuestionOptions QuizApplication::process_options( const std::vector<std::string> &tokens )
{
QuestionOptions question_options;
auto iter = std::find( tokens.cbegin(), tokens.cend(), "<option>" );
if( iter == tokens.cend() )
return question_options;
auto iter2 = std::find( tokens.cbegin(), tokens.cend(), "</option>" );
if( iter2 == tokens.cend() )
return question_options;
auto iter_sub1 = std::find( iter + 1, iter2, "<option-item>" );
while( iter_sub1 != iter2 )
{
auto iter_sub2 = std::find( iter_sub1, iter2, "</option-item>" );
if( iter_sub2 == iter2 )
return question_options;
std::string option;
for( auto it = iter_sub1 + 1; it != iter_sub2; ++it )
{
option += *it;
option += " ";
}
question_options.options_.push_back( option );
iter_sub1 = std::find( iter_sub2, iter2, "<option-item>" );
}
process_correct_options( question_options, tokens );
return question_options;
}
void QuizApplication::process_correct_options( QuestionOptions &question_options, const std::vector<std::string> &tokens )
{
auto iter = std::find( tokens.cbegin(), tokens.cend(), "<correct-option>" );
if( iter == tokens.cend() )
return;
auto iter2 = std::find( tokens.cbegin(), tokens.cend(), "</correct-option>" );
if( iter2 == tokens.cend() )
return;
question_options.correct_option_ = *(iter + 1);
}
void QuizApplication::display()
{
for( const auto item : quiz_container_ )
std::cout << item.quiz_tag_ << "\n" << item.quiz_ << "\n" << item.quiz_options_ << "\n";
}
QuizApplication& QuizApplication::append( const QuizMaker::Quiz &quiz )
{
quiz_container_.push_back( quiz );
return *this;
}
QuizApplication& QuizApplication::remove( const std::string &title )
{
auto iter = get( title );
quiz_container_.erase( iter );
return *this;
}
QuizContainer::const_iterator QuizApplication::get( const std::string &title ) const
{
for( auto beg = quiz_container_.cbegin(); beg != quiz_container_.cend(); ++beg )
{
if( beg->quiz_.title_ == title )
return beg;
}
Exception e;
e.throw_get_error();
}
QuizContainer::iterator QuizApplication::get( const std::string &title )
{
for( auto beg = quiz_container_.begin(); beg != quiz_container_.end(); ++beg )
{
if( beg->quiz_.title_ == title )
return beg;
}
Exception e;
e.throw_get_error();
}
</code></pre>
<h1>main.cpp</h1>
<pre><code>#include "Quiz_Application.h"
#include "PersistenceMgr.h"
#include "Quiz_Maker.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace QuizMaker;
int main()
{
std::ifstream file_handle{ "file.txt" };
QuizApplication quiz_app{ file_handle };
Question new_question{ "STL Containers", "The _______ container member returns true if no element is present otherwise returns false" };
QuestionOptions my_options;
my_options.options_ = {
"emplace",
"fill",
"empty",
"size"
};
my_options.correct_option_ = { "C" };
TagContainer my_tags;
std::vector<std::string> tags = { "STL", "Programming", "Algorithm" };
my_tags.tag_container_ = tags;
Quiz new_quiz{ new_question, my_options, my_tags };
quiz_app.append( new_quiz );
/* delete a quiz */
quiz_app.remove( "STL Containers" );
/* modify a quiz */
auto iter = quiz_app.get( "STL Equality Comparison" );
iter->quiz_tag_.tag_container_.push_back( "STL" );
quiz_app.display();
/* Save to file */
PersistenceMgr per_mgr;
std::ofstream file_handle2{ "app.txt" };
per_mgr.output( file_handle2, quiz_app );
std::cout << "Quit total count: " << quiz_app.count() << "\n";
/* Load Quiz App */
std::ifstream file_handle3{ "app.txt" };
QuizApplication quiz_loaded = per_mgr.input( file_handle3 );
std::cout << "Successfully loaded the application\n\n";
quiz_loaded.display();
}
</code></pre>
<p>This is a sample question text file</p>
<pre class="lang-html prettyprint-override"><code><quiz>
<tag> C++ Programming </tag>
<title> STL Sorting Iterator </title>
<question> The sort algorithm requires a(n) _____________ iterator </question>
<option>
<option-item> random-access </option-item>
<option-item> bidirectional </option-item>
<option-item> forward </option-item>
<option-item> None of the above </option-item>
</option>
<correct-option> A </correct-option>
</quiz>
<quiz>
<tag> C++ Programming </tag>
<title> STL Equality Comparison </title>
<question> The ___________ algorithm compares two sequence for equality </question>
<option>
<option-item> find </option-item>
<option-item> equal </option-item>
<option-item> fill_n </option-item>
<option-item> copy </option-item>
</option>
<correct-option> B </correct-option>
</quiz>
<quiz>
<tag> C++ Programming </tag>
<title> STL Remove_if Algorithm </title>
<question> The remove_if algorithm does not modify the number of elements in the container,
but it does move to the beginning of the containe all element that are not remove
</question>
<option>
<option-item> True </option-item>
<option-item> False </option-item>
<option-item> Not exactly </option-item>
<option-item> Maybe </option-item>
</option>
<correct-option> A </correct-option>
</quiz>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T13:59:05.200",
"Id": "496649",
"Score": "2",
"body": "Not having a default constructor forces the class to be constructed as expected. There is no problem with the class not having a default constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T14:03:12.653",
"Id": "496650",
"Score": "2",
"body": "Since the boost libraries are primarily implemented as header files, I expect that your compile times were longer as well. Now that you are really getting into OOP it might be a good idea to try creating your own dynamically linked libraries to implement some portions the your solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T15:11:01.780",
"Id": "496661",
"Score": "1",
"body": "`Now that you are really getting into OOP it might be a good idea to try creating your own dynamically linked libraries to implement some portions the your solutions.` Please, can you explain further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T18:55:22.653",
"Id": "496694",
"Score": "1",
"body": "As an aside, consider \"*[What's the difference between “STL” and “C++ Standard Library”?](//stackoverflow.com/questions/5205491/whats-the-difference-between-stl-and-c-standard-library)*\"."
}
] |
[
{
"body": "<p>Don't re-invent the wheel. You are manually parsing an XML file. This has been done before and there exist many mature libraries that already do this. I personally use <a href=\"https://github.com/leethomason/tinyxml2\" rel=\"noreferrer\">TinyXml2</a>. It only requires a single header and source file instead of all of boost and is very fast.</p>\n<hr />\n<p>It makes no sense for a Question to not have any text or choices associated with it, nor for a multiple-choice Quiz to have no questions. Creating a default question or quiz puts the classes in an invalid state, therefore, I would suggest removing the default constructors.</p>\n<hr />\n<p>Instead of throwing, you can use the STL implementation of returning the <code>end</code> iterator when an object cannot be found. The user then would just have to check for it before using the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T00:19:03.247",
"Id": "496623",
"Score": "1",
"body": "The project is meant for practice purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T04:20:04.443",
"Id": "496626",
"Score": "7",
"body": "@theProgrammer If you didn't want people to address the concerns you had on a code review site, why did you post it in the first place?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T23:45:08.930",
"Id": "252129",
"ParentId": "252125",
"Score": "6"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Use the library for XML data</h2>\n<p>It's peculiar to me that the code does manual parsing of XML tags, even though the Boost serialization library already has explicit <a href=\"https://www.boost.org/doc/libs/1_74_0/libs/serialization/doc/wrappers.html#nvp\" rel=\"noreferrer\">support for XML</a>. Since you specifically mention the size of the resulting application as a concern, one simple way to reduce the size would be to not duplicate things that are already in the library.</p>\n<h2>If it has private members, it should be a <code>class</code></h2>\n<p>The <code>Quiz</code> <code>struct</code> really deserves to be a <code>class</code>, I think. Otherwise we could alter questions and answers and options at will, which seems a bit suspect to me. Also, see <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-class\" rel=\"noreferrer\">C.8</a></p>\n<h2>Rethink your class structure</h2>\n<p>What you name <code>Quiz</code> ought to be called <code>Question</code>. We have a dizzying array of similarly named classes and namespaces including <code>QuizApplication</code>, <code>QuizContainer</code>, <code>QuizMaker</code>, <code>Quiz</code>, <code>Question</code>, <code>QuestionOptions</code> which seem to be largely trivial wrappers for each other. I would strongly suggest that a <code>Quiz</code> is a container for <code>Question</code> objects and that is probably all that is necessary. Also, a <code>Question</code> should contain the question, the answer(s) and subject tags. Instead of requiring a separate value to indicate which is the correct option, I'd suggest simply making the first answer (as stored and serialized) the correct answer and to simply randomize the display of options when presenting them for a quiz-taker. Also, does every question really need a title?</p>\n<h2>Unused parameters should be unnamed</h2>\n<p>The specializations of <code>boost::serialization::access</code> do not use the <code>version</code> parameter which causes a number of compiler warnings. To signal that the parameter is deliberately unused, omit the name. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-unused\" rel=\"noreferrer\">F.9</a></p>\n<h2>Minimize the interface</h2>\n<p>The <code>main.cpp</code> file includes <code>Quiz_Application.h</code>, <code>PersistenceMgr.h</code> and <code>Quiz_Maker.h</code>. In addition to the inconsistencies in the use of abbreviations and underscores, this suggests to me that the interface is not yet optimal. The <code>PersistenceMrg</code> <code>struct</code> seems particularly worth of elimination, since it provides only functions that probably ought to be functions of the <code>QuizApplication</code> class instead. Rather than convenience functions, these appear to be <em>inconvenience functions</em> which obfuscate rather than clarify. Also, why do we need both a <code>QuizApplication</code> and a <code>QuizMaker</code>? The <code>Exception</code> class also serves little value except to confuse, since it does not appear to have any relationship to <code>std::exception</code>.</p>\n<h2>Use standard library functions</h2>\n<p>Both versions of <code>QuizApplication::get()</code> which you ask about (and the compiler complains about) could easily be replace with <code>std::find()</code>. Note that <code>std::find()</code> returns the ending iterator if the value is not found, rather than throwing an exception. I would advise that behavior.</p>\n<h2>Use better naming</h2>\n<p>The <code>QuizApplication</code> class has member functions <code>display</code>, <code>append</code> and <code>remove</code> which are not great names, but at least somewhat explanatory. However, <code>process_correct_options</code> and <code>process_options</code> are quite vague names that could be improved, or as per my first suggestion, complelely eliminated. I'd also suggest that the entire class is probably not needed if you refactor your classes as suggested above.</p>\n<h2>Create better constructors</h2>\n<p>If I were using this library, I'd want to be able to create a question like this:</p>\n<pre><code>Question q{"Value of Pi", // title\n "The value of pi is approximately 3.14159.", // question\n {"True", "False"}, // choices, first one is the correct one\n {"Mathematics", "Constants"} // tags\n };\n</code></pre>\n<p>I would also want to be able to create a <code>Quiz</code> of such questions using a <a href=\"https://en.cppreference.com/w/cpp/utility/initializer_list\" rel=\"noreferrer\"><code>std::initializer_list</code></a></p>\n<h2>Consider alternatives</h2>\n<p>It depends on your needs and preferences, but it's probably worth considering potential alternatives to the Boost serialization library, such as perhaps <a href=\"https://www.boost.org/doc/libs/1_74_0/doc/html/property_tree.html\" rel=\"noreferrer\">Boost.PropertyTree</a> or perhaps Google's <a href=\"https://developers.google.com/protocol-buffers\" rel=\"noreferrer\">Protocol Buffers</a>.</p>\n<h2>Fix the minor bug</h2>\n<p>The code prints a spurious <code>Title:</code> at the end of every quiz when <code>display</code> is called. That's because there is a fault in the code which causes it to create four questions when reading only three; the fourth is empty and invalid.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:12:49.733",
"Id": "496679",
"Score": "0",
"body": "Unused parameters can also be declared `[[maybe_unused]]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:14:14.373",
"Id": "496680",
"Score": "0",
"body": "The OP's implementation of `options` and `corrrect-option` allows for answers other than the first. How would you go about making sure the user can't always pick the first choice and get the question correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:32:16.177",
"Id": "496683",
"Score": "1",
"body": "@Casey: As I wrote in my answer, how they are *stored* isn't necessarily how they would *presented* to someone taking the quiz. I'd randomize the display of the answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:39:51.483",
"Id": "496684",
"Score": "1",
"body": "Also, `[[maybe_unused]]` shouldn't be used if the parameter is *definitely* unused. See https://stackoverflow.com/questions/49320810/when-should-i-use-maybe-unused"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:49:19.233",
"Id": "496688",
"Score": "0",
"body": "All good points. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T06:41:42.163",
"Id": "496737",
"Score": "0",
"body": "@Edward, great review. I would rethink my design. I knew having those default constructor indicates something wasn't right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T08:15:25.350",
"Id": "496744",
"Score": "0",
"body": "@Edward I forgot to add. QuizMaker was designed to bring questions, options and answers together. QuizApplication was designed as one of the way the user of QuizMaker class might want to use the class to create a quiz app."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T16:11:26.407",
"Id": "252148",
"ParentId": "252125",
"Score": "11"
}
},
{
"body": "<p>Most of what I wanted to add has been covered by others, however</p>\n<h3>Bulk insert and assign</h3>\n<p><code>std::vector</code> has bulk insert and assign functions <code>insert</code> and <code>assign</code>. Assign completely overwrites the contents, insert... inserts. When you use these, instead of pushing back space, then constructing, and repeating; the total area is reserved, and then all the items are copied at once.</p>\n<p>Additionally, you should refactor so functions do the minimal amount of work necessary.</p>\n<p>An example:</p>\n<pre><code>std::vector<std::string> QuizApplication::process_tag( const std::vector<std::string> &tokens )\n{\n std::vector<std::string> tag;\n\n auto begin = std::find( tokens.cbegin(), tokens.cend(), "<tag>" );\n if( begin == tokens.cend() )\n return tag;\n\n auto end = std::find( std::next(begin), tokens.cend(), "</tag>" );\n if( end == tokens.cend() )\n return tag;\n\n tag.assign( std::next(begin) , end );\n\n return tag;\n} \n</code></pre>\n<p>You could <strong>then</strong> assign the result to a tag_container instead of needing to instantiate a complete tag container, and needing to jump through a lot of noisy indirection.</p>\n<h3>find_if & standard algorithms</h3>\n<p>In <code>Quiz_application::get</code> you're doing exactly what <code>std::find_if</code> does, with an extra exception if you don't find the target.</p>\n<pre><code>QuizContainer::iterator QuizApplication::get( const std::string &title )\n{\n for( auto beg = quiz_container_.begin(); beg != quiz_container_.end(); ++beg )\n {\n if( beg->quiz_.title_ == title )\n return beg;\n } \n Exception e;\n e.throw_get_error();\n}\n\n// Is equivalent to\nQuizContainer::iterator QuizApplication::get( const std::string &title )\n{\n auto const title_match =\n [title](auto const & item){\n return item.title == title;\n };\n auto itr = std::find_if(cbegin(quiz_container_), cend(quiz_container_),title_match);\n if (itr != cend(quiz_container_))\n return itr;\n Exception e;\n e.throw_get_error();\n}\n\n</code></pre>\n<p>The standard algorithms are your friends! Don't be afraid to lean on them!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T19:40:12.077",
"Id": "252153",
"ParentId": "252125",
"Score": "1"
}
},
{
"body": "<h2>Overall Observations</h2>\n<p>Each question is showing real improvement in the code and in the quality of the question, nice job!</p>\n<p>@Edward and others gave some very good reviews and covered everything I was going to cover.</p>\n<h2>Exceptions</h2>\n<p>As a concept and as a type / class exceptions already exist in C++. It might be better if the exceptions class was renamed to QuizExceptions and inherits either the base <code>exception</code> class or inherits from one of the <code>exception</code> sub classes such <code>std::runtime_error</code> or <code>std::logic_error</code>. This provides you with some basic <code>exception</code> methods and functions so that you don't have to roll your own.</p>\n<p>Make your throws explicit rather than calling a function in the exception to execute the throw. That would remove the warning messages from the 2 versions of <code>get()</code>.</p>\n<h2>Dynamically Linked Libraries</h2>\n<p>Since the 1990s there has been the concept of libraries that are loaded as necessary and aren't part of the main executable program. On Windows these libraries are known as DLLs (LIBNAME.dll) and on Linux and Unix these libraries are known as Shared Objects (LIBNAME.so). You have your choice of linking these libraries at link time or loading them and unloading them as necessary during the execution of the program. If you are running in an environment with limited memory such as in embedded programming and want to limit the size of the executable you can load the libraries at run time, otherwise I suggest that you link the libraries at build time using the linker.</p>\n<p>On windows a dll can be loaded using <a href=\"https://docs.microsoft.com/en-us/windows/win32/dlls/using-run-time-dynamic-linking\" rel=\"nofollow noreferrer\">LoadLibrary</a> on Linux a shared library can be loaded using <a href=\"https://stackoverflow.com/questions/7626526/load-shared-library-by-path-at-runtime\">dlopen</a>. Creating portable code to compile and run on both systems isn't possible without using <code>ifdef</code> to figure out which system you are on because the operating system gets involved with this operation.</p>\n<p>Because this is implementing shared objects on both Windows and Linux these libraries can be implemented as classes. You will also want to read up on the <a href=\"https://en.wikipedia.org/wiki/Facade_pattern\" rel=\"nofollow noreferrer\">Facade Design Pattern</a> before you attempt this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:06:30.643",
"Id": "496718",
"Score": "1",
"body": "If the called library is installed properly on a Linux system, there is no need to call `dlopen` explicitly. Just link when creating the program that needs the library and the loader will automagically take care of the rest. See [this](https://stackoverflow.com/a/497067/3191481) for an example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T08:17:29.073",
"Id": "496747",
"Score": "0",
"body": "@pacmaninbw Does this mean I wouldn't have to `#include` any header file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T13:57:37.463",
"Id": "496777",
"Score": "0",
"body": "@theProgrammer Your code would have to be restructured but there would be still be some need for header files. Every dynamic library will have header files to define their interfaces."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T22:08:25.003",
"Id": "252163",
"ParentId": "252125",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252148",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:33:13.047",
"Id": "252125",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"design-patterns"
],
"Title": "Console-Based Quiz Application"
}
|
252125
|
<p>For any input symmetric matrix with zero diagonals <code>W</code>, I have the following implementation in <code>PyTorch</code>. I was wondering if the following can be improved in terms of efficiency,</p>
<p>P.S. Would current implementation break backpropagation?</p>
<pre><code>import torch
W = torch.tensor([[0,1,0,0,0,0,0,0,0],
[1,0,1,0,0,1,0,0,0],
[0,1,0,3,0,0,0,0,0],
[0,0,3,0,1,0,0,0,0],
[0,0,0,1,0,1,1,0,0],
[0,1,0,0,1,0,0,0,0],
[0,0,0,0,1,0,0,1,0],
[0,0,0,0,0,0,1,0,1],
[0,0,0,0,0,0,0,1,0]])
n = len(W)
C = torch.empty(n, n)
I = torch.eye(n)
for i in range(n):
for j in range(n):
B = W.clone()
B[i, j] = 0
B[j, i] = 0
tmp = torch.inverse(n * I - B)
C[i, j] = tmp[i, j]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:29:08.570",
"Id": "496645",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
}
] |
[
{
"body": "<p>A few hints for improving efficiency:</p>\n<ul>\n<li><p>When <code>W[i, j] == 0</code>, <code>B</code> equals to <code>W</code> so <code>tmp</code> remains unchanged. In this case, the computation of <code>C</code> values can be done only once outside the loop instead of inside the loop.</p>\n</li>\n<li><p><code>torch.nonzero</code> / <code>torch.Tensor.nonzero</code> can be used to obtain all indices of non-zero values in a tensor.</p>\n</li>\n<li><p>Since <code>W</code> is symmetric, <code>C</code> is also symmetric and only half of its values need to be computed.</p>\n</li>\n<li><p>All repeated computation can be moved out of the loop to improve effciency.</p>\n</li>\n</ul>\n<p>Improved code:</p>\n<pre><code>n = len(W)\nnIW = n * torch.eye(n) - W\nnIB = nIW.clone()\nC = nIB.inverse()\n\nfor i, j in W.nonzero():\n if i < j:\n nIB[i, j] = nIB[j, i] = 0\n C[j, i] = C[i, j] = nIB.inverse()[i, j]\n nIB[i, j] = nIB[j, i] = nIW[i, j]\n</code></pre>\n<p>Further performance improvement may be achieved according to <a href=\"https://cs.stackexchange.com/questions/9875/computing-inverse-matrix-when-an-element-changes\">this</a>.</p>\n<p>As for backpropagation, I have no idea how it can be done on elements of matrix inverses.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T08:54:20.897",
"Id": "252138",
"ParentId": "252127",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252138",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T22:52:54.273",
"Id": "252127",
"Score": "3",
"Tags": [
"python",
"pytorch"
],
"Title": "increase efficiency of loops and element-wise operations in PyTorch implementation"
}
|
252127
|
<p>There is an source and target.</p>
<h1>example:</h1>
<p><strong>source:[a,b,e,d,s,t,c,v,t]</strong></p>
<p><strong>target:[a,e,v,g,r,b,c,v,t]</strong></p>
<p>target and source have same number of elements.</p>
<p>how can I count elements in source ordered correctly according to target?</p>
<p>so, target means that elements in source should be ordered in target's order.</p>
<p>and count maximum number of properly ordered elements in source.</p>
<p>so the answer for example is 5 (a,b,c,v,t).</p>
<p>of course there are two elements in order like (a,e),(a,b) but out put should be maximum elements.</p>
<p>how can I do it neat and compactly?</p>
<h1>My code</h1>
<p>I used combinations, counting from max element number to 0.</p>
<pre><code>n=len(target)
k=1
for check in range(n,-1,-1):
while k!=0:
for j in combinations(souce,check):
if j in combinations(target,check):
answer_co.append(check)
k=0
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T09:57:39.410",
"Id": "496637",
"Score": "1",
"body": "This problem can be solved more efficiently using dynamic programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T16:10:36.800",
"Id": "496664",
"Score": "0",
"body": "@GZ0 how can i do that??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:22:23.417",
"Id": "496681",
"Score": "0",
"body": "Have you learned DP before? If so, are you able to identify the overlapping subproblem and come up with a recurrence?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T06:32:30.917",
"Id": "496734",
"Score": "0",
"body": "@GZ0 I searched for it and i understood what it is. Is this same with recursive programming?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T09:31:15.390",
"Id": "496754",
"Score": "0",
"body": "It can be implemented using recursion with memorization. However the more common implementation is tabulation. Some explanations can be found [here](https://www.geeksforgeeks.org/tabulation-vs-memoization/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T16:54:15.097",
"Id": "496803",
"Score": "0",
"body": "@GZ0 thanks!! to use dynamic programming in this problem, can you give me more hint? I tried to separate 'target' but elements don't have to be in adjacent place. both target and source."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T21:54:13.990",
"Id": "496831",
"Score": "1",
"body": "This is a classical problem. You can search for \"longest common subsequence\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T10:26:48.230",
"Id": "496858",
"Score": "0",
"body": "@GZ0 thx, I studied about it."
}
] |
[
{
"body": "<p>This is a classical LCS problem, which can be solved in DP as suggested by earlier post. Time Complexity of the implementation is <strong>O(mn)</strong> which is much better than the original code implementation. (An exercise for the reader to study. ;-)</p>\n<p>The next code fragment assumes that the source/target are both strings.</p>\n<p>Here is the DP approach:</p>\n<pre><code>class Solution:\n\ndef lcs(self, source: str, target: str) -> int:\n n, m = len(source), len(target)\n dp = [[0] * (m + 1) for _ in range(n + 1)]\n\n for i in range(n):\n for j in range(m):\n if source[i] == target[j]:\n dp[i + 1][j + 1]= dp[i][j] + 1\n else:\n dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])\n return dp[-1][-1]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T02:40:45.777",
"Id": "499105",
"Score": "1",
"body": "Formatted your answer, but I don't know what to do with \"(recursion way)\". Please try and think of a better sentence for that and remove the parentheses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T17:10:38.933",
"Id": "499210",
"Score": "0",
"body": "Welcome to the Code Review Community. This community is primarily about improving the original posters ability to code, as such meaningful observations about the code posted in the question are more important than providing alternate code only solutions. Code only alternate solutions are quite often down voted and deleted by the community. The only meaningful observation in your post is `This is a classical LCS problem, which can be solved in DP as suggested by earlier post.` Why is the code you have posted any better than the code in the original post (update your answer with the reason)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T19:25:37.147",
"Id": "499225",
"Score": "0",
"body": "Agreed. Add the Run Time info. (still learning how to put info. together...) Thx"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T02:53:36.533",
"Id": "499251",
"Score": "0",
"body": "@DanielHao what does dp[i][j] stand for? Explain that in your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-08T03:04:10.020",
"Id": "499256",
"Score": "0",
"body": "DP == Dynamic Programming . See this reference - https://en.wikipedia.org/wiki/Dynamic_programming"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-07T02:32:58.340",
"Id": "253157",
"ParentId": "252135",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "253157",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T07:36:09.670",
"Id": "252135",
"Score": "3",
"Tags": [
"python-3.x"
],
"Title": "Counting maximum number of elements in right order"
}
|
252135
|
<p>I solved <a href="https://projecteuler.net/problem=60" rel="nofollow noreferrer">Project Euler #60</a>:</p>
<blockquote>
<p>The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.</p>
<p>Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.</p>
</blockquote>
<p>in Scheme.</p>
<p>Considering primes under 10000, it takes 21 second to find the correct prime set and about 12 minutes to traverse the rest of the combinations (which don’t include other prime sets that satisfy the constraint).</p>
<p>I found a Haskell code that implements the same logic <a href="https://zach.se/project-euler-solutions/60/" rel="nofollow noreferrer">here</a>.</p>
<p>The code found there and the one implemented by myself uses a very simple brute-force strategy: Search a pair that satisfies the constraint, and if it does, search for another prime to form a triple that satisfies the constraint, and if it does not, discard the triple, and so on.</p>
<p>This is not the smartest algorithm out there (this can be solved by search for 5-cliques in a graph), so I don’t expect it to run very fast.
However, the <a href="https://zach.se/project-euler-solutions/60/" rel="nofollow noreferrer">Haskell version</a> takes half a second to find the first solution, and takes another 15 seconds to traverse other prime sets that actually don’t include other satisfying sets. (Note that the code linked above halts after finding the first prime set. I modified the <code>main</code> function to print all candidates: <code>main = print $ candidates</code>.)</p>
<p>I demonstrate my Scheme code below:</p>
<p>I used a custom stream implementation to generate primes.
For reference, I put the relevant part of the module here:</p>
<pre class="lang-lisp prettyprint-override"><code>(define-library (stream)
(export cons-stream stream-car stream-cdr stream-null? the-empty-stream
stream-filter stream-take stream-take-while
integers-starting-from
prime-stream prime?)
(import (scheme base)
(scheme lazy))
(begin
(define-syntax cons-stream
(syntax-rules ()
((_ a b)
(cons a (delay b)))))
(define (stream-car stream)
(car stream))
(define (stream-cdr stream)
(force (cdr stream)))
(define (stream-null? stream)
(null? stream))
(define the-empty-stream '())
(define (stream-filter pred s)
(cond ((stream-null? s) the-empty-stream)
((pred (stream-car s))
(cons-stream
(stream-car s)
(stream-filter pred (stream-cdr s))))
(else
(stream-filter pred (stream-cdr s)))))
(define (stream-take-while pred s)
(if (or (stream-null? s)
(not (pred (stream-car s))))
'()
(cons (stream-car s)
(stream-take-while pred (stream-cdr s)))))
(define (integers-starting-from n)
(cons-stream
n
(integers-starting-from (+ n 1))))
(define (divisible? n q)
(zero? (remainder n q)))
(define prime-stream
(cons-stream
2
(stream-filter prime?
(integers-starting-from 3))))
(define (prime? n)
(let loop ((ps prime-stream))
(cond ((< n (square (stream-car ps)))
#t)
((divisible? n (stream-car ps))
#f)
(else
(loop (stream-cdr ps))))))))
</code></pre>
<p>In short, <code>primes</code> and <code>prime?</code> given above incrementally generates new prime numbers using a stream.
The stream module follows the definitions given in <a href="https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-24.html#%_sec_3.5" rel="nofollow noreferrer">SICP</a>.</p>
<p>I imported the above <code>stream</code> module and SRFI-1 (for procedures like <code>drop-while</code>):</p>
<pre class="lang-lisp prettyprint-override"><code>(import (except srfi-1 concatenate)
stream)
(define (concatenate n m)
(define (count-digits n)
(if (= n 0)
0
(+ 1 (count-digits (quotient n 10)))))
(+ m
(* n (expt 10 (count-digits m)))))
(define (check p . rest)
(if (null? rest)
#t
(let ((l-concat
(map (lambda (q) (concatenate p q))
rest))
(r-concat
(map (lambda (q) (concatenate q p))
rest)))
(and (every prime? l-concat)
(every prime? r-concat)))))
(define primes
(stream-take-while (lambda (p) (< p 10000))
prime-stream))
</code></pre>
<p>Note that I just took out primes as a list <code>primes</code> that are less than 10000.</p>
<p><code>(concatenate n m)</code> concatenates <code>n</code> and <code>m</code>, e.g., <code>(concatenate 123 456) -> 123456</code> (It is not the one in SRFI-1.).
<code>(check p . rest)</code> checks if <code>p</code> satisfies the constraint concatenated with other primes in <code>rest</code>. Prime set <code>rest</code> is assumed to already satisfy the constraint.</p>
<p>I now present two implementations, one with nested <code>flatmap</code>s, and the other using SRFI-42 (eager comprehension), for a Haskell-like list comprehension.
The two implementations show very little (< 1s) performance difference, so the later is just for syntactic clarity.</p>
<p>The first one:</p>
<pre class="lang-lisp prettyprint-override"><code>(define (flatmap proc lst)
(if (null? lst)
'()
(foldr append '() (map proc lst))))
(define satisfying-tuples
(flatmap
(lambda (p)
(flatmap
(lambda (q)
(flatmap
(lambda (r)
(flatmap
(lambda (s)
(map (lambda (t) (let ((satisfying (list p q r s t)))
(display "Found (p q r s t), sum: ")
(display satisfying)
(display #\,)
(display (+ p q r s t))
(newline)
satisfying))
(filter
(lambda (t) (check t s r q p))
(drop-while (lambda (t) (<= t s)) primes))))
(filter
(lambda (s) (check s r q p))
(drop-while (lambda (s) (<= s r)) primes))))
(filter
(lambda (r) (check r q p))
(drop-while (lambda (r) (<= r q)) primes))))
(filter
(lambda (q) (check q p))
(drop-while (lambda (q) (<= q p)) primes))))
primes))
(display satisfying-tuples)
(newline)
</code></pre>
<p>The second one using eager comprehension:</p>
<pre class="lang-lisp prettyprint-override"><code>; Should (import srfi-42) as well
(define satisfying-tuples-2
(list-ec (:list p primes)
(:list q primes)
(if (and (> q p)
(check q p)))
(:list r primes)
(if (and (> r q)
(check r q p)))
(:list s primes)
(if (and (> s r)
(check s r q p)))
(:list t primes)
(if (and (> t s)
(check t s r q p)))
(begin
(let ((satisfying (list p q r s t)))
(display "Found (p q r s t), sum: ")
(display satisfying)
(display #\,)
(display (+ p q r s t))
(newline)))
(list p q r s t)))
(display satisfying-tuples-2)
(newline)
</code></pre>
<p>The second version emphasizes the similarity with the <a href="https://zach.se/project-euler-solutions/60/" rel="nofollow noreferrer">Haskell version</a>, yet it shows almost 50 times performance difference.</p>
<p>Is this just a classic example of</p>
<blockquote>
<p><a href="http://www.cs.yale.edu/homes/perlis-alan/quotes.html" rel="nofollow noreferrer">A LISP programmer knows the value of everything, but the cost of nothing.</a></p>
</blockquote>
<p>, or is there a room for improvement in my code?
I’m using Chicken Scheme, and I compiled my code with <code>csc -R r7rs my-code.scm</code>.</p>
<p><a href="https://github.com/Zeta611/project-euler/blob/c4c15da44761edfd4fc664d3cd8bba781242a50c/stream/stream.scm" rel="nofollow noreferrer">Here is a link to my <code>stream</code> library</a> and <a href="https://github.com/Zeta611/project-euler/blob/c4c15da44761edfd4fc664d3cd8bba781242a50c/060-prime-pair-sets.scm" rel="nofollow noreferrer">to the complete code</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:23:57.917",
"Id": "252139",
"Score": "3",
"Tags": [
"programming-challenge",
"haskell",
"primes",
"scheme"
],
"Title": "Performance issue regarding Project Euler #60 in Scheme"
}
|
252139
|
<p>I'm currently trying to improve my skills in Java. I have created a simple console-based bank system with four classes. A user interface, account holder, abstract bank account class which account holder extends, and finally a main to run the UI.</p>
<p>Basically, I want to get some suggested improvements and ideas on how to improve it and maybe implement some more OOP concepts.</p>
<pre><code> public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);
UserInterface ui = new UserInterface(myObj);
ui.start();
}
}
</code></pre>
<pre><code>public class UserInterface {
private Scanner scanner;
private AccountHolder accountHolder;
private Map<String, AccountHolder> accounts;
public UserInterface(Scanner scanner) {
this.scanner = scanner;
this.accounts = new HashMap<String, AccountHolder>();
}
public void start() {
while(true) {
System.out.println("Welcome to the bank please select from the options below by pressing the required number");
System.out.println("1 - Create Account");
System.out.println("2 - Log into account");
System.out.println("3 - Quit");
System.out.print("Please make a choice: ");
String input = scanner.nextLine();
switch(input) {
case "1":
createAccount();
break;
case "2":
login();
break;
case "3":
System.exit(0);
break;
default:
System.out.println("Invalid option");
break;
}
}
}
private void createAccount() {
System.out.println("Please enter a username");
String username = scanner.nextLine();
System.out.println("Please enter a password");
String password = scanner.nextLine();
System.out.println("Please enter name:");
String name = scanner.nextLine();
System.out.println("Please enter address:");
String address = scanner.nextLine();
System.out.println("Please enter mobile number:");
String number = scanner.nextLine();
System.out.println("Please enter an initial deposit ammount");
double deposit = scanner.nextDouble();
accountHolder = new AccountHolder(username, password, name, address, number, deposit);
accounts.put(username, accountHolder);
scanner.nextLine();
}
private void login() {
System.out.println("Please enter your username");
String username = scanner.nextLine();
System.out.println("Please enter your password");
String password = scanner.nextLine();
if(accounts.containsKey(username)) {
accountHolder = accounts.get(username);
if(accountHolder.getPassword().equals(password)) {
while(true) {
System.out.println("Please make a choice");
System.out.println("1 - Deposit");
System.out.println("2 - Withdraw");
System.out.println("3 - Balance");
System.out.println("4 - User information");
System.out.println("5 - Logout");
System.out.print("Please make a choice: ");
String choice = scanner.nextLine();
switch(choice) {
case "1":
System.out.println("Please enter an ammount to deposit");
double deposit = scanner.nextDouble();
accountHolder.deposit(deposit);
break;
case "2":
System.out.println("Please enter an ammount to withdraw");
double withdraw = scanner.nextDouble();
accountHolder.withdraw(withdraw);
break;
case "3":
System.out.println("Your current balance is: " + accountHolder.getBalance());
break;
case "4":
System.out.println(accountHolder);
break;
case "5":
System.exit(0);
break;
default:
System.out.println("Invalid option");
}
}
}
}
}
}
</code></pre>
<pre><code>public class AccountHolder extends BankAccount {
private String username;
private String password;
private String name;
private String address;
private String mobileNumber;
private double deposit;
public AccountHolder(String username, String password, String name, String address, String mobileNumber, double deposit) {
this.username = username;
this.password = password;
this.name = name;
this.address = address;
this.mobileNumber = mobileNumber;
this.deposit = deposit;
}
public String getName() {
return this.name;
}
public String getAddress() {
return this.address;
}
public String getNumber() {
return this.mobileNumber;
}
public String getusername() {
return this.username;
}
public String getPassword() {
return this.password;
}
@Override
double getBalance() {
// TODO Auto-generated method stub
return this.deposit += super.balance;
}
public String toString() {
return this.name + "\n" + this.address+ "\n" + this.mobileNumber+ "\n" + super.getRandomAccountNumber()+ "\n" + super.getRandomSortcode();
}
}
</code></pre>
<pre><code>public abstract class BankAccount {
protected double balance;
public BankAccount() {
this.balance = 0;
this.sortcode = "";
this.accountNumber = "";
}
abstract double getBalance();
public void withdraw(double moneyWithdrawn) {
this.balance -= moneyWithdrawn;
}
public void deposit(double depositAmount) {
this.balance += depositAmount;
}
public String getRandomSortcode() {
Random rnd = new Random();
int newSortcode = rnd.nextInt(999999);
return String.format("%06d", newSortcode);
}
public String getRandomAccountNumber() {
Random rnd = new Random();
int newAccountNum = rnd.nextInt(999999);
return String.format("%08d", newAccountNum);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T14:13:49.790",
"Id": "496652",
"Score": "0",
"body": "Are you interested in more general review comments (code style, variable naming, etc), rather than just OOP principle related suggestions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T14:23:38.810",
"Id": "496657",
"Score": "0",
"body": "A bit of everything really, im just trying to improve in every aspect weather that be general comments or other OOP suggestions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:27:12.097",
"Id": "496707",
"Score": "1",
"body": "As an additional note: `System.exit` is not a \"soft\" exit, but rather a hard kill of the JVM process (f.e. `finally` blocks will not be executed). It might or might not be wanted to do that."
}
] |
[
{
"body": "<p>You can extract interface from <code>UserInterface</code> class to use several realizations of app functionality</p>\n<pre><code>public interface UserInterface {\n public void start();\n}\n</code></pre>\n<p>And usage:</p>\n<pre><code>public class ConsoleUserInterface implements UserInterface {\n private Scanner scanner;\n private AccountHolder accountHolder;\n private Map<String, AccountHolder> accounts;\n\n public ConsoleUserInterface(Scanner scanner) {\n...\n</code></pre>\n<p>main:</p>\n<pre><code>UserInterface ui = new ConsoleUserInterface(myObj);\nui.start();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T11:01:01.250",
"Id": "252143",
"ParentId": "252141",
"Score": "2"
}
},
{
"body": "<h2>Single Responsibility</h2>\n<p>My first piece of advice is to remember the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>. Take, for example, your <code>login</code> method in your <code>UserInterface</code> class, which is currently handling the rendering of the login inputs, checking whether it was a successful login, and then a host of bank account related operations.</p>\n<p>Instead, we ought to have something more <a href=\"https://en.wikipedia.org/wiki/Cohesion_(computer_science)\" rel=\"nofollow noreferrer\">cohesive</a>.</p>\n<pre><code>private void login() {\n System.out.println("Please enter your username");\n String username = scanner.nextLine();\n System.out.println("Please enter your password");\n String password = scanner.nextLine();\n if (new Authenticator(username, password).authenticate()) {\n presentAccountOperations();\n }\n}\n</code></pre>\n<p>Your <code>UserInterface</code> class is also managing accounts which probably ought to be handled by a dedicated class.</p>\n<h2>Inversion of Control</h2>\n<p>Typically it is best to leave the creation of "dependencies" to another class rather than handling them inside the class that needs them. So rather than calling <code>new AccountManager()</code> or <code>new Authenticator()</code> inside the <code>UserInterface</code> we ought to pass them in already created. We call this <a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Inversion of Control</a>. For example we could do the following;</p>\n<pre><code>public static void main(String[] args) {\n Scanner myObj = new Scanner(System.in); \n Authenticator authenticator = new Authenticator();\n AccountManager accountManager = new AccountManager(authenticator);\n UserInterface ui = new UserInterface(myObj, accountManager);\n ui.start(); \n}\n</code></pre>\n<h2>Composition over Inheritance</h2>\n<p>Your <code>AccountHolder</code> currently extends <code>BankAccount</code>. This is violating both the single responsibility principle, and it is semantically incorrect. A person with an account is not a type of bank account. Here is where you will want to know about the <a href=\"https://en.wikipedia.org/wiki/Composition_over_inheritance\" rel=\"nofollow noreferrer\">Composition over Inheritance</a> principle.</p>\n<p>It is better for an <code>AccountHolder</code> to <em><strong>have a</strong></em> <code>BankAccount</code>, rather than extending one. Additionally, if we want our account holder to have multiple bank accounts then we can change this relatively easily (which is not true if you use inheritance).</p>\n<h2>Consistent Styling</h2>\n<p>People have differing opinions of how code should be styled, but something everyone agrees on is that the way you style your code should be consistent. The first thing that stands out to me from your code's styling and formatting is the number of new lines separating each section.</p>\n<p>In some places you have 4 or more lines under your object fields, 2 at the end of method before the closing brace, 2 after the closing brace, 2 after one constructor but not others, and one between methods. <a href=\"https://www.oracle.com/technetwork/java/codeconventions-150003.pdf\" rel=\"nofollow noreferrer\">The Oracle java code conventions</a> recommends only 1 new line between methods, constructors, fields, and logical sections in code.</p>\n<p>If you decide to leave 1 new line after method declarations it is better to do this always, or not at all. Consistency is key.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T14:22:44.060",
"Id": "496656",
"Score": "0",
"body": "Thank you for your response, in regards to the abstract bank account class, would it make more sense to say create classes such as savings acount, debit account and then those extend the bank acount class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T14:39:13.360",
"Id": "496658",
"Score": "0",
"body": "@dawnofwar Yes, absolutely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T14:55:20.127",
"Id": "496659",
"Score": "0",
"body": "Right okay, my next question would be how would i then let the user choose which bank account they want using my user interface? Thank you for all your comments i appreciate it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T14:04:08.073",
"Id": "252145",
"ParentId": "252141",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T10:45:14.020",
"Id": "252141",
"Score": "5",
"Tags": [
"java",
"object-oriented"
],
"Title": "OOP concepts In a console application"
}
|
252141
|
<p>Currently, my game is a basic target shooting game.</p>
<ul>
<li>The targets rise to the top, if the target reaches the top an end screen is shown.</li>
<li>If you shoot a target you get more score, and the speed in which the targets move increases.</li>
<li>If you shoot the fake target, the end screen is shown</li>
</ul>
<p>If anyone could help me and clean up my code I'd appreciate it greatly.</p>
<pre><code>namespace ProjectProtoypeUI
{
public partial class gameForm : Form
{
bool gameOver;
int targetSpeed;
int score;
Random randomValue = new Random();
public gameForm()
{
InitializeComponent();
GameRestart();
}
private void textScore_Click(object sender, EventArgs e)
{
}
private void MainTimeEvent(object sender, EventArgs e)
{
textScore.Text = "Score: " + score;
if (gameOver == true)
{
targetTimer.Stop();
textScore.Text = "Score :" + score + "Game over, press enter to reset game";
}
foreach(Control test in this.Controls)
{
if (test is PictureBox)
{
test.Top -= targetSpeed;
//test.Left -= targetSpeed;
if (test.Top < -100)
{
test.Top = randomValue.Next(700, 1000);
test.Left = randomValue.Next(5, 500);
}
if ((string)test.Tag == "target")
{
if (test.Top < -50)
{
gameOver = true;
}
}
if (gnomeImage.Bounds.IntersectsWith(pictureBox2.Bounds) || gnomeImage.Bounds.IntersectsWith(pictureBox1.Bounds))
{
test.Top = randomValue.Next(650, 800);
test.Left = randomValue.Next(50, 450);
}
if (pictureBox1.Bounds.IntersectsWith(pictureBox2.Bounds))
{
test.Top = randomValue.Next(700, 1000);
test.Left = randomValue.Next(5, 500);
}
}
}
}
private void shootTarget(object sender, EventArgs e)
{
if (gameOver == false)
{
var target = (PictureBox)sender;
target.Top = randomValue.Next(750, 1000);
target.Left = randomValue.Next(5, 500);
if (target.Top > 800 && target.Left > 514)
{
target.Top = randomValue.Next(100, 1000);
target.Left = randomValue.Next(5, 1000);
}
score += 1;
targetSpeed += 1;
}
}
private void gameLost(object sender, EventArgs e)
{
if (gameOver == false)
{
gameOver = true;
}
}
private void GameOver(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && gameOver == true)
{
GameRestart();
}
}
private void GameRestart()
{
targetSpeed = 10;
score = 0;
gameOver = false;
foreach (Control pictures in this.Controls)
{
if (pictures is PictureBox)
{
pictures.Top = randomValue.Next(750, 1000);
pictures.Left = randomValue.Next(5, 500);
}
}
targetTimer.Start();
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T05:56:40.883",
"Id": "496729",
"Score": "0",
"body": "Don't forget to add the necessary `using` directives"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T06:04:45.993",
"Id": "496730",
"Score": "2",
"body": "Welcome to code review, please take your time to learn about the scope of this site. We can review your code, but we cannot refactor it (ie. to use more OOP, inheritance,...) or add new features (ie. targets coming in different angles)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T12:28:16.013",
"Id": "496770",
"Score": "0",
"body": "thank you very much, is there anyway I could be pointed in the right direction to learn how to do these things?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:20:42.843",
"Id": "496789",
"Score": "0",
"body": "@Tytal124 Not on this site, here we review working code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T15:26:04.960",
"Id": "252147",
"Score": "4",
"Tags": [
"c#",
"object-oriented",
"game",
"winforms"
],
"Title": "Simple target shooter game using Windows Forms"
}
|
252147
|
<blockquote>
<h2>Problem</h2>
<p>You are given an <em>HxW</em> matrix. Each element is either 0 (passable space) or 1 (wall).
Given that you can remove <strong>one</strong> wall, find the shortest path from [0,0] (<strong>start</strong>)
to [width-1, height-1] (<strong>end</strong>).</p>
<blockquote>
<h2>Test cases</h2>
</blockquote>
<p>Inputs:</p>
<pre><code>int[][] case 1 = {
{0, 1, 1, 0},
{0, 0, 0, 1},
{1, 1, 0, 0},
{1, 1, 1, 0},
};
</code></pre>
<p>Outputs:</p>
<pre><code>7
</code></pre>
<p>Inputs:</p>
<pre><code>int[][] case2 = {
{0, 0, 0, 0, 0, 0},
{1, 1, 1, 1, 1, 0},
{0, 0, 0, 0, 0, 0},
{0, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1},
{0, 0, 0, 0, 0, 0},
}
</code></pre>
<p>Outputs:</p>
<pre><code>11
</code></pre>
</blockquote>
<p>Note, this is one of the google foobar challenges. There are quite a few algorithms out there for this problem. However, I'm trying to solve this using a variation of A*. My problem is that currently, my algorithms works like this:</p>
<ol>
<li>Get all wall locations.</li>
<li>For each wall:
<ol>
<li>Construct maze without the wall.</li>
<li>Use A* to find the shortest path.</li>
</ol>
</li>
<li>Return the min of the found shortest paths.</li>
</ol>
<pre><code>import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class Cell {
// Normal Cell things..
int x,y;
boolean isWall;
// A* shenanigans (should probably be decoupled).
int localScore; // The distance from the start.
int globalScore; // The distance from the end (heuristic).
boolean isVisited;
// What I tried is to include a `canRemove` boolean here to indicate whether we can still remove walls within this point.
Cell(int x, int y, boolean isWall) {
this.x = x;
this.y = y;
this.isWall = isWall;
this.localScore = Integer.MAX_VALUE;
this.globalScore = Integer.MAX_VALUE;
}
// Copy constructor.
Cell(Cell anotherCell) {
this.x = anotherCell.x;
this.y = anotherCell.y;
this.isWall = anotherCell.isWall;
this.isVisited = anotherCell.isVisited;
this.localScore = anotherCell.localScore;
this.globalScore = anotherCell.globalScore;
}
}
class Station {
Cell[][] cells;
List<Cell> walls;
int height, width;
Station(int[][] rawStation) {
// Create Maze
this.height = rawStation.length;
this.width = rawStation[0].length;
this.cells = new Cell[height][width];
walls = new ArrayList<>();
for(int y=0; y<height; y++){
for(int x=0; x<width; x++){
Cell cell = new Cell(x, y, rawStation[y][x] == 1);
this.cells[y][x] = cell;
if(cell.isWall) walls.add(cell);
}
}
}
Station(Station station) {
this.height = station.height;
this.width = station.width;
this.cells = new Cell[height][width];
this.walls = new ArrayList<>();
for(int y=0; y<height; y++){
for(int x=0; x<width; x++){
cells[y][x] = new Cell(station.cells[y][x]);
}
}
}
Cell start() {
return cells[0][0];
}
Cell end() {
return cells[height-1][width-1];
}
Optional<Cell> getCell(int x, int y) {
if(x >= 0 && x < width && y >= 0 && y < height) {
return Optional.of(cells[y][x]);
}
return Optional.empty();
}
List<Cell> getCellNeighbours(Cell cell) {
List<Optional<Cell>> neighbours = new ArrayList<>();
neighbours.add(getCell(cell.x, cell.y+1)); // TOP
neighbours.add(getCell(cell.x, cell.y-1)); // BOTTOM
neighbours.add(getCell(cell.x-1, cell.y)); // LEFT
neighbours.add(getCell(cell.x+1, cell.y)); // RIGHT
return neighbours.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
}
}
class BunnySaver {
Station station;
List<Cell> discoveredCells;
boolean hasBomb;
BunnySaver(Station station) {
this.station = station;
this.discoveredCells = new ArrayList<>();
this.hasBomb = true;
}
int findShortestPath() {
Cell current = station.start();
current.localScore = 1;
current.isVisited = false;
current.globalScore = distance(current, station.end());
discoveredCells.add(station.start());
while(!discoveredCells.isEmpty() && current != station.end()) {
// Get the cell that has the lowest global score - aka lowest potential
// distance from end. Also remove it from the discovered list.
discoveredCells = discoveredCells.stream()
.sorted(Comparator.comparingInt(cell -> cell.globalScore))
.filter(cell -> !cell.isVisited)
.collect(Collectors.toList());
if(discoveredCells.isEmpty()) break;
current = discoveredCells.remove(0);
current.isVisited = true;
for(Cell neighbour : station.getCellNeighbours(current)) {
// If the neighbour is not already visited and it's not a wall,
// mark it as discovered.
if(neighbour.isVisited || neighbour.isWall)
continue;
discoveredCells.add(neighbour);
// If the neighbour's new localScore is lower than
// the old one => update the cell.
int possibleNeighbourLocalScore = current.localScore + distance(current, neighbour);
if(neighbour.localScore > possibleNeighbourLocalScore) {
neighbour.localScore = possibleNeighbourLocalScore;
neighbour.globalScore = neighbour.localScore + distance(neighbour, station.end());
}
}
}
if (current == station.end())
return current.localScore;
return Integer.MAX_VALUE;
}
// Manhattan distance used for A*.
int distance(Cell cell1, Cell cell2) {
int deltaX = Math.abs(cell1.x - cell2.x);
int deltaY = Math.abs(cell1.y - cell2.y);
return deltaX + deltaY;
}
}
public class Solution {
public static int solution(int[][] map) {
Station station = new Station(map);
int minPath = Integer.MAX_VALUE;
// Edge case: there are no walls.
if(station.walls.isEmpty()) {
BunnySaver saver = new BunnySaver(station);
return saver.findShortestPath();
}
// Remove check all possible wall removals.
for(Cell wall : station.walls) {
Station copy = new Station(station);
copy.cells[wall.y][wall.x].isWall = false;
BunnySaver saver = new BunnySaver(copy);
minPath = Math.min(minPath, saver.findShortestPath());
}
return minPath;
}
}
</code></pre>
<p>This as you can guess is very inefficient. What would be a good way of implementing the wall logic to be within the A* algorithm? I've tried to simply add a <code>canRemove</code> boolean to the Cell object (which is holding the state), however, that causes backtracking issues as diverged paths can alter the same state. I need to find a way of decoupling the state away from the <code>Cell</code> object and ultimately the A* algo.</p>
|
[] |
[
{
"body": "<p>You could try creating a parent object Node that has Cell as a member and canRemove as another member.\nGetting neighbors might be messier but should be doable with member functions.</p>\n<blockquote>\n<p>I need to find a way of decoupling the state away from the Cell object and ultimately the A* algo.</p>\n</blockquote>\n<p>I don't think you want to decouple state from the algorithm, because A-star needs state to calculate the heuristic, but putting Cell in a parent object at least decouples it from canRemove.</p>\n<p>Edit: My answer is an implementation of what harold is saying below. He explains it in more detail. Treating Cell and canRemove as different members of parent Node, is like having three dimensions in your state space: x, y, and canRemove.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T18:49:24.167",
"Id": "252152",
"ParentId": "252150",
"Score": "3"
}
},
{
"body": "<h1>The high level approach</h1>\n<blockquote>\n<p>What would be a good way of implementing the wall logic to be within the A* algorithm? I've tried to simply add a canRemove boolean to the Cell object (which is holding the state), however, that causes backtracking issues as diverged paths can alter the same state.</p>\n</blockquote>\n<p>The way I see it, the main issue is that you're not treating "number of bombs left" as part of the coordinate, but that is what it should be. The state space that is being explored is not just positions, it has a (small, in this case) extra dimension representing how many bombs are left. A* relies on the property that how long a path is going to be from a given coordinate depends only on the coordinate and not on how you got there, in order to make it work you need to ensure that that property is true, and you can make it true by treating the number of bombs as part of the coordinate.</p>\n<p>It would cost an extra layer of cells to represent that dimension, but that's no big deal - if the state space was large, I would have recommended creating nodes on-demand only, but that's not the case here. Anyway, the most important part is that there are also extra neighbours possible: the bunny can make a step from a has-a-bomb-left coordinate to a spacially-adjacent no-bombs-left coordinate with a wall on it (a move which represents using the bomb to blow up that wall and then stepping onto the rubble).</p>\n<p>I suppose that is "the trick" of this problem, hopefully explaining it didn't ruin the experience.</p>\n<p>If a coordinate with more than just a physical position in it sounds weird to you, consider that in additional to finding a path through a maze, an other common "example use" of A* is to solve N-puzzles. In that application, an entire board-state is a coordinate in the state space (all possible board states) which is being explored. That is also an example where the nodes really have to made on-demand only, the 16-puzzle has 20922789888000 potential states that clearly cannot all get a node pre-made for them.</p>\n<h1>Data structures</h1>\n<blockquote>\n<pre><code>// A* shenanigans (should probably be decoupled).\n</code></pre>\n</blockquote>\n<p>If there was a map on which multiple searches are done (effectively that does happen now, which I guess is why you copy the <code>Station</code>, but with the change of approach you would no longer need that), it's good to split the state into "state the map has" and "temporary state used by A*" (for example to absolutely positively avoid cross-contamination between searches). But in this case, what would you gain? I think it's fine to leave that as it is.</p>\n<blockquote>\n<pre><code>List<Cell> discoveredCells\n</code></pre>\n</blockquote>\n<p>If I'm reading your implementation of A* right, that's the Open Set. It's not a priority queue, which resulted in <code>.sorted</code> on a stream. That's not really a great way to do it, it's more heavy-duty than necessary. Changing the list to a PQ is not as easy as it sounds, since the cost-update step (the <code>if</code> in the loop over the neighbours) requires finding the position of an element within the PQ to be able to reestablish the heap property for it. Java's built-in PQ has no facility to do so.</p>\n<p>On the other hand, the Closed Set (implemented via the <code>isVisited</code> field) is already implemented efficiently. A separate grid of booleans or a hash set of coordinates is also possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:15:07.843",
"Id": "496712",
"Score": "0",
"body": "Correct me if I'm wrong, but you're basically saying that the station object should be a 3-dimensional space (x,y, and hasBomb)? - and whenever the bunny *destroys* a wall, we move within the 3rd dimension. That allows us to not *contaminate* the map within different searches (say search A reaches cell x using bomb and search B reaches cell x without bomb)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:49:40.807",
"Id": "496713",
"Score": "0",
"body": "@Mitch yes, not just for the purpose of not contaminating the map though (it's a nice bonus), the main improvement that creates is not needing to try every wall"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:11:05.173",
"Id": "252156",
"ParentId": "252150",
"Score": "6"
}
},
{
"body": "<blockquote>\n<p>What would be a good way of implementing the wall logic to be within the A* algorithm?</p>\n</blockquote>\n<p>This question is outside the scope of this site, but I will answer it anyways.</p>\n<p>A good way to solve these sort of problems is to alter the graph, rather than altering the pathfinding algorithm. Then any normal pathfinding algorithm (such as A*) can be used. We will "store" the state by having multiple copies of each node; which copy we're in determines whether or not a wall can still be removed.</p>\n<p>Start with two identical copies of the directed graph <em>(if the graph is undirected, you can make it directed by replacing each undirected edge with two directed edges, one in each direction)</em>. In the second graph <em>(representing "wall cannot be removed")</em>, add one node for each wall, with outgoing but <strong>not</strong> incoming edges for each neighbor. Then from the first graph <em>(representing "wall can be removed")</em>, add incoming but <strong>not</strong> edges to each wall-node for each neighbor. Make the start node in the first graph, and make sure both graphs have end-nodes.</p>\n<p>That's it. The algorithm will search through the first copy of the graph like usual, and allow one, and only one, jump into the second graph through a wall. You only need to run A* one time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:51:41.263",
"Id": "252168",
"ParentId": "252150",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252156",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T17:05:26.180",
"Id": "252150",
"Score": "8",
"Tags": [
"java",
"object-oriented",
"programming-challenge",
"pathfinding",
"a-star"
],
"Title": "A* (shortest path) with the ability to remove up to one wall"
}
|
252150
|
<p>My adjacency matrix looks like this, where non-zero weights denote edges.</p>
<p>[0, 2, 0, 0, 3]</p>
<p>[2, 0, 2, 4, 0]</p>
<p>[0, 2, 0, 3, 0]</p>
<p>[0, 4, 3, 0, 1]</p>
<p>[3, 0, 0, 1, 0]</p>
<p>Here's my attempt:</p>
<pre><code>//nested class, only showing the relevant parts of code
class Edge implements Comparable<Edge> {
int source;
int destination;
int weight;
public Edge(int source, int destination, int weight) {
this.source = source;
this.destination = destination;
this.weight = weight;
}
public String toString() {
return source + "---" + weight + "---" + destination;
}
@Override
public int compareTo(Edge other) {
return Integer.compare(this.weight, other.weight);
}
}
public void printPrimsMST(int[][] matrix) {
// Start with any vertex.
Set<Integer> visited = new HashSet<>();
Queue<Edge> edgeQueue = new PriorityQueue<>();
int currentNode = 0;
visited.add(0);
while (visited.size() < matrix.length) {
for (int col = 0; col<matrix[currentNode].length; col++) {
// Take all edges from this node.
if (col == currentNode || matrix[currentNode][col] == 0) {
//skip self as well as 0-weight edges.
continue;
}
edgeQueue.add(new Edge(currentNode, col, matrix[currentNode][col]));
}
if (edgeQueue.isEmpty())
return;
//find cheapest edge to a not already visited destination.
Edge edge = edgeQueue.remove();
while (visited.contains(edge.destination)) {
if (edgeQueue.isEmpty())
return;
edge = edgeQueue.remove();
}
System.out.println(edge.source + "--" + edge.weight + "--" + edge.destination);
// Now that you've reached this edge as a destination, record it.
currentNode = edge.destination;
visited.add(edge.destination);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:30:11.523",
"Id": "496708",
"Score": "2",
"body": "Please elaborate your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:59:12.647",
"Id": "496819",
"Score": "0",
"body": "@BillalBegueradj There's no question, this is a codereview forum and I'm asking for a code review."
}
] |
[
{
"body": "<p>I'll comment on code style, mainly.</p>\n<h2><code>printPrimsMST()</code> method</h2>\n<p>It both computes the MST and prints it to <code>System.out</code>. This way you can't reuse it if you want to do some additional processing with its results.</p>\n<p>So, change it to return <code>Collection<Edge></code> without printing anything, and introduce a <code>print()</code> method that takes <code>Collection<Edge></code>.</p>\n<p>For printing, you wrote:</p>\n<pre><code>System.out.println(edge.source + "--" + edge.weight + "--" + edge.destination);\n</code></pre>\n<p>That's unneccessarily complex, as you defined a <code>toString()</code> method in the <code>Edge</code> class, giving exactly that format. So it's enough to use</p>\n<pre><code>System.out.println(edge);\n</code></pre>\n<h2>Curly braces</h2>\n<p>I'd recommend to always surround blocks with curly braces (you do most of the time, but not always):</p>\n<pre><code> while (visited.contains(edge.destination)) {\n if (edgeQueue.isEmpty())\n return;\n edge = edgeQueue.remove();\n }\n</code></pre>\n<p>Someone editing the code might be tempted to insert an additional instruction before returning, e.g.</p>\n<pre><code> while (visited.contains(edge.destination)) {\n if (edgeQueue.isEmpty())\n doneIt = true;\n return;\n edge = edgeQueue.remove();\n }\n</code></pre>\n<p>That's a nasty trap. By indentation, it looks like a block of two statements, but it isn't (in your specific case, it's not that bad, as the compiler will flag the <code>edge = edgeQueue.remove();</code> statement as unreachable, but you get the idea). So, make it a habit to always write</p>\n<pre><code> while (visited.contains(edge.destination)) {\n if (edgeQueue.isEmpty()) {\n return;\n }\n edge = edgeQueue.remove();\n }\n</code></pre>\n<h2>Restricting field access</h2>\n<pre><code>class Edge implements Comparable<Edge> {\n int source;\n int destination;\n int weight;\n ...\n}\n</code></pre>\n<p>The internals of a class should only be visible to the class itself. The idea of OOP is that a class defines an API visible to the outside world, and is free to decide on (and change) its inner workings. That's close to impossible if outside code directly accesses instance fields.</p>\n<p>For that reason, make all fields <code>private</code>, unless you have good reason otherwise. And add only the necessary public getters and setters. And if you don't intend to change a field's value after construction of the instance, make it <code>final</code> as well.</p>\n<p>You might argue that <code>Edge</code> is a class only meant for local use. Then make <code>Edge</code> a private class.</p>\n<h2>Argument checks</h2>\n<p>You are talking about undirected graphs represented as adjacency matrix. Depending on who will be calling your method, you might want to include a test whether the <code>matrix</code> is valid:</p>\n<ul>\n<li>All rows must have the same length.</li>\n<li>The matrix must be square.</li>\n<li>The matrix must be symmetric.</li>\n</ul>\n<p>If any of these conditions are violated, you should throw an <code>IllegalArgumentException</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T18:02:28.637",
"Id": "496820",
"Score": "0",
"body": "Thank you for all the invaluable advice. Yes, i've gotten into a poor habit of not using curlies for one-line conditionals :) I also forgot that fields are package-private by default, so its better to restrict them to be entirely private."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T18:02:42.190",
"Id": "496821",
"Score": "0",
"body": "The idea to check the matrix for validity is also fantastic, thank you!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T13:07:01.907",
"Id": "252182",
"ParentId": "252157",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252182",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T20:11:27.197",
"Id": "252157",
"Score": "2",
"Tags": [
"java",
"graph"
],
"Title": "Prim's algorithm via Priority Queues to print the minimum spanning tree of an adjacency matrix undirected graph"
}
|
252157
|
<p>I wrote a SHA256 password cracker. I initially used lists to store the information in <code>list1.txt</code> and <code>list2.txt</code> but I would end up getting memory overloads. So I now use files.
I noticed that when I made this transition, the programme speed reduced hugely. Is there a way to optimise the speed of this programming without running into memory overload issues?</p>
<p>Thanks</p>
<pre><code>import hashlib
import time
import os
def extract_password(fname):
if fname == 0:
filename = "list2.txt"
else:
filename = "list1.txt"
for line in open(filename, "r"):
yield line.strip()
def save_password(fname, password):
if fname == 0:
filename = "list1.txt"
else:
filename = "list2.txt"
file = open(filename, "a")
file.write(password)
file.write("\n")
file.close()
def next_password(lsta, item,next_char, secure_password):
found = 0
guess = item + chr(next_char)
if hash_password(guess) == secure_password:
print(guess)
found = 1
save_password(lsta, guess)
return found
def hash_password(pwrd):
#Generates hash of original password
pwrd = pwrd.encode("UTF-8")
password = hashlib.sha256()
password.update(pwrd)
return password.hexdigest()
def delete_file(ltsa):
try:
if ltsa == 1:
os.remove("list2.txt")
else:
os.remove("list1.txt")
except:
pass
def reset_file_status():
try:
os.remove("list2.txt")
os.remove("list1.txt")
except:
pass
def find_password(secure_password):
#Brute force to find original password
found = 0
lsta = 1
for length in range(1, 15):
if found == 1: break
lsta = lsta^1
delete_file(lsta)
for next_char in range(65, 123):
if found == 1: break
if length == 1:
found = next_password(lsta, "", next_char, secure_password)
if found == 1: break
else:
for item in extract_password(lsta):
found = next_password(lsta, item, next_char, secure_password)
if found == 1: break
if __name__ == "__main__":
reset_file_status()
start = time.time()
secure_password = hash_password("AAAA")
find_password(secure_password)
print(f"{(time.time() - start)} seconds")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T02:49:39.053",
"Id": "496724",
"Score": "0",
"body": "This appears to be Python 3, is that correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T09:44:00.963",
"Id": "496756",
"Score": "0",
"body": "Yes. This is python 3"
}
] |
[
{
"body": "<p>The optimization you are looking for is very simple:<br />\nAsk your self - what do I really need to keep?</p>\n<p>The answer: only the password guess I am currently checking.</p>\n<p>There is no need to store all the old guesses, so there is no need for files or huge lists.</p>\n<p>All you really need is one string you will keep updating.</p>\n<p>To visualize this, think of your string as a growing number, with each letter being a base 58 digit.</p>\n<p>Now. all you really need is to do a +1 on the first digit, checking for carry and updating following digits if needed just like usual addition.</p>\n<p>Unfortunately, Python strings don't allow assignment by index, but they do support <a href=\"https://www.journaldev.com/23584/python-slice-string\" rel=\"nofollow noreferrer\">slicing</a>.</p>\n<p>Here is a function that would generate sequential passwords running through all the letters and growing the length as needed (one password per call!):</p>\n<pre><code>def make_next_guess(guess):\n carry = 1\n next_guess = guess\n\n for i in range(len(guess)):\n cur_char = ord(guess[i]) + carry\n if cur_char > ord('z'):\n cur_char = ord('A')\n carry = 1\n else:\n carry = 0\n\n next_guess = next_guess[:i] + chr(cur_char) + guess[i + 1:]\n if carry == 0:\n break\n\n if carry = 1:\n next_guess += 'A'\n\n return next_guess\n</code></pre>\n<p>With this you can use one loop for all the possibilities up to the maximum length:</p>\n<pre><code>guess = 'A'\n\nfor _ in range(58 ** 14): #password maximum length 14 and there are 58 characters that can be used\n \n if hash_password(guess) == secure_password:\n print(guess)\n break\n\n guess = make_next_guess(guess)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:05:34.217",
"Id": "496758",
"Score": "0",
"body": "Amazing. Thank you. Really appreciate it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:10:37.003",
"Id": "496759",
"Score": "0",
"body": "You are welcome! If forgot to add that his exercise is also good for learning multiprocessing and working with threads. You can speed this up even more if you divide the work between multiple threads or processes that run concurrently. https://www.machinelearningplus.com/python/parallel-processing-python/ https://www.tutorialspoint.com/python/python_multithreading.htm Say your processor can run 8 threads - just split the range of passwords to 8 sections and check them all simultaneously."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:40:14.353",
"Id": "252167",
"ParentId": "252159",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252167",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:11:52.937",
"Id": "252159",
"Score": "3",
"Tags": [
"hash"
],
"Title": "SHA256 password cracker - brute force"
}
|
252159
|
<p>I was asked to create a method that would:</p>
<ul>
<li>Return a Change object or null if there was no possible change</li>
<li>The "machine" has unlimited bills of: 2, 5 and 10</li>
<li>The Change object must return the most minimal amount of bills possible</li>
</ul>
<p>This was a question asked in codingame.com and wanted to investigate further on it:</p>
<pre><code>package moc;
class Change {
long coin2 = 0, bill5 = 0, bill10 = 0;
}
public class Test {
static Change c = new Change();
public static void main(String[] args) {
Change m = optimalChange(19L);
if (m == null) {
System.out.println("no change possible ...");
return;
}
System.out.println("Coin 2E: " + m.coin2);
System.out.println("bill 5E: " + m.bill5);
System.out.println("bill 10E: " + m.bill10);
long result = m.coin2 * 2 + m.bill5 * 5 + m.bill10 * 10;
System.out.println("Change given: " + result);
}
static Change optimalChange(long s) {
if (s < 2) {
return s == 0 ? c : null;
} else {
int decrementor = 0;
if (s < 5) {
c.coin2++;
decrementor = 2;
} else if (s < 10) {
if (s % 2 != 0) {
c.bill5++;
decrementor = 5;
} else {
c.coin2++;
decrementor = 2;
}
} else {
c.bill10++;
decrementor = 10;
}
return optimalChange(s - decrementor);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks like there is no need to recurse or loop at all. If the change is odd, it must include a 5-bill (special cases are changes of 1 and 3, which are impossible to make). The rest would be given by 10-bills (there will be <code>change / 10</code> of them), and 2-bills (there will be <code>(change % 10) / 2</code> of them). BTW, this is exactly what your code is doing, but in a very long way.</p>\n<p>That said, your second version makes the recursive call a tail recursion. This is good. However, Java does not support tail call elimination. This is not so good. I strongly recommend to eliminate it manually.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:30:05.520",
"Id": "496761",
"Score": "2",
"body": "Re \"this is exactly what your code is doing\", not exactly. OP's code would fail for s = 11, because it would choose $10. Your algorithm would see that it is odd, choose $5, and then choose 3x $2 for the rest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:31:19.477",
"Id": "496762",
"Score": "0",
"body": "Re \"Java does not support tail call elimination\", I think what you mean is that it doesn't *require* it? Presumably a compiler can do it as an optimization if it doesn't change the behavior of the code?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:59:13.763",
"Id": "252162",
"ParentId": "252160",
"Score": "10"
}
},
{
"body": "<p>As vnp said, it looks like for the specific constraints of this problem, there is an easier way without recursion.</p>\n<p>However, for different parameter/denominations, this might not be the case.</p>\n<p>I suggest writing more robust code without the extra if loops checking for parity, because those work specifically for this problem.</p>\n<p>There is a small flaw in your algorithm. You assume that the least bills will be found by picking the largest bill every time. As you can see with your example of s=8, this is not always the case. At every recursive node, you have to try all possible options (I think. There might be an optimization you can do at this step. Perhaps you can prune if one option's a multiple of the other), in case the biggest option doesn't work out.</p>\n<p>You can also do dynamic programming if you know that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T08:48:27.877",
"Id": "496751",
"Score": "0",
"body": "In this case, without the $1 available, 4x $2 really is the best you can do for $8. This problem is a simple one because amounts more than $10 you can always give a $10, until you have something less than $10. Then you can just enumerate the best solutions below $10."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:24:41.053",
"Id": "496760",
"Score": "1",
"body": "@Jeremy, re \"amounts more than $10 you can always give a $10\": This doesn't work for $11, which requires 1 x $5 and 3 x $2."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T22:13:58.097",
"Id": "252164",
"ParentId": "252160",
"Score": "1"
}
},
{
"body": "<p>Others can give advice on algorithms, I'll leave yours as-is and just give a few stylistic pointers.</p>\n<hr />\n<p><code>Test</code> is a class responsible for displaying things, <code>Change</code> is a class responsible for dealing with logic relating to change. So <code>optimalChange</code> should go in <code>Change</code>.</p>\n<hr />\n<p><code>int decrementor = 0</code></p>\n<p>You can avoid initializing this, and then your IDE will tell you if there are any branches you forget to set it's value before using it. (You never actually want this to be zero -- infinite loop!)</p>\n<hr />\n<pre><code> if (s < 2) {\n return s == 0 ? c : null;\n } else {\n</code></pre>\n<p>When you have an early return, you can avoid increasing the nesting level, which can make the code easier to read, by just dropping the <code>else</code> block.</p>\n<hr />\n<pre><code> } else if (s < 10) {\n if (s % 2 != 0) {\n c.bill5++;\n decrementor = 5;\n } else {\n</code></pre>\n<p>You can avoid the nesting by checking for both conditions at the top level, followed by the second condition.</p>\n<hr />\n<pre><code>static Change c = new Change();\n</code></pre>\n<p>I moved this first to <code>Change</code> since <code>optimalChange</code> was already moved there, and it depended on it. Then it didn't make sense for <code>Change</code> to have a <code>static Change</code> member, since <code>optimalChange</code> won't be valid when called more than once, or if used by other threads. You want an instance of <code>Change</code> per call to <code>optimalChange</code>, and it makes sense for <code>optimalChange</code> to remain <code>static</code> so where to keep that state between recursions? A: I made a separate function for the recursive part.</p>\n<hr />\n<pre><code>package moc;\n\npublic class Test {\n\n static class Change {\n long coin2 = 0;\n long bill5 = 0;\n long bill10 = 0;\n \n public static Change optimalChange(long s) {\n return optimalChangeRecursive(s, new Change());\n }\n \n private static Change optimalChangeRecursive(long s, Change c) {\n int decrement;\n if (s == 0} {\n return c;\n } else if (s < 2) {\n return null;\n } else if (s < 5) {\n c.coin2++;\n decrement = 2;\n } else if (s < 10 && s % 2 != 0) {\n c.bill5++;\n decrement = 5;\n } else if (s < 10) {\n c.coin2++;\n decrement = 2;\n } else {\n c.bill10++;\n decrement = 10;\n }\n return optimalChangeRecursive(s - decrement, c);\n }\n }\n\n public static void main(String[] args) {\n Change m = Change.optimalChange(19L);\n\n if (m == null) {\n System.out.println("no change possible ...");\n return;\n }\n\n System.out.println("Coin 2E: " + m.coin2);\n System.out.println("bill 5E: " + m.bill5);\n System.out.println("bill 10E: " + m.bill10);\n\n long result = m.coin2 * 2 + m.bill5 * 5 + m.bill10 * 10;\n\n System.out.println("Change given: " + result);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T08:21:47.533",
"Id": "252179",
"ParentId": "252160",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "252162",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:20:57.560",
"Id": "252160",
"Score": "6",
"Tags": [
"java",
"performance",
"recursion"
],
"Title": "Money change exam"
}
|
252160
|
<p>On recent interview I was asked to write program that print "Zero" and "One" to stdout from different threads, but in ordered manner:</p>
<pre><code>zero
one
zero
one
zero
one
...
</code></pre>
<p>Now I decided to write more generalized solution and this is my first attempt:</p>
<pre><code>#include <string>
#include <vector>
#include <mutex>
#include <initializer_list>
#include <condition_variable>
#include <thread>
#include <iostream>
struct OrderNumberPrinter
{
OrderNumberPrinter(const std::initializer_list<std::string>& list)
: m_len(list.size())
, m_cv(list.size())
{
size_t num = 0;
for(auto it = list.begin(); it != list.end(); ++it, ++num)
{
m_workers.emplace_back([this, num, message = *it](){
while(true)
{
std::unique_lock<std::mutex> lock(m_printLock);
m_cv[num].wait(lock, [this, num](){ return m_current == num; });
std::cout << message << "\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
++m_current;
if (m_current == m_len)
{
m_current = 0;
}
m_cv[m_current].notify_one();
}
});
}
}
~OrderNumberPrinter()
{
for(auto& w: m_workers)
{
if (w.joinable())
{
w.join();
}
}
}
private:
int m_len = 0;
int m_current = 0;
std::vector<std::condition_variable> m_cv;
std::mutex m_printLock;
std::vector<std::thread> m_workers;
};
int main(int argc, char* argv[])
{
OrderNumberPrinter printer = {"zero", "one", "two", "three"};
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:55:50.217",
"Id": "496714",
"Score": "0",
"body": "If you're using a c++20 compiler, I'd suggest [`std::basic_osyncstream`](https://en.cppreference.com/w/cpp/io/basic_osyncstream)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T22:03:15.660",
"Id": "496716",
"Score": "0",
"body": "@Edward Thank you will try it. I think in this case it would be better to use C++11/14/17"
}
] |
[
{
"body": "<p>Here are some things that may help you improve your program.</p>\n<h2>If it has private members, it should be a <code>class</code></h2>\n<p>The <code>OrderNumberPrinter</code> <code>struct</code> really should be a <code>class</code> because it has <code>private</code> member data. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-class\" rel=\"nofollow noreferrer\">C.8</a></p>\n<h2>Use <code>std::size_t</code> rather than <code>int</code></h2>\n<p>The values <code>m_len</code> and <code>m_current</code> should both probably be <code>std::size_t</code> rather than <code>int</code>, not least because they are compared to <code>num</code> and initialized with <code>list.size()</code> which are both explicitly <code>std::size_t</code>.</p>\n<h2>Exercise all functions</h2>\n<p>There is no way that the destructor ever gets called in the current code because there is no exit condition in the code. For that reason, how do you know if it works? I'd ask that for an interview. I'd also ask why <code>w.joinable()</code> is tested before calling <code>w.join()</code>. Is there a circumstance in which <code>w.joinable()</code> will return <code>false</code>?</p>\n<h2>Think about further derivation</h2>\n<p>What would happen if a user derived from this class? I'd recommend either declaring the destructor as <code>virtual</code> or declaring the class <code>final</code> to prevent derivation.</p>\n<h2>Be clear about what each mutex is locking</h2>\n<p>The name <code>m_printLock</code> suggests that the shared resource being protected is <code>std::cout</code>. If we used <code>std::basic_osyncstream</code> as suggested in a comment, would you still need a mutex? If so, what would it then be locking? Generally, I like to have each mutex just lock one thing because it simplifies maintenance and clarifies the intent to other programmers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T06:26:14.007",
"Id": "496732",
"Score": "0",
"body": "Thank you so much for the code review. Can you recommend me what to do with calling destructor in this example? I want to call it. I can add signal handler (for example, `SIGINT`), `m_run` variable flag to `OrderNumberPrinter` and stop method that will set m_run to false. Talking about your question: there is no circumstance in which join returns joinable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T06:32:29.803",
"Id": "496733",
"Score": "0",
"body": "Talking about `m_printLock`, yes, the name of this mutex isn't so good. This mutex should lock step increment, to be more precise `m_current` change. Also `cout` object access should be locked, otherwise, thread sanitizer will warn about data races. If I want to print to stdout using`std::cout` what should I do in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T14:31:06.387",
"Id": "496782",
"Score": "1",
"body": "One idea for ending would be to pass in a `limit` value to count down the number of messages printed. For the `m_printLock`, I think it's OK to leave it as it is in the code; mostly I was just asking the kinds of questions that come up in interviews. A comment in the code about exactly what is being locked would be sufficient."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T00:50:36.927",
"Id": "252170",
"ParentId": "252161",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T21:31:43.547",
"Id": "252161",
"Score": "5",
"Tags": [
"c++",
"multithreading",
"interview-questions"
],
"Title": "Multithreaded number printer in ordered manner"
}
|
252161
|
<p><strong>Question -You are given a primitive calculator that can perform the following three operations with the current number : multiply by 2, multiply by 3, or add 1 to . Your goal is given apositive integer , find the minimum number of operations needed to obtain the number
starting from the number 1.</strong></p>
<pre><code>ll n;
cin>>n;
vector<ll>vec;
vec.pb(n);
if(n==1)
{
cout<<0<<endl<<1;
}
else
{
while(n!=1)
{
if(n%3==0)
n=n/3;
else if(n%2==0)
n=n/2;
else
n=n-1;
vec.pb(n);
}
cout<<vec.size()-1<<endl;
for(int i=(vec.size()-1);i>=0;i--)
cout<<vec[i]<<" ";
}
return 0;
</code></pre>
<p>}</p>
<p>for input 96234 iam getting</p>
<p>15</p>
<p>1 2 4 5 10 11 22 66 198 594 1782 5346 16038 16039 32078 96234</p>
<p>but the optimal soln is</p>
<p>14</p>
<p>1 3 9 10 11 22 66 198 594 1782 5346 16038 16039 32078 96234</p>
<p>i know i am going wrong at the step when 10 is converted into 5 in my code but it should convert it in to 9, Please help me,</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:39:47.533",
"Id": "496720",
"Score": "0",
"body": "I'm sorry, but code review is for reviewing correctly working code. If it's going wrong, then it's off topic (also, Python and Java have nothing to do with what you've posted)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:40:53.523",
"Id": "496721",
"Score": "0",
"body": "i have removed the python and java tags , sorry for the mistake."
}
] |
[
{
"body": "<p><strong>Edit</strong></p>\n<p>I realized that my distinction between bottom-top and top-bottom might have caused some confusion. Going top to bottom and bottom to top is the exact same thing, just switched the starting and end points. I just made a habit of thinking about it differently. It's an unnecessary distinction (sorry for any confusion). But the general algorithm is the same.</p>\n<p>More detailed explanation:</p>\n<p>Just as explained below, you can start at 96234. You check the ways to get to 9623<strong>3</strong>. There is only one way (subtract 1) so it is automatically the least moves. The numbers of moves it takes is 1 + number of moves takes to get to 96234, which is 0. So you store 1 into 96233. You do the same thing for 96232, 96231...</p>\n<p>...You get to 32078, you check the paths to get there, /3 from 96234, /2 from 64156, -1 from 32079. The paths each have moves 1, 32079, and 64156 respectively. You store the smallest into the current slot.</p>\n<p>Eventually, you get to 1, and you compare the values stored at slots 2,2,and 3. You return the lowest one + 1.</p>\n<p><strong>Previous Answer</strong></p>\n<p>Shouldn't you be going from bottom to top? Your code is doing exactly what you're telling it to do. You check if <code>n%2==0</code> first, before you ever do <code>n=n-1</code>. That works most of the time, but as you can see, sometimes n-1 is less moves.</p>\n<p>You won't be able to know which is the best operation if you go from top to bottom.</p>\n<p>Instead, you should start at 1, and calculate the least amount moves it takes to get to 2,3,4... all the way to 96234. This is still of O(n), and memory wise, it is O(n) although I think you can get it down with a trick (not sure).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T07:43:23.433",
"Id": "496740",
"Score": "0",
"body": "Yeah i get my mistake but not able to think about logic how could i go form top to bottom ??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T07:46:17.697",
"Id": "496741",
"Score": "0",
"body": "Top to bottom would be more tree recursion than dp, if I'm not mistaken. since at every step you have to check potentially three options, (divide 3, divide 2, subtract 1)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T07:53:30.727",
"Id": "496742",
"Score": "0",
"body": "is there an easy approch so i could go towars solution :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:53:31.190",
"Id": "496816",
"Score": "0",
"body": "Please don't answer questions that are off topic, instead [flag](https://codereview.stackexchange.com/help/privileges/flag-posts) them for problems so certain members of the community can decide what to do :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:53:41.490",
"Id": "252169",
"ParentId": "252166",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252169",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-15T23:34:46.890",
"Id": "252166",
"Score": "1",
"Tags": [
"c++",
"programming-challenge",
"dynamic-programming"
],
"Title": "Code A Primitive Calculator ( x3,x2,+1) Using Dynamic programming"
}
|
252166
|
<p>I wrote a logger module in C, that is essentially a printf wrapper + some additional color coding:</p>
<p><a href="https://i.stack.imgur.com/xqIgc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xqIgc.png" alt="" /></a></p>
<p>I'd like get feedback how I can improve performance and also use better coding style. Right now, I feel like a lot of the code is redundant/can be written in a better way.</p>
<p><strong>log.c</strong></p>
<pre><code>#include <stdarg.h>
#include <stdio.h>
#include <time.h>
#include "log.h"
bool time_prefix = false;
void log_use_time_prefix(bool toggle)
{
time_prefix = toggle;
}
void log_info(char *format_string, ...)
{
va_list args1;
va_start(args1, format_string);
va_list args2;
va_copy(args2, args1);
char buf[1 + vsnprintf(NULL, 0, format_string, args1)];
va_end(args1);
vsnprintf(buf, sizeof buf, format_string, args2);
va_end(args2);
if (time_prefix)
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%d:%d:%d \033[0m\033[1;34m[INFO]\033[0m %s", tm.tm_hour, tm.tm_min, tm.tm_sec, buf);
}
else
{
printf("\033[0m\033[1;34m[INFO]\033[0m %s", buf);
}
}
void log_error(char *format_string, ...)
{
va_list args1;
va_start(args1, format_string);
va_list args2;
va_copy(args2, args1);
char buf[1 + vsnprintf(NULL, 0, format_string, args1)];
va_end(args1);
vsnprintf(buf, sizeof buf, format_string, args2);
va_end(args2);
if (time_prefix)
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%d:%d:%d \033[0m\033[1;31m[FAIL]\033[0m %s", tm.tm_hour, tm.tm_min, tm.tm_sec, buf);
}
else
{
printf("\033[0m\033[1;31m[FAIL]\033[0m %s", buf);
}
}
void log_success(char *format_string, ...)
{
va_list args1;
va_start(args1, format_string);
va_list args2;
va_copy(args2, args1);
char buf[1 + vsnprintf(NULL, 0, format_string, args1)];
va_end(args1);
vsnprintf(buf, sizeof buf, format_string, args2);
va_end(args2);
if (time_prefix)
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%d:%d:%d \033[0m\033[1;32m[PASS]\033[0m %s", tm.tm_hour, tm.tm_min, tm.tm_sec, buf);
}
else
{
printf("\033[0m\033[1;32m[PASS]\033[0m %s", buf);
}
}
void log_warning(char *format_string, ...)
{
va_list args1;
va_start(args1, format_string);
va_list args2;
va_copy(args2, args1);
char buf[1 + vsnprintf(NULL, 0, format_string, args1)];
va_end(args1);
vsnprintf(buf, sizeof buf, format_string, args2);
va_end(args2);
if (time_prefix)
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
printf("%d:%d:%d \033[0m\033[1;33m[WARN]\033[0m %s", tm.tm_hour, tm.tm_min, tm.tm_sec, buf);
}
else
{
printf("\033[0m\033[1;33m[WARN]\033[0m %s", buf);
}
}
</code></pre>
<p><strong>log.h</strong></p>
<pre><code>#include <stdbool.h>
void log_use_time_prefix(bool toggle);
void log_info(char* message, ...);
void log_error(char* message, ...);
void log_success(char* message, ...);
void log_warning(char* message, ...);
</code></pre>
<p><strong>main.c</strong></p>
<pre><code>#include "log.h"
#include <stdio.h>
#include <stdarg.h>
#include <time.h>
int main(){
log_use_time_prefix(true);
log_info("Loading level number %#x ...\n", 123456);
log_error("Failed to load level. Error code: %d\n", 123);
log_warning("Deprecated function %s used.\n", "puts");
log_success("Level loaded successfully.\n");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T11:45:55.533",
"Id": "496865",
"Score": "1",
"body": "Logger modules are like compilers. You should definitively write one to get the satisfaction and the experience to appreciate and then use what others have done."
}
] |
[
{
"body": "<p><strong>Redundant code</strong></p>\n<p>As the 4 functions are nearly identical, consider coding helper functions.</p>\n<p>At a minimum, I recommend a <code>printf_prefix(const char *ansi_color, const char *pass);</code></p>\n<p>To form a helper function of the first part with a <code>va_list</code> parameter is tricky. See below.</p>\n<p><strong>Time</strong></p>\n<p>I'd code for a fixed width time</p>\n<pre><code>// %d:%d:%d\n%02d:%02d:%02d\n</code></pre>\n<p><strong>Flush</strong></p>\n<p>For the more critical outputs like <code>fail,warn</code>, consider <code>fflush(stdout)</code> to insure data is seen.</p>\n<p><strong><code>'\\n'</code></strong></p>\n<p>Perhaps code the <code>'\\n'</code> in the print function and not oblige the user to code it. I am on the fence on this one.</p>\n<p><strong>Fixed buffer</strong></p>\n<p>The nature of failures, warnings, etc. hint that something is <em>wrong</em>. To insure things like <code>"Error, code is about to die due to blah blah blah ...."</code> gets printed out, I'd consider avoiding a VLA like <code>char buf[1 + vsnprintf(...)];</code> and use a <em>generous</em> fixed length buffer. I'd rather get a truncated noticed than have the last words of errant code fail to print due to a buffer overrun/stack-overflow.</p>\n<p><strong>Sentinels</strong></p>\n<p>When printing an <em>error</em> message, consider sentinels when printing the string. Error string sometimes are themselves dubious and good to know just were the message starts and stops.</p>\n<pre><code>//printf("... %s", ... buf);\nprintf("... \\"%s\\"\\n", ... buf);\n// ^^ ^^\n</code></pre>\n<p><strong>Error checking</strong></p>\n<p>Since this is code to debug errors, extra precaution should occur to test is the log functions themselves generate any error.</p>\n<p>Check the return value of <code>vsnprintf(), time(), localtime(), printf()</code> for potential errors.</p>\n<p>In other words, assume when printing error messages, the system itself in on <a href=\"https://news.csdpool.org/2018/10/19/dont-skate-on-thin-ice/\" rel=\"nofollow noreferrer\">thin ice</a>.</p>\n<p><strong>No color</strong></p>\n<p>Consider a global flag to print/not print the <a href=\"https://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"nofollow noreferrer\">ANSI color</a> sequences.</p>\n<p><strong>Missing include</strong></p>\n<pre><code>#include <stdarg.h>\n</code></pre>\n<p><strong><code>log.h</code> first, guards</strong></p>\n<p>For <code>log.c</code>, consider first including <code>log.h</code> before <code><></code> includes to test that <code>log.h</code> compiles on its own without additional includes.</p>\n<p>I expected the idiomatic <a href=\"https://en.wikipedia.org/wiki/Include_guard\" rel=\"nofollow noreferrer\">include guard</a> in <code>log.h</code>.</p>\n<p><strong>Sample</strong></p>\n<p>Sample code to fold in the 4 functions. See <a href=\"https://stackoverflow.com/q/3369588/2410359\">Pass va_list or pointer to va_list?</a>.</p>\n<pre><code>#include <stdbool.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <time.h>\n\nbool time_prefix = false;\n\nvoid log_general(bool time_prefix, const char *color, const char *name,\n const char *format_string, va_list *arg) {\n va_list argCopy;\n va_copy(argCopy, *arg);\n int len = vsnprintf(NULL, 0, format_string, argCopy);\n va_end(argCopy);\n if (len < 0) {\n return;\n }\n char buf[len + 1];\n len = vsnprintf(buf, sizeof buf, format_string, *arg);\n if (len < 0) {\n return;\n }\n if (time_prefix) {\n time_t t = time(NULL);\n if (t == -1) {\n return;\n }\n struct tm *tm = localtime(&t);\n if (tm == NULL) {\n return;\n }\n printf("%02d:%02d:%02d ", tm->tm_hour, tm->tm_min, tm->tm_sec);\n }\n printf("\\033[0m\\033[%sm[%s]\\033[0m %s\\n", color, name, buf);\n}\n\n\nvoid log_warning(const char *format_string, ...) {\n va_list args1;\n va_start(args1, format_string);\n log_general(time_prefix, "1;33", "WARN", format_string, &args1);\n va_end(args1);\n fflush(stdout);\n}\n\nvoid log_info(const char *format_string, ...) {\n va_list args1;\n va_start(args1, format_string);\n log_general(time_prefix, "1;34", "INFO", format_string, &args1);\n va_end(args1);\n // fflush(stdout); // No need for flush info messages.\n}\n\nint main() {\n time_prefix = true;\n log_warning("%d", 123);\n log_info("%f", 123.0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:44:10.400",
"Id": "496793",
"Score": "0",
"body": "Thanks for the detailled feedback. Definitely helpful! I am currently trying to work through your example, and I noticed that `int len = vsnprintf(NULL, 0, format_string, *arg);` segfaults for me when providing a single string with an integer value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:48:29.263",
"Id": "496796",
"Score": "0",
"body": "@766F6964 I can review code later today. BTW, did you code `&args1` as above?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:56:23.850",
"Id": "496797",
"Score": "0",
"body": "I figured out that `va_start(args1, format_string);` was missing in the `log_warning function`. However, it seems that the parameter is interpreted incorrectly as it renders to gibberish: https://i.imgur.com/WVXNq5s.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T01:07:35.813",
"Id": "496840",
"Score": "0",
"body": "@766F6964 I did not reproduce your problem. Try a cut/paste of posted code of this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T02:39:44.157",
"Id": "496844",
"Score": "1",
"body": "The whole ANSI color sequences deserves abstraction. Perhaps later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T14:07:01.773",
"Id": "496888",
"Score": "0",
"body": "Something is wrong with your example. I tried running exactly your codes, and it messes up the formatting/parameters that are passed to it: https://i.imgur.com/fpSUDFj.png\nI really wonder what causes this behaviour? My original solution did not suffer from this problem.\n\nAs for the color codes, maybe it makes sense to use the `termcap` library for this as suggested below, or at least store all color codes in an enum or an array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T14:43:12.270",
"Id": "496894",
"Score": "1",
"body": "@766F6964 Certainly it is related to passing `args1`. Will review later. I can not see the .png right now. Hopefully it shows your code and what compiler/options you used. If not, is the code exactly as posted here? What compiler/options used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T14:50:39.337",
"Id": "496895",
"Score": "1",
"body": "The compiler options are the default ones of gcc. Essentially just running `gcc -o logger logger.c`. I was also able to reproduce the same problem on a different machine (Ubuntu VM). The code is exactly yours, 1:1. I'll play around with some more compiler options and see if that helps to pinpoint the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T11:51:53.150",
"Id": "497017",
"Score": "1",
"body": "@766F6964 1) I am confident that some form of `va_..., vsprintf()` will work where the lion share of code is in `log_general()`. 2) I, so far, failed to reproduce your failing output 3) As answered \"va_list parameter is tricky\" It is easy to post something that \"works\", yet not portable. 4) `log_general()` may need to use `va_copy()`. See posted alternate code - both work for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T12:02:56.890",
"Id": "497019",
"Score": "1",
"body": "@766F6964 On review, I am more certain that my initial lack of `va_copy` with a 2nd `vsnprintf()` call is the oops. `va_copy` appears necessary. What are your results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-18T14:32:56.117",
"Id": "497032",
"Score": "1",
"body": "Yeah, the second version of the `log_general` function results in the expected behaviour. :)"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T04:24:00.453",
"Id": "252174",
"ParentId": "252171",
"Score": "11"
}
},
{
"body": "<p>Yes, there is a plenty of redundancy here. Let's start with <code>if (time_prefix)</code> part. Consider</p>\n<pre><code> if (time_prefix) {\n printf("%d:%d:%d ", tm.tm_hour, tm.tm_min, tm.tm_sec);\n }\n printf("\\033[0m\\033[1;34m[INFO]\\033[0m %s", buf);\n</code></pre>\n<p>Next step is to unify <code>INFO, WARNING, ERROR, SUCCESS</code>. All of them are identical, except the coloured prefix. Factor out the functionality, and pass the prefix down, e.g.</p>\n<pre><code> void log_info(char* format_string, ...)\n {\n va_list args;\n va_start(args, format_string);\n do_log(INFO_PREFIX, format_string, args);\n }\n</code></pre>\n<p>etc, with</p>\n<pre><code>void do_log(char prefix, char format_string, va_list args)\n{\n if (time_prefix) {\n printf("%d:%d:%d ", tm.tm_hour, tm.tm_min, tm.tm_sec);\n }\n printf("\\033[0m\\033[1;34m[INFO]\\033[0m %s", buf);\n \n char buf[1 + vsnprintf(NULL, 0, format_string, args)];\n vsnprintf(buf, sizeof buf, format_string, args);\n va_end(args);\n}\n</code></pre>\n<p>It is worth noticing that neither of your functions invoke <code>va_arg()</code>. It means that from the function standpoint <code>va_list</code> never changes. <code>va_copy</code> is not necessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T04:25:18.737",
"Id": "252175",
"ParentId": "252171",
"Score": "5"
}
},
{
"body": "<p>Output stream is not necessarily a terminal, and even if it is, it's not necessarily an ANSI terminal.</p>\n<p>Hard-coding those terminal control sequences makes it harder to process the output with other tools such as <code>grep</code>.</p>\n<p>Libraries such as <code>termcap</code> exist to abstract the handling of terminal escapes, so that your program adapts to what it's connected to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T14:58:54.003",
"Id": "496897",
"Score": "0",
"body": "Thanks for the suggestion. I am a bit hesitant to add another dependency. What is the advantage of `termcap` of, say, storing all the color-bound escape sequences in an array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T15:19:29.427",
"Id": "496899",
"Score": "0",
"body": "The main advantage is that all the work of identifying different terminals and recording the necessary control sequences for each one (and keeping all the data updated) is already done for you. Like most libraries, it saves a lot of developer time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T11:39:17.053",
"Id": "252181",
"ParentId": "252171",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "252174",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T02:29:20.817",
"Id": "252171",
"Score": "13",
"Tags": [
"c",
"console",
"formatting",
"logging"
],
"Title": "Logger module in C"
}
|
252171
|
Coronavirus disease 2019 (COVID-19) is a contagious respiratory and vascular disease caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T03:12:36.650",
"Id": "252173",
"Score": "0",
"Tags": null,
"Title": null
}
|
252173
|
<p>I have the following models:</p>
<pre><code>class Client(BaseModel):
#other fields
engineers = models.ManyToManyField(Engineer, null = True, blank = True, related_name='clients')
class OrganizationMember(MPTTModel):
designation = models.CharField(max_length = 100, blank = True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.SET_NULL)
</code></pre>
<p>Now I would like to get <code>all engineers</code> of a <code>client</code> instance and check if each <code>engineer</code> has an <code>organizationmember</code> instance or not.
Then if they belong to some organization then I should <code>get_ancestors</code> of that <code>organizationmember</code> and then the users.
If they do not have any <code>organizationmember</code> then just get the user of that engineer instance.</p>
<p>For this I have written a method in <code>Client</code> model as below:</p>
<pre><code>class Client(BaseModel):
def get_users_from_engineers(self):
users_in_organization = []
users_outside_organization = []
engineers = self.engineers.all()
if engineers:
for engineer in engineers:
user = engineer.user
if hasattr(user, "organizationmember"):
users_in_organization += [orgmember.user for orgmember in user.organizationmember.get_ancestors(include_self=True)]
else:
users_outside_organization.append(user)
</code></pre>
<p>Now this code is working correctly but I am sure that I can use django filters here instead of two <code>for</code> loops and optimize this code. But I do not know how.</p>
<p>For eg:</p>
<pre><code>OrganizationMember.objects.filter(user__engineer__in=self.engineers.all())
</code></pre>
<p>can be used to get all the <code>organizationmembers</code> of the <code>engineers</code> of that particular <code>client</code> instance. But I need the users of those <code>organizationmembers</code>.
Also if I use <code>get_ancestors</code> on multiple engineers then more than one engineer might have the same ancestor thereby adding the same person more than once in the <code>users_in_organization</code> list. How can I rectify this if I use django filters?</p>
<p>Edit:</p>
<p>In the method <code>get_users_from_engineers</code> I can also use as follows:</p>
<pre><code>users_outside_organization = list(User.objects.filter(engineer__in=engineers, organizationmember__isnull=True)
</code></pre>
<p>But I do not know how to get the <code>users_in_organization</code> values as stated above using django orm methods.</p>
<p>Note: This is my first question in <strong>codereview</strong>. I do not know if this question should be asked here or in <strong>stackoverflow</strong> since I already have a working code. Anyway I have asked the same question in <strong>stackoverflow</strong> also. Please feel free to correct me regarding the same.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T08:12:09.940",
"Id": "496743",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:00:30.603",
"Id": "496757",
"Score": "0",
"body": "I have changed the title of the question now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T10:55:28.290",
"Id": "496763",
"Score": "1",
"body": "Your title is still about your code, and not what it does. There are mentions of organizations and members in your code: that is what your code's function is, not general things like \"getting data\". Look at the link I posted, look at other questions here. Please follow the guidelines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T12:33:22.867",
"Id": "496771",
"Score": "0",
"body": "@BCdotWEB I have made further changes to the title as per the guidelines and your suggestions in the comments."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T05:04:23.970",
"Id": "252176",
"Score": "1",
"Tags": [
"django"
],
"Title": "Get user and users of ancestors of a model instance if it has `organizationmember` attribute or else only user of the instance in Django"
}
|
252176
|
<p>I have a project, for which I use Tokenauthentication with JWT Tokens. I am relatively new to Angular Development and rxjs in particular, so there are a lot of concepts I am likely not yet familiar with or can't apply properly. My Backend is Django 3, using the Django Rest Framework and rest_framework_simplejwt.</p>
<p>What the interceptor is doing is check any outgoing HTTP request on if it's a call to my API. If it is, attach the JWT Token. If it is and the Access Token is expired, refresh the Access Token first, then send the call to the API. I haven't yet coded in the scenario on what to do if the Refresh Token expires/is close to expiring but I'm doing this step by step and that's next on the list.</p>
<p>I don't like my code here. It's hard for me to grasp to the point I need comments to make it easier. An even bigger problem is that I don't fully understand the code and thus am struggling to split the intercept function into smaller chunks to move into their own functions.</p>
<p>What could I be doing to make it more comprehensible? What could I "split off" into some nicely named function?</p>
<p>Here the code:</p>
<pre><code>//jwt-interceptor.ts
@Injectable()
export class JWTInterceptor implements HttpInterceptor{
private tokenRefreshInProgress: boolean = false;
private refreshAccessTokenSubject: Subject<any> = new BehaviorSubject<any>(null);
constructor(private userService: UserService){}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
if (this.isApiUrl(request.url)){
const accessToken = this.userService.getAccessToken();
//Below: If Access Token Expired and no refresh of it currently running
if(this.userService.isTokenExpired(accessToken) && !this.tokenRefreshInProgress){
this.tokenRefreshInProgress = true;
this.refreshAccessTokenSubject.next(null);
return this.userService.refreshToken().pipe(
switchMap(authResponse => {
this.userService.setAccessToken(authResponse.access);
this.tokenRefreshInProgress = false;
this.refreshAccessTokenSubject.next(authResponse.access);
request = this.addTokenToRequest(authResponse.access, request);
return next.handle(request);
})
)
//Below: If Access Token is expired and a refresh of it already running
} else if(this.userService.isTokenExpired(accessToken) && this.tokenRefreshInProgress){
return this.refreshAccessTokenSubject.pipe(
filter(result => result !== null),
first(),
switchMap(response => {
request = this.addTokenToRequest(this.userService.getAccessToken(), request);
return next.handle(request);
})
)
//Below: If Access Token Valid
} else {
request = this.addTokenToRequest(accessToken, request);
}
}
return next.handle(request);
}
isApiUrl(url: string): boolean{
const isApiUrl: boolean = url.startsWith(Constants.wikiApiUrl);
const isTokenLoginUrl: boolean = url.endsWith('/token');
const isTokenRefreshUrl: boolean = url.endsWith('/token/refresh');
return isApiUrl && !isTokenLoginUrl && !isTokenRefreshUrl;
}
addTokenToRequest(token: string, request: HttpRequest<any>): HttpRequest<any>{
const httpHeaders = new HttpHeaders().set("Authorization", `Bearer ${token}`);
request = request.clone({headers: httpHeaders});
return request;
}
}
//methods from UserService class in user.service.ts
isTokenExpired(token: string): boolean{
const [encodedHeader, encodedPayload, encodedSignature] = token.split('.');
const payload = JSON.parse(atob(encodedPayload));
const expiryTimestamp = payload.exp;
const currentTimestamp = Math.floor((new Date).getTime()/1000);
return currentTimestamp >= expiryTimestamp;
}
getRefreshToken(): string{
return localStorage.getItem('refresh_token');
}
getAccessToken(): string{
return localStorage.getItem('access_token');
}
setAccessToken(accessToken: string): void{
localStorage.setItem('access_token', accessToken);
}
refreshToken(): Observable<{access: string, refresh: string}>{
const refreshToken = this.getRefreshToken();
return this.http.post<{access, refresh}>(Constants.wikiTokenRefreshUrl, {refresh: refreshToken});
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Short explanation of the code</h1>\n<p>If the token is expired and not yet requested, the process is quite straight:</p>\n<ul>\n<li>Change <code>tokenRefreshInProgress</code> status to true so that other interceptions will know that and do not trigger the refresh also</li>\n<li>The <code>refreshAccessTokenSubject</code> BehaviorSubject gets set to null</li>\n<li>Refresh the token and as soon as we get a result\n<ul>\n<li>set the token</li>\n<li>change the <code>tokenRefreshInProgress</code> to false</li>\n<li>store the token in our BehaviorSubject.</li>\n<li>add the token to the current request</li>\n<li>and now finally execute the current request and we return that observable of the request</li>\n</ul>\n</li>\n</ul>\n<p>If the token is expired but already requested</p>\n<ul>\n<li>Listen to the <code>refreshAccessTokenSubject</code> and wait until it sends an event\n<ul>\n<li>The first event is the current value in the BehaviorSubject, most likely a "null" (because the token refresh is still in progress), that event gets filtered out by <code>filter</code> .</li>\n<li>The second event is the refreshed token, that will pass the filter</li>\n<li>We are only interested in that token, so with ''first'' we take the first that passed the filter (the event reached the <code>first</code> pipe) and after processing that we stop listening to the BehaviorSubject</li>\n<li>Now we switch from the stream of the BehaviorSubject to a new Stream\n<ul>\n<li>We add the token to the current request</li>\n<li>and now we finally handle the current request and return the observable of that request</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<h1>Things I would change</h1>\n<h2>Danger of multiple instances</h2>\n<p>Be aware that there may be multiple instances of your interceptor if you import HTTPCLientModule multiple times (see <a href=\"https://angular.io/api/common/http/HttpInterceptor\" rel=\"noreferrer\">HTTPInterceptor documentation</a>).</p>\n<p>There are two ways of handling that.</p>\n<ul>\n<li>Hope that nobody will add the HTTPClientModule ever somewhere else.</li>\n<li>Extract the logic into a class and make it a singleton (having a service with <code>Injectable( {providedIn: 'root'})</code> makes it a singleton the easy way)</li>\n</ul>\n<h2>Access Modifier</h2>\n<p>I would always use access modifiers (<code>public / private</code>). Yes, if none is mentioned it's <code>publi</code>c by default. But the reader does not know if its public by intention or if the developer has missed the <code>private</code> modifier.</p>\n<h2>Add Types whereever possible</h2>\n<p>I love typed variables, therefore, I would take the extra step to create custom types if none are provided</p>\n<h2>RxJs side effects</h2>\n<p>There are some side effects (like changing the status or changing the Behavior Subject. I would move those into a <code>tap</code> to make it more obvious that those are wished side effects and that we are aware of that.</p>\n<h2>Omit else parts</h2>\n<p>I personally omit the <code>else</code> part, when the if part clearly returns out of the method (<code>return</code>). With "clearly" I mean that when I read the <code>if</code> that I already see the <code>return</code>, that means the <code>if</code> block may only be 1-3 lines long.<br />\nIn this case, the blocks are a bit longer because of the pipe and the switchMap, but the return is on the first line after the <code>if</code> statement, so the approach is still okay for me.</p>\n<h2>Changed Code</h2>\n<p>I would move each exported element into its own file, to separate them more clearly</p>\n<pre><code>export interface AccessToken{\n ...\n}\n\nInjectable()\nexport class JWTInterceptor implements HttpInterceptor {\n\n constructor(private refreshToken: RefreshTokenService) {\n }\n\n public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n if (this.isApiUrl(request.url)) {\n return this.refreshToken.handleRequest(request, next);\n }\n return next.handle(request);\n }\n\n private isApiUrl(url: string): boolean{\n const isApiUrl: boolean = url.startsWith(Constants.wikiApiUrl);\n const isTokenLoginUrl: boolean = url.endsWith('/token');\n const isTokenRefreshUrl: boolean = url.endsWith('/token/refresh');\n return isApiUrl && !isTokenLoginUrl && !isTokenRefreshUrl;\n }\n}\n\nInjectable({\n providedIn: 'root'\n})\nexport class RefreshTokenService{\n private tokenRefreshInProgress: boolean = false;\n private refreshAccessTokenSubject: Subject<AccessToken> = new BehaviorSubject<AccessToken>(null);\n\n constructor(private userService: UserService){}\n\n public handleRequest(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n const accessToken: AccessToken = this.userService.getAccessToken();\n\n if(this.tokenNeedsRefresh(accessToken)){\n return this.refreshToken().pipe(\n switchMap((token:AccessToken) => {\n request = this.addTokenToRequest(token, request);\n return next.handle(request);\n })\n )\n }\n if(this.hasToWaitForRefresh(accessToken)){\n return this.waitForRefreshToken.pipe(\n switchMap((token:AccessToken) => {\n request = this.addTokenToRequest(token, request);\n return next.handle(request);\n })\n )\n } \n\n request = this.addTokenToRequest(accessToken, request);\n return next.handle(request);\n }\n\n private tokenNeedsRefresh(accessToken: AccessToken):boolean{\n return this.userService.isTokenExpired(accessToken) && !this.tokenRefreshInProgress\n }\n\n private hasToWaitForRefresh(accessToken: AccessToken):boolean{\n return this.userService.isTokenExpired(accessToken) && this.tokenRefreshInProgress\n }\n\n // Completes after first event\n private refreshToken():Observable<AccessToken>{\n return this.userService.refreshToken().pipe(\n map((authRespose):AccessToken => authRespose.access),\n tap((token:AccessToken) => {\n this.userService.setAccessToken(token);\n this.tokenRefreshInProgress = false;\n this.refreshAccessTokenSubject.next(token);\n })\n );\n }\n\n // Completes after first event\n private waitForRefreshToken():Observable<AccessToken>{\n return this.refreshAccessTokenSubject.pipe(\n filter(result => result !== null),\n first()\n )\n }\n\n private addTokenToRequest(token: string, request: HttpRequest<any>): HttpRequest<any>{\n const httpHeaders = new HttpHeaders().set("Authorization", `Bearer ${token}`);\n request = request.clone({headers: httpHeaders});\n return request;\n }\n}\n</code></pre>\n<p>At least that would be my approach. Three developers -> four approaches. And all are kind of valid :-)<br />\nPick the parts you like and ignore the rest :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T12:39:54.030",
"Id": "496873",
"Score": "0",
"body": "Thank you very much! This is helping (and teaching) me tons! Would have never thought of the potential stumbling block of the multiple interceptor instances as e.g. I'm importing the HTTPClientModule in root, but it's a valid point ! I'll accept this answer and likely add a reply later attempting to apply the suggestions from you that I can! I particularly liked how you managed to split off the event handling from the logic to decide when to do the event handling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T12:47:37.923",
"Id": "496874",
"Score": "0",
"body": "Sidenote though. Previously (because it wasn't *that* much code) I had just thrown in the logic around Refreshtokens into my service for fetching and manipulating user data (for now I'm only at the stage that I'm fetching it, if at all). Since I am now moving this into its own service, wouldn't it also make sense to move the entire logic of setting and retrieving tokens into the refresh-token-service?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T12:57:29.957",
"Id": "496877",
"Score": "0",
"body": "Oh also, is it syntactically possible to not have the switchmap end on \"return next handle\" but instead just add the token to the request and be done in the switchmap at that point?\nThis way, the logic would always flow to the one \"return next.handle(request)\" at the end, avoiding that I repeat that line. I'll be experimenting with this either way, I just don't know if that's somehow complicated... I really don't have a solid grasp on rxjs yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T12:58:21.047",
"Id": "496878",
"Score": "0",
"body": "When a file gets bigger, then i evaluate the \"complexity\" of the code and if its not VERY simple (i accept a 400 row switch statement as simple), i try to split it. Therefor i would seperate the logic for retrieving the token from the refreshing. I would move both services near each other, but still keep them in seperate files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T13:24:10.217",
"Id": "496881",
"Score": "0",
"body": "In theory you could try to have multiple event sources, combining them into one stream and handle the request manipulation there. Then, depending on the context, trigger the sources. But i would assume its much more complicated. For learning purpose, take a look at \"https://rxjs-dev.firebaseapp.com/operator-decision-tree\". It provides solutions for different situations"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T15:27:47.647",
"Id": "496901",
"Score": "0",
"body": "Thank you very much for your time and help! The solution that I ended up with followed pretty much your suggestions, but with the added constraint that I didn't want the refreshTokenService to handle any of the logic for handling the request."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T07:55:53.453",
"Id": "252233",
"ParentId": "252180",
"Score": "5"
}
},
{
"body": "<p>Thanks to the efforts of Jan Recker I gained a much better understanding of what was happening there. I followed all of his suggestions, but arrived at a different final code structure. My main difference was, that I also wanted <code>jwt-interceptor.ts</code> to contain <strong>all</strong> logic about handling the request and <code>refresh-token.service.ts</code> to only care about logic about refreshing tokens.</p>\n<p>Thus I gained 4 files:</p>\n<ol>\n<li>jwttoken.ts - Contains the models/interfaces</li>\n<li>jwt-interceptor.ts - Contains the Interceptor and all logic to handle requests</li>\n<li>refresh-token.service.ts - Contains all logic specific to refreshing tokens</li>\n<li>token.service.ts - Contains logic to generally handle tokens</li>\n</ol>\n<p><strong>jwttoken.ts</strong></p>\n<pre><code>export interface EncodedJWTToken{\n access: string,\n refresh: string,\n}\n\nexport interface DecodedTokenPayload{\n exp: number,\n jti: string,\n token_type: string,\n user_id: number,\n}\n</code></pre>\n<p><strong>jwt-interceptor.ts</strong></p>\n<pre><code>@Injectable()\nexport class JWTInterceptor implements HttpInterceptor{\n constructor(\n private refreshTokenService: RefreshTokenService,\n private tokenService: TokenService\n ){}\n\n public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{\n if (this.isApiUrl(request.url)){\n const accessToken = this.userService.getAccessToken();\n\n if (this.refreshTokenService.tokenNeedsRefresh(accessToken)){\n return this.handleByRefreshingAccessToken(request, next);\n }\n\n if (this.refreshTokenService.hasToWaitForRefresh(accessToken)){\n return this.handleByWaitingForRefresh(request, next);\n }\n\n request = this.addTokenToRequest(accessToken, request);\n return next.handle(request);\n } \n\n return next.handle(request);\n }\n\n private handleByRefreshingAccessToken(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{\n return this.refreshTokenService.refreshAccessToken().pipe(\n switchMap((newAccessToken: string) => {\n request = this.addTokenToRequest(newAccessToken, request);\n return next.handle(request);\n }),\n )\n }\n \n private handleByWaitingForRefresh(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{\n return this.refreshTokenService.waitForAccessTokenRefresh().pipe(\n switchMap((newAccessToken: string) => {\n request = this.addTokenToRequest(newAccessToken, request);\n return next.handle(request);\n })\n )\n }\n\n private isApiUrl(url: string): boolean{\n const isApiUrl: boolean = url.startsWith(Constants.wikiApiUrl);\n const isTokenLoginUrl: boolean = url.endsWith('/token');\n const isTokenRefreshUrl: boolean = url.endsWith('/token/refresh');\n return isApiUrl && !isTokenLoginUrl && !isTokenRefreshUrl;\n }\n\n private addTokenToRequest(token: string, request: HttpRequest<any>): HttpRequest<any>{\n const httpHeaders = new HttpHeaders().set("Authorization", `Bearer ${token}`);\n request = request.clone({headers: httpHeaders});\n return request; \n }\n}\n</code></pre>\n<p><strong>refresh-token.service.ts</strong></p>\n<pre><code>@Injectable({\n providedIn: 'root'\n})\nexport class RefreshTokenService {\n private tokenRefreshInProgress: boolean = false;\n private refreshAccessTokenSubject: Subject<string> = new BehaviorSubject<string>(null);\n\n constructor(private tokenService: TokenService) { }\n\n public refreshAccessToken(): Observable<string>{\n return this.tokenService.refreshToken().pipe(\n map((tokenResponse: EncodedJWTToken) => tokenResponse.access),\n tap((accessToken: string) => {\n this.tokenService.setAccessToken(accessToken);\n this.tokenRefreshInProgress = false;\n this.refreshAccessTokenSubject.next(accessToken);\n })\n )\n }\n\n public waitForAccessTokenRefresh(): Observable<string>{\n return this.refreshAccessTokenSubject.pipe(\n filter(result => result !== null),\n first()\n )\n }\n\n public tokenNeedsRefresh(accessToken: string): boolean{\n return this.tokenService.isTokenExpired(accessToken) && !this.tokenRefreshInProgress;\n }\n\n public hasToWaitForRefresh(accessToken: string): boolean{\n return this.tokenService.isTokenExpired(accessToken) && this.tokenRefreshInProgress;\n }\n}\n\n</code></pre>\n<p><strong>token.service.ts</strong></p>\n<pre><code>@Injectable({\n providedIn: 'root'\n})\nexport class TokenService {\n private jwtTokenUrl: string = Constants.wikiTokenUrl;\n private refreshTokenUrl: string = Constants.wikiTokenRefreshUrl;\n\n constructor(private http: HttpClient, private router: Router) { }\n\n public getAccessToken(): string{\n return localStorage.getItem(Constants.accessTokenKey);\n }\n\n public refreshToken(): Observable<EncodedJWTToken>{\n const refreshToken = this.getRefreshToken();\n return this.http.post<EncodedJWTToken>(this.refreshTokenUrl, {refresh: refreshToken});\n }\n\n public setAccessToken(token: string): void{\n if(this.decodeTokenPayload(token).token_type !== Constants.accessTokenType){\n throw "The Token you are trying to set as an Access Token is not an Access Token. Something is incorrectly handled about JWT token storage!"\n }\n localStorage.setItem(Constants.accessTokenKey, token);\n }\n\n public isTokenExpired(token: string): boolean{\n const payload: DecodedTokenPayload = this.decodeTokenPayload(token);\n const expiryTimestamp = payload.exp;\n const currentTimestamp = Math.floor((new Date).getTime()/1000);\n return currentTimestamp >= expiryTimestamp;\n }\n\n public decodeTokenPayload(token: string): DecodedTokenPayload{\n const [encodedHeader, encodedPayload, encodedSignature]: string[] = token.split('.');\n return JSON.parse(atob(encodedPayload));\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T15:26:02.253",
"Id": "252252",
"ParentId": "252180",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "252233",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T09:18:01.540",
"Id": "252180",
"Score": "4",
"Tags": [
"typescript",
"angular-2+",
"rxjs"
],
"Title": "Angular10 RxJS - Interceptor to add/refresh JWT Token"
}
|
252180
|
<p>So I've written a function which parses a fairly simple key-value pair syntax.
Each pair can span across multiple lines, as long as the value does not have a colon in it. If it does, then any new line must be preceded by three spaces. For each pair, I create an object with the key, the value, and the offset at which they appear (from the beginning of the string).</p>
<p>You can get a better idea of this syntax from the following image (keys in blue, values in green):</p>
<p><a href="https://i.stack.imgur.com/5TVbY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5TVbY.png" alt="enter image description here" /></a></p>
<p>I thought about using regex, but seeing as I also need to keep track of the offsets for each item, and performance is extremely important - I thought it may be easier/more efficient to just use plain typescript. Here's the function I came up with:</p>
<pre class="lang-js prettyprint-override"><code>function parseTitlePageChunk(text: string):{key:string, value:string, keyoffset:number, valueoffset:number}[] {
console.time("pairs");
let pairs = [];
let potentialValue = ""; //keep track of a string which may be a key
let potentialKey = ""; //keep track of a string which may be a value
let potentialKeyOffset = 0;
let potentialValueOffset = 0;
let colonInLine = false;
let forceValue = false; //true if a line starts with three spaces
let spaceCounter = -1; //if the spaceCounter==-1 there's no more spaces at the beginning of the line
for (let i = 0; i < text.length; i++) {
let c = text[i];
if (c == ':' && !colonInLine && !forceValue) {
//We ran into a colon, promote the potential key to an actual one
pairs.push({key: potentialKey, value:"", keyoffset:potentialKeyOffset, valueoffset:potentialValueOffset});
potentialValue = ""; //reset the potential value
potentialValueOffset = i+1; //reset the potential value offset
colonInLine = true;
}
else if (c == '\n' && pairs.length > 0) {
//we hit a new line, and there exists a previous key
pairs[pairs.length - 1].value = potentialValue; //set the value of the previous key
pairs[pairs.length - 1].valueoffset = potentialValueOffset;
potentialValue += '\n';
potentialKey = "\n";
potentialKeyOffset = i;
colonInLine = false;
forceValue = false;
spaceCounter = 0;
}
else {
if(spaceCounter!=-1 && c == ' '){
spaceCounter++;
}
else{
spaceCounter = -1;
}
potentialValue += c;
potentialKey += c;
if(spaceCounter>=3) forceValue=true;
}
}
if (pairs.length > 0) {
//add the last potential value as a key
pairs[pairs.length - 1].value = potentialValue;
pairs[pairs.length - 1].valueoffset = potentialValueOffset;
}
console.timeEnd("pairs");
return pairs;
}
</code></pre>
<p>Here's a sample input:</p>
<pre><code>Key: in-line value
Key2: in-line value: with a colon
Key3: multi-line value
which continues here
Key4: multi-line value which
continues here: has a colon
yet is still a value
</code></pre>
<p>which outputs the following (stringified to JSON):</p>
<pre><code>[{
"key": "Key",
"value": " in-line value",
"keyoffset": 0,
"valueoffset": 4
}, {
"key": "\nKey2",
"value": " in-line value: with a colon",
"keyoffset": 18,
"valueoffset": 24
}, {
"key": "\nKey3",
"value": " multi-line value\nwhich continues here",
"keyoffset": 52,
"valueoffset": 58
}, {
"key": "\nKey4",
"value": " multi-line value which\n continues here: has a colon\n yet is still a value\n",
"keyoffset": 96,
"valueoffset": 102
}]
</code></pre>
<p>It works pretty flawlessly as far as I can tell, and seems quite efficient (it's only iterating through the string once), but I also find it's a little overcomplicated for what seems like a fairly simple task. However I can't figure out how to simplify it any further. Thoughts?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T11:59:18.137",
"Id": "496867",
"Score": "0",
"body": "Java .properties files use a backslash `key: xxx/` new line `__yyy/` new line `__zz`. Which seems a bit more safe. But that is a matter of taste."
}
] |
[
{
"body": "<p><strong>Readability</strong></p>\n<p>Depending on how often this function is going to be called you could opt for a more readable version that may be slightly less performant. Using functions like <code>split</code> and <code>map</code> you could make this pretty simple. Here is an example below.</p>\n<pre><code>// Start with kvp strings and newline kvp strings.\nvar texts = [\n "key1: value1\\r\\nkey2: value2",\n "key3: value3",\n "key4: value4\\r\\nkey5: value5"\n];\n\n// Splits the newlines into their own kvp strings.\ntexts = texts.map(function (text) {\n return text.split("\\r\\n");\n}).reduce(function (finalArray, arrayContainingArrays) { \n // Pro-tip: Do not name these parameters a and b, it helps no one.\n return finalArray.concat(arrayContainingArrays);\n});\n\n// Now that we don't have to worry about newlines anymore.\nvar texts = [\n "key1: value1",\n "key2: value2",\n "key3: value3",\n "key4: value4",\n "key5: value5",\n // etc.\n];\n\n// Map each kvp string by splitting on colon.\nvar kvps = texts.map(function (text) { \n var parts = text.split(":");\n // Split usually returns an array of at least one object, but something like "".split("") can return an empty array, so if there's an empty array set the value to [text].\n parts = parts.length > 0 ? parts : [text];\n // Shift(): Removes the first item in the array and returns it.\n var key = parts.shift(); \n // Join on colon in case there were multiple colons (e.g. "key1: value1:hello" would result in { key: "key1", value: "value1:hello" }).\n // Additionally, if text doesn't contain a colon, add it as the key with an undefined value (e.g. "Hello World!" will become (e.g. { key: "Hello World!", value: undefined }).\n var value = parts.length > 0 ? parts.join(":").trim() : undefined;\n return { key: key, value: value };\n});\n</code></pre>\n<p>Now, I want to state, I may have missed some of the functionality your function does and honestly, that's okay, I've written this for you to see an alternate path, not to necessarily walk you through that alternate path.</p>\n<p><strong>Other Notes</strong></p>\n<ul>\n<li>I used <code>\\r\\n</code> instead of just <code>\\n</code>, it's what I'm used to typing, working in a Windows environment.</li>\n<li>Not only is the way outlined above more readable, but it doesn't have any opportunities for those pesky "off by 1" errors.</li>\n<li>I've never written any TypeScript, but it doesn't seem like you're taking much advantage of TypeScript aside from the function declaration.</li>\n<li>Don't accept this as an answer, it is really just a note on readability. Someone that better knows TypeScript should write a code review.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T14:35:50.787",
"Id": "496784",
"Score": "0",
"body": "Thanks! It'll be run pretty often (on every keypress) so I'd rather keep it as performant as possible - but it's a good point about \\r\\n, I haven't actually tested it properly with anything other than LF line endings.\nAbout typescript, it's true I'm not really taking advantage of it much, but that's because it's all pretty straightforward code. As far as I can tell there's not really many occasions to utilize it, so yeah it's pretty much just javascript at this point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T00:16:41.317",
"Id": "496838",
"Score": "1",
"body": "@user2950509 IMO, TypeScript shines best when the code that is written looks almost identical to JavaScript. That way, it's as easy to understand as JS, except with the added bonus that it warns you when you attempt to use a certain value unsafely. Code with lots of TypeScript syntax (while sometimes necessary) can be harder to read and is sometimes an indication of over-engineering."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-25T13:02:36.890",
"Id": "497891",
"Score": "0",
"body": "To whoever downvoted me, I would appreciate a comment on why I was downvoted. Is something I wrote incorrect?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T14:26:19.603",
"Id": "252186",
"ParentId": "252184",
"Score": "0"
}
},
{
"body": "<p>Regular expressions <em>are</em> a good solution here:</p>\n<ul>\n<li>They are often more performant than manually messing with indicies and checking values, especially when the logic to implement isn't trivial</li>\n<li>Their logic is much easier to understand at a glance than a long chunk of code</li>\n<li>The indicies of each match can be kept track of by checking the length of the full match</li>\n</ul>\n<p>For this problem, you may use:</p>\n<pre><code>^(\\w+):(.+(?:\\n .*|\\n[^:\\n]+$)*)\n</code></pre>\n<p><a href=\"https://regex101.com/r/8NgGLZ/1\" rel=\"nofollow noreferrer\">https://regex101.com/r/8NgGLZ/1</a></p>\n<ul>\n<li><code>^(\\w+):</code> - Match the key at the beginning of a line, put it in a capture group, followed by <code>:</code></li>\n<li><code>(.+(?:\\n .*|\\n[^:\\n]+$)*)</code> - Match the value in a capture group:\n<ul>\n<li><code>.+</code> - Match anything on the first line, followed by zero or more occurrences of:\n<ul>\n<li><code>\\n .*</code> - A newline, followed by 3 spaces, followed by anything else on the line, OR:</li>\n<li><code>\\n[^:\\n]+$</code> - A newline, followed by anything but a colon or newline</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>Perform a global regular expression match using the above pattern, and then you can iterate through the capture groups:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function parseTitlePageChunk(text) {\n let currentOffset = 0;\n const pairs = [];\n const pattern = /^(\\w+):(.+(?:\\n .*|\\n[^:\\n]+$)*)/gm;\n for (const [fullMatch, key, value] of text.matchAll(pattern)) {\n pairs.push({\n key,\n value,\n keyoffset: currentOffset,\n valueoffset: currentOffset + key.length + 1, // add 1 due to the ;\n });\n currentOffset += fullMatch.length + 1; // add 1 due to the \\n that follows\n }\n return pairs;\n}\n\nconst result = parseTitlePageChunk(`Key: in-line value\nKey2: in-line value: with a colon\nKey3: multi-line value\nwhich continues here\nKey4: multi-line value which\n continues here: has a colon\n yet is still a value`);\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I compared the runtime required of the above against your original code. Using <code>.repeat(50000)</code> on the example input, this looks to run 5 to 10 times faster: 800-1500ms vs 100-150ms.</p>\n<p>Note that in my implementation, the keys do not include the newlines, which is why my indicies are one off of yours. (If you actually do want the keys to include possibly-existing prior newlines, it's a simple tweak)</p>\n<p>In TypeScript syntax, change to the following:</p>\n<pre><code>type Pair = {\n key: string;\n value: string;\n keyoffset: number;\n valueoffset: number;\n};\nfunction parseTitlePageChunk(text: string) {\n let currentOffset = 0;\n const pairs: Array<Pair> = [];\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T01:03:07.970",
"Id": "496839",
"Score": "1",
"body": "\"Their logic is much easier to understand at a glance than a long chunk of code.\" I definitely disagree with that. `^(\\w+):` Completely agree. I barely know regex and this makes sense to me. However, none of this `(.+(?:\\n .*|\\n[^:\\n]+$)*)` makes any sense at a glance. I'm not saying regex is bad, it's performant and has its place, but it's definitely incorrect to say it is any degree of easy to understand at a glance. Maybe a very very long glance lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T10:58:19.523",
"Id": "496863",
"Score": "0",
"body": "Thanks! I always underestimate how fast regular expressions are - and you're right, this is a hell of a lot faster. Running it x1000 on each keystroke, i'm getting between two to ten times the performance that my initial function is. I'm curious what the difference would be on a lower-level language though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T11:01:24.347",
"Id": "496864",
"Score": "0",
"body": "also, I replaced `for (const [fullMatch, key, value] of text.matchAll(pattern))` with `while ((match = pattern.exec(text)) !== null)` so that it isn't incompatible with any browsers which haven't implemented ECMAScript 2020"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T16:56:26.860",
"Id": "252196",
"ParentId": "252184",
"Score": "2"
}
},
{
"body": "<p>My idea is to split text for the lines and then merge them by separating different key/value pairs. Next just parse all pairs from the list. This is similar to what Shelby suggested. Here is the code for complete solution:</p>\n<pre><code>const joinUntil = (lines, test) => {\n const index = lines.findIndex(test);\n const offset = index === -1 ? Infinity : index;\n return [lines.slice(0, offset).join('\\n'), lines.slice(offset)];\n}\n\nconst normalize = (lines) => {\n if (lines.length === 0) return [];\n const stop = (line, i) => i > 0 && line.includes(':') && !line.startsWith(' ');\n const [result, rest] = joinUntil(lines, stop);\n return [result].concat(normalize(rest));\n}\n\nconst splitOnce = (str, sep) => {\n const [first, ...rest] = str.split(sep);\n return [first, rest.join(sep)];\n}\n\nconst parsePair = (str) => {\n const [key, value] = splitOnce(str, ':');\n return { [key]: value }\n}\n\nconst parse = (str) => normalize(str.split('\\n')).map(parsePair);\n\nconsole.log(parse(`Key: in-line value\nKey2: in-line value: with a colon\nKey3: multi-line value\nwhich continues here\nKey4: multi-line value which\n continues here: has a colon\n yet is still a value`));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-24T11:43:29.837",
"Id": "252587",
"ParentId": "252184",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T13:28:21.120",
"Id": "252184",
"Score": "4",
"Tags": [
"javascript",
"parsing",
"typescript"
],
"Title": "Parsing \"key: value\" format in which values can span multiple lines"
}
|
252184
|
<p>Here is a C program to print a heart star animation using a <code>while</code> loop <a href="https://github.com/albert10jp/c_learning/blob/main/heart_star_animation.c" rel="nofollow noreferrer">written by myself</a>.</p>
<p>I've tested it on <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_18.04_LTS_.28Bionic_Beaver.29" rel="nofollow noreferrer">Ubuntu 18.04</a> (Bionic Beaver) and <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_20.04_LTS_(Focal_Fossa)" rel="nofollow noreferrer">Ubuntu 20.04</a> (Focal Fossa).</p>
<p>To animate it, I print a sequence of heart star patterns in different sizes.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <unistd.h>
int main() {
int i, j, h, k = 0;
while (k < 99) {
/* code */
h = k % 3;
printf("\e[1;1H\e[2J");
printf("\e[?25l");
i = 0;
while (i < 3) {
j = 0;
while (j < (2 - i) * 2 + h) {
printf(" ");
j++;
}
j = 0;
while (j < (i + 2) * 2 - h * 2) {
printf("* ");
j++;
}
j = 0;
while (j < (2 - i) * 2 + 1 + h) {
printf(" ");
j++;
}
j = 0;
while (j < (i + 2) * 2 - h * 2) {
printf("* ");
j++;
}
printf("\n");
i++;
}
i = 0;
while (i < 9) {
j = 0;
while (j < i * 2 + h * 2) {
printf(" ");
j++;
}
j = 0;
while (j < 17 - i * 2 - h * 4) {
printf("* ");
j++;
}
printf("\n");
i++;
}
fflush(stdout);
usleep(200000);
k++;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to CodeReview! The program doesn't look too bad, however there are some ways to improve it:</p>\n<h1>Naming things</h1>\n<p>The biggest issue with your code is that there is a bunch of single-letter variable names (<code>i</code>...<code>k</code>), some magic constants (<code>2</code>, <code>3</code>, <code>4</code>, <code>17</code> and <code>99</code>), and nested <code>while</code>-loops. If I wasn't told what this program would do and didn't run it for myself, I would have no clue reading this code what it is going to do. However, if you would give (better) names to things, it might explain what everything means to the reader. That includes you yourself in the future!</p>\n<p>Let's start with the outer loop:</p>\n<pre><code>int main() {\n for (int i = 0; i < 99; i++) {\n int size = i % 3;\n clear_screen();\n draw_heart(size);\n usleep(200000);\n }\n}\n</code></pre>\n<p>Keeping <code>i</code> as a generic loop counter is OK, as this is so commonplace that a longer name is not going to make this more readable. But I renamed <code>h</code> to <code>size</code>. Then I assume you have created two functions, one for clearing the screen, and another for drawing a heart of a given size. If you now read this code, you can very quickly see that you are repeatedly drawing a heart of a varying size, without requiring any comments.</p>\n<p>Here is the function to clear the screen:</p>\n<pre><code>void clear_screen(void) {\n // Use ANSI escape codes to clear the screen\n printf("\\e[1;1H\\e[2J");\n printf("\\e[?25l");\n}\n</code></pre>\n<p>The name of the function alone is already enough to know what the function tries to do, the comment here is to explain the weird characters that are printed. Someone who doesn't recognize these escape codes now knows what these are, and can search for "ANSI escape codes" to find out more about them.</p>\n<p>The constants you have in your code could be given names, like so:</p>\n<pre><code>void draw_heart(int size) {\n static const int top_size = 3;\n static const int bottom_size = 9;\n ...\n}\n</code></pre>\n<p>And then used consistently in the calculations you use, such that if you want to change the size of the heart, you can just change these constants.</p>\n<h1>Use <code>for</code>-loops where appropriate</h1>\n<p>You are using a lot of <code>while</code>-loops in cases where you can more clearly write <code>for</code>-loops. Any time you initialize a variable, run <code>while</code> the variable satisfies some condition, and then update that variable, use <code>for</code>, like so:</p>\n<pre><code>void draw_heart(int size) {\n // Draw two small upward pointing triangles\n for (int i = 0; i < 3; i++) {\n for (int j = 0; i < (2 - i) * 2 + size; j++) {\n printf(" ");\n }\n\n ...\n }\n\n // Draw one large downward pointing triangle\n for (int i = 0; i < 9; i++) {\n ...\n }\n}\n</code></pre>\n<p>The advantage is that in one line you combine all this information, so just from reading that line you can see what the start condition is, what the end condition is and how the variable is updated every step.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:36:17.257",
"Id": "252200",
"ParentId": "252185",
"Score": "9"
}
},
{
"body": "<p>If you are going to write raw terminal codes to output, I'd advise encapsulating that into a well-named function. Few of us can tell by looking exactly what effect <code>\\e[1;1H\\e[2J\\e[?25l</code> will have.</p>\n<p>There's a lot of use of <code>while</code> loops that, while not functionally incorrect, would be more idiomatically written as <code>for</code> loops, enabling other developers to read and understand the code more quickly. E.g.</p>\n<blockquote>\n<pre><code> j = 0;\n while (j < (2 - i) * 2 + h) {\n printf(" ");\n j++;\n }\n</code></pre>\n</blockquote>\n<p>can be rewritten as</p>\n<pre><code> for (int j = 0; j < (2 - i) * 2 + h; j++) {\n printf(" ");\n }\n</code></pre>\n<p>It might be worth giving a name to the calculation <code>(2 - i) * 2 + h</code> here.</p>\n<p>If we know the upper bound for that value, we could avoid the loop, by printing a substring of a larger string:</p>\n<pre><code>char many_spaces[90]; /* my guess at largest bound */\nmemset(many_spaces, ' ', sizeof many_spaces);\n...\nprintf("%.*s", (2 - i) * 2 + h, many_spaces);\n</code></pre>\n<p>A similar trick could be used for the other loops that repeat the same string many times.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T17:38:51.083",
"Id": "252201",
"ParentId": "252185",
"Score": "5"
}
},
{
"body": "<p>Aside from anything else, like how you might want to save your output as a string and print that, the <code>usleep()</code> function is deprecated and has been removed from version 4 of the Single Unix Specification.</p>\n<p>Either use <code>nanosleep()</code>, or <code>#define _XOPEN_SOURCE</code> and <code>_POSIX_C_SOURCE</code> to values that will select a version of the system libraries that still supports <code>usleep()</code>. Otherwise, your source might not compile. I’d recommend changing to <code>nanosleep()</code> and also specifying the feature-test macros for it.</p>\n<p>So:</p>\n<pre><code>#define _XOPEN_SOURCE 700\n#define _POSIX_C_SOURCE 200809L\n\n#include <stdio.h>\n#include <unistd.h>\n\n/* ... */\n\n static const struct timespec to_sleep_200ms = {\n .tv_sec = 0,\n .tv_nsec = 200000000\n };\n \n nanosleep( &to_sleep_200ms, NULL );\n</code></pre>\n<p>In theory, defining <code>_XOPEN_SOURCE</code> is enough, but defining both is good defensive coding in case someone later defines only the other. For example, if you had specified only <code>_POSIX_C_SOURCE</code> for an older version and someone later compiled with <code>-D_XOPEN_SOURCE=700</code>, that would remove the declaration of <code>usleep()</code> and your program would no longer compile. So, specify both. That way, if anyone ever merges in a version clash, you’ll get a compilation error immediately that tells you what the bug is.</p>\n<p>In a project with more than one source file, you probably want to move the feature-test macros into a new header file or the makefile.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T15:50:20.837",
"Id": "496906",
"Score": "0",
"body": "At least in glibc stdio is buffered internally so there shouldn't be a need to buffer the output in the program itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T16:33:31.067",
"Id": "496913",
"Score": "0",
"body": "@JanDorniak The overhead is small, but there’s really no need to generate the output and buffer it all over again on every iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T16:34:42.023",
"Id": "496914",
"Score": "0",
"body": "True that. There are like three variations. Traditional speed vs memory trade-off."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T16:37:13.247",
"Id": "496916",
"Score": "0",
"body": "@JanDorniak Exactly. There’s a genuine trade-off, so I just suggest it as something to consider. On a modern system with gigabytes of RAM, I’d pretty much always trade off this little memory!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T17:07:37.973",
"Id": "496923",
"Score": "0",
"body": "even on an embedded 600 MHz ARM with 512 MB I'd make that trade-off. Considering how single-use those devices tend to be saving CPU beats saving memory unless you run out."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-17T03:58:20.203",
"Id": "252226",
"ParentId": "252185",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T13:52:39.263",
"Id": "252185",
"Score": "6",
"Tags": [
"c",
"console"
],
"Title": "Printing a heartbeat (heart star) animation"
}
|
252185
|
<p>I've written bounded spigot algorithms(<a href="https://en.wikipedia.org/wiki/Spigot_algorithm" rel="nofollow noreferrer">Spigot Algorithm</a>) for e and pi. I would like to understand if there is anything I can do to make this more efficient. I've done things already like move the carry over check to the very end, precompute values etc.</p>
<p>You run the functions and pass it the number of digits you want i.e. print(pispig(1000))`</p>
<p>The spigot algorithm for computing functions you can apply a Horner schema to is one of the coolest things I have ever learned.</p>
<pre class="lang-py prettyprint-override"><code>def espig(n):
estr = '2.'
(multq, asum, carover) = (0, 0, 0)
prec = 10 ** n
(remainders, tsum) = ([], [])
b = [x for x in range(2, n + 1)]
init = [1 for x in range(2, n + 1)]
x10 = [prec * x for x in init]
while True:
for (x, y) in zip(reversed(b), x10):
asum = carover + y
remainders.insert(0, asum % x)
tsum.insert(0, asum)
multq = asum // x
carover = multq
estr += str(int(tsum[0] // 2))
x10 = [prec * x for x in list(reversed(remainders))]
(carover, asum) = (0, 0)
(remainders, tsum) = ([], [])
if len(estr) > n:
break
return estr
def pispig(n):
e = n
xfact = 10 ** e
n = int(round(3.4 * n))
prec = n // 3.4
(pilist, remainders, tsum) = ([], [], [])
(multq, asum, carover, counter) = (0, 0, 0, 0)
a = [x for x in range(n)]
b = [2 * x + 1 for x in range(n)]
init = [2 for x in range(1, n + 1)]
x10 = [xfact * x for x in init]
while True:
for (A, B, R) in zip(reversed(a), reversed(b), reversed(x10)):
asum = carover + R
remainders.insert(0, asum % B)
tsum.insert(0, asum)
multq = asum // B
carover = multq * A
pilist.append(tsum[0] // 10)
remainders[0] = tsum[0] % xfact
x10 = [10 * x for x in list(remainders)]
(carover, asum) = (0, 0)
(remainders, tsum) = ([], [])
if len(''.join([str(x) for x in pilist])) > prec:
break
for D in reversed(pilist):
counter = 0
if D >= xfact:
pilist[pilist.index(D) - 1] += 1
pilist[pilist.index(D)] = pilist[pilist.index(D)] % xfact
counter += 1
return str('3.' + ''.join(str(x) for x in pilist[1:]))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T16:11:55.257",
"Id": "496798",
"Score": "0",
"body": "I do realize I have an inert counter in pispig now, but Ill leave unedited in spirit of code review."
}
] |
[
{
"body": "<p>About the first function. If you are so inclined, apply these ideas to the second one too.</p>\n<p>Generally I'd love to see more descriptive variable names, comments, a docstring.\nI tried to stick to your algorithm/implementation as much as possible, i.e. I'm just playing the role of a linter here.</p>\n<p>That being said.</p>\n<p>Why</p>\n<pre><code>while True:\n ....\n if len(estr) > n:\n break\n</code></pre>\n<p>instead of</p>\n<pre><code>while len(estr) <= n:\n ....\n</code></pre>\n<p>?</p>\n<p>Why</p>\n<pre><code> asum = carover + y\n remainders.insert(0, asum % x)\n tsum.insert(0, asum)\n multq = asum // x\n carover = multq\n</code></pre>\n<p>instead of</p>\n<pre><code> asum = carover + y\n tsum.insert(0, asum)\n divx, modx = divmod(asum, x)\n remainders.insert(0, modx)\n carover = divx\n</code></pre>\n<p>?</p>\n<p>Why not move</p>\n<pre><code> (carover, asum) = (0, 0)\n (remainders, tsum) = ([], [])\n</code></pre>\n<p>to the start of the loop, so that you can remove these from before the loop.</p>\n<p>Why not write e.g.</p>\n<pre><code>carover, asum = 0, 0\n</code></pre>\n<p>instead, and lose the parens?</p>\n<p>Why build an inner list in</p>\n<pre><code>x10 = [prec * x for x in list(reversed(remainders))]\n</code></pre>\n<p>instead of just using the iterator</p>\n<pre><code>x10 = [prec * x for x in reversed(remainders)]\n</code></pre>\n<p>?</p>\n<p>Why cast to int after integer division? You shouldn't need the <code>int</code> in the following:</p>\n<pre><code>int(tsum[0] // 2)\n</code></pre>\n<p>Why reverse <code>b</code>, <code>remainders</code>? Why not construct them so that they are "reversed" by default:</p>\n<pre><code>b = list(range(n, 1, -1))\n\nremainders.append(asum % x)\n</code></pre>\n<p>To maintain symmetry, let us do the same to <code>tsum</code>:</p>\n<pre><code>estr += str(tsum[-1] // 2)\n\ntsum.append(asum)\n</code></pre>\n<p>Why do we need <code>multq = 0</code>? Why do we need <code>multq</code> at all?</p>\n<p>You don't use <code>tsum</code>, only its first value. I don't think there's a need to build <code>b</code> either.</p>\n<p>OK, so far we have something like the following:</p>\n<pre><code>def espig(n):\n estr = '2.'\n prec = 10 ** n\n ys = [1 for _ in range(2, n + 1)]\n \n while len(estr) <= n:\n carover, asum, remainders = 0, 0, []\n \n for x, y in zip(range(n, 1, -1), ys):\n asum = carover + prec * y\n carover, remainder = divmod(asum, x)\n remainders.append(remainder)\n \n ys = remainders\n estr += str(asum // 2)\n\n return estr\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T23:17:37.047",
"Id": "252217",
"ParentId": "252187",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "252217",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:05:10.907",
"Id": "252187",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"numerical-methods"
],
"Title": "Bounded spigot algorithms for e and pi in Python"
}
|
252187
|
<p>I have a working string indexing method in Java and did convert in Kotlin.</p>
<p>All methods shown below produce the same result but as I am really new to the Kotlin language I wanted to ask which of my two Kotlin implementations is semantically "more equal" to my Java code.</p>
<p>Here is my Java code where "copiedList" is an ArrayList:</p>
<pre><code>public static Map<String, Integer> count(List<String> copiedList) {
Map<String, Integer> map = new HashMap<>();
for (String string : copiedList) {
String lowerString = string.toLowerCase();
if (!map.containsKey(lowerString)) {
map.put(lowerString, 1);
} else {
int integer = map.get(lowerString);
map.put(lowerString, integer + 1);
}
}
return map;
}
</code></pre>
<p>My Kotlin implementation 1:</p>
<pre><code>fun countWords(splittedArray: Array<String>): Map<String, Int> {
return splittedArray.asSequence().filterNot { it.isBlank() }.map { it.toLowerCase() }. groupingBy { it }.eachCount()
}
</code></pre>
<p>or Kotlin implementation 2:</p>
<pre><code>fun countWordsSeq(textSequence: Sequence<String>): Map<String, Int> {
return textSequence.filterNot { it.isBlank() }.map { it.toLowerCase() }. groupingBy { it }.eachCount()
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T19:09:11.720",
"Id": "496823",
"Score": "0",
"body": "Hi and welcome to Code Review Stack Exchange. The two different implementations you want us to compare here are *extremely* similar. The first one is basically doing `countWordsSeq(splittedArray.asSequence())` - that's pretty much all I can say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T19:16:39.733",
"Id": "496825",
"Score": "0",
"body": "Hello @SimonForsberg thanks for your answer. I know that both are extremely similar. My question is which is closer to the java implementation as Java uses List immediately and in the first Kotlin implementation has to convert it first to a \"list\".\nHas that an impact on runtime?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T09:11:14.210",
"Id": "498455",
"Score": "1",
"body": "1) `.filterNot { it.isBlank() }` is not inside your java code, so the code examples are not equal! 2) Your implementation 1 is closer t0 your java code, because both do not evaluate lazily - which Sequence does. To achieve this, the java code must have used Streams."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-04T07:38:53.133",
"Id": "498777",
"Score": "0",
"body": "If you actually want to compare Java and Kotlin in this scenario, better to compare Java 8 Stream implementation of this with Kotlin."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T15:13:00.307",
"Id": "252188",
"Score": "2",
"Tags": [
"java",
"comparative-review",
"kotlin"
],
"Title": "Which of my string indexing functions in Kotlin is semantically closer to my Java one?"
}
|
252188
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.